From 1c6d19f28302b8caa3cbecc9b20de69e61fcc958 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 29 Jul 2026 21:51:30 +0000 Subject: [PATCH 1/6] Update @github/copilot to 1.0.76-5 - Updated nodejs and test harness dependencies - Re-ran code generators - Formatted generated code --- dotnet/src/Generated/Rpc.cs | 20450 +++++++++------- dotnet/src/Generated/SessionEvents.cs | 555 +- go/rpc/zrpc.go | 3212 ++- go/rpc/zrpc_encoding.go | 183 +- go/rpc/zsession_encoding.go | 25 + go/rpc/zsession_events.go | 216 +- go/zsession_events.go | 24 + java/pom.xml | 2 +- java/scripts/codegen/package-lock.json | 72 +- java/scripts/codegen/package.json | 2 +- .../generated/AssistantMessageEvent.java | 1 + .../generated/AssistantReasoningEvent.java | 3 +- .../generated/AssistantUsageEvent.java | 3 + .../copilot/generated/CompactionTrigger.java | 41 + .../generated/FactoryRunUpdatedEvent.java | 42 + .../generated/ModelCallFailureEvent.java | 1 + .../generated/ModelCallStartEvent.java | 4 +- .../generated/PermissionRequestedEvent.java | 2 + .../copilot/generated/ScheduleOrigin.java | 35 + .../SessionAutoModeResolvedEvent.java | 20 +- .../SessionCompactionCompleteEvent.java | 6 +- .../SessionCompactionStartEvent.java | 8 +- .../generated/SessionContextChangedEvent.java | 4 +- .../copilot/generated/SessionEvent.java | 2 + .../SessionManagedSettingsResolvedEvent.java | 2 + .../copilot/generated/SessionResumeEvent.java | 4 +- .../SessionScheduleCreatedEvent.java | 4 +- .../generated/SessionTaskCompleteEvent.java | 10 +- .../copilot/generated/SystemMessageEvent.java | 2 + .../generated/TaskCompletionOutcome.java | 37 + .../generated/ToolExecutionCompleteEvent.java | 1 + .../generated/ToolExecutionStartEvent.java | 1 + .../copilot/generated/UserMessageEvent.java | 2 +- .../generated/WorkingDirectoryContext.java | 4 +- .../copilot/generated/rpc/AgentInfo.java | 10 +- .../rpc/BuiltInModelCatalogEntry.java | 27 + .../copilot/generated/rpc/ConnectParams.java | 2 +- .../rpc/ContentExclusionPathCheck.java | 29 + .../generated/rpc/FactoryAgentSummary.java | 38 + .../generated/rpc/FactoryCurrentPhase.java | 27 + .../generated/rpc/FactoryDeclaredLimits.java | 29 + .../generated/rpc/FactoryExecuteParams.java | 2 + .../rpc/FactoryPhaseObservation.java | 38 + .../generated/rpc/FactoryPhaseStatus.java | 39 + .../generated/rpc/FactoryProgressLine.java | 37 + .../generated/rpc/FactoryProgressPage.java | 33 + .../generated/rpc/FactoryRunConsumed.java | 28 + .../generated/rpc/FactoryRunLimits.java | 6 +- .../generated/rpc/FactoryRunResult.java | 39 + .../generated/rpc/FactoryRunSummary.java | 44 + .../generated/rpc/FactoryRunTerminal.java | 29 + .../rpc/HistoryFileRestoreSkipReason.java | 35 + .../rpc/HistoryRewindChangeType.java | 37 + .../rpc/HistoryRewindFilePreview.java | 33 + .../generated/rpc/HistoryRewindMode.java | 35 + .../generated/rpc/HistoryRewindOutcome.java | 49 + .../generated/rpc/HistoryRewindPoint.java | 43 + .../rpc/HistoryRewindUnavailableReason.java | 37 + .../rpc/HistorySkippedFileRestore.java | 29 + .../generated/rpc/InstructionSource.java | 2 +- .../generated/rpc/McpFilteredServer.java | 4 +- .../copilot/generated/rpc/McpHostState.java | 2 +- .../copilot/generated/rpc/ModelBilling.java | 2 +- .../generated/rpc/ModelBillingPromo.java | 6 +- .../rpc/ModelsGetBuiltInCatalogResult.java | 31 + .../generated/rpc/QueueInsertMessage.java | 51 + .../generated/rpc/QueuePendingItems.java | 6 +- .../rpc/SandboxConfigUserPolicyNetwork.java | 4 +- .../SandboxConfigUserPolicyNetworkProxy.java | 31 + .../generated/rpc/SendMessageItem.java | 2 +- .../generated/rpc/ServerModelsApi.java | 11 + .../generated/rpc/ServerSessionsApi.java | 33 + .../generated/rpc/SessionAgentApi.java | 4 +- .../generated/rpc/SessionAgentListResult.java | 4 +- ...ssionCancelAllBackgroundAgentsParams.java} | 4 +- .../generated/rpc/SessionCommandsApi.java | 2 +- .../rpc/SessionContentExclusionApi.java | 49 + ...ssionContentExclusionCheckPathsParams.java | 33 + ...ssionContentExclusionCheckPathsResult.java | 33 + .../rpc/SessionEventLogReadParams.java | 4 +- .../rpc/SessionEventLogReadResult.java | 2 +- .../rpc/SessionFactoryAgentParams.java | 2 + .../generated/rpc/SessionFactoryApi.java | 59 + .../rpc/SessionFactoryGetRunDetailParams.java | 32 + .../rpc/SessionFactoryGetRunDetailResult.java | 51 + .../SessionFactoryGetRunProgressParams.java | 40 + .../SessionFactoryGetRunProgressResult.java | 36 + .../rpc/SessionFactoryJournalGetParams.java | 2 + .../rpc/SessionFactoryJournalPutParams.java | 2 + .../rpc/SessionFactoryListRunsParams.java | 30 + .../rpc/SessionFactoryListRunsResult.java | 30 + .../rpc/SessionFactoryLogParams.java | 2 + .../rpc/SessionFactoryResumeParams.java | 34 + .../rpc/SessionFactoryResumeResult.java | 32 + .../rpc/SessionFsSqliteQueryParams.java | 2 +- .../rpc/SessionFsSqliteQueryResult.java | 3 - .../rpc/SessionFsSqliteTransactionError.java | 27 + .../SessionFsSqliteTransactionErrorClass.java | 37 + .../rpc/SessionFsSqliteTransactionParams.java | 32 + .../rpc/SessionFsSqliteTransactionResult.java | 31 + .../SessionFsSqliteTransactionStatement.java | 32 + .../generated/rpc/SessionHistoryApi.java | 45 +- .../SessionHistoryListRewindPointsParams.java | 30 + .../SessionHistoryListRewindPointsResult.java | 35 + .../SessionHistoryPreviewRewindParams.java | 32 + .../SessionHistoryPreviewRewindResult.java | 37 + .../rpc/SessionHistoryRewindParams.java | 34 + .../rpc/SessionHistoryRewindResult.java | 39 + .../rpc/SessionHistoryTruncateResult.java | 6 +- .../rpc/SessionInterruptMainTurnParams.java | 32 + .../rpc/SessionInterruptMainTurnResult.java | 30 + .../rpc/SessionLimitPredictionApi.java | 42 + .../SessionLimitPredictionBaselineData.java | 29 + .../rpc/SessionLimitPredictionClientType.java | 35 + .../rpc/SessionLimitPredictionDetails.java | 44 + .../rpc/SessionLimitPredictionResult.java | 35 + ...SessionLimitPredictionResultAvailable.java | 37 + ...ssionLimitPredictionResultUnavailable.java | 37 + .../rpc/SessionLimitPredictionSource.java | 37 + .../rpc/SessionLimitPredictionTier.java | 39 + .../rpc/SessionLimitPredictionTierOption.java | 28 + ...ssionLimitPredictionUnavailableReason.java | 35 + .../copilot/generated/rpc/SessionMcpApi.java | 2 +- .../generated/rpc/SessionMcpOauthApi.java | 16 + .../rpc/SessionMcpOauthRespondParams.java | 32 + .../rpc/SessionMcpOauthRespondResult.java | 30 + .../rpc/SessionMcpStartServerParams.java | 4 +- .../generated/rpc/SessionModelApi.java | 2 +- .../rpc/SessionModelSwitchToParams.java | 4 +- .../rpc/SessionModelSwitchToResult.java | 4 +- .../rpc/SessionOptionsUpdateParams.java | 10 +- .../generated/rpc/SessionPermissionsApi.java | 11 +- ...ermissionsResetSessionApprovalsParams.java | 6 +- .../generated/rpc/SessionPluginsApi.java | 2 +- .../generated/rpc/SessionProviderApi.java | 2 +- .../rpc/SessionProviderGetEndpointParams.java | 30 - .../generated/rpc/SessionQueueApi.java | 222 + ...sionQueueBeginDeferredIdleDrainParams.java | 32 + ...sionQueueBeginDeferredIdleDrainResult.java | 30 + ...QueueConsumeSystemNotificationsParams.java | 32 + ...QueueConsumeSystemNotificationsResult.java | 30 + .../SessionQueueDeferSessionIdleParams.java | 32 + ...ava => SessionQueueDuplicateAtParams.java} | 7 +- .../rpc/SessionQueueDuplicateAtResult.java | 30 + ...essionQueueEnqueueResumePendingParams.java | 30 + ...essionQueueEnqueueResumePendingResult.java | 30 + ...ionQueueFinishDeferredIdleDrainParams.java | 34 + ...ionQueueFinishDeferredIdleDrainResult.java | 32 + ...java => SessionQueueHasPendingParams.java} | 4 +- .../rpc/SessionQueueHasPendingResult.java | 30 + .../rpc/SessionQueueInsertAtParams.java | 33 + .../rpc/SessionQueueInsertAtResult.java | 30 + .../rpc/SessionQueueMoveItemParams.java | 34 + .../rpc/SessionQueueMoveItemResult.java | 30 + ...ms.java => SessionQueueProcessParams.java} | 2 +- .../rpc/SessionQueueRemoveAtParams.java | 31 + .../rpc/SessionQueueRemoveAtResult.java | 30 + .../rpc/SessionQueueSendNowParams.java | 31 + .../rpc/SessionQueueSendNowResult.java | 30 + .../rpc/SessionQueueSetDrainPausedParams.java | 31 + ...s.java => SessionQueueSnapshotParams.java} | 4 +- .../rpc/SessionQueueSnapshotResult.java | 37 + .../rpc/SessionQueueUpdateTextParams.java | 33 + .../rpc/SessionQueueUpdateTextResult.java | 30 + .../copilot/generated/rpc/SessionRpc.java | 49 + .../rpc/SessionScheduleAddAtParams.java | 38 + .../rpc/SessionScheduleAddAtResult.java | 32 + .../rpc/SessionScheduleAddCronParams.java | 40 + .../rpc/SessionScheduleAddCronResult.java | 32 + .../rpc/SessionScheduleAddParams.java | 38 + .../rpc/SessionScheduleAddResult.java | 32 + .../SessionScheduleAddSelfPacedParams.java | 34 + .../SessionScheduleAddSelfPacedResult.java | 32 + .../generated/rpc/SessionScheduleApi.java | 102 + .../SessionScheduleHasSelfPacedParams.java | 30 + .../SessionScheduleHasSelfPacedResult.java | 30 + .../rpc/SessionScheduleHydrateParams.java | 30 + .../SessionScheduleRearmSelfPacedParams.java | 34 + .../SessionScheduleRearmSelfPacedResult.java | 32 + .../rpc/SessionSendMessagesParams.java | 2 +- .../generated/rpc/SessionSendParams.java | 4 +- .../SessionSendSystemNotificationParams.java | 36 + .../SessionWorkspacesAddSummaryParams.java | 34 + .../SessionWorkspacesAddSummaryResult.java | 31 + .../generated/rpc/SessionWorkspacesApi.java | 113 + ...kspacesAutopilotObjectiveExistsParams.java | 30 + ...kspacesAutopilotObjectiveExistsResult.java | 30 + ...kspacesDeleteAutopilotObjectiveParams.java | 30 + ...kspacesDeleteAutopilotObjectiveResult.java | 30 + .../rpc/SessionWorkspacesDiffResult.java | 6 +- .../rpc/SessionWorkspacesEnsureParams.java | 32 + .../rpc/SessionWorkspacesEnsureResult.java | 57 + ...orkspacesReadAutopilotObjectiveParams.java | 30 + ...orkspacesReadAutopilotObjectiveResult.java | 30 + ...sionWorkspacesTruncateSummariesParams.java | 32 + ...sionWorkspacesTruncateSummariesResult.java | 57 + ...SessionWorkspacesUpdateMetadataParams.java | 34 + ...SessionWorkspacesUpdateMetadataResult.java | 57 + ...rkspacesWriteAutopilotObjectiveParams.java | 32 + ...rkspacesWriteAutopilotObjectiveResult.java | 30 + .../generated/rpc/SessionsDeleteParams.java | 32 + .../rpc/SessionsGetMetadataParams.java | 30 + .../rpc/SessionsGetMetadataResult.java | 30 + .../SessionsListNonEmptySessionIdsParams.java | 30 + .../SessionsListNonEmptySessionIdsResult.java | 31 + .../generated/rpc/ShellInitProfile.java | 35 + .../generated/rpc/ShellInitScript.java | 29 + .../generated/rpc/ShellInitScriptShell.java | 35 + .../copilot/generated/rpc/ShellOptions.java | 42 + .../generated/rpc/UIExitPlanModeResponse.java | 4 +- .../rpc/WorkspaceDiffFileChange.java | 2 +- nodejs/package-lock.json | 72 +- nodejs/package.json | 2 +- nodejs/samples/package-lock.json | 2 +- nodejs/src/generated/rpc.ts | 3055 ++- nodejs/src/generated/session-events.ts | 272 +- python/copilot/generated/rpc.py | 5169 +++- python/copilot/generated/session_events.py | 352 +- rust/src/generated/api_types.rs | 11934 +++++---- rust/src/generated/rpc.rs | 1761 +- rust/src/generated/session_events.rs | 267 +- test/harness/package-lock.json | 72 +- test/harness/package.json | 2 +- 223 files changed, 38834 insertions(+), 14153 deletions(-) create mode 100644 java/src/generated/java/com/github/copilot/generated/CompactionTrigger.java create mode 100644 java/src/generated/java/com/github/copilot/generated/FactoryRunUpdatedEvent.java create mode 100644 java/src/generated/java/com/github/copilot/generated/ScheduleOrigin.java create mode 100644 java/src/generated/java/com/github/copilot/generated/TaskCompletionOutcome.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/BuiltInModelCatalogEntry.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/ContentExclusionPathCheck.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/FactoryAgentSummary.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/FactoryCurrentPhase.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/FactoryDeclaredLimits.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/FactoryPhaseObservation.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/FactoryPhaseStatus.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/FactoryProgressLine.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/FactoryProgressPage.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/FactoryRunConsumed.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/FactoryRunResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/FactoryRunSummary.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/FactoryRunTerminal.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/HistoryFileRestoreSkipReason.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindChangeType.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindFilePreview.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindMode.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindOutcome.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindPoint.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindUnavailableReason.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/HistorySkippedFileRestore.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/ModelsGetBuiltInCatalogResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/QueueInsertMessage.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SandboxConfigUserPolicyNetworkProxy.java rename java/src/generated/java/com/github/copilot/generated/rpc/{SessionPluginsReloadParams.java => SessionCancelAllBackgroundAgentsParams.java} (89%) create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionContentExclusionApi.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionContentExclusionCheckPathsParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionContentExclusionCheckPathsResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunDetailParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunDetailResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunProgressParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunProgressResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryListRunsParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryListRunsResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryResumeParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryResumeResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteTransactionError.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteTransactionErrorClass.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteTransactionParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteTransactionResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteTransactionStatement.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryListRewindPointsParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryListRewindPointsResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryPreviewRewindParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryPreviewRewindResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryRewindParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryRewindResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionInterruptMainTurnParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionInterruptMainTurnResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionApi.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionBaselineData.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionClientType.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionDetails.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionResultAvailable.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionResultUnavailable.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionSource.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionTier.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionTierOption.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionUnavailableReason.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpOauthRespondParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpOauthRespondResult.java delete mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionProviderGetEndpointParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueBeginDeferredIdleDrainParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueBeginDeferredIdleDrainResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueConsumeSystemNotificationsParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueConsumeSystemNotificationsResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueDeferSessionIdleParams.java rename java/src/generated/java/com/github/copilot/generated/rpc/{SessionCommandsListParams.java => SessionQueueDuplicateAtParams.java} (84%) create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueDuplicateAtResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueEnqueueResumePendingParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueEnqueueResumePendingResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueFinishDeferredIdleDrainParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueFinishDeferredIdleDrainResult.java rename java/src/generated/java/com/github/copilot/generated/rpc/{SessionHistoryCompactParams.java => SessionQueueHasPendingParams.java} (92%) create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueHasPendingResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueInsertAtParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueInsertAtResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueMoveItemParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueMoveItemResult.java rename java/src/generated/java/com/github/copilot/generated/rpc/{SessionAgentListParams.java => SessionQueueProcessParams.java} (96%) create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueRemoveAtParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueRemoveAtResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueSendNowParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueSendNowResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueSetDrainPausedParams.java rename java/src/generated/java/com/github/copilot/generated/rpc/{SessionModelListParams.java => SessionQueueSnapshotParams.java} (92%) create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueSnapshotResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueUpdateTextParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueUpdateTextResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddAtParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddAtResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddCronParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddCronResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddSelfPacedParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddSelfPacedResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleHasSelfPacedParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleHasSelfPacedResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleHydrateParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleRearmSelfPacedParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleRearmSelfPacedResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionSendSystemNotificationParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesAddSummaryParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesAddSummaryResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesAutopilotObjectiveExistsParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesAutopilotObjectiveExistsResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesDeleteAutopilotObjectiveParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesDeleteAutopilotObjectiveResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesEnsureParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesEnsureResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesReadAutopilotObjectiveParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesReadAutopilotObjectiveResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesTruncateSummariesParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesTruncateSummariesResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesUpdateMetadataParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesUpdateMetadataResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesWriteAutopilotObjectiveParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesWriteAutopilotObjectiveResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionsDeleteParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionsGetMetadataParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionsGetMetadataResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionsListNonEmptySessionIdsParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionsListNonEmptySessionIdsResult.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/ShellInitProfile.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/ShellInitScript.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/ShellInitScriptShell.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/ShellOptions.java diff --git a/dotnet/src/Generated/Rpc.cs b/dotnet/src/Generated/Rpc.cs index d09976bc80..427cc0d77c 100644 --- a/dotnet/src/Generated/Rpc.cs +++ b/dotnet/src/Generated/Rpc.cs @@ -65,7 +65,7 @@ internal sealed class ConnectResult [Experimental(Diagnostics.Experimental)] internal sealed class ConnectRequest { - /// Opt this connection in to GitHub telemetry forwarding for its lifetime. When set, the runtime forwards every internal telemetry event it emits — across all sessions, plus sessionless events — to this connection over the `gitHubTelemetry.event` notification, in addition to the runtime's normal GitHub/CTS emission (dual-write). Intended for first-party hosts that re-emit the events into their own telemetry stores. Both unrestricted and restricted events are forwarded, each tagged with a `restricted` discriminator; a backstop drops restricted events when restricted telemetry is disabled. + /// Opt this connection in to GitHub telemetry forwarding for its lifetime. When set, the runtime forwards every internal telemetry event it emits — across all sessions, plus sessionless events — to this connection over the `gitHubTelemetry.event` notification. Regular events are also written to the runtime's normal GitHub/CTS path (dual-write); host-only compatibility events are forward-only and intentionally skip that path. Intended for first-party hosts that re-emit the events into their own telemetry stores. Both unrestricted and restricted events are forwarded, each tagged with a `restricted` discriminator; a backstop drops restricted events when restricted telemetry is disabled — using the process-global gate for ordinary events and an explicit session-scoped decision for host-only events. [JsonPropertyName("enableGitHubTelemetryForwarding")] public bool? EnableGitHubTelemetryForwarding { get; set; } @@ -74,7 +74,7 @@ internal sealed class ConnectRequest public string? Token { get; set; } } -/// Active server-driven promotion for a model, including its discount and expiry. +/// Active server-driven promotion for a model, including its discount and optional expiry. [Experimental(Diagnostics.Experimental)] public sealed class ModelBillingPromo { @@ -82,15 +82,15 @@ public sealed class ModelBillingPromo [JsonPropertyName("discountPercent")] public double? DiscountPercent { get; set; } - /// UTC ISO 8601 timestamp marking when the promotion ends. Always present: the API only surfaces a promo whose expiry parses and is in the future. Consumers should treat a past value as expired. + /// UTC ISO 8601 timestamp marking when the promotion ends. Optional: an open-ended promotion omits this field. When present, the API only surfaces a promo whose expiry parses and is in the future, so consumers should treat a past value as expired. [JsonPropertyName("endsAt")] - public string EndsAt { get; set; } = string.Empty; + public string? EndsAt { get; set; } /// Stable identifier for the promotion campaign. [JsonPropertyName("id")] public string? Id { get; set; } - /// Human-readable promotion message. Does not include the expiry timestamp; consumers may format endsAt and append it. + /// Human-readable promotion message. Does not include the expiry timestamp; consumers may format endsAt and append it when present. [JsonPropertyName("message")] public string? Message { get; set; } } @@ -197,7 +197,7 @@ public sealed class ModelBilling [JsonPropertyName("multiplier")] public double? Multiplier { get; set; } - /// Active server-driven promotion for this model, if any. Present when the model is being promoted with a time-boxed discount. + /// Active server-driven promotion for this model, if any. Present when the model is being promoted with a discount, which may be time-boxed or open-ended. [JsonPropertyName("promo")] public ModelBillingPromo? Promo { get; set; } @@ -346,6 +346,24 @@ internal sealed class ModelsListRequest public string? GitHubToken { get; set; } } +/// A well-known model in the runtime's built-in catalog. +[Experimental(Diagnostics.Experimental)] +public sealed class BuiltInModelCatalogEntry +{ + /// Well-known runtime model ID suitable for `ProviderConfig.modelId` or `ProviderModelConfig.modelId`. This is not necessarily the provider-facing deployment or model name and does not indicate CAPI entitlement or provider availability. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; +} + +/// The running runtime's complete catalog of well-known built-in model IDs, including supported models and additional IDs with built-in metadata. +[Experimental(Diagnostics.Experimental)] +public sealed class BuiltInModelCatalog +{ + /// Built-in model entries. + [JsonPropertyName("models")] + public IList Models { get => field ??= []; set; } +} + /// Built-in tool metadata with identifier, optional namespaced name, description, input-parameter schema, and usage instructions. [Experimental(Diagnostics.Experimental)] public sealed class Tool @@ -1588,7 +1606,7 @@ internal sealed class SkillsConfigSetDisabledSkillsRequest public IList DisabledSkills { get => field ??= []; set; } } -/// Custom agent metadata, including identifiers, display details, source, tools, model, MCP servers, skills, and file path. +/// Agent metadata, including identifiers, display details, source, tools, model, MCP servers, skills, and file path. [Experimental(Diagnostics.Experimental)] public sealed class AgentInfo { @@ -1609,11 +1627,11 @@ public sealed class AgentInfo [JsonPropertyName("mcpServers")] public IDictionary? McpServers { get; set; } - /// Preferred model id for this agent. When omitted, inherits the outer agent's model. + /// Authored preferred model id for this agent. Runtime model selection may choose a different model; omitted means no authored preference. [JsonPropertyName("model")] public string? Model { get; set; } - /// Unique identifier of the custom agent. + /// Name of the agent. Use `id` as the stable selection identifier. [JsonPropertyName("name")] public string Name { get; set; } = string.Empty; @@ -1621,6 +1639,10 @@ public sealed class AgentInfo [JsonPropertyName("path")] public string? Path { get; set; } + /// Authored base prompt for the agent. Runtime prompt assembly may add dynamic context at invocation time. Omitted from `session.agent.list` unless `includePrompt` is true. + [JsonPropertyName("prompt")] + public string? Prompt { get; set; } + /// Skill names preloaded into this agent's context. Omitted means none. [JsonPropertyName("skills")] public IList? Skills { get; set; } @@ -1735,7 +1757,7 @@ public sealed class InstructionSource [JsonPropertyName("location")] public InstructionSourceLocation Location { get; set; } - /// The project path this source was discovered from. Only set by sessionless discovery for repository/working-directory sources, where it disambiguates same-named files (e.g. .github/copilot-instructions.md) across multiple workspace roots. The session-scoped getSources leaves it unset. + /// The project path this source was discovered from. Only set by sessionless discovery for repository, working-directory, and project-scoped plugin sources, where it disambiguates sources across multiple workspace roots. The session-scoped getSources leaves it unset. [JsonPropertyName("projectPath")] public string? ProjectPath { get; set; } @@ -2484,6 +2506,87 @@ internal sealed class SessionsListRequest public bool? ThrowOnError { get; set; } } +/// Persisted local session metadata, including identifiers, timestamps, summary/name, client, context, detached state, and task ID. +[Experimental(Diagnostics.Experimental)] +public sealed class LocalSessionMetadataValue +{ + /// Runtime client name that created/last resumed this session. + [JsonPropertyName("clientName")] + public string? ClientName { get; set; } + + /// Pre-resolved working-directory context for session startup. + [JsonPropertyName("context")] + public SessionContext? Context { get; set; } + + /// True for detached maintenance sessions that should be hidden from normal resume lists. + [JsonPropertyName("isDetached")] + public bool? IsDetached { get; set; } + + /// Always false for local sessions. + [JsonPropertyName("isRemote")] + public bool IsRemote { get; set; } + + /// GitHub task ID, when this local session is bound to one. Only present for local sessions exported to remote control. + [JsonPropertyName("mcTaskId")] + public string? McTaskId { get; set; } + + /// Last-modified time of the session's persisted state, as ISO 8601. + [JsonPropertyName("modifiedTime")] + public string ModifiedTime { get; set; } = string.Empty; + + /// Optional human-friendly name set via /rename. + [JsonPropertyName("name")] + public string? Name { get; set; } + + /// Stable session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; + + /// Session creation time as an ISO 8601 timestamp. + [JsonPropertyName("startTime")] + public string StartTime { get; set; } = string.Empty; + + /// Short summary of the session, when one has been derived. + [JsonPropertyName("summary")] + public string? Summary { get; set; } +} + +/// Persisted local session metadata when the session exists. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionsGetMetadataResult +{ + /// Local session metadata, omitted when the session does not exist. + [JsonPropertyName("session")] + public LocalSessionMetadataValue? Session { get; set; } +} + +/// Session ID whose persisted metadata should be read. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionsGetMetadataRequest +{ + /// Session ID to inspect. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Recent local session IDs that contain user-visible history. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionsListNonEmptySessionIdsResult +{ + /// Session IDs ordered newest-first. + [JsonPropertyName("sessionIds")] + public IList SessionIds { get => field ??= []; set; } +} + +/// Limit for non-empty local session IDs. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionsListNonEmptySessionIdsRequest +{ + /// Maximum number of session IDs to return. + [JsonPropertyName("limit")] + public long? Limit { get; set; } +} + /// ID of the local session bound to the given GitHub task, or omitted when none. [Experimental(Diagnostics.Experimental)] public sealed class SessionsFindByTaskIDResult @@ -2634,6 +2737,19 @@ internal sealed class SessionsBulkDeleteRequest public IList SessionIds { get => field ??= []; set; } } +/// Session ID to delete from disk. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionsDeleteRequest +{ + /// Session ID to delete. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; + + /// Internal resolved session directory path to delete. + [JsonPropertyName("sessionPath")] + public string? SessionPath { get; set; } +} + /// Outcome of the prune operation: deleted IDs, dry-run candidates, skipped IDs, total bytes freed, and the dry-run flag. [Experimental(Diagnostics.Experimental)] public sealed class SessionPruneResult @@ -2710,51 +2826,6 @@ internal sealed class SessionsReleaseLockRequest public string SessionId { get; set; } = string.Empty; } -/// Persisted local session metadata, including identifiers, timestamps, summary/name, client, context, detached state, and task ID. -[Experimental(Diagnostics.Experimental)] -public sealed class LocalSessionMetadataValue -{ - /// Runtime client name that created/last resumed this session. - [JsonPropertyName("clientName")] - public string? ClientName { get; set; } - - /// Pre-resolved working-directory context for session startup. - [JsonPropertyName("context")] - public SessionContext? Context { get; set; } - - /// True for detached maintenance sessions that should be hidden from normal resume lists. - [JsonPropertyName("isDetached")] - public bool? IsDetached { get; set; } - - /// Always false for local sessions. - [JsonPropertyName("isRemote")] - public bool IsRemote { get; set; } - - /// GitHub task ID, when this local session is bound to one. Only present for local sessions exported to remote control. - [JsonPropertyName("mcTaskId")] - public string? McTaskId { get; set; } - - /// Last-modified time of the session's persisted state, as ISO 8601. - [JsonPropertyName("modifiedTime")] - public string ModifiedTime { get; set; } = string.Empty; - - /// Optional human-friendly name set via /rename. - [JsonPropertyName("name")] - public string? Name { get; set; } - - /// Stable session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; - - /// Session creation time as an ISO 8601 timestamp. - [JsonPropertyName("startTime")] - public string StartTime { get; set; } = string.Empty; - - /// Short summary of the session, when one has been derived. - [JsonPropertyName("summary")] - public string? Summary { get; set; } -} - /// The enriched metadata records, with summary and context fields backfilled where available. Sessions confirmed empty and unnamed are omitted. [Experimental(Diagnostics.Experimental)] public sealed class SessionEnrichMetadataResult @@ -3451,8 +3522,8 @@ internal sealed class SendRequest [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; - /// Optional provenance tag copied to the resulting user.message event. Must match one of three forms: the literal `system`, `command-<command-id>` for messages originating from a command (e.g. slash command, Mission Control command), or `schedule-<numeric-id>` for messages originating from a scheduled job. - [RegularExpression("^(system|command-.*|schedule-\\d+)$")] + /// Optional provenance tag copied to the resulting user.message event. Must be `user`, `system`, `command-<command-id>` for command-originated messages, `schedule-<numeric-id>` for scheduled prompts, or `agent-<agent-id>` for prompts sent by another agent. + [RegularExpression("^(user|system|command-.*|schedule-\\d+|agent-.+)$")] [JsonInclude] [JsonPropertyName("source")] internal string? Source { get; set; } @@ -3465,7 +3536,7 @@ internal sealed class SendRequest [JsonPropertyName("tracestate")] public string? Tracestate { get; set; } - /// If true, await completion of the agentic loop for this message before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageId`; the caller can rely on the agent having processed the message before the call resolves. + /// If true, await completion of the agentic loop for this message before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageId`; the caller can rely on the agent having processed the message before the call resolves. Transport-dependent tail semantics: on a LOCAL (in-process) session the wait additionally blocks until the completed turn's event tail has been dispatched to this session's in-process subscribers, so a subsequent read of subscriber state already reflects the turn; on a REMOTE session the wait resolves once the loop completes and mirrored delivery follows over the wire. Callers that need the stronger local guarantee on remote sessions should await the event stream explicitly. [JsonPropertyName("wait")] public bool? Wait { get; set; } } @@ -3504,8 +3575,8 @@ public sealed class SendMessageItem [JsonPropertyName("requiredTool")] public string? RequiredTool { get; set; } - /// Optional provenance tag copied to the resulting user.message event. Must match one of three forms: the literal `system`, `command-<command-id>` for messages originating from a command (e.g. slash command, Mission Control command), or `schedule-<numeric-id>` for messages originating from a scheduled job. - [RegularExpression("^(system|command-.*|schedule-\\d+)$")] + /// Optional provenance tag copied to the resulting user.message event. Must be `user`, `system`, `command-<command-id>` for command-originated messages, `schedule-<numeric-id>` for scheduled prompts, or `agent-<agent-id>` for prompts sent by another agent. + [RegularExpression("^(user|system|command-.*|schedule-\\d+|agent-.+)$")] [JsonInclude] [JsonPropertyName("source")] internal string? Source { get; set; } @@ -3547,11 +3618,32 @@ internal sealed class SendMessagesRequest [JsonPropertyName("tracestate")] public string? Tracestate { get; set; } - /// If true, await completion of the agentic loop for this turn before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageIds`; the caller can rely on the agent having processed the messages before the call resolves. + /// If true, await completion of the agentic loop for this turn before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageIds`; the caller can rely on the agent having processed the messages before the call resolves. Transport-dependent tail semantics: on a LOCAL (in-process) session the wait additionally blocks until the completed turn's event tail has been dispatched to this session's in-process subscribers, so a subsequent read of subscriber state already reflects the turn; on a REMOTE session the wait resolves once the loop completes and mirrored delivery follows over the wire. Callers that need the stronger local guarantee on remote sessions should await the event stream explicitly. [JsonPropertyName("wait")] public bool? Wait { get; set; } } +/// Internal request for sending a system notification. +[Experimental(Diagnostics.Experimental)] +internal sealed class SendSystemNotificationRequest +{ + /// Optional structured notification kind. + [JsonPropertyName("kind")] + public JsonElement? Kind { get; set; } + + /// Notification text to deliver to the model. + [JsonPropertyName("message")] + public string Message { get; set; } = string.Empty; + + /// Internal delivery options, including passive policy. + [JsonPropertyName("options")] + public JsonElement? Options { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + /// Result of aborting the current turn. [Experimental(Diagnostics.Experimental)] public sealed class AbortResult @@ -3578,6 +3670,37 @@ internal sealed class AbortRequest public string SessionId { get; set; } = string.Empty; } +/// Result of interrupting the main agent turn. +[Experimental(Diagnostics.Experimental)] +public sealed class InterruptMainTurnResult +{ + /// Whether an in-flight main agent turn was interrupted. False when the main loop was not processing. + [JsonPropertyName("interrupted")] + public bool Interrupted { get; set; } +} + +/// Parameters for interrupting the main agent turn. +[Experimental(Diagnostics.Experimental)] +internal sealed class InterruptMainTurnRequest +{ + /// When true, the user's queued prompts are preserved and run as the next turn once the interrupted turn unwinds; when false (the default), the queue is cleared like a plain abort. + [JsonPropertyName("flushQueued")] + public bool? FlushQueued { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Identifies the target session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionCancelAllBackgroundAgentsRequest +{ + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + /// Parameters for shutting down the session. [Experimental(Diagnostics.Experimental)] internal sealed class ShutdownRequest @@ -4095,6 +4218,7 @@ internal sealed class CanvasActionInvokeRequest UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] [JsonDerivedType(typeof(FactoryRunFailureFactoryLimitReached), "factory_limit_reached")] [JsonDerivedType(typeof(FactoryRunFailureFactoryResumeDeclined), "factory_resume_declined")] +[JsonDerivedType(typeof(FactoryRunFailureFactoryDurableFailure), "factory_durable_failure")] public partial class FactoryRunFailure { /// The type discriminator. @@ -4141,6 +4265,27 @@ public partial class FactoryRunFailureFactoryResumeDeclined : FactoryRunFailure public required string RunId { get; set; } } +/// The factory_durable_failure variant of . +[Experimental(Diagnostics.Experimental)] +public partial class FactoryRunFailureFactoryDurableFailure : FactoryRunFailure +{ + /// + [JsonIgnore] + public override string Type => "factory_durable_failure"; + + /// Stable failure code. + [JsonPropertyName("code")] + public required string Code { get; set; } + + /// Execution-critical durable operation that failed. + [JsonPropertyName("operation")] + public required FactoryDurableOperation Operation { get; set; } + + /// Factory run identifier. + [JsonPropertyName("runId")] + public required string RunId { get; set; } +} + /// Complete current or terminal factory run envelope. [Experimental(Diagnostics.Experimental)] public sealed class FactoryRunResult @@ -4178,6 +4323,10 @@ public sealed class FactoryRunResult [Experimental(Diagnostics.Experimental)] public sealed class FactoryRunLimits { + /// Maximum AI credits consumed by factory subagents and their descendants. The post-paid ceiling is soft: parallel turns can settle beyond it before the run stops. + [JsonPropertyName("maxAiCredits")] + public double? MaxAiCredits { get; set; } + /// Maximum number of factory subagents that may run concurrently. [JsonPropertyName("maxConcurrentSubagents")] public long? MaxConcurrentSubagents { get; set; } @@ -4186,9 +4335,9 @@ public sealed class FactoryRunLimits [JsonPropertyName("maxTotalSubagents")] public long? MaxTotalSubagents { get; set; } - /// Factory active-run timeout in milliseconds. - [JsonPropertyName("timeout")] - public double? Timeout { get; set; } + /// Maximum accumulated active-execution time in seconds. Active execution includes the entire extension body, subprocess waits, queued-agent waits, and sleeps; time between resumed attempts is not counted. + [JsonPropertyName("timeoutSeconds")] + public double? TimeoutSeconds { get; set; } } /// Options controlling factory invocation. @@ -4225,10 +4374,27 @@ internal sealed class FactoryRunRequest public string SessionId { get; set; } = string.Empty; } -/// Parameters for retrieving a factory run. +/// Resolved persisted factory identity and resumed run envelope. [Experimental(Diagnostics.Experimental)] -internal sealed class FactoryGetRunRequest +public sealed class FactoryResumeResult +{ + /// Persisted factory name resolved for the resumed run. + [JsonPropertyName("factoryName")] + public string FactoryName { get; set; } = string.Empty; + + /// Terminal resumed run envelope. + [JsonPropertyName("run")] + public FactoryRunResult Run { get => field ??= new(); set; } +} + +/// Parameters for resuming a factory run from its persisted identity. +[Experimental(Diagnostics.Experimental)] +internal sealed class FactoryResumeRequest { + /// Optional per-invocation resource ceiling overrides. + [JsonPropertyName("limits")] + public FactoryRunLimits? Limits { get; set; } + /// Factory run identifier. [JsonPropertyName("runId")] public string RunId { get; set; } = string.Empty; @@ -4238,9 +4404,9 @@ internal sealed class FactoryGetRunRequest public string SessionId { get; set; } = string.Empty; } -/// Parameters for cancelling a factory run. +/// Parameters for retrieving a factory run. [Experimental(Diagnostics.Experimental)] -internal sealed class FactoryCancelRequest +internal sealed class FactoryGetRunRequest { /// Factory run identifier. [JsonPropertyName("runId")] @@ -4251,2327 +4417,2533 @@ internal sealed class FactoryCancelRequest public string SessionId { get; set; } = string.Empty; } -/// Acknowledgement that a factory request was accepted. +/// Declared or approved factory resource ceilings. [Experimental(Diagnostics.Experimental)] -public sealed class FactoryAckResult +public sealed class FactoryDeclaredLimits { -} + /// Gets or sets the maxAiCredits value. + [JsonPropertyName("maxAiCredits")] + public double? MaxAiCredits { get; set; } -/// One ordered factory progress line. -[Experimental(Diagnostics.Experimental)] -public sealed class FactoryLogLine -{ - /// Progress line kind. - [JsonPropertyName("kind")] - public FactoryLogLineKind Kind { get; set; } + /// Gets or sets the maxConcurrentSubagents value. + [JsonPropertyName("maxConcurrentSubagents")] + public long? MaxConcurrentSubagents { get; set; } - /// Monotonic sequence number within the factory run. - [JsonPropertyName("seq")] - public long Seq { get; set; } + /// Gets or sets the maxTotalSubagents value. + [JsonPropertyName("maxTotalSubagents")] + public long? MaxTotalSubagents { get; set; } - /// Progress text. - [JsonPropertyName("text")] - public string Text { get; set; } = string.Empty; + /// Gets or sets the timeoutSeconds value. + [JsonPropertyName("timeoutSeconds")] + public double? TimeoutSeconds { get; set; } } -/// Parameters for recording factory progress. +/// Durable factory resource consumption. [Experimental(Diagnostics.Experimental)] -internal sealed class FactoryLogRequest +public sealed class FactoryRunConsumed { - /// Ordered progress lines to append. - [JsonPropertyName("lines")] - public IList Lines { get => field ??= []; set; } + /// Gets or sets the activeMs value. + [JsonPropertyName("activeMs")] + public long ActiveMs { get; set; } - /// Factory run identifier. - [JsonPropertyName("runId")] - public string RunId { get; set; } = string.Empty; + /// Gets or sets the nanoAiu value. + [JsonPropertyName("nanoAiu")] + public long NanoAiu { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Gets or sets the subagents value. + [JsonPropertyName("subagents")] + public long Subagents { get; set; } } -/// Result of one factory-scoped subagent call. +/// Current factory phase identity. [Experimental(Diagnostics.Experimental)] -public sealed class FactoryAgentResult +public sealed class FactoryCurrentPhase { - /// Agent result, omitted when the agent produced no result. - [JsonPropertyName("result")] - public JsonElement? Result { get; set; } + /// Gets or sets the id value. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; + + /// Gets or sets the ordinal value. + [JsonPropertyName("ordinal")] + public long? Ordinal { get; set; } } -/// Options for one factory-scoped subagent call. +/// Prompt-safe terminal factory outcome. [Experimental(Diagnostics.Experimental)] -public sealed class FactoryAgentOptions +public sealed class FactoryRunTerminal { - /// Optional label distinguishing otherwise identical memoized agent calls. - [JsonPropertyName("label")] - public string? Label { get; set; } + /// Gets or sets the error value. + [JsonPropertyName("error")] + public string? Error { get; set; } - /// Optional model identifier for the subagent. - [JsonPropertyName("model")] - public string? Model { get; set; } + /// Gets or sets the failure value. + [JsonPropertyName("failure")] + public FactoryRunFailure? Failure { get; set; } - /// Optional JSON Schema for structured agent output. - [JsonPropertyName("schema")] - public JsonElement? Schema { get; set; } + /// Gets or sets the reason value. + [JsonPropertyName("reason")] + public string? Reason { get; set; } + + /// Gets or sets the resultPreview value. + [JsonPropertyName("resultPreview")] + public string? ResultPreview { get; set; } } -/// Parameters for one factory-scoped subagent call. +/// Durable factory run summary with read-time live overlays. [Experimental(Diagnostics.Experimental)] -internal sealed class FactoryAgentRequest +public sealed class FactoryRunSummary { - /// Factory run identifier that owns the subagent. - [JsonPropertyName("factoryRunId")] - public string FactoryRunId { get; set; } = string.Empty; + /// Gets or sets the activeSegmentStartedAt value. + [JsonPropertyName("activeSegmentStartedAt")] + public long? ActiveSegmentStartedAt { get; set; } - /// Subagent execution options. - [JsonPropertyName("opts")] - public FactoryAgentOptions Opts { get => field ??= new(); set; } + /// Gets or sets the approved value. + [JsonPropertyName("approved")] + public FactoryDeclaredLimits? Approved { get; set; } - /// Prompt to send to the subagent. - [JsonPropertyName("prompt")] - public string Prompt { get; set; } = string.Empty; + /// Gets or sets the completedAt value. + [JsonPropertyName("completedAt")] + public long? CompletedAt { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// Gets or sets the consumed value. + [JsonPropertyName("consumed")] + public FactoryRunConsumed Consumed { get => field ??= new(); set; } -/// Result of reading a factory journal entry. -[Experimental(Diagnostics.Experimental)] -public sealed class FactoryJournalGetResult -{ - /// Whether the journal contained the requested key. - [JsonPropertyName("hit")] - public bool Hit { get; set; } + /// Gets or sets the createdAt value. + [JsonPropertyName("createdAt")] + public long CreatedAt { get; set; } - /// Cached JSON result. The hit field distinguishes a cached JSON null from a miss. - [JsonPropertyName("resultJson")] - public JsonElement? ResultJson { get; set; } -} + /// Gets or sets the currentPhase value. + [JsonPropertyName("currentPhase")] + public FactoryCurrentPhase? CurrentPhase { get; set; } -/// Parameters for reading a factory journal entry. -[Experimental(Diagnostics.Experimental)] -internal sealed class FactoryJournalGetRequest -{ - /// Namespaced journal key. - [JsonPropertyName("key")] - public string Key { get; set; } = string.Empty; + /// Gets or sets the declaredLimits value. + [JsonPropertyName("declaredLimits")] + public FactoryDeclaredLimits DeclaredLimits { get => field ??= new(); set; } - /// Factory run identifier. - [JsonPropertyName("runId")] - public string RunId { get; set; } = string.Empty; + /// Gets or sets the declaredPhaseCount value. + [JsonPropertyName("declaredPhaseCount")] + public long DeclaredPhaseCount { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// Gets or sets the description value. + [JsonPropertyName("description")] + public string Description { get; set; } = string.Empty; -/// Parameters for storing a factory journal entry. -[Experimental(Diagnostics.Experimental)] -internal sealed class FactoryJournalPutRequest -{ - /// Namespaced journal key. - [JsonPropertyName("key")] - public string Key { get; set; } = string.Empty; + /// Gets or sets the factoryName value. + [JsonPropertyName("factoryName")] + public string FactoryName { get; set; } = string.Empty; - /// JSON result to memoize. - [JsonPropertyName("resultJson")] - public JsonElement ResultJson { get; set; } + /// Gets or sets the liveAgentCount value. + [JsonPropertyName("liveAgentCount")] + public long LiveAgentCount { get; set; } - /// Factory run identifier. + /// Gets or sets the observedAt value. + [JsonPropertyName("observedAt")] + public long ObservedAt { get; set; } + + /// Gets or sets the revision value. + [JsonPropertyName("revision")] + public long Revision { get; set; } + + /// Gets or sets the runId value. [JsonPropertyName("runId")] public string RunId { get; set; } = string.Empty; - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Gets or sets the startedAt value. + [JsonPropertyName("startedAt")] + public long? StartedAt { get; set; } + + /// Gets or sets the status value. + [JsonPropertyName("status")] + public FactoryRunStatus Status { get; set; } + + /// Gets or sets the terminal value. + [JsonPropertyName("terminal")] + public FactoryRunTerminal? Terminal { get; set; } + + /// Gets or sets the totalSpawnedAgentCount value. + [JsonPropertyName("totalSpawnedAgentCount")] + public long TotalSpawnedAgentCount { get; set; } + + /// Gets or sets the updatedAt value. + [JsonPropertyName("updatedAt")] + public long UpdatedAt { get; set; } } -/// The currently selected model, reasoning effort, and context tier for the session. The context tier reflects `Session.getContextTier()`, restored from the session journal on resume. +/// Factory runs in durable creation order. [Experimental(Diagnostics.Experimental)] -public sealed class CurrentModel +public sealed class FactoryListRunsResult { - /// Context tier for models that support multiple context-window sizes. - [JsonPropertyName("contextTier")] - public ContextTier? ContextTier { get; set; } - - /// Currently active model identifier. - [JsonPropertyName("modelId")] - public string? ModelId { get; set; } - - /// Reasoning effort level currently applied to the active model, when one is set. Reads `Session.getReasoningEffort()` synchronously after `getSelectedModel()` resolves so the two values are reported as a snapshot. - [JsonPropertyName("reasoningEffort")] - public string? ReasoningEffort { get; set; } + /// Gets or sets the runs value. + [JsonPropertyName("runs")] + public IList Runs { get => field ??= []; set; } } -/// Identifies the target session. +/// Empty parameters for listing factory runs. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionModelGetCurrentRequest +internal sealed class FactoryListRunsRequest { /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// The model identifier active on the session after the switch. +/// Prompt-safe durable identity and live status for a direct factory agent. [Experimental(Diagnostics.Experimental)] -public sealed class ModelSwitchToResult +public sealed class FactoryAgentSummary { - /// Currently active model identifier after the switch. - [JsonPropertyName("modelId")] - public string? ModelId { get; set; } -} + /// Gets or sets the activeMs value. + [JsonPropertyName("activeMs")] + public long ActiveMs { get; set; } -/// Vision-specific limits. -[Experimental(Diagnostics.Experimental)] -public sealed class ModelCapabilitiesOverrideLimitsVision -{ - /// Maximum image size in bytes. - [JsonPropertyName("max_prompt_image_size")] - public long? MaxPromptImageSize { get; set; } + /// Gets or sets the activity value. + [JsonPropertyName("activity")] + public string? Activity { get; set; } - /// Maximum number of images per prompt. - [JsonPropertyName("max_prompt_images")] - public long? MaxPromptImages { get; set; } + /// Gets or sets the agentId value. + [JsonPropertyName("agentId")] + public string AgentId { get; set; } = string.Empty; - /// MIME types the model accepts. - [JsonPropertyName("supported_media_types")] - public IList? SupportedMediaTypes { get; set; } -} + /// Gets or sets the agentType value. + [JsonPropertyName("agentType")] + public string AgentType { get; set; } = string.Empty; -/// Token limits for prompts, outputs, and context window. -[Experimental(Diagnostics.Experimental)] -public sealed class ModelCapabilitiesOverrideLimits -{ - /// Maximum total context window size in tokens. - [JsonPropertyName("max_context_window_tokens")] - public long? MaxContextWindowTokens { get; set; } + /// Gets or sets the completedAt value. + [JsonPropertyName("completedAt")] + public long? CompletedAt { get; set; } - /// Maximum number of output/completion tokens. - [JsonPropertyName("max_output_tokens")] - public long? MaxOutputTokens { get; set; } + /// Gets or sets the label value. + [JsonPropertyName("label")] + public string Label { get; set; } = string.Empty; - /// Maximum number of prompt/input tokens. - [JsonPropertyName("max_prompt_tokens")] - public long? MaxPromptTokens { get; set; } + /// Gets or sets the phaseId value. + [JsonPropertyName("phaseId")] + public string? PhaseId { get; set; } - /// Vision-specific limits. - [JsonPropertyName("vision")] - public ModelCapabilitiesOverrideLimitsVision? Vision { get; set; } -} + /// Gets or sets the requestedModel value. + [JsonPropertyName("requestedModel")] + public string? RequestedModel { get; set; } -/// Feature flags indicating what the model supports. -[Experimental(Diagnostics.Experimental)] -public sealed class ModelCapabilitiesOverrideSupports -{ - /// Resolved Anthropic adaptive-thinking capability — unsupported / optional / required. 'required' models reject thinking.type='enabled' with HTTP 400 (e.g. opus-4.7/4.8). - [JsonPropertyName("adaptive_thinking")] - public AdaptiveThinkingSupport? AdaptiveThinking { get; set; } + /// Gets or sets the resolvedModel value. + [JsonPropertyName("resolvedModel")] + public string? ResolvedModel { get; set; } - /// Whether this model supports reasoning effort configuration. - [JsonPropertyName("reasoningEffort")] - public bool? ReasoningEffort { get; set; } + /// Gets or sets the runId value. + [JsonPropertyName("runId")] + public string RunId { get; set; } = string.Empty; - /// Whether this model supports vision/image input. - [JsonPropertyName("vision")] - public bool? Vision { get; set; } -} + /// Gets or sets the startedAt value. + [JsonPropertyName("startedAt")] + public long? StartedAt { get; set; } -/// Optional capability overrides (vision, tool_calls, reasoning, etc.). -[Experimental(Diagnostics.Experimental)] -public sealed class ModelCapabilitiesOverride -{ - /// Token limits for prompts, outputs, and context window. - [JsonPropertyName("limits")] - public ModelCapabilitiesOverrideLimits? Limits { get; set; } + /// Gets or sets the status value. + [JsonPropertyName("status")] + public string Status { get; set; } = string.Empty; - /// Feature flags indicating what the model supports. - [JsonPropertyName("supports")] - public ModelCapabilitiesOverrideSupports? Supports { get; set; } + /// Gets or sets the toolCallId value. + [JsonPropertyName("toolCallId")] + public string ToolCallId { get; set; } = string.Empty; } -/// Target model identifier and optional reasoning effort, summary, capability overrides, and context tier. +/// Durable lifecycle and timing for one factory phase. [Experimental(Diagnostics.Experimental)] -internal sealed class ModelSwitchToRequest +public sealed class FactoryPhaseObservation { - /// Explicit context tier for the selected model. `"default"` / `"long_context"` apply the requested tier; omit this field to use normal model behavior with no explicit tier. - [JsonPropertyName("contextTier")] - public ContextTier? ContextTier { get; set; } + /// Gets or sets the accumulatedActiveMs value. + [JsonPropertyName("accumulatedActiveMs")] + public long AccumulatedActiveMs { get; set; } - /// Override individual model capabilities resolved by the runtime. - [JsonPropertyName("modelCapabilities")] - public ModelCapabilitiesOverride? ModelCapabilities { get; set; } + /// Gets or sets the completedAt value. + [JsonPropertyName("completedAt")] + public long? CompletedAt { get; set; } - /// Model selection id to switch to, as returned by `list`. A bare id (e.g. `claude-sonnet-4.6`) names a Copilot (CAPI) model; a provider-qualified id (`provider/id`, e.g. `acme/claude-sonnet`) targets a registry BYOK model. - [JsonPropertyName("modelId")] - public string ModelId { get; set; } = string.Empty; + /// Gets or sets the currentActiveMs value. + [JsonPropertyName("currentActiveMs")] + public long CurrentActiveMs { get; set; } - /// Reasoning effort level to use for the model. "none" disables reasoning. - [JsonPropertyName("reasoningEffort")] - public string? ReasoningEffort { get; set; } + /// Gets or sets the detail value. + [JsonPropertyName("detail")] + public string? Detail { get; set; } - /// Reasoning summary mode to request for supported model clients. - [JsonPropertyName("reasoningSummary")] - public ReasoningSummary? ReasoningSummary { get; set; } + /// Gets or sets the entryCount value. + [JsonPropertyName("entryCount")] + public long EntryCount { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Gets or sets the id value. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; - /// Output verbosity level to request for supported models. - [JsonPropertyName("verbosity")] - public Verbosity? Verbosity { get; set; } -} + /// Gets or sets the lastEnteredRunAttempt value. + [JsonPropertyName("lastEnteredRunAttempt")] + public long LastEnteredRunAttempt { get; set; } -/// Update the session's reasoning effort without changing the selected model. Use `switchTo` instead when you also need to change the model. The runtime stores the effort on the session and applies it to subsequent turns. -[Experimental(Diagnostics.Experimental)] -public sealed class ModelSetReasoningEffortResult -{ - /// Reasoning effort level recorded on the session after the update. - [JsonPropertyName("reasoningEffort")] - public string ReasoningEffort { get; set; } = string.Empty; -} + /// Gets or sets the liveAgentCount value. + [JsonPropertyName("liveAgentCount")] + public long LiveAgentCount { get; set; } -/// Reasoning effort level to apply to the currently selected model. -[Experimental(Diagnostics.Experimental)] -internal sealed class ModelSetReasoningEffortRequest -{ - /// Reasoning effort level to apply to the currently selected model. The host is responsible for validating the value against the model's supported levels before calling. - [JsonPropertyName("reasoningEffort")] - public string ReasoningEffort { get; set; } = string.Empty; + /// Gets or sets the ordinal value. + [JsonPropertyName("ordinal")] + public long? Ordinal { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// Gets or sets the startedAt value. + [JsonPropertyName("startedAt")] + public long? StartedAt { get; set; } -/// Cost-category metadata for a CAPI model. -[Experimental(Diagnostics.Experimental)] -public sealed class SessionModelPriceCategory -{ - /// Gets or sets the id value. - [JsonPropertyName("id")] - public string Id { get; set; } = string.Empty; + /// Gets or sets the status value. + [JsonPropertyName("status")] + public FactoryPhaseStatus Status { get; set; } - /// Gets or sets the priceCategory value. - [JsonPropertyName("priceCategory")] - public ModelPickerPriceCategory PriceCategory { get; set; } + /// Gets or sets the title value. + [JsonPropertyName("title")] + public string Title { get; set; } = string.Empty; + + /// Gets or sets the totalAgentCount value. + [JsonPropertyName("totalAgentCount")] + public long TotalAgentCount { get; set; } } -/// The list of models available to this session. +/// One durable factory progress record. [Experimental(Diagnostics.Experimental)] -public sealed class SessionModelList +public sealed class FactoryProgressLine { - /// Available models, ordered with the most preferred default first. Includes both Copilot (CAPI) models and any registry BYOK models; a BYOK model appears under its provider-qualified selection id (`provider/id`). - [JsonPropertyName("list")] - public IList List { get => field ??= []; set; } + /// Resume attempt that emitted this record. + [JsonPropertyName("attempt")] + public long Attempt { get; set; } - /// Cost categories for the full CAPI catalog, including picker-disabled models that Auto may select. Metadata only; entries absent from `list` are not manually selectable. - [JsonPropertyName("modelPriceCategories")] - public IList? ModelPriceCategories { get; set; } + /// Progress record kind. + [JsonPropertyName("kind")] + public FactoryLogLineKind Kind { get; set; } - /// Per-quota snapshots returned alongside the model list, keyed by quota type. - [JsonPropertyName("quotaSnapshots")] - public IDictionary? QuotaSnapshots { get; set; } + /// Phase active when the record was emitted, or null before any phase. + [JsonPropertyName("phaseId")] + public string? PhaseId { get; set; } + + /// Epoch milliseconds when the record was persisted. + [JsonPropertyName("recordedAt")] + public long RecordedAt { get; set; } + + /// Global monotonic sequence number within the run. + [JsonPropertyName("seq")] + public long Seq { get; set; } + + /// Prompt-safe progress text. + [JsonPropertyName("text")] + public string Text { get; set; } = string.Empty; } -/// Optional listing options. +/// A bidirectional page of factory progress. [Experimental(Diagnostics.Experimental)] -public sealed class ModelListRequest +public sealed class FactoryProgressPage { - /// If true, bypasses the per-session model list cache and re-fetches from CAPI. - [JsonPropertyName("skipCache")] - public bool? SkipCache { get; set; } + /// Gets or sets the hasMoreNewer value. + [JsonPropertyName("hasMoreNewer")] + public bool HasMoreNewer { get; set; } + + /// Gets or sets the hasMoreOlder value. + [JsonPropertyName("hasMoreOlder")] + public bool HasMoreOlder { get; set; } + + /// Gets or sets the newestSeq value. + [JsonPropertyName("newestSeq")] + public long? NewestSeq { get; set; } + + /// Gets or sets the oldestSeq value. + [JsonPropertyName("oldestSeq")] + public long? OldestSeq { get; set; } + + /// Gets or sets the records value. + [JsonPropertyName("records")] + public IList Records { get => field ??= []; set; } + + /// Run revision reflected by this page. + [JsonPropertyName("revision")] + public long Revision { get; set; } } -/// Optional listing options. +/// Full factory run observability detail. [Experimental(Diagnostics.Experimental)] -internal sealed class ModelListRequestWithSession +public sealed class FactoryRunDetail { - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Gets or sets the activeSegmentStartedAt value. + [JsonPropertyName("activeSegmentStartedAt")] + public long? ActiveSegmentStartedAt { get; set; } - /// If true, bypasses the per-session model list cache and re-fetches from CAPI. - [JsonPropertyName("skipCache")] - public bool? SkipCache { get; set; } + /// Gets or sets the agents value. + [JsonPropertyName("agents")] + public IList Agents { get => field ??= []; set; } + + /// Gets or sets the approved value. + [JsonPropertyName("approved")] + public FactoryDeclaredLimits? Approved { get; set; } + + /// Gets or sets the completedAt value. + [JsonPropertyName("completedAt")] + public long? CompletedAt { get; set; } + + /// Gets or sets the consumed value. + [JsonPropertyName("consumed")] + public FactoryRunConsumed Consumed { get => field ??= new(); set; } + + /// Gets or sets the createdAt value. + [JsonPropertyName("createdAt")] + public long CreatedAt { get; set; } + + /// Gets or sets the currentPhase value. + [JsonPropertyName("currentPhase")] + public FactoryCurrentPhase? CurrentPhase { get; set; } + + /// Gets or sets the declaredLimits value. + [JsonPropertyName("declaredLimits")] + public FactoryDeclaredLimits DeclaredLimits { get => field ??= new(); set; } + + /// Gets or sets the declaredPhaseCount value. + [JsonPropertyName("declaredPhaseCount")] + public long DeclaredPhaseCount { get; set; } + + /// Gets or sets the description value. + [JsonPropertyName("description")] + public string Description { get; set; } = string.Empty; + + /// Gets or sets the factoryName value. + [JsonPropertyName("factoryName")] + public string FactoryName { get; set; } = string.Empty; + + /// Gets or sets the liveAgentCount value. + [JsonPropertyName("liveAgentCount")] + public long LiveAgentCount { get; set; } + + /// Gets or sets the observedAt value. + [JsonPropertyName("observedAt")] + public long ObservedAt { get; set; } + + /// Gets or sets the phases value. + [JsonPropertyName("phases")] + public IList Phases { get => field ??= []; set; } + + /// Gets or sets the progress value. + [JsonPropertyName("progress")] + public FactoryProgressPage Progress { get => field ??= new(); set; } + + /// Gets or sets the revision value. + [JsonPropertyName("revision")] + public long Revision { get; set; } + + /// Gets or sets the runId value. + [JsonPropertyName("runId")] + public string RunId { get; set; } = string.Empty; + + /// Gets or sets the startedAt value. + [JsonPropertyName("startedAt")] + public long? StartedAt { get; set; } + + /// Gets or sets the status value. + [JsonPropertyName("status")] + public FactoryRunStatus Status { get; set; } + + /// Gets or sets the terminal value. + [JsonPropertyName("terminal")] + public FactoryRunTerminal? Terminal { get; set; } + + /// Gets or sets the totalSpawnedAgentCount value. + [JsonPropertyName("totalSpawnedAgentCount")] + public long TotalSpawnedAgentCount { get; set; } + + /// Gets or sets the updatedAt value. + [JsonPropertyName("updatedAt")] + public long UpdatedAt { get; set; } } -/// Identifies the target session. +/// Parameters for paging factory progress. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionModeGetRequest +internal sealed class FactoryGetRunProgressRequest { + /// Exclusive forward cursor. + [JsonPropertyName("afterSeq")] + public long? AfterSeq { get; set; } + + /// Exclusive backward cursor. + [JsonPropertyName("beforeSeq")] + public long? BeforeSeq { get; set; } + + /// Maximum records to return. Defaults to 200 and is capped at 500. + [JsonPropertyName("limit")] + public int? Limit { get; set; } + + /// Optional phase identifier used to scope records and cursors. + [JsonPropertyName("phaseId")] + public string? PhaseId { get; set; } + + /// Factory run identifier. + [JsonPropertyName("runId")] + public string RunId { get; set; } = string.Empty; + /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Agent interaction mode to apply to the session. +/// Parameters for cancelling a factory run. [Experimental(Diagnostics.Experimental)] -internal sealed class ModeSetRequest +internal sealed class FactoryCancelRequest { - /// The session mode the agent is operating in. - [JsonPropertyName("mode")] - public SessionMode Mode { get; set; } + /// Factory run identifier. + [JsonPropertyName("runId")] + public string RunId { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// The session's friendly name, or null when not yet set. +/// Acknowledgement that a factory request was accepted. [Experimental(Diagnostics.Experimental)] -public sealed class NameGetResult +public sealed class FactoryAckResult { - /// The session name (user-set or auto-generated), or null if not yet set. - [JsonPropertyName("name")] - public string? Name { get; set; } } -/// Identifies the target session. +/// One ordered factory progress line. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionNameGetRequest +public sealed class FactoryLogLine { - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Progress line kind. + [JsonPropertyName("kind")] + public FactoryLogLineKind Kind { get; set; } + + /// Monotonic sequence number within the factory run. + [JsonPropertyName("seq")] + public long Seq { get; set; } + + /// Progress text. + [JsonPropertyName("text")] + public string Text { get; set; } = string.Empty; } -/// New friendly name to apply to the session. +/// Parameters for recording factory progress. [Experimental(Diagnostics.Experimental)] -internal sealed class NameSetRequest +internal sealed class FactoryLogRequest { - /// New session name (1–100 characters, trimmed of leading/trailing whitespace). - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] - [MinLength(1)] - [MaxLength(100)] - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; + /// Opaque token identifying the current factory execution attempt. + [JsonPropertyName("executionToken")] + public string ExecutionToken { get; set; } = string.Empty; + + /// Ordered progress lines to append. + [JsonPropertyName("lines")] + public IList Lines { get => field ??= []; set; } + + /// Factory run identifier. + [JsonPropertyName("runId")] + public string RunId { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Indicates whether the auto-generated summary was applied as the session's name. +/// Result of one factory-scoped subagent call. [Experimental(Diagnostics.Experimental)] -public sealed class NameSetAutoResult +public sealed class FactoryAgentResult { - /// Whether the auto-generated summary was persisted. False if the session already has a user-set name, the summary normalized to empty, or the session does not have a workspace. - [JsonPropertyName("applied")] - public bool Applied { get; set; } + /// Agent result, omitted when the agent produced no result. + [JsonPropertyName("result")] + public JsonElement? Result { get; set; } } -/// Auto-generated session summary to apply as the session's name when no user-set name exists. +/// Options for one factory-scoped subagent call. [Experimental(Diagnostics.Experimental)] -internal sealed class NameSetAutoRequest +public sealed class FactoryAgentOptions { - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Optional label distinguishing otherwise identical memoized agent calls. + [JsonPropertyName("label")] + public string? Label { get; set; } - /// Auto-generated session summary. Empty/whitespace-only values are ignored; values are trimmed before persisting. - [JsonPropertyName("summary")] - public string Summary { get; set; } = string.Empty; + /// Optional model identifier for the subagent. + [JsonPropertyName("model")] + public string? Model { get; set; } + + /// Optional JSON Schema for structured agent output. + [JsonPropertyName("schema")] + public JsonElement? Schema { get; set; } } -/// Existence, contents, and resolved path of the session plan file. +/// Parameters for one factory-scoped subagent call. [Experimental(Diagnostics.Experimental)] -public sealed class PlanReadResult +internal sealed class FactoryAgentRequest { - /// The content of the plan file, or null if it does not exist. - [JsonPropertyName("content")] - public string? Content { get; set; } + /// Opaque token identifying the current factory execution attempt. + [JsonPropertyName("executionToken")] + public string ExecutionToken { get; set; } = string.Empty; - /// Whether the plan file exists in the workspace. - [JsonPropertyName("exists")] - public bool Exists { get; set; } + /// Factory run identifier that owns the subagent. + [JsonPropertyName("factoryRunId")] + public string FactoryRunId { get; set; } = string.Empty; - /// Absolute file path of the plan file, or null if workspace is not enabled. - [JsonPropertyName("path")] - public string? Path { get; set; } -} + /// Subagent execution options. + [JsonPropertyName("opts")] + public FactoryAgentOptions Opts { get => field ??= new(); set; } + + /// Prompt to send to the subagent. + [JsonPropertyName("prompt")] + public string Prompt { get; set; } = string.Empty; -/// Identifies the target session. -[Experimental(Diagnostics.Experimental)] -internal sealed class SessionPlanReadRequest -{ /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Replacement contents to write to the session plan file. +/// Result of reading a factory journal entry. [Experimental(Diagnostics.Experimental)] -internal sealed class PlanUpdateRequest +public sealed class FactoryJournalGetResult { - /// The new content for the plan file. - [JsonPropertyName("content")] - public string Content { get; set; } = string.Empty; + /// Whether the journal contained the requested key. + [JsonPropertyName("hit")] + public bool Hit { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Cached JSON result. The hit field distinguishes a cached JSON null from a miss. + [JsonPropertyName("resultJson")] + public JsonElement? ResultJson { get; set; } } -/// Identifies the target session. +/// Parameters for reading a factory journal entry. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionPlanDeleteRequest +internal sealed class FactoryJournalGetRequest { + /// Opaque token identifying the current factory execution attempt. + [JsonPropertyName("executionToken")] + public string ExecutionToken { get; set; } = string.Empty; + + /// Namespaced journal key. + [JsonPropertyName("key")] + public string Key { get; set; } = string.Empty; + + /// Factory run identifier. + [JsonPropertyName("runId")] + public string RunId { get; set; } = string.Empty; + /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// A single todo row read from the session SQL `todos` table. All fields are optional because the SQL schema is best-effort and the agent may not have populated every column. +/// Parameters for storing a factory journal entry. [Experimental(Diagnostics.Experimental)] -public sealed class PlanSqlTodosRow +internal sealed class FactoryJournalPutRequest { - /// Todo description. - [JsonPropertyName("description")] - public string? Description { get; set; } + /// Opaque token identifying the current factory execution attempt. + [JsonPropertyName("executionToken")] + public string ExecutionToken { get; set; } = string.Empty; - /// Todo identifier. - [JsonPropertyName("id")] - public string? Id { get; set; } + /// Namespaced journal key. + [JsonPropertyName("key")] + public string Key { get; set; } = string.Empty; - /// Todo status. - [JsonPropertyName("status")] - public string? Status { get; set; } + /// JSON result to memoize. + [JsonPropertyName("resultJson")] + public JsonElement ResultJson { get; set; } - /// Todo title. - [JsonPropertyName("title")] - public string? Title { get; set; } + /// Factory run identifier. + [JsonPropertyName("runId")] + public string RunId { get; set; } = string.Empty; + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Todo rows read from the session SQL database. Empty when no session database is available. +/// The currently selected model, reasoning effort, and context tier for the session. The context tier reflects `Session.getContextTier()`, restored from the session journal on resume. [Experimental(Diagnostics.Experimental)] -public sealed class PlanReadSqlTodosResult +public sealed class CurrentModel { - /// Rows from the session SQL todos table, ordered by creation time and id. - [JsonPropertyName("rows")] - public IList Rows { get => field ??= []; set; } + /// Context tier for models that support multiple context-window sizes. + [JsonPropertyName("contextTier")] + public ContextTier? ContextTier { get; set; } + + /// Currently active model identifier. + [JsonPropertyName("modelId")] + public string? ModelId { get; set; } + + /// Reasoning effort level currently applied to the active model, when one is set. Reads `Session.getReasoningEffort()` synchronously after `getSelectedModel()` resolves so the two values are reported as a snapshot. + [JsonPropertyName("reasoningEffort")] + public string? ReasoningEffort { get; set; } } /// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionPlanReadSqlTodosRequest +internal sealed class SessionModelGetCurrentRequest { /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// A single dependency edge read from the session SQL `todo_deps` table, indicating that one todo must complete before another. +/// The model identifier active on the session after the switch. [Experimental(Diagnostics.Experimental)] -public sealed class PlanSqlTodoDependency +public sealed class ModelSwitchToResult { - /// ID of the todo it depends on. - [JsonPropertyName("dependsOn")] - public string DependsOn { get; set; } = string.Empty; + /// True when the switch was deferred (enqueued as a cancellable `/model` command) because a turn was active or another model change was already queued, rather than applied immediately. When true, the session's live model is unchanged until the queued change drains. + [JsonPropertyName("deferred")] + public bool? Deferred { get; set; } - /// ID of the todo that has the dependency. - [JsonPropertyName("todoId")] - public string TodoId { get; set; } = string.Empty; + /// Currently active model identifier after the switch. + [JsonPropertyName("modelId")] + public string? ModelId { get; set; } } -/// Todo rows + dependency edges read from the session SQL database. +/// Vision-specific limits. [Experimental(Diagnostics.Experimental)] -public sealed class PlanReadSqlTodosWithDependenciesResult +public sealed class ModelCapabilitiesOverrideLimitsVision { - /// Edges from the session SQL todo_deps table. Empty when no database, no todo_deps table, or the SELECT failed. Read independently from `rows`, so a broken todo_deps table does not affect the rows result and vice versa. - [JsonPropertyName("dependencies")] - public IList Dependencies { get => field ??= []; set; } + /// Maximum image size in bytes. + [JsonPropertyName("max_prompt_image_size")] + public long? MaxPromptImageSize { get; set; } - /// Rows from the session SQL todos table, ordered by creation time and id. Empty when no database, no todos table, or the SELECT failed. - [JsonPropertyName("rows")] - public IList Rows { get => field ??= []; set; } -} + /// Maximum number of images per prompt. + [JsonPropertyName("max_prompt_images")] + public long? MaxPromptImages { get; set; } -/// Identifies the target session. -[Experimental(Diagnostics.Experimental)] -internal sealed class SessionPlanReadSqlTodosWithDependenciesRequest -{ - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// MIME types the model accepts. + [JsonPropertyName("supported_media_types")] + public IList? SupportedMediaTypes { get; set; } } -/// RPC data type for WorkspacesGetWorkspaceResultWorkspace operations. -public sealed class WorkspacesGetWorkspaceResultWorkspace +/// Token limits for prompts, outputs, and context window. +[Experimental(Diagnostics.Experimental)] +public sealed class ModelCapabilitiesOverrideLimits { - /// Gets or sets the branch value. - [JsonPropertyName("branch")] - public string? Branch { get; set; } + /// Maximum total context window size in tokens. + [JsonPropertyName("max_context_window_tokens")] + public long? MaxContextWindowTokens { get; set; } - /// Gets or sets the chronicle_sync_dismissed value. - [JsonPropertyName("chronicle_sync_dismissed")] - public bool? ChronicleSyncDismissed { get; set; } + /// Maximum number of output/completion tokens. + [JsonPropertyName("max_output_tokens")] + public long? MaxOutputTokens { get; set; } - /// Gets or sets the client_name value. - [JsonPropertyName("client_name")] - public string? ClientName { get; set; } + /// Maximum number of prompt/input tokens. + [JsonPropertyName("max_prompt_tokens")] + public long? MaxPromptTokens { get; set; } - /// Gets or sets the created_at value. - [JsonPropertyName("created_at")] - public DateTimeOffset? CreatedAt { get; set; } + /// Vision-specific limits. + [JsonPropertyName("vision")] + public ModelCapabilitiesOverrideLimitsVision? Vision { get; set; } +} - /// Gets or sets the cwd value. - [JsonPropertyName("cwd")] - public string? Cwd { get; set; } +/// Feature flags indicating what the model supports. +[Experimental(Diagnostics.Experimental)] +public sealed class ModelCapabilitiesOverrideSupports +{ + /// Resolved Anthropic adaptive-thinking capability — unsupported / optional / required. 'required' models reject thinking.type='enabled' with HTTP 400 (e.g. opus-4.7/4.8). + [JsonPropertyName("adaptive_thinking")] + public AdaptiveThinkingSupport? AdaptiveThinking { get; set; } - /// Gets or sets the git_root value. - [JsonPropertyName("git_root")] - public string? GitRoot { get; set; } + /// Whether this model supports reasoning effort configuration. + [JsonPropertyName("reasoningEffort")] + public bool? ReasoningEffort { get; set; } - /// Allowed values for the `WorkspacesWorkspaceDetailsHostType` enumeration. - [JsonPropertyName("host_type")] - public WorkspacesWorkspaceDetailsHostType? HostType { get; set; } + /// Whether this model supports vision/image input. + [JsonPropertyName("vision")] + public bool? Vision { get; set; } +} - /// Gets or sets the id value. - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] - [MinLength(1)] - [JsonPropertyName("id")] - public string Id { get; set; } = string.Empty; +/// Optional capability overrides (vision, tool_calls, reasoning, etc.). +[Experimental(Diagnostics.Experimental)] +public sealed class ModelCapabilitiesOverride +{ + /// Token limits for prompts, outputs, and context window. + [JsonPropertyName("limits")] + public ModelCapabilitiesOverrideLimits? Limits { get; set; } - /// Gets or sets the mc_last_event_id value. - [JsonPropertyName("mc_last_event_id")] - public string? McLastEventId { get; set; } + /// Feature flags indicating what the model supports. + [JsonPropertyName("supports")] + public ModelCapabilitiesOverrideSupports? Supports { get; set; } +} - /// Gets or sets the mc_session_id value. - [JsonPropertyName("mc_session_id")] - public string? McSessionId { get; set; } +/// Target model identifier and optional reasoning effort, summary, capability overrides, and context tier. +[Experimental(Diagnostics.Experimental)] +internal sealed class ModelSwitchToRequest +{ + /// Explicit context tier for the selected model. `"default"` / `"long_context"` apply the requested tier; omit this field to use normal model behavior with no explicit tier. + [JsonPropertyName("contextTier")] + public ContextTier? ContextTier { get; set; } - /// Gets or sets the mc_task_id value. - [JsonPropertyName("mc_task_id")] - public string? McTaskId { get; set; } + /// When true, defer this switch (enqueue it) if another model change is already queued, even when no turn is active — so it drains last (FIFO) and wins over the already-queued change. Intended for genuine user-initiated model selections; internal restore/reapply switches omit it and apply immediately when no turn is active. When no other model change is queued this has no effect (a switch still applies immediately unless a turn is active). + [JsonPropertyName("deferIfModelChangeQueued")] + public bool? DeferIfModelChangeQueued { get; set; } - /// Gets or sets the name value. - [JsonPropertyName("name")] - public string? Name { get; set; } + /// Override individual model capabilities resolved by the runtime. + [JsonPropertyName("modelCapabilities")] + public ModelCapabilitiesOverride? ModelCapabilities { get; set; } - /// Gets or sets the remote_steerable value. - [JsonPropertyName("remote_steerable")] - public bool? RemoteSteerable { get; set; } + /// Model selection id to switch to, as returned by `list`. A bare id (e.g. `claude-sonnet-4.6`) names a Copilot (CAPI) model; a provider-qualified id (`provider/id`, e.g. `acme/claude-sonnet`) targets a registry BYOK model. + [JsonPropertyName("modelId")] + public string ModelId { get; set; } = string.Empty; - /// Gets or sets the repository value. - [JsonPropertyName("repository")] - public string? Repository { get; set; } + /// Reasoning effort level to use for the model. "none" disables reasoning. + [JsonPropertyName("reasoningEffort")] + public string? ReasoningEffort { get; set; } - /// Gets or sets the summary_count value. - [JsonPropertyName("summary_count")] - public long? SummaryCount { get; set; } + /// Reasoning summary mode to request for supported model clients. + [JsonPropertyName("reasoningSummary")] + public ReasoningSummary? ReasoningSummary { get; set; } - /// Gets or sets the updated_at value. - [JsonPropertyName("updated_at")] - public DateTimeOffset? UpdatedAt { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; - /// Gets or sets the user_named value. - [JsonPropertyName("user_named")] - public bool? UserNamed { get; set; } + /// Output verbosity level to request for supported models. + [JsonPropertyName("verbosity")] + public Verbosity? Verbosity { get; set; } } -/// Current workspace metadata for the session, including its absolute filesystem path when available. +/// Update the session's reasoning effort without changing the selected model. Use `switchTo` instead when you also need to change the model. The runtime stores the effort on the session and applies it to subsequent turns. [Experimental(Diagnostics.Experimental)] -public sealed class WorkspacesGetWorkspaceResult +public sealed class ModelSetReasoningEffortResult { - /// Absolute filesystem path to the workspace directory. Omitted when the session has no workspace (e.g. remote sessions). - [JsonPropertyName("path")] - public string? Path { get; set; } - - /// Current workspace metadata, or null if not available. - [JsonPropertyName("workspace")] - public WorkspacesGetWorkspaceResultWorkspace? Workspace { get; set; } + /// Reasoning effort level recorded on the session after the update. + [JsonPropertyName("reasoningEffort")] + public string ReasoningEffort { get; set; } = string.Empty; } -/// Identifies the target session. +/// Reasoning effort level to apply to the currently selected model. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionWorkspacesGetWorkspaceRequest +internal sealed class ModelSetReasoningEffortRequest { + /// Reasoning effort level to apply to the currently selected model. The host is responsible for validating the value against the model's supported levels before calling. + [JsonPropertyName("reasoningEffort")] + public string ReasoningEffort { get; set; } = string.Empty; + /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Relative paths of files stored in the session workspace files directory. +/// Cost-category metadata for a CAPI model. [Experimental(Diagnostics.Experimental)] -public sealed class WorkspacesListFilesResult +public sealed class SessionModelPriceCategory { - /// Relative file paths in the workspace files directory. - [JsonPropertyName("files")] - public IList Files { get => field ??= []; set; } + /// Gets or sets the id value. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; + + /// Gets or sets the priceCategory value. + [JsonPropertyName("priceCategory")] + public ModelPickerPriceCategory PriceCategory { get; set; } } -/// Identifies the target session. +/// The list of models available to this session. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionWorkspacesListFilesRequest +public sealed class SessionModelList { - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Available models, ordered with the most preferred default first. Includes both Copilot (CAPI) models and any registry BYOK models; a BYOK model appears under its provider-qualified selection id (`provider/id`). + [JsonPropertyName("list")] + public IList List { get => field ??= []; set; } + + /// Cost categories for the full CAPI catalog, including picker-disabled models that Auto may select. Metadata only; entries absent from `list` are not manually selectable. + [JsonPropertyName("modelPriceCategories")] + public IList? ModelPriceCategories { get; set; } + + /// Per-quota snapshots returned alongside the model list, keyed by quota type. + [JsonPropertyName("quotaSnapshots")] + public IDictionary? QuotaSnapshots { get; set; } } -/// Contents of the requested workspace file as a UTF-8 string. +/// RPC data type for SessionModelList operations. [Experimental(Diagnostics.Experimental)] -public sealed class WorkspacesReadFileResult +public sealed class SessionModelListRequest { - /// File content as a UTF-8 string. - [JsonPropertyName("content")] - public string Content { get; set; } = string.Empty; + /// If true, bypasses the per-session model list cache and re-fetches from CAPI. + [JsonPropertyName("skipCache")] + public bool? SkipCache { get; set; } } -/// Relative path of the workspace file to read. +/// RPC data type for SessionModelListRequestWithSession operations. [Experimental(Diagnostics.Experimental)] -internal sealed class WorkspacesReadFileRequest +internal sealed class SessionModelListRequestWithSession { - /// Relative path within the workspace files directory. - [JsonPropertyName("path")] - public string Path { get; set; } = string.Empty; - /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; + + /// If true, bypasses the per-session model list cache and re-fetches from CAPI. + [JsonPropertyName("skipCache")] + public bool? SkipCache { get; set; } } -/// Relative path and UTF-8 content for the workspace file to create or overwrite. +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class WorkspacesCreateFileRequest +internal sealed class SessionModeGetRequest { - /// File content to write as a UTF-8 string. - [JsonPropertyName("content")] - public string Content { get; set; } = string.Empty; - - /// Relative path within the workspace files directory. - [JsonPropertyName("path")] - public string Path { get; set; } = string.Empty; - /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Workspace checkpoint metadata with assigned number, human-readable title, and checkpoint filename. +/// Agent interaction mode to apply to the session. [Experimental(Diagnostics.Experimental)] -public sealed class WorkspacesCheckpoints +internal sealed class ModeSetRequest { - /// Filename of the checkpoint within the workspace checkpoints directory. - [JsonPropertyName("filename")] - public string Filename { get; set; } = string.Empty; - - /// Checkpoint number assigned by the workspace manager. - [JsonPropertyName("number")] - public long Number { get; set; } + /// The session mode the agent is operating in. + [JsonPropertyName("mode")] + public SessionMode Mode { get; set; } - /// Human-readable checkpoint title. - [JsonPropertyName("title")] - public string Title { get; set; } = string.Empty; + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Workspace checkpoints in chronological order; empty when the workspace is not enabled. +/// The session's friendly name, or null when not yet set. [Experimental(Diagnostics.Experimental)] -public sealed class WorkspacesListCheckpointsResult +public sealed class NameGetResult { - /// Workspace checkpoints in chronological order. Empty when workspace is not enabled. - [JsonPropertyName("checkpoints")] - public IList Checkpoints { get => field ??= []; set; } -} - + /// The session name (user-set or auto-generated), or null if not yet set. + [JsonPropertyName("name")] + public string? Name { get; set; } +} + /// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionWorkspacesListCheckpointsRequest +internal sealed class SessionNameGetRequest { /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Checkpoint content as a UTF-8 string, or null when the checkpoint or workspace is missing. -[Experimental(Diagnostics.Experimental)] -public sealed class WorkspacesReadCheckpointResult -{ - /// Checkpoint content as a UTF-8 string, or null when the checkpoint or workspace is missing. - [JsonPropertyName("content")] - public string? Content { get; set; } -} - -/// Checkpoint number to read. +/// New friendly name to apply to the session. [Experimental(Diagnostics.Experimental)] -internal sealed class WorkspacesReadCheckpointRequest +internal sealed class NameSetRequest { - /// Checkpoint number to read. - [JsonPropertyName("number")] - public long Number { get; set; } + /// New session name (1–100 characters, trimmed of leading/trailing whitespace). + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] + [MinLength(1)] + [MaxLength(100)] + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// RPC data type for WorkspacesSaveLargePasteResultSaved operations. -public sealed class WorkspacesSaveLargePasteResultSaved -{ - /// Filename within the workspace files directory. - [JsonPropertyName("filename")] - public string Filename { get; set; } = string.Empty; - - /// Absolute filesystem path to the saved paste file. - [JsonPropertyName("filePath")] - public string FilePath { get; set; } = string.Empty; - - /// Size of the saved file in bytes. - [JsonPropertyName("sizeBytes")] - public long SizeBytes { get; set; } -} - -/// Descriptor for the saved paste file, or null when the workspace is unavailable. +/// Indicates whether the auto-generated summary was applied as the session's name. [Experimental(Diagnostics.Experimental)] -public sealed class WorkspacesSaveLargePasteResult +public sealed class NameSetAutoResult { - /// Saved-paste descriptor, or null when the workspace is unavailable (e.g. CCA runtime, non-infinite sessions, remote sessions). - [JsonPropertyName("saved")] - public WorkspacesSaveLargePasteResultSaved? Saved { get; set; } + /// Whether the auto-generated summary was persisted. False if the session already has a user-set name, the summary normalized to empty, or the session does not have a workspace. + [JsonPropertyName("applied")] + public bool Applied { get; set; } } -/// Pasted content to save as a UTF-8 file in the session workspace. +/// Auto-generated session summary to apply as the session's name when no user-set name exists. [Experimental(Diagnostics.Experimental)] -internal sealed class WorkspacesSaveLargePasteRequest +internal sealed class NameSetAutoRequest { - /// Pasted content to save as a UTF-8 file. - [JsonPropertyName("content")] - public string Content { get; set; } = string.Empty; - /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; + + /// Auto-generated session summary. Empty/whitespace-only values are ignored; values are trimmed before persisting. + [JsonPropertyName("summary")] + public string Summary { get; set; } = string.Empty; } -/// A single changed file and its unified diff. +/// Existence, contents, and resolved path of the session plan file. [Experimental(Diagnostics.Experimental)] -public sealed class WorkspaceDiffFileChange +public sealed class PlanReadResult { - /// Type of change represented by this file diff. - [JsonPropertyName("changeType")] - public WorkspaceDiffFileChangeType ChangeType { get; set; } - - /// Unified diff content for the file. Empty when the diff was truncated. - [JsonPropertyName("diff")] - public string Diff { get; set; } = string.Empty; - - /// Whether the diff content was omitted because it exceeded the per-file size limit. - [JsonPropertyName("isTruncated")] - public bool? IsTruncated { get; set; } + /// The content of the plan file, or null if it does not exist. + [JsonPropertyName("content")] + public string? Content { get; set; } - /// Original file path for renamed files. - [JsonPropertyName("oldPath")] - public string? OldPath { get; set; } + /// Whether the plan file exists in the workspace. + [JsonPropertyName("exists")] + public bool Exists { get; set; } - /// Path to the changed file, relative to the workspace root. + /// Absolute file path of the plan file, or null if workspace is not enabled. [JsonPropertyName("path")] - public string Path { get; set; } = string.Empty; + public string? Path { get; set; } } -/// Workspace diff result for the requested mode. +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -public sealed class WorkspaceDiffResult +internal sealed class SessionPlanReadRequest { - /// Default branch used for a branch diff, when branch mode was requested. - [JsonPropertyName("baseBranch")] - public string? BaseBranch { get; set; } - - /// Changed files and their unified diffs. - [JsonPropertyName("changes")] - public IList Changes { get => field ??= []; set; } - - /// Whether a requested branch diff fell back to unstaged changes because branch diff failed. - [JsonPropertyName("isFallback")] - public bool IsFallback { get; set; } - - /// Effective mode used for the returned changes. - [JsonPropertyName("mode")] - public WorkspaceDiffMode Mode { get; set; } - - /// Diff mode requested by the client. - [JsonPropertyName("requestedMode")] - public WorkspaceDiffMode RequestedMode { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Parameters for computing a workspace diff. +/// Replacement contents to write to the session plan file. [Experimental(Diagnostics.Experimental)] -internal sealed class WorkspacesDiffRequest +internal sealed class PlanUpdateRequest { - /// When true, ignore whitespace-only changes (git `--ignore-all-space`). Defaults to false. - [JsonPropertyName("ignoreWhitespace")] - public bool? IgnoreWhitespace { get; set; } - - /// Diff mode requested by the client. - [JsonPropertyName("mode")] - public WorkspaceDiffMode Mode { get; set; } + /// The new content for the plan file. + [JsonPropertyName("content")] + public string Content { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Characters that, when typed in the composer, should trigger a `completions.request`. Empty when the session has no host-driven completions (e.g. local sessions, or a relay host that does not advertise `completionTriggerCharacters`). -[Experimental(Diagnostics.Experimental)] -public sealed class CompletionsGetTriggerCharactersResult -{ - /// Trigger characters advertised by the host (e.g. `["@", "#"]`). Empty disables host-driven completions for the session. - [JsonPropertyName("triggerCharacters")] - public IList TriggerCharacters { get => field ??= []; set; } -} - /// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionCompletionsGetTriggerCharactersRequest +internal sealed class SessionPlanDeleteRequest { /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// A single host-driven completion. Accepting an item replaces `[rangeStart, rangeEnd)` (UTF-16 code units) in the composer with `insertText`; when the range is absent, the active token around the cursor is replaced. -[Experimental(Diagnostics.Experimental)] -public sealed class SessionCompletionItem -{ - /// Text spliced into the composer when the item is accepted. - [JsonPropertyName("insertText")] - public string InsertText { get; set; } = string.Empty; - - /// Render-kind hint for the picker row (e.g. `"document"`, `"directory"`), derived from the host's display kind. - [JsonPropertyName("kind")] - public string? Kind { get; set; } - - /// Primary display label for the picker row. Falls back to `insertText` when absent. - [JsonPropertyName("label")] - public string? Label { get; set; } - - /// End (exclusive) of the replacement range in `text`, in UTF-16 code units. - [JsonPropertyName("rangeEnd")] - public long? RangeEnd { get; set; } - - /// Start of the replacement range in `text`, in UTF-16 code units. - [JsonPropertyName("rangeStart")] - public long? RangeStart { get; set; } -} - -/// Host-driven completion items for the current composer input. Empty when the host returns no items or does not support completions. +/// A single todo row read from the session SQL `todos` table. All fields are optional because the SQL schema is best-effort and the agent may not have populated every column. [Experimental(Diagnostics.Experimental)] -public sealed class CompletionsRequestResult +public sealed class PlanSqlTodosRow { - /// Completion items in host-ranked order. - [JsonPropertyName("items")] - public IList Items { get => field ??= []; set; } -} + /// Todo description. + [JsonPropertyName("description")] + public string? Description { get; set; } -/// Request host-driven completions for the current composer input. -[Experimental(Diagnostics.Experimental)] -internal sealed class CompletionsRequestRequest -{ - /// Cursor offset within `text`, in UTF-16 code units. - [JsonPropertyName("offset")] - public long Offset { get; set; } + /// Todo identifier. + [JsonPropertyName("id")] + public string? Id { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Todo status. + [JsonPropertyName("status")] + public string? Status { get; set; } - /// The full composed composer input. - [JsonPropertyName("text")] - public string Text { get; set; } = string.Empty; + /// Todo title. + [JsonPropertyName("title")] + public string? Title { get; set; } } -/// Instruction sources loaded for the session, in merge order. +/// Todo rows read from the session SQL database. Empty when no session database is available. [Experimental(Diagnostics.Experimental)] -public sealed class InstructionsGetSourcesResult +public sealed class PlanReadSqlTodosResult { - /// Instruction sources for the session. - [JsonPropertyName("sources")] - public IList Sources { get => field ??= []; set; } + /// Rows from the session SQL todos table, ordered by creation time and id. + [JsonPropertyName("rows")] + public IList Rows { get => field ??= []; set; } } /// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionInstructionsGetSourcesRequest +internal sealed class SessionPlanReadSqlTodosRequest { /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Indicates whether fleet mode was successfully activated. -[Experimental(Diagnostics.Experimental)] -public sealed class FleetStartResult -{ - /// Whether fleet mode was successfully activated. - [JsonPropertyName("started")] - public bool Started { get; set; } -} - -/// Optional user prompt to combine with the fleet orchestration instructions. +/// A single dependency edge read from the session SQL `todo_deps` table, indicating that one todo must complete before another. [Experimental(Diagnostics.Experimental)] -internal sealed class FleetStartRequest +public sealed class PlanSqlTodoDependency { - /// Optional user prompt to combine with fleet instructions. - [JsonPropertyName("prompt")] - public string? Prompt { get; set; } + /// ID of the todo it depends on. + [JsonPropertyName("dependsOn")] + public string DependsOn { get; set; } = string.Empty; - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// ID of the todo that has the dependency. + [JsonPropertyName("todoId")] + public string TodoId { get; set; } = string.Empty; } -/// Custom agents available to the session. +/// Todo rows + dependency edges read from the session SQL database. [Experimental(Diagnostics.Experimental)] -public sealed class AgentList +public sealed class PlanReadSqlTodosWithDependenciesResult { - /// Available custom agents. - [JsonPropertyName("agents")] - public IList Agents { get => field ??= []; set; } + /// Edges from the session SQL todo_deps table. Empty when no database, no todo_deps table, or the SELECT failed. Read independently from `rows`, so a broken todo_deps table does not affect the rows result and vice versa. + [JsonPropertyName("dependencies")] + public IList Dependencies { get => field ??= []; set; } + + /// Rows from the session SQL todos table, ordered by creation time and id. Empty when no database, no todos table, or the SELECT failed. + [JsonPropertyName("rows")] + public IList Rows { get => field ??= []; set; } } /// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionAgentListRequest +internal sealed class SessionPlanReadSqlTodosWithDependenciesRequest { /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// The currently selected custom agent, or null when using the default agent. -[Experimental(Diagnostics.Experimental)] -public sealed class AgentGetCurrentResult -{ - /// Currently selected custom agent, or null if using the default agent. - [JsonPropertyName("agent")] - public AgentInfo? Agent { get; set; } +/// RPC data type for WorkspacesGetWorkspaceResultWorkspace operations. +public sealed class WorkspacesGetWorkspaceResultWorkspace +{ + /// Gets or sets the branch value. + [JsonPropertyName("branch")] + public string? Branch { get; set; } + + /// Gets or sets the chronicle_sync_dismissed value. + [JsonPropertyName("chronicle_sync_dismissed")] + public bool? ChronicleSyncDismissed { get; set; } + + /// Gets or sets the client_name value. + [JsonPropertyName("client_name")] + public string? ClientName { get; set; } + + /// Gets or sets the created_at value. + [JsonPropertyName("created_at")] + public DateTimeOffset? CreatedAt { get; set; } + + /// Gets or sets the cwd value. + [JsonPropertyName("cwd")] + public string? Cwd { get; set; } + + /// Gets or sets the git_root value. + [JsonPropertyName("git_root")] + public string? GitRoot { get; set; } + + /// Allowed values for the `WorkspacesWorkspaceDetailsHostType` enumeration. + [JsonPropertyName("host_type")] + public WorkspacesWorkspaceDetailsHostType? HostType { get; set; } + + /// Gets or sets the id value. + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] + [MinLength(1)] + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; + + /// Gets or sets the mc_last_event_id value. + [JsonPropertyName("mc_last_event_id")] + public string? McLastEventId { get; set; } + + /// Gets or sets the mc_session_id value. + [JsonPropertyName("mc_session_id")] + public string? McSessionId { get; set; } + + /// Gets or sets the mc_task_id value. + [JsonPropertyName("mc_task_id")] + public string? McTaskId { get; set; } + + /// Gets or sets the name value. + [JsonPropertyName("name")] + public string? Name { get; set; } + + /// Gets or sets the remote_steerable value. + [JsonPropertyName("remote_steerable")] + public bool? RemoteSteerable { get; set; } + + /// Gets or sets the repository value. + [JsonPropertyName("repository")] + public string? Repository { get; set; } + + /// Gets or sets the summary_count value. + [JsonPropertyName("summary_count")] + public long? SummaryCount { get; set; } + + /// Gets or sets the updated_at value. + [JsonPropertyName("updated_at")] + public DateTimeOffset? UpdatedAt { get; set; } + + /// Gets or sets the user_named value. + [JsonPropertyName("user_named")] + public bool? UserNamed { get; set; } +} + +/// Current workspace metadata for the session, including its absolute filesystem path when available. +[Experimental(Diagnostics.Experimental)] +public sealed class WorkspacesGetWorkspaceResult +{ + /// Absolute filesystem path to the workspace directory. Omitted when the session has no workspace (e.g. remote sessions). + [JsonPropertyName("path")] + public string? Path { get; set; } + + /// Current workspace metadata, or null if not available. + [JsonPropertyName("workspace")] + public WorkspacesGetWorkspaceResultWorkspace? Workspace { get; set; } } /// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionAgentGetCurrentRequest +internal sealed class SessionWorkspacesGetWorkspaceRequest { /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// The newly selected custom agent. +/// Workspace metadata fields to update. [Experimental(Diagnostics.Experimental)] -public sealed class AgentSelectResult +internal sealed class WorkspacesUpdateMetadataRequest { - /// The newly selected custom agent. - [JsonPropertyName("agent")] - public AgentInfo Agent { get => field ??= new(); set; } -} + /// Opaque workspace context supplied by the session host. + [JsonPropertyName("context")] + public JsonElement? Context { get; set; } -/// Name of the custom agent to select for subsequent turns. -[Experimental(Diagnostics.Experimental)] -internal sealed class AgentSelectRequest -{ - /// Name of the custom agent to select. + /// Optional workspace display name override. [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; + public string? Name { get; set; } /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Identifies the target session. +/// Optional session context used when creating a local workspace. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionAgentDeselectRequest +internal sealed class WorkspacesEnsureRequest { + /// Opaque workspace context supplied by the session host. + [JsonPropertyName("context")] + public JsonElement? Context { get; set; } + /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Custom agents available to the session after reloading definitions from disk. +/// Relative paths of files stored in the session workspace files directory. [Experimental(Diagnostics.Experimental)] -public sealed class AgentReloadResult +public sealed class WorkspacesListFilesResult { - /// Reloaded custom agents. - [JsonPropertyName("agents")] - public IList Agents { get => field ??= []; set; } + /// Relative file paths in the workspace files directory. + [JsonPropertyName("files")] + public IList Files { get => field ??= []; set; } } /// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionAgentReloadRequest +internal sealed class SessionWorkspacesListFilesRequest { /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Identifier assigned to the newly started background agent task. +/// Contents of the requested workspace file as a UTF-8 string. [Experimental(Diagnostics.Experimental)] -public sealed class TasksStartAgentResult +public sealed class WorkspacesReadFileResult { - /// Generated agent ID for the background task. - [JsonPropertyName("agentId")] - public string AgentId { get; set; } = string.Empty; + /// File content as a UTF-8 string. + [JsonPropertyName("content")] + public string Content { get; set; } = string.Empty; } -/// Agent type, prompt, name, and optional description and model override for the new task. +/// Relative path of the workspace file to read. [Experimental(Diagnostics.Experimental)] -internal sealed class TasksStartAgentRequest +internal sealed class WorkspacesReadFileRequest { - /// Type of agent to start (e.g., 'explore', 'task', 'general-purpose'). - [JsonPropertyName("agentType")] - public string AgentType { get; set; } = string.Empty; - - /// Short description of the task. - [JsonPropertyName("description")] - public string? Description { get; set; } + /// Relative path within the workspace files directory. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; - /// Optional model override. - [JsonPropertyName("model")] - public string? Model { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// Short name for the agent, used to generate a human-readable ID. - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; +/// Relative path and UTF-8 content for the workspace file to create or overwrite. +[Experimental(Diagnostics.Experimental)] +internal sealed class WorkspacesCreateFileRequest +{ + /// File content to write as a UTF-8 string. + [JsonPropertyName("content")] + public string Content { get; set; } = string.Empty; - /// Task prompt for the agent. - [JsonPropertyName("prompt")] - public string Prompt { get; set; } = string.Empty; + /// Relative path within the workspace files directory. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Tracked task union returned by task APIs, containing either an agent task or a shell task. -/// Polymorphic base type discriminated by type. +/// Workspace checkpoint metadata with assigned number, human-readable title, and checkpoint filename. [Experimental(Diagnostics.Experimental)] -[JsonPolymorphic( - TypeDiscriminatorPropertyName = "type", - UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] -[JsonDerivedType(typeof(TaskInfoAgent), "agent")] -[JsonDerivedType(typeof(TaskInfoShell), "shell")] -public partial class TaskInfo +public sealed class WorkspacesCheckpoints { - /// The type discriminator. - [JsonPropertyName("type")] - public virtual string Type { get; set; } = string.Empty; + /// Filename of the checkpoint within the workspace checkpoints directory. + [JsonPropertyName("filename")] + public string Filename { get; set; } = string.Empty; + + /// Checkpoint number assigned by the workspace manager. + [JsonPropertyName("number")] + public long Number { get; set; } + + /// Human-readable checkpoint title. + [JsonPropertyName("title")] + public string Title { get; set; } = string.Empty; } +/// Workspace checkpoints in chronological order; empty when the workspace is not enabled. +[Experimental(Diagnostics.Experimental)] +public sealed class WorkspacesListCheckpointsResult +{ + /// Workspace checkpoints in chronological order. Empty when workspace is not enabled. + [JsonPropertyName("checkpoints")] + public IList Checkpoints { get => field ??= []; set; } +} -/// Tracked background agent task metadata, including IDs, status, timing, agent type, prompt, model, result, and latest response. -/// The agent variant of . +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -public partial class TaskInfoAgent : TaskInfo +internal sealed class SessionWorkspacesListCheckpointsRequest { - /// - [JsonIgnore] - public override string Type => "agent"; + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// ISO 8601 timestamp when the current active period began. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("activeStartedAt")] - public DateTimeOffset? ActiveStartedAt { get; set; } +/// Checkpoint content as a UTF-8 string, or null when the checkpoint or workspace is missing. +[Experimental(Diagnostics.Experimental)] +public sealed class WorkspacesReadCheckpointResult +{ + /// Checkpoint content as a UTF-8 string, or null when the checkpoint or workspace is missing. + [JsonPropertyName("content")] + public string? Content { get; set; } +} - /// Accumulated active execution time in milliseconds. - [JsonConverter(typeof(MillisecondsTimeSpanConverter))] - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("activeTimeMs")] - public TimeSpan? ActiveTime { get; set; } +/// Checkpoint number to read. +[Experimental(Diagnostics.Experimental)] +internal sealed class WorkspacesReadCheckpointRequest +{ + /// Checkpoint number to read. + [JsonPropertyName("number")] + public long Number { get; set; } - /// Type of agent running this task. - [JsonPropertyName("agentType")] - public required string AgentType { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// Whether the task is currently in the original sync wait and can be moved to background mode. False once it is already backgrounded, idle, finished, or no longer has a promotable sync waiter. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("canPromoteToBackground")] - public bool? CanPromoteToBackground { get; set; } +/// RPC data type for WorkspacesAddSummaryResultSummary operations. +public sealed class WorkspacesAddSummaryResultSummary +{ +} - /// ISO 8601 timestamp when the task finished. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("completedAt")] - public DateTimeOffset? CompletedAt { get; set; } +/// RPC data type for WorkspacesAddSummaryResultWorkspace operations. +public sealed class WorkspacesAddSummaryResultWorkspace +{ +} - /// Short description of the task. - [JsonPropertyName("description")] - public required string Description { get; set; } - - /// Error message when the task failed. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("error")] - public string? Error { get; set; } - - /// Whether task execution is synchronously awaited or managed in the background. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("executionMode")] - public TaskExecutionMode? ExecutionMode { get; set; } - - /// Unique task identifier. - [JsonPropertyName("id")] - public required string Id { get; set; } - - /// ISO 8601 timestamp when the agent entered idle state. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("idleSince")] - public DateTimeOffset? IdleSince { get; set; } - - /// Most recent response text from the agent. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("latestResponse")] - public string? LatestResponse { get; set; } - - /// Requested model override for the task when specified. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("model")] - public string? Model { get; set; } - - /// Most recent prompt delivered to the agent. Updated whenever the agent receives a follow-up message. - [JsonPropertyName("prompt")] - public required string Prompt { get; set; } - - /// Runtime model resolved for the task when available. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("resolvedModel")] - public string? ResolvedModel { get; set; } - - /// Result text from the task when available. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("result")] - public string? Result { get; set; } - - /// ISO 8601 timestamp when the task was started. - [JsonPropertyName("startedAt")] - public required DateTimeOffset StartedAt { get; set; } - - /// Current lifecycle status of the task. - [JsonPropertyName("status")] - public required TaskStatus Status { get; set; } +/// Persisted summary metadata and refreshed workspace metadata. +[Experimental(Diagnostics.Experimental)] +public sealed class WorkspacesAddSummaryResult +{ + /// Gets or sets the summary value. + [JsonPropertyName("summary")] + public WorkspacesAddSummaryResultSummary? Summary { get; set; } - /// Tool call ID associated with this agent task. - [JsonPropertyName("toolCallId")] - public required string ToolCallId { get; set; } + /// Gets or sets the workspace value. + [JsonPropertyName("workspace")] + public WorkspacesAddSummaryResultWorkspace? Workspace { get; set; } } -/// Tracked shell task metadata, including ID, command, status, timing, attachment/execution mode, log path, and PID. -/// The shell variant of . +/// Compaction summary checkpoint to persist. [Experimental(Diagnostics.Experimental)] -public partial class TaskInfoShell : TaskInfo +internal sealed class WorkspacesAddSummaryRequest { - /// - [JsonIgnore] - public override string Type => "shell"; - - /// Whether the shell runs inside a managed PTY session or as an independent background process. - [JsonPropertyName("attachmentMode")] - public required TaskShellInfoAttachmentMode AttachmentMode { get; set; } - - /// Whether this shell task can be promoted to background mode. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("canPromoteToBackground")] - public bool? CanPromoteToBackground { get; set; } - - /// Command being executed. - [JsonPropertyName("command")] - public required string Command { get; set; } - - /// ISO 8601 timestamp when the task finished. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("completedAt")] - public DateTimeOffset? CompletedAt { get; set; } - - /// Short description of the task. - [JsonPropertyName("description")] - public required string Description { get; set; } - - /// Whether task execution is synchronously awaited or managed in the background. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("executionMode")] - public TaskExecutionMode? ExecutionMode { get; set; } - - /// Unique task identifier. - [JsonPropertyName("id")] - public required string Id { get; set; } + /// Markdown summary content to persist. + [JsonPropertyName("content")] + public string Content { get; set; } = string.Empty; - /// Path to the detached shell log, when available. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("logPath")] - public string? LogPath { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; - /// Process ID when available. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("pid")] - public long? Pid { get; set; } + /// Summary title shown in checkpoint listings. + [JsonPropertyName("title")] + public string Title { get; set; } = string.Empty; +} - /// ISO 8601 timestamp when the task was started. - [JsonPropertyName("startedAt")] - public required DateTimeOffset StartedAt { get; set; } +/// Rollback point for local workspace summaries. +[Experimental(Diagnostics.Experimental)] +internal sealed class WorkspacesTruncateSummariesRequest +{ + /// Number of newest summaries to keep. + [JsonPropertyName("keepCount")] + public long KeepCount { get; set; } - /// Current lifecycle status of the task. - [JsonPropertyName("status")] - public required TaskStatus Status { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Background tasks currently tracked by the session. +/// Autopilot objective file content, or null when missing. [Experimental(Diagnostics.Experimental)] -public sealed class TaskList +public sealed class WorkspacesReadAutopilotObjectiveResult { - /// Currently tracked tasks. - [JsonPropertyName("tasks")] - public IList Tasks { get => field ??= []; set; } + /// Autopilot objective file content, or null when missing. + [JsonPropertyName("content")] + public string? Content { get; set; } } /// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionTasksListRequest +internal sealed class SessionWorkspacesReadAutopilotObjectiveRequest { /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Refresh metadata for any detached background shells the runtime knows about. Use after a long pause to pick up exit/output state for shells running outside the agent loop. +/// Result of writing the autopilot objective file. [Experimental(Diagnostics.Experimental)] -public sealed class TasksRefreshResult +public sealed class WorkspacesWriteAutopilotObjectiveResult { + /// Filesystem operation performed. + [JsonPropertyName("operation")] + public string Operation { get; set; } = string.Empty; } -/// Identifies the target session. +/// Autopilot objective file content to persist. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionTasksRefreshRequest +internal sealed class WorkspacesWriteAutopilotObjectiveRequest { + /// Autopilot objective file content. + [JsonPropertyName("content")] + public string Content { get; set; } = string.Empty; + /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Wait until all in-flight background tasks (agents + shells) and any follow-up turns scheduled by their completions have settled. Returns when the runtime is fully drained or after an internal timeout (default 10 minutes; configurable via COPILOT_TASK_WAIT_TIMEOUT_SECONDS). +/// Result of deleting the autopilot objective file. [Experimental(Diagnostics.Experimental)] -public sealed class TasksWaitForPendingResult +public sealed class WorkspacesDeleteAutopilotObjectiveResult { + /// True when a file was deleted. + [JsonPropertyName("deleted")] + public bool Deleted { get; set; } } /// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionTasksWaitForPendingRequest +internal sealed class SessionWorkspacesDeleteAutopilotObjectiveRequest { /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Polymorphic base type discriminated by type. -[JsonPolymorphic( - TypeDiscriminatorPropertyName = "type", - UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] -[JsonDerivedType(typeof(TasksGetProgressResultProgressAgent), "agent")] -[JsonDerivedType(typeof(TasksGetProgressResultProgressShell), "shell")] -public partial class TasksGetProgressResultProgress -{ - /// The type discriminator. - [JsonPropertyName("type")] - public virtual string Type { get; set; } = string.Empty; -} - - -/// Timestamped display line for task progress output or recent agent activity. +/// Whether the autopilot objective file exists. [Experimental(Diagnostics.Experimental)] -public sealed class TaskProgressLine +public sealed class WorkspacesAutopilotObjectiveExistsResult { - /// Display message, e.g., "▸ bash", "✓ edit src/foo.ts". - [JsonPropertyName("message")] - public string Message { get; set; } = string.Empty; - - /// ISO 8601 timestamp when this event occurred. - [JsonPropertyName("timestamp")] - public DateTimeOffset Timestamp { get; set; } + /// True when the objective file exists. + [JsonPropertyName("exists")] + public bool Exists { get; set; } } -/// Progress snapshot for an agent task, with recent activity lines and optional latest intent. -/// The agent variant of . -public partial class TasksGetProgressResultProgressAgent : TasksGetProgressResultProgress +/// Identifies the target session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionWorkspacesAutopilotObjectiveExistsRequest { - /// - [JsonIgnore] - public override string Type => "agent"; - - /// The most recent intent reported by the agent. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("latestIntent")] - public string? LatestIntent { get; set; } - - /// Recent tool execution events converted to display lines. - [JsonPropertyName("recentActivity")] - public required IList RecentActivity { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Progress snapshot for a shell task, with recent stdout/stderr output and optional process ID. -/// The shell variant of . -public partial class TasksGetProgressResultProgressShell : TasksGetProgressResultProgress +/// RPC data type for WorkspacesSaveLargePasteResultSaved operations. +public sealed class WorkspacesSaveLargePasteResultSaved { - /// - [JsonIgnore] - public override string Type => "shell"; + /// Filename within the workspace files directory. + [JsonPropertyName("filename")] + public string Filename { get; set; } = string.Empty; - /// Process ID when available. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("pid")] - public long? Pid { get; set; } + /// Absolute filesystem path to the saved paste file. + [JsonPropertyName("filePath")] + public string FilePath { get; set; } = string.Empty; - /// Recent stdout/stderr lines from the running shell command. - [JsonPropertyName("recentOutput")] - public required string RecentOutput { get; set; } + /// Size of the saved file in bytes. + [JsonPropertyName("sizeBytes")] + public long SizeBytes { get; set; } } -/// Progress information for the task, or null when no task with that ID is tracked. +/// Descriptor for the saved paste file, or null when the workspace is unavailable. [Experimental(Diagnostics.Experimental)] -public sealed class TasksGetProgressResult +public sealed class WorkspacesSaveLargePasteResult { - /// Progress information for the task, discriminated by type. Returns null when no task with this ID is currently tracked. - [JsonPropertyName("progress")] - public TasksGetProgressResultProgress? Progress { get; set; } + /// Saved-paste descriptor, or null when the workspace is unavailable (e.g. CCA runtime, non-infinite sessions, remote sessions). + [JsonPropertyName("saved")] + public WorkspacesSaveLargePasteResultSaved? Saved { get; set; } } -/// Identifier of the background task to fetch progress for. +/// Pasted content to save as a UTF-8 file in the session workspace. [Experimental(Diagnostics.Experimental)] -internal sealed class TasksGetProgressRequest +internal sealed class WorkspacesSaveLargePasteRequest { - /// Task identifier (agent ID or shell ID). - [JsonPropertyName("id")] - public string Id { get; set; } = string.Empty; + /// Pasted content to save as a UTF-8 file. + [JsonPropertyName("content")] + public string Content { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// The first sync-waiting task that can currently be promoted to background mode. +/// A single changed file and its unified diff. [Experimental(Diagnostics.Experimental)] -public sealed class TasksGetCurrentPromotableResult +public sealed class WorkspaceDiffFileChange { - /// The first sync-waiting task (agent first, then shell) that can currently be promoted to background mode. Omitted if no such task exists. The returned task is guaranteed to have executionMode='sync' and canPromoteToBackground=true at the time of the call. - [JsonPropertyName("task")] - public TaskInfo? Task { get; set; } -} + /// Type of change represented by this file diff. + [JsonPropertyName("changeType")] + public WorkspaceDiffFileChangeType ChangeType { get; set; } -/// Identifies the target session. -[Experimental(Diagnostics.Experimental)] -internal sealed class SessionTasksGetCurrentPromotableRequest -{ - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// Unified diff content for the file. Empty when the diff was truncated. + [JsonPropertyName("diff")] + public string Diff { get; set; } = string.Empty; -/// Indicates whether the task was successfully promoted to background mode. -[Experimental(Diagnostics.Experimental)] -public sealed class TasksPromoteToBackgroundResult + /// Whether the diff content was omitted because it exceeded the per-file size limit. + [JsonPropertyName("isTruncated")] + public bool? IsTruncated { get; set; } + + /// Original file path for renamed files. + [JsonPropertyName("oldPath")] + public string? OldPath { get; set; } + + /// Path to the changed file, relative to the workspace root when the file lives under it. A file changed outside the workspace root keeps a `../`-relative path, or an absolute path when no relative path exists (for example a different Windows drive). + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; +} + +/// Workspace diff result for the requested mode. +[Experimental(Diagnostics.Experimental)] +public sealed class WorkspaceDiffResult { - /// Whether the task was successfully promoted to background mode. - [JsonPropertyName("promoted")] - public bool Promoted { get; set; } + /// Default branch used for a branch diff, when branch mode was requested. + [JsonPropertyName("baseBranch")] + public string? BaseBranch { get; set; } + + /// Changed files and their unified diffs. + [JsonPropertyName("changes")] + public IList Changes { get => field ??= []; set; } + + /// Whether the requested diff fell back to unstaged changes, either because branch diff failed or session diff was unavailable. + [JsonPropertyName("isFallback")] + public bool IsFallback { get; set; } + + /// Effective mode used for the returned changes. + [JsonPropertyName("mode")] + public WorkspaceDiffMode Mode { get; set; } + + /// Diff mode requested by the client. + [JsonPropertyName("requestedMode")] + public WorkspaceDiffMode RequestedMode { get; set; } + + /// Why the session diff could not be produced, when applicable. Set only when `session` mode was requested and `isFallback` is true, so a client can tell the permanent `file-change-tracking-disabled` apart from the transient `session-busy`, which the same request answers once the session settles. Never set for `unstaged` or `branch` mode, and never `unsupported-remote-session`: a remote session's captures live on its own host, so a `session`-mode diff is rejected for one rather than answered with a controller-side fallback. + [JsonPropertyName("unavailableReason")] + public HistoryRewindUnavailableReason? UnavailableReason { get; set; } } -/// Identifier of the task to promote to background mode. +/// Parameters for computing a workspace diff. [Experimental(Diagnostics.Experimental)] -internal sealed class TasksPromoteToBackgroundRequest +internal sealed class WorkspacesDiffRequest { - /// Task identifier. - [JsonPropertyName("id")] - public string Id { get; set; } = string.Empty; + /// When true, ignore whitespace-only changes (git `--ignore-all-space`). Defaults to false. + [JsonPropertyName("ignoreWhitespace")] + public bool? IgnoreWhitespace { get; set; } + + /// Diff mode requested by the client. + [JsonPropertyName("mode")] + public WorkspaceDiffMode Mode { get; set; } /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// The promoted task as it now exists in background mode, omitted if no promotable task was waiting. +/// Characters that, when typed in the composer, should trigger a `completions.request`. Empty when the session has no host-driven completions (e.g. local sessions, or a relay host that does not advertise `completionTriggerCharacters`). [Experimental(Diagnostics.Experimental)] -public sealed class TasksPromoteCurrentToBackgroundResult +public sealed class CompletionsGetTriggerCharactersResult { - /// The promoted task as it now exists in background mode, omitted if no promotable task was waiting. Atomic operation: avoids the race window of getCurrentPromotable + promoteToBackground. - [JsonPropertyName("task")] - public TaskInfo? Task { get; set; } + /// Trigger characters advertised by the host (e.g. `["@", "#"]`). Empty disables host-driven completions for the session. + [JsonPropertyName("triggerCharacters")] + public IList TriggerCharacters { get => field ??= []; set; } } /// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionTasksPromoteCurrentToBackgroundRequest +internal sealed class SessionCompletionsGetTriggerCharactersRequest { /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Indicates whether the background task was successfully cancelled. +/// A single host-driven completion. Accepting an item replaces `[rangeStart, rangeEnd)` (UTF-16 code units) in the composer with `insertText`; when the range is absent, the active token around the cursor is replaced. [Experimental(Diagnostics.Experimental)] -public sealed class TasksCancelResult +public sealed class SessionCompletionItem { - /// Whether the task was successfully cancelled. - [JsonPropertyName("cancelled")] - public bool Cancelled { get; set; } + /// Text spliced into the composer when the item is accepted. + [JsonPropertyName("insertText")] + public string InsertText { get; set; } = string.Empty; + + /// Render-kind hint for the picker row (e.g. `"document"`, `"directory"`), derived from the host's display kind. + [JsonPropertyName("kind")] + public string? Kind { get; set; } + + /// Primary display label for the picker row. Falls back to `insertText` when absent. + [JsonPropertyName("label")] + public string? Label { get; set; } + + /// End (exclusive) of the replacement range in `text`, in UTF-16 code units. + [JsonPropertyName("rangeEnd")] + public long? RangeEnd { get; set; } + + /// Start of the replacement range in `text`, in UTF-16 code units. + [JsonPropertyName("rangeStart")] + public long? RangeStart { get; set; } } -/// Identifier of the background task to cancel. +/// Host-driven completion items for the current composer input. Empty when the host returns no items or does not support completions. [Experimental(Diagnostics.Experimental)] -internal sealed class TasksCancelRequest +public sealed class CompletionsRequestResult { - /// Task identifier. - [JsonPropertyName("id")] - public string Id { get; set; } = string.Empty; + /// Completion items in host-ranked order. + [JsonPropertyName("items")] + public IList Items { get => field ??= []; set; } +} + +/// Request host-driven completions for the current composer input. +[Experimental(Diagnostics.Experimental)] +internal sealed class CompletionsRequestRequest +{ + /// Cursor offset within `text`, in UTF-16 code units. + [JsonPropertyName("offset")] + public long Offset { get; set; } /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; + + /// The full composed composer input. + [JsonPropertyName("text")] + public string Text { get; set; } = string.Empty; } -/// Indicates whether the task was removed. False when the task does not exist or is still running/idle. +/// Instruction sources loaded for the session, in merge order. [Experimental(Diagnostics.Experimental)] -public sealed class TasksRemoveResult +public sealed class InstructionsGetSourcesResult { - /// Whether the task was removed. Returns false if the task does not exist or is still running/idle (cancel it first). - [JsonPropertyName("removed")] - public bool Removed { get; set; } + /// Instruction sources for the session. + [JsonPropertyName("sources")] + public IList Sources { get => field ??= []; set; } } -/// Identifier of the completed or cancelled task to remove from tracking. +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class TasksRemoveRequest +internal sealed class SessionInstructionsGetSourcesRequest { - /// Task identifier. - [JsonPropertyName("id")] - public string Id { get; set; } = string.Empty; - /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Indicates whether the message was delivered, with an error message when delivery failed. +/// Indicates whether fleet mode was successfully activated. [Experimental(Diagnostics.Experimental)] -public sealed class TasksSendMessageResult +public sealed class FleetStartResult { - /// Error message if delivery failed. - [JsonPropertyName("error")] - public string? Error { get; set; } - - /// Whether the message was successfully delivered or steered. - [JsonPropertyName("sent")] - public bool Sent { get; set; } + /// Whether fleet mode was successfully activated. + [JsonPropertyName("started")] + public bool Started { get; set; } } -/// Identifier of the target agent task, message content, and optional sender agent ID. +/// Optional user prompt to combine with the fleet orchestration instructions. [Experimental(Diagnostics.Experimental)] -internal sealed class TasksSendMessageRequest +internal sealed class FleetStartRequest { - /// Agent ID of the sender, if sent on behalf of another agent. - [JsonPropertyName("fromAgentId")] - public string? FromAgentId { get; set; } - - /// Agent task identifier. - [JsonPropertyName("id")] - public string Id { get; set; } = string.Empty; - - /// Message content to send to the agent. - [JsonPropertyName("message")] - public string Message { get; set; } = string.Empty; + /// Optional user prompt to combine with fleet instructions. + [JsonPropertyName("prompt")] + public string? Prompt { get; set; } /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Skill metadata available to a session, with name, description, source, enabled/invocable state, path, plugin, and argument hint. +/// Agents available to the session. [Experimental(Diagnostics.Experimental)] -public sealed class Skill +public sealed class AgentList { - /// Optional freeform hint describing the skill's expected arguments, from the `argument-hint` frontmatter field. - [JsonPropertyName("argumentHint")] - public string? ArgumentHint { get; set; } - - /// Description of what the skill does. - [JsonPropertyName("description")] - public string Description { get; set; } = string.Empty; - - /// Whether the skill is currently enabled. - [JsonPropertyName("enabled")] - public bool Enabled { get; set; } + /// Available agents. + [JsonPropertyName("agents")] + public IList Agents { get => field ??= []; set; } +} - /// Unique identifier for the skill. - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; +/// RPC data type for SessionAgentList operations. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionAgentListRequest +{ + /// When true, request the session's configured built-in agents alongside custom agents. Listing applies feature, context, inclusion, exclusion, and user-disabled-agent policy, but does not evaluate transient invocation requirements such as model availability. Built-in metadata may be omitted when the session cannot project it, such as a relay session. + [JsonPropertyName("includeBuiltInAgents")] + public bool? IncludeBuiltInAgents { get; set; } - /// Absolute path to the skill file. - [JsonPropertyName("path")] - public string? Path { get; set; } + /// When true, request authored base prompt text on each AgentInfo. Prompt text may be omitted when unavailable, such as for agents projected through a relay session. + [JsonPropertyName("includePrompt")] + public bool? IncludePrompt { get; set; } +} - /// Name of the plugin that provides the skill, when source is 'plugin'. - [JsonPropertyName("pluginName")] - public string? PluginName { get; set; } +/// RPC data type for SessionAgentListRequestWithSession operations. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionAgentListRequestWithSession +{ + /// When true, request the session's configured built-in agents alongside custom agents. Listing applies feature, context, inclusion, exclusion, and user-disabled-agent policy, but does not evaluate transient invocation requirements such as model availability. Built-in metadata may be omitted when the session cannot project it, such as a relay session. + [JsonPropertyName("includeBuiltInAgents")] + public bool? IncludeBuiltInAgents { get; set; } - /// Source location type (e.g., project, personal-copilot, plugin, builtin). - [JsonPropertyName("source")] - public SkillSource Source { get; set; } + /// When true, request authored base prompt text on each AgentInfo. Prompt text may be omitted when unavailable, such as for agents projected through a relay session. + [JsonPropertyName("includePrompt")] + public bool? IncludePrompt { get; set; } - /// Whether the skill can be invoked by the user as a slash command. - [JsonPropertyName("userInvocable")] - public bool UserInvocable { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Skills available to the session, with their enabled state. +/// The currently selected custom agent, or null when using the default agent. [Experimental(Diagnostics.Experimental)] -public sealed class SkillList +public sealed class AgentGetCurrentResult { - /// Available skills. - [JsonPropertyName("skills")] - public IList Skills { get => field ??= []; set; } + /// Currently selected custom agent, or null if using the default agent. + [JsonPropertyName("agent")] + public AgentInfo? Agent { get; set; } } /// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionSkillsListRequest +internal sealed class SessionAgentGetCurrentRequest { /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Skill invocation record with name, path, content, allowed tools, and turn number. +/// The newly selected custom agent. [Experimental(Diagnostics.Experimental)] -public sealed class SkillsInvokedSkill +public sealed class AgentSelectResult { - /// Tools that should be auto-approved when this skill is active, captured at invocation time. - [JsonPropertyName("allowedTools")] - public IList? AllowedTools { get; set; } - - /// Full content of the skill file. - [JsonPropertyName("content")] - public string Content { get; set; } = string.Empty; - - /// Turn number when the skill was invoked. - [JsonPropertyName("invokedAtTurn")] - public long InvokedAtTurn { get; set; } - - /// Unique identifier for the skill. - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; - - /// Path to the SKILL.md file. - [JsonPropertyName("path")] - public string Path { get; set; } = string.Empty; + /// The newly selected custom agent. + [JsonPropertyName("agent")] + public AgentInfo Agent { get => field ??= new(); set; } } -/// Skills invoked during this session, ordered by invocation time (most recent last). +/// Name of the custom agent to select for subsequent turns. [Experimental(Diagnostics.Experimental)] -public sealed class SkillsGetInvokedResult +internal sealed class AgentSelectRequest { - /// Skills invoked during this session, ordered by invocation time (most recent last). - [JsonPropertyName("skills")] - public IList Skills { get => field ??= []; set; } -} + /// Name of the custom agent to select. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; -/// Identifies the target session. -[Experimental(Diagnostics.Experimental)] -internal sealed class SessionSkillsGetInvokedRequest -{ /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Name of the skill to enable for the session. -[Experimental(Diagnostics.Experimental)] -internal sealed class SkillsEnableRequest -{ - /// Name of the skill to enable. - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; - - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} - -/// Name of the skill to disable for the session. +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class SkillsDisableRequest +internal sealed class SessionAgentDeselectRequest { - /// Name of the skill to disable. - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; - /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Diagnostics from reloading skill definitions, with warnings and errors as separate lists. +/// Custom agents available to the session after reloading definitions from disk. [Experimental(Diagnostics.Experimental)] -public sealed class SkillsLoadDiagnostics +public sealed class AgentReloadResult { - /// Errors emitted while loading skills (e.g. skills that failed to load entirely). - [JsonPropertyName("errors")] - public IList Errors { get => field ??= []; set; } - - /// Warnings emitted while loading skills (e.g. skills that loaded but had issues). - [JsonPropertyName("warnings")] - public IList Warnings { get => field ??= []; set; } + /// Reloaded custom agents. + [JsonPropertyName("agents")] + public IList Agents { get => field ??= []; set; } } /// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionSkillsReloadRequest +internal sealed class SessionAgentReloadRequest { /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Identifies the target session. +/// Identifier assigned to the newly started background agent task. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionSkillsEnsureLoadedRequest +public sealed class TasksStartAgentResult { - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Generated agent ID for the background task. + [JsonPropertyName("agentId")] + public string AgentId { get; set; } = string.Empty; } -/// Recorded MCP server connection failure. +/// Agent type, prompt, name, and optional description and model override for the new task. [Experimental(Diagnostics.Experimental)] -public sealed class McpServerFailureInfo +internal sealed class TasksStartAgentRequest { - /// Failure message produced when the MCP server connection failed. - [JsonPropertyName("message")] - public string Message { get; set; } = string.Empty; + /// Type of agent to start (e.g., 'explore', 'task', 'general-purpose'). + [JsonPropertyName("agentType")] + public string AgentType { get; set; } = string.Empty; - /// epoch-ms timestamp at which the failure was recorded. - [JsonPropertyName("timestamp")] - public long Timestamp { get; set; } + /// Short description of the task. + [JsonPropertyName("description")] + public string? Description { get; set; } + + /// Optional model override. + [JsonPropertyName("model")] + public string? Model { get; set; } + + /// Short name for the agent, used to generate a human-readable ID. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; + + /// Task prompt for the agent. + [JsonPropertyName("prompt")] + public string Prompt { get; set; } = string.Empty; + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Recorded MCP server pending-auth state. +/// Tracked task union returned by task APIs, containing either an agent task or a shell task. +/// Polymorphic base type discriminated by type. [Experimental(Diagnostics.Experimental)] -public sealed class McpServerNeedsAuthInfo +[JsonPolymorphic( + TypeDiscriminatorPropertyName = "type", + UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] +[JsonDerivedType(typeof(TaskInfoAgent), "agent")] +[JsonDerivedType(typeof(TaskInfoShell), "shell")] +public partial class TaskInfo { - /// epoch-ms timestamp at which the server signalled it needs authentication. - [JsonPropertyName("timestamp")] - public long Timestamp { get; set; } + /// The type discriminator. + [JsonPropertyName("type")] + public virtual string Type { get; set; } = string.Empty; } -/// Host-level state, omitted when no MCP host is initialized. + +/// Tracked background agent task metadata, including IDs, status, timing, agent type, prompt, model, result, and latest response. +/// The agent variant of . [Experimental(Diagnostics.Experimental)] -public sealed class McpHostState +public partial class TaskInfoAgent : TaskInfo { - /// Names of currently-connected MCP clients. - [JsonPropertyName("clients")] - public IList Clients { get => field ??= []; set; } + /// + [JsonIgnore] + public override string Type => "agent"; - /// Configured servers that are explicitly disabled. - [JsonPropertyName("disabledServers")] - public IList DisabledServers { get => field ??= []; set; } + /// ISO 8601 timestamp when the current active period began. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("activeStartedAt")] + public DateTimeOffset? ActiveStartedAt { get; set; } - /// Map of server name to recorded connection failure. - [JsonPropertyName("failedServers")] - public IDictionary FailedServers { get => field ??= new Dictionary(); set; } + /// Accumulated active execution time in milliseconds. + [JsonConverter(typeof(MillisecondsTimeSpanConverter))] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("activeTimeMs")] + public TimeSpan? ActiveTime { get; set; } - /// Configured servers filtered out by enterprise allowlist policy. - [JsonPropertyName("filteredServers")] - public IList FilteredServers { get => field ??= []; set; } + /// Type of agent running this task. + [JsonPropertyName("agentType")] + public required string AgentType { get; set; } - /// Whether third-party MCP servers are policy-enabled for this session. - [JsonPropertyName("mcp3pEnabled")] - public bool Mcp3pEnabled { get; set; } + /// Whether the task is currently in the original sync wait and can be moved to background mode. False once it is already backgrounded, idle, finished, or no longer has a promotable sync waiter. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("canPromoteToBackground")] + public bool? CanPromoteToBackground { get; set; } - /// Map of server name to recorded pending-auth state. - [JsonPropertyName("needsAuthServers")] - public IDictionary NeedsAuthServers { get => field ??= new Dictionary(); set; } + /// ISO 8601 timestamp when the task finished. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("completedAt")] + public DateTimeOffset? CompletedAt { get; set; } - /// Names of servers with in-flight connection attempts. - [JsonPropertyName("pendingConnections")] - public IList PendingConnections { get => field ??= []; set; } -} + /// Short description of the task. + [JsonPropertyName("description")] + public required string Description { get; set; } -/// MCP server status entry, including config source/plugin source and any connection error. -[Experimental(Diagnostics.Experimental)] -public sealed class McpServer -{ - /// Error message if the server failed to connect. + /// Error message when the task failed. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("error")] public string? Error { get; set; } - /// Server name (config key). - [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] - [MinLength(1)] - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; + /// Whether task execution is synchronously awaited or managed in the background. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("executionMode")] + public TaskExecutionMode? ExecutionMode { get; set; } - /// Configuration source: user, workspace, plugin, or builtin. - [JsonPropertyName("source")] - public McpServerSource? Source { get; set; } + /// Unique task identifier. + [JsonPropertyName("id")] + public required string Id { get; set; } - /// Plugin name that provided this server, when source is plugin. - [JsonPropertyName("sourcePlugin")] - public string? SourcePlugin { get; set; } + /// ISO 8601 timestamp when the agent entered idle state. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("idleSince")] + public DateTimeOffset? IdleSince { get; set; } - /// Plugin version that provided this server, when source is plugin. - [JsonPropertyName("sourcePluginVersion")] - public string? SourcePluginVersion { get; set; } + /// Most recent response text from the agent. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("latestResponse")] + public string? LatestResponse { get; set; } - /// Connection status: connected, failed, needs-auth, pending, disabled, or not_configured. - [JsonPropertyName("status")] - public McpServerStatus Status { get; set; } -} + /// Requested model override for the task when specified. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("model")] + public string? Model { get; set; } -/// MCP servers configured for the session, with their connection status and host-level state. -[Experimental(Diagnostics.Experimental)] -public sealed class McpServerList -{ - /// Host-level state, omitted when no MCP host is initialized. - [JsonPropertyName("host")] - public McpHostState? Host { get; set; } + /// Most recent prompt delivered to the agent. Updated whenever the agent receives a follow-up message. + [JsonPropertyName("prompt")] + public required string Prompt { get; set; } - /// Configured MCP servers. - [JsonPropertyName("servers")] - public IList Servers { get => field ??= []; set; } -} + /// Runtime model resolved for the task when available. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("resolvedModel")] + public string? ResolvedModel { get; set; } -/// Identifies the target session. -[Experimental(Diagnostics.Experimental)] -internal sealed class SessionMcpListRequest -{ - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// Result text from the task when available. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("result")] + public string? Result { get; set; } -/// Normalized MCP Apps discovery metadata from a tool's `_meta.ui` block. -[Experimental(Diagnostics.Experimental)] -public sealed class McpToolUi -{ - /// URI of the tool's MCP App resource, typically a `ui://` resource identifier. Use `session.mcp.resources.read` to fetch its HTML and resource metadata. - [JsonPropertyName("resourceUri")] - public string? ResourceUri { get; set; } + /// ISO 8601 timestamp when the task was started. + [JsonPropertyName("startedAt")] + public required DateTimeOffset StartedAt { get; set; } - /// Tool visibility advertised by the server. When absent, MCP Apps defaults apply. - [JsonPropertyName("visibility")] - public IList? Visibility { get; set; } + /// Current lifecycle status of the task. + [JsonPropertyName("status")] + public required TaskStatus Status { get; set; } + + /// Tool call ID associated with this agent task. + [JsonPropertyName("toolCallId")] + public required string ToolCallId { get; set; } } -/// MCP tool metadata with tool name, optional description, and normalized MCP Apps discovery metadata. +/// Tracked shell task metadata, including ID, command, status, timing, attachment/execution mode, log path, and PID. +/// The shell variant of . [Experimental(Diagnostics.Experimental)] -public sealed class McpTools +public partial class TaskInfoShell : TaskInfo { - /// Tool description, when provided. - [JsonPropertyName("description")] - public string? Description { get; set; } + /// + [JsonIgnore] + public override string Type => "shell"; - /// Tool name. - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; + /// Whether the shell runs inside a managed PTY session or as an independent background process. + [JsonPropertyName("attachmentMode")] + public required TaskShellInfoAttachmentMode AttachmentMode { get; set; } - /// Normalized MCP Apps discovery metadata. An empty object indicates that a valid `_meta.ui` block was present without recognized fields. - [JsonPropertyName("ui")] - public McpToolUi? Ui { get; set; } + /// Whether this shell task can be promoted to background mode. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("canPromoteToBackground")] + public bool? CanPromoteToBackground { get; set; } + + /// Command being executed. + [JsonPropertyName("command")] + public required string Command { get; set; } + + /// ISO 8601 timestamp when the task finished. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("completedAt")] + public DateTimeOffset? CompletedAt { get; set; } + + /// Short description of the task. + [JsonPropertyName("description")] + public required string Description { get; set; } + + /// Whether task execution is synchronously awaited or managed in the background. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("executionMode")] + public TaskExecutionMode? ExecutionMode { get; set; } + + /// Unique task identifier. + [JsonPropertyName("id")] + public required string Id { get; set; } + + /// Path to the detached shell log, when available. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("logPath")] + public string? LogPath { get; set; } + + /// Process ID when available. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("pid")] + public long? Pid { get; set; } + + /// ISO 8601 timestamp when the task was started. + [JsonPropertyName("startedAt")] + public required DateTimeOffset StartedAt { get; set; } + + /// Current lifecycle status of the task. + [JsonPropertyName("status")] + public required TaskStatus Status { get; set; } } -/// Tools exposed by the connected MCP server. Throws when the server is not connected. +/// Background tasks currently tracked by the session. [Experimental(Diagnostics.Experimental)] -public sealed class McpListToolsResult +public sealed class TaskList { - /// Tools exposed by the server. - [JsonPropertyName("tools")] - public IList Tools { get => field ??= []; set; } + /// Currently tracked tasks. + [JsonPropertyName("tasks")] + public IList Tasks { get => field ??= []; set; } } -/// Server name whose tool list should be returned. +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class McpListToolsRequest +internal sealed class SessionTasksListRequest { - /// Name of the connected MCP server whose tools to list. - [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] - [MinLength(1)] - [JsonPropertyName("serverName")] - public string ServerName { get; set; } = string.Empty; - /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Name of the MCP server to enable for the session. +/// Refresh metadata for any detached background shells the runtime knows about. Use after a long pause to pick up exit/output state for shells running outside the agent loop. [Experimental(Diagnostics.Experimental)] -internal sealed class McpEnableRequest +public sealed class TasksRefreshResult { - /// Name of the MCP server to enable. - [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] - [MinLength(1)] - [JsonPropertyName("serverName")] - public string ServerName { get; set; } = string.Empty; +} +/// Identifies the target session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionTasksRefreshRequest +{ /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Name of the MCP server to disable for the session. +/// Wait until all in-flight background tasks (agents + shells) and any follow-up turns scheduled by their completions have settled. Returns when the runtime is fully drained or after an internal timeout (default 10 minutes; configurable via COPILOT_TASK_WAIT_TIMEOUT_SECONDS). [Experimental(Diagnostics.Experimental)] -internal sealed class McpDisableRequest +public sealed class TasksWaitForPendingResult { - /// Name of the MCP server to disable. - [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] - [MinLength(1)] - [JsonPropertyName("serverName")] - public string ServerName { get; set; } = string.Empty; - - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; } /// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionMcpReloadRequest +internal sealed class SessionTasksWaitForPendingRequest { /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// MCP server allowed by policy, with server name and optional PII-free explanatory note. +/// Polymorphic base type discriminated by type. +[JsonPolymorphic( + TypeDiscriminatorPropertyName = "type", + UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] +[JsonDerivedType(typeof(TasksGetProgressResultProgressAgent), "agent")] +[JsonDerivedType(typeof(TasksGetProgressResultProgressShell), "shell")] +public partial class TasksGetProgressResultProgress +{ + /// The type discriminator. + [JsonPropertyName("type")] + public virtual string Type { get; set; } = string.Empty; +} + + +/// Timestamped display line for task progress output or recent agent activity. [Experimental(Diagnostics.Experimental)] -public sealed class McpAllowedServer +public sealed class TaskProgressLine { - /// Allowed server name. - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; + /// Display message, e.g., "▸ bash", "✓ edit src/foo.ts". + [JsonPropertyName("message")] + public string Message { get; set; } = string.Empty; - /// PII-free note explaining why the server was allowed. - [JsonPropertyName("redactedNote")] - public string? RedactedNote { get; set; } + /// ISO 8601 timestamp when this event occurred. + [JsonPropertyName("timestamp")] + public DateTimeOffset Timestamp { get; set; } } -/// MCP server filtered by policy, with name, reason, optional redacted reason, and enterprise login. -[Experimental(Diagnostics.Experimental)] -public sealed class McpFilteredServer +/// Progress snapshot for an agent task, with recent activity lines and optional latest intent. +/// The agent variant of . +public partial class TasksGetProgressResultProgressAgent : TasksGetProgressResultProgress { - /// Enterprise login associated with an allowlist policy. - [JsonPropertyName("enterpriseName")] - public string? EnterpriseName { get; set; } + /// + [JsonIgnore] + public override string Type => "agent"; - /// Filtered server name. - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; + /// The most recent intent reported by the agent. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("latestIntent")] + public string? LatestIntent { get; set; } - /// Human-readable filter reason. - [JsonPropertyName("reason")] - public string Reason { get; set; } = string.Empty; + /// Recent tool execution events converted to display lines. + [JsonPropertyName("recentActivity")] + public required IList RecentActivity { get; set; } +} - /// PII-free filter reason. - [JsonPropertyName("redactedReason")] - public string? RedactedReason { get; set; } +/// Progress snapshot for a shell task, with recent stdout/stderr output and optional process ID. +/// The shell variant of . +public partial class TasksGetProgressResultProgressShell : TasksGetProgressResultProgress +{ + /// + [JsonIgnore] + public override string Type => "shell"; + + /// Process ID when available. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("pid")] + public long? Pid { get; set; } + + /// Recent stdout/stderr lines from the running shell command. + [JsonPropertyName("recentOutput")] + public required string RecentOutput { get; set; } } -/// MCP server startup filtering result. +/// Progress information for the task, or null when no task with that ID is tracked. [Experimental(Diagnostics.Experimental)] -internal sealed class McpStartServersResult +public sealed class TasksGetProgressResult { - /// Non-default servers allowed by policy. - [JsonPropertyName("allowedServers")] - public IList? AllowedServers { get; set; } - - /// Servers filtered out before startup. - [JsonPropertyName("filteredServers")] - public IList FilteredServers { get => field ??= []; set; } + /// Progress information for the task, discriminated by type. Returns null when no task with this ID is currently tracked. + [JsonPropertyName("progress")] + public TasksGetProgressResultProgress? Progress { get; set; } } -/// Opaque MCP reload configuration. +/// Identifier of the background task to fetch progress for. [Experimental(Diagnostics.Experimental)] -internal sealed class McpReloadWithConfigRequest +internal sealed class TasksGetProgressRequest { - /// Opaque runtime MCP reload configuration. Marked internal: an in-process runtime shape (reloadMcpServers throws over the wire). - [JsonInclude] - [JsonPropertyName("config")] - internal JsonElement Config { get; set; } + /// Task identifier (agent ID or shell ID). + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// 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. +/// The first sync-waiting task that can currently be promoted to background mode. [Experimental(Diagnostics.Experimental)] -public sealed class McpExecuteSamplingResult +public sealed class TasksGetCurrentPromotableResult { + /// The first sync-waiting task (agent first, then shell) that can currently be promoted to background mode. Omitted if no such task exists. The returned task is guaranteed to have executionMode='sync' and canPromoteToBackground=true at the time of the call. + [JsonPropertyName("task")] + public TaskInfo? Task { get; set; } } -/// Outcome of an MCP sampling execution: success result, failure error, or cancellation. +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -public sealed class McpSamplingExecutionResult +internal sealed class SessionTasksGetCurrentPromotableRequest { - /// 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. - [JsonPropertyName("action")] - public McpSamplingExecutionAction Action { get; set; } - - /// Error description, present when action='failure'. - [JsonPropertyName("error")] - public string? Error { get; set; } - - /// 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. - [JsonPropertyName("result")] - public McpExecuteSamplingResult? Result { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// 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. +/// Indicates whether the task was successfully promoted to background mode. [Experimental(Diagnostics.Experimental)] -public sealed class McpExecuteSamplingRequest +public sealed class TasksPromoteToBackgroundResult { + /// Whether the task was successfully promoted to background mode. + [JsonPropertyName("promoted")] + public bool Promoted { get; set; } } -/// Identifiers and raw MCP CreateMessageRequest params used to run a sampling inference. +/// Identifier of the task to promote to background mode. [Experimental(Diagnostics.Experimental)] -internal sealed class McpExecuteSamplingParams +internal sealed class TasksPromoteToBackgroundRequest { - /// 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 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")] - public McpExecuteSamplingRequest Request { get => field ??= new(); set; } - - /// Caller-provided unique identifier for this sampling execution. Use this same ID with cancelSamplingExecution to cancel the in-flight call. Must be unique within the session for the lifetime of the call. - [JsonPropertyName("requestId")] - public string RequestId { get; set; } = string.Empty; - - /// Name of the MCP server that initiated the sampling request. - [JsonPropertyName("serverName")] - public string ServerName { get; set; } = string.Empty; + /// Task identifier. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Indicates whether an in-flight sampling execution with the given requestId was found and cancelled. +/// The promoted task as it now exists in background mode, omitted if no promotable task was waiting. [Experimental(Diagnostics.Experimental)] -public sealed class McpCancelSamplingExecutionResult +public sealed class TasksPromoteCurrentToBackgroundResult { - /// True if an in-flight execution with the given requestId was found and signalled to cancel. False when no such execution is in flight (already completed, never started, or cancelled by another caller). - [JsonPropertyName("cancelled")] - public bool Cancelled { get; set; } + /// The promoted task as it now exists in background mode, omitted if no promotable task was waiting. Atomic operation: avoids the race window of getCurrentPromotable + promoteToBackground. + [JsonPropertyName("task")] + public TaskInfo? Task { get; set; } } -/// The requestId previously passed to executeSampling that should be cancelled. +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class McpCancelSamplingExecutionParams +internal sealed class SessionTasksPromoteCurrentToBackgroundRequest { - /// The requestId previously passed to executeSampling that should be cancelled. - [JsonPropertyName("requestId")] - public string RequestId { get; set; } = string.Empty; - /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Env-value mode recorded on the session after the update. +/// Indicates whether the background task was successfully cancelled. [Experimental(Diagnostics.Experimental)] -public sealed class McpSetEnvValueModeResult +public sealed class TasksCancelResult { - /// Mode recorded on the session after the update. - [JsonPropertyName("mode")] - public McpSetEnvValueModeDetails Mode { get; set; } + /// Whether the task was successfully cancelled. + [JsonPropertyName("cancelled")] + public bool Cancelled { get; set; } } -/// Mode controlling how MCP server env values are resolved (`direct` or `indirect`). +/// Identifier of the background task to cancel. [Experimental(Diagnostics.Experimental)] -internal sealed class McpSetEnvValueModeParams +internal sealed class TasksCancelRequest { - /// 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". - [JsonPropertyName("mode")] - public McpSetEnvValueModeDetails Mode { get; set; } + /// Task identifier. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Indicates whether the auto-managed `github` MCP server was removed (false when nothing to remove). +/// Indicates whether the task was removed. False when the task does not exist or is still running/idle. [Experimental(Diagnostics.Experimental)] -public sealed class McpRemoveGitHubResult +public sealed class TasksRemoveResult { - /// True when the auto-managed `github` MCP server was removed; false when no removal happened (e.g. user has explicitly configured a `github` server, or the server was not registered). + /// Whether the task was removed. Returns false if the task does not exist or is still running/idle (cancel it first). [JsonPropertyName("removed")] public bool Removed { get; set; } } -/// Identifies the target session. +/// Identifier of the completed or cancelled task to remove from tracking. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionMcpRemoveGitHubRequest +internal sealed class TasksRemoveRequest { + /// Task identifier. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; + /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Result of configuring GitHub MCP. +/// Indicates whether the message was delivered, with an error message when delivery failed. [Experimental(Diagnostics.Experimental)] -internal sealed class McpConfigureGitHubResult +public sealed class TasksSendMessageResult { - /// Whether GitHub MCP configuration changed. - [JsonPropertyName("changed")] - public bool Changed { get; set; } + /// Error message if delivery failed. + [JsonPropertyName("error")] + public string? Error { get; set; } + + /// Whether the message was successfully delivered or steered. + [JsonPropertyName("sent")] + public bool Sent { get; set; } } -/// Opaque auth info used to configure GitHub MCP. +/// Identifier of the target agent task, message content, and optional sender agent ID. [Experimental(Diagnostics.Experimental)] -internal sealed class McpConfigureGitHubRequest +internal sealed class TasksSendMessageRequest { - /// Opaque runtime auth info for GitHub MCP configuration. Marked internal: an in-process runtime shape (configureGitHubMcp is a no-op over the wire). - [JsonInclude] - [JsonPropertyName("authInfo")] - internal JsonElement AuthInfo { get; set; } + /// Agent ID of the sender, if sent on behalf of another agent. + [JsonPropertyName("fromAgentId")] + public string? FromAgentId { get; set; } + + /// Agent task identifier. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; + + /// Message content to send to the agent. + [JsonPropertyName("message")] + public string Message { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Server name and configuration for an individual MCP server start. +/// Skill metadata available to a session, with name, description, source, enabled/invocable state, path, plugin, and argument hint. [Experimental(Diagnostics.Experimental)] -internal sealed class McpStartServerRequest +public sealed class Skill { - /// MCP server configuration (stdio process or remote HTTP/SSE). - [JsonPropertyName("config")] - public JsonElement Config { get; set; } + /// Optional freeform hint describing the skill's expected arguments, from the `argument-hint` frontmatter field. + [JsonPropertyName("argumentHint")] + public string? ArgumentHint { get; set; } - /// Name of the MCP server to start. - [JsonPropertyName("serverName")] - public string ServerName { get; set; } = string.Empty; + /// Description of what the skill does. + [JsonPropertyName("description")] + public string Description { get; set; } = string.Empty; + + /// Whether the skill is currently enabled. + [JsonPropertyName("enabled")] + public bool Enabled { get; set; } + + /// Unique identifier for the skill. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; + + /// Absolute path to the skill file. + [JsonPropertyName("path")] + public string? Path { get; set; } + + /// Name of the plugin that provides the skill, when source is 'plugin'. + [JsonPropertyName("pluginName")] + public string? PluginName { get; set; } + + /// Source location type (e.g., project, personal-copilot, plugin, builtin). + [JsonPropertyName("source")] + public SkillSource Source { get; set; } + + /// Whether the skill can be invoked by the user as a slash command. + [JsonPropertyName("userInvocable")] + public bool UserInvocable { get; set; } +} + +/// Skills available to the session, with their enabled state. +[Experimental(Diagnostics.Experimental)] +public sealed class SkillList +{ + /// Available skills. + [JsonPropertyName("skills")] + public IList Skills { get => field ??= []; set; } +} +/// Identifies the target session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionSkillsListRequest +{ /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Server name and optional replacement configuration for an individual MCP server restart. Omit `config` for a config-free restart-by-name of an already-configured server. +/// Skill invocation record with name, path, content, allowed tools, and turn number. [Experimental(Diagnostics.Experimental)] -internal sealed class McpRestartServerRequest +public sealed class SkillsInvokedSkill { - /// Replacement MCP server configuration (stdio process or remote HTTP/SSE). Omit to restart the server with its already-registered configuration (config-free restart-by-name). - [JsonPropertyName("config")] - public JsonElement? Config { get; set; } + /// Tools that should be auto-approved when this skill is active, captured at invocation time. + [JsonPropertyName("allowedTools")] + public IList? AllowedTools { get; set; } - /// Name of the MCP server to restart. - [JsonPropertyName("serverName")] - public string ServerName { get; set; } = string.Empty; + /// Full content of the skill file. + [JsonPropertyName("content")] + public string Content { get; set; } = string.Empty; - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Turn number when the skill was invoked. + [JsonPropertyName("invokedAtTurn")] + public long InvokedAtTurn { get; set; } + + /// Unique identifier for the skill. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; + + /// Path to the SKILL.md file. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; } -/// Server name for an individual MCP server stop. +/// Skills invoked during this session, ordered by invocation time (most recent last). [Experimental(Diagnostics.Experimental)] -internal sealed class McpStopServerRequest +public sealed class SkillsGetInvokedResult { - /// Name of the MCP server to stop. - [JsonPropertyName("serverName")] - public string ServerName { get; set; } = string.Empty; + /// Skills invoked during this session, ordered by invocation time (most recent last). + [JsonPropertyName("skills")] + public IList Skills { get => field ??= []; set; } +} +/// Identifies the target session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionSkillsGetInvokedRequest +{ /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Registration parameters for an external MCP client. +/// Name of the skill to enable for the session. [Experimental(Diagnostics.Experimental)] -internal sealed class McpRegisterExternalClientRequest +internal sealed class SkillsEnableRequest { - /// In-process MCP Client instance. Marked internal: cannot be serialized across the JSON-RPC boundary. - [JsonInclude] - [JsonPropertyName("client")] - internal JsonElement Client { get; set; } - - /// In-process server config (MCPServerConfig) paired with the in-process client/transport. Marked internal alongside its companions. - [JsonInclude] - [JsonPropertyName("config")] - internal JsonElement Config { get; set; } - - /// Logical server name for the external client. - [JsonPropertyName("serverName")] - public string ServerName { get; set; } = string.Empty; + /// Name of the skill to enable. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; - - /// In-process MCP Transport instance. Marked internal: cannot be serialized across the JSON-RPC boundary. - [JsonInclude] - [JsonPropertyName("transport")] - internal JsonElement Transport { get; set; } } -/// Server name identifying the external client to remove. +/// Name of the skill to disable for the session. [Experimental(Diagnostics.Experimental)] -internal sealed class McpUnregisterExternalClientRequest +internal sealed class SkillsDisableRequest { - /// Server name of the external client to unregister. - [JsonPropertyName("serverName")] - public string ServerName { get; set; } = string.Empty; + /// Name of the skill to disable. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Whether the named MCP server is running. +/// Diagnostics from reloading skill definitions, with warnings and errors as separate lists. [Experimental(Diagnostics.Experimental)] -public sealed class McpIsServerRunningResult +public sealed class SkillsLoadDiagnostics { - /// True if the server has an active client and transport. - [JsonPropertyName("running")] - public bool Running { get; set; } + /// Errors emitted while loading skills (e.g. skills that failed to load entirely). + [JsonPropertyName("errors")] + public IList Errors { get => field ??= []; set; } + + /// Warnings emitted while loading skills (e.g. skills that loaded but had issues). + [JsonPropertyName("warnings")] + public IList Warnings { get => field ??= []; set; } } -/// Server name to check running status for. +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class McpIsServerRunningRequest +internal sealed class SessionSkillsReloadRequest { - /// Name of the MCP server to check. - [JsonPropertyName("serverName")] - public string ServerName { get; set; } = string.Empty; - /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Indicates whether the pending MCP OAuth response was accepted. +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -public sealed class McpOauthHandlePendingResult +internal sealed class SessionSkillsEnsureLoadedRequest { - /// Whether the response was accepted. False if the request was unknown, timed out, or already resolved. - [JsonPropertyName("success")] - public bool Success { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Host response to the pending OAuth request. -/// Polymorphic base type discriminated by kind. +/// Recorded MCP server connection failure. [Experimental(Diagnostics.Experimental)] -[JsonPolymorphic( - TypeDiscriminatorPropertyName = "kind", - UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] -[JsonDerivedType(typeof(McpOauthPendingRequestResponseToken), "token")] -[JsonDerivedType(typeof(McpOauthPendingRequestResponseCancelled), "cancelled")] -public partial class McpOauthPendingRequestResponse +public sealed class McpServerFailureInfo { - /// The type discriminator. - [JsonPropertyName("kind")] - public virtual string Kind { get; set; } = string.Empty; + /// Failure message produced when the MCP server connection failed. + [JsonPropertyName("message")] + public string Message { get; set; } = string.Empty; + + /// epoch-ms timestamp at which the failure was recorded. + [JsonPropertyName("timestamp")] + public long Timestamp { get; set; } } +/// Recorded MCP server pending-auth state. +[Experimental(Diagnostics.Experimental)] +public sealed class McpServerNeedsAuthInfo +{ + /// epoch-ms timestamp at which the server signalled it needs authentication. + [JsonPropertyName("timestamp")] + public long Timestamp { get; set; } +} -/// The token variant of . +/// Host-level state, omitted when no MCP host is initialized. [Experimental(Diagnostics.Experimental)] -public partial class McpOauthPendingRequestResponseToken : McpOauthPendingRequestResponse +public sealed class McpHostState { - /// - [JsonIgnore] - public override string Kind => "token"; + /// Names of currently-connected MCP clients. + [JsonPropertyName("clients")] + public IList Clients { get => field ??= []; set; } - /// Access token acquired by the SDK host. - [JsonPropertyName("accessToken")] - public required string AccessToken { get; set; } + /// Configured servers that are explicitly disabled. + [JsonPropertyName("disabledServers")] + public IList DisabledServers { get => field ??= []; set; } - /// Token lifetime in seconds, if known. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("expiresIn")] - public long? ExpiresIn { get; set; } + /// Map of server name to recorded connection failure. + [JsonPropertyName("failedServers")] + public IDictionary FailedServers { get => field ??= new Dictionary(); set; } - /// OAuth token type. Defaults to Bearer when omitted. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("tokenType")] - public string? TokenType { get; set; } + /// Configured servers filtered out by MCP server policy. + [JsonPropertyName("filteredServers")] + public IList FilteredServers { get => field ??= []; set; } + + /// Whether third-party MCP servers are policy-enabled for this session. + [JsonPropertyName("mcp3pEnabled")] + public bool Mcp3pEnabled { get; set; } + + /// Map of server name to recorded pending-auth state. + [JsonPropertyName("needsAuthServers")] + public IDictionary NeedsAuthServers { get => field ??= new Dictionary(); set; } + + /// Names of servers with in-flight connection attempts. + [JsonPropertyName("pendingConnections")] + public IList PendingConnections { get => field ??= []; set; } } -/// The cancelled variant of . +/// MCP server status entry, including config source/plugin source and any connection error. [Experimental(Diagnostics.Experimental)] -public partial class McpOauthPendingRequestResponseCancelled : McpOauthPendingRequestResponse +public sealed class McpServer { - /// - [JsonIgnore] - public override string Kind => "cancelled"; + /// Error message if the server failed to connect. + [JsonPropertyName("error")] + public string? Error { get; set; } + + /// Server name (config key). + [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] + [MinLength(1)] + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; + + /// Configuration source: user, workspace, plugin, or builtin. + [JsonPropertyName("source")] + public McpServerSource? Source { get; set; } + + /// Plugin name that provided this server, when source is plugin. + [JsonPropertyName("sourcePlugin")] + public string? SourcePlugin { get; set; } + + /// Plugin version that provided this server, when source is plugin. + [JsonPropertyName("sourcePluginVersion")] + public string? SourcePluginVersion { get; set; } + + /// Connection status: connected, failed, needs-auth, pending, disabled, or not_configured. + [JsonPropertyName("status")] + public McpServerStatus Status { get; set; } } -/// Pending MCP OAuth request ID and host-provided token or cancellation response. +/// MCP servers configured for the session, with their connection status and host-level state. [Experimental(Diagnostics.Experimental)] -internal sealed class McpOauthHandlePendingRequest +public sealed class McpServerList { - /// OAuth request identifier from the mcp.oauth_required event. - [JsonPropertyName("requestId")] - public string RequestId { get; set; } = string.Empty; + /// Host-level state, omitted when no MCP host is initialized. + [JsonPropertyName("host")] + public McpHostState? Host { get; set; } - /// Host response to the pending OAuth request. - [JsonPropertyName("result")] - public McpOauthPendingRequestResponse Result { get => field ??= new(); set; } + /// Configured MCP servers. + [JsonPropertyName("servers")] + public IList Servers { get => field ??= []; set; } +} +/// Identifies the target session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionMcpListRequest +{ /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// OAuth authorization URL the caller should open, or empty when cached tokens already authenticated the server. +/// Normalized MCP Apps discovery metadata from a tool's `_meta.ui` block. [Experimental(Diagnostics.Experimental)] -public sealed class McpOauthLoginResult +public sealed class McpToolUi { - /// URL the caller should open in a browser to complete OAuth. Omitted when cached tokens were still valid and no browser interaction was needed — the server is already reconnected in that case. When present, the runtime starts the callback listener before returning and continues the flow in the background; completion is signaled via session.mcp_server_status_changed. - [Url] - [StringSyntax(StringSyntaxAttribute.Uri)] - [JsonPropertyName("authorizationUrl")] - public string? AuthorizationUrl { get; set; } + /// URI of the tool's MCP App resource, typically a `ui://` resource identifier. Use `session.mcp.resources.read` to fetch its HTML and resource metadata. + [JsonPropertyName("resourceUri")] + public string? ResourceUri { get; set; } + + /// Tool visibility advertised by the server. When absent, MCP Apps defaults apply. + [JsonPropertyName("visibility")] + public IList? Visibility { get; set; } } -/// Remote MCP server name and optional overrides controlling reauthentication, OAuth client display name, callback success-page copy, and static OAuth client selection. +/// MCP tool metadata with tool name, optional description, and normalized MCP Apps discovery metadata. [Experimental(Diagnostics.Experimental)] -internal sealed class McpOauthLoginRequest +public sealed class McpTools { - /// Optional override for the body text shown on the OAuth loopback callback success page. When omitted, the runtime applies a neutral fallback; callers driving interactive auth should pass surface-specific copy telling the user where to return. - [JsonPropertyName("callbackSuccessMessage")] - public string? CallbackSuccessMessage { get; set; } - - /// Optional OAuth client ID override for this login. When set, the runtime uses this pre-registered static client instead of dynamic client registration. - [JsonPropertyName("clientId")] - public string? ClientId { get; set; } - - /// Optional override for the OAuth client display name shown on the consent screen. Applies to newly registered dynamic clients only — existing registrations keep the name they were created with. When omitted, the runtime applies a neutral fallback; callers driving interactive auth should pass their own surface-specific label so the consent screen matches the product the user sees. - [JsonPropertyName("clientName")] - public string? ClientName { get; set; } - - /// Optional OAuth client secret override for this login. The runtime treats this as an ephemeral host-owned secret, uses it for this authentication attempt and does not persist it. - [JsonPropertyName("clientSecret")] - public string? ClientSecret { get; set; } + /// Tool description, when provided. + [JsonPropertyName("description")] + public string? Description { get; set; } - /// When true, clears any cached OAuth token for the server and runs a full new authorization. Use when the user explicitly wants to switch accounts or believes their session is stuck. - [JsonPropertyName("forceReauth")] - public bool? ForceReauth { get; set; } + /// Tool name. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; - /// Optional OAuth grant type override for this login. Defaults to the server configuration, or authorization_code when no grant type is specified. - [JsonPropertyName("grantType")] - public McpOauthLoginGrantType? GrantType { get; set; } + /// Normalized MCP Apps discovery metadata. An empty object indicates that a valid `_meta.ui` block was present without recognized fields. + [JsonPropertyName("ui")] + public McpToolUi? Ui { get; set; } +} - /// Optional override indicating whether the static OAuth client is public. When false, the runtime treats it as confidential and uses the per-login clientSecret if provided, otherwise retrieving the client secret from the MCP OAuth secret store. - [JsonPropertyName("publicClient")] - public bool? PublicClient { get; set; } +/// Tools exposed by the connected MCP server. Throws when the server is not connected. +[Experimental(Diagnostics.Experimental)] +public sealed class McpListToolsResult +{ + /// Tools exposed by the server. + [JsonPropertyName("tools")] + public IList Tools { get => field ??= []; set; } +} - /// Name of the remote MCP server to authenticate. +/// Server name whose tool list should be returned. +[Experimental(Diagnostics.Experimental)] +internal sealed class McpListToolsRequest +{ + /// Name of the connected MCP server whose tools to list. [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] [MinLength(1)] @@ -6583,343 +6955,290 @@ internal sealed class McpOauthLoginRequest public string SessionId { get; set; } = string.Empty; } -/// Indicates whether the pending MCP headers refresh response was accepted. +/// Name of the MCP server to enable for the session. [Experimental(Diagnostics.Experimental)] -public sealed class McpHeadersHandlePendingHeadersRefreshRequestResult +internal sealed class McpEnableRequest { - /// Whether the response was accepted. False if the request was unknown, timed out, or already resolved. - [JsonPropertyName("success")] - public bool Success { get; set; } + /// Name of the MCP server to enable. + [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] + [MinLength(1)] + [JsonPropertyName("serverName")] + public string ServerName { get; set; } = string.Empty; + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Host response: supply dynamic headers or decline this refresh. -/// Polymorphic base type discriminated by kind. +/// Name of the MCP server to disable for the session. [Experimental(Diagnostics.Experimental)] -[JsonPolymorphic( - TypeDiscriminatorPropertyName = "kind", - UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] -[JsonDerivedType(typeof(McpHeadersHandlePendingHeadersRefreshRequestHeaders), "headers")] -[JsonDerivedType(typeof(McpHeadersHandlePendingHeadersRefreshRequestNone), "none")] -public partial class McpHeadersHandlePendingHeadersRefreshRequest +internal sealed class McpDisableRequest { - /// The type discriminator. - [JsonPropertyName("kind")] - public virtual string Kind { get; set; } = string.Empty; -} + /// Name of the MCP server to disable. + [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] + [MinLength(1)] + [JsonPropertyName("serverName")] + public string ServerName { get; set; } = string.Empty; + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} -/// The headers variant of . +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -public partial class McpHeadersHandlePendingHeadersRefreshRequestHeaders : McpHeadersHandlePendingHeadersRefreshRequest +internal sealed class SessionMcpReloadRequest { - /// - [JsonIgnore] - public override string Kind => "headers"; - - /// Headers to overlay onto the MCP request. Dynamic headers override static config headers but do not replace SDK-managed request headers. - [JsonPropertyName("headers")] - public required IDictionary Headers { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// The none variant of . +/// MCP server allowed by policy, with server name and optional PII-free explanatory note. [Experimental(Diagnostics.Experimental)] -public partial class McpHeadersHandlePendingHeadersRefreshRequestNone : McpHeadersHandlePendingHeadersRefreshRequest +public sealed class McpAllowedServer { - /// - [JsonIgnore] - public override string Kind => "none"; + /// Allowed server name. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; + + /// PII-free note explaining why the server was allowed. + [JsonPropertyName("redactedNote")] + public string? RedactedNote { get; set; } } -/// MCP headers refresh request id and the host response. +/// MCP server filtered by policy, with name, reason, and optional redacted reason. [Experimental(Diagnostics.Experimental)] -internal sealed class McpHeadersHandlePendingHeadersRefreshRequestRequest +public sealed class McpFilteredServer { - /// Headers refresh request identifier from mcp.headers_refresh_required. - [JsonPropertyName("requestId")] - public string RequestId { get; set; } = string.Empty; - - /// Host response: supply dynamic headers or decline this refresh. - [JsonPropertyName("result")] - public McpHeadersHandlePendingHeadersRefreshRequest Result { get => field ??= new(); set; } - - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} - -/// MCP Apps resource content with URI, optional MIME type, text or base64 blob, and resource metadata. -[Experimental(Diagnostics.Experimental)] -public sealed class McpAppsResourceContent -{ - /// Resource-level metadata (CSP, permissions, etc.). - [JsonPropertyName("_meta")] - public IDictionary? Meta { get; set; } - - /// Base64-encoded binary content. - [JsonPropertyName("blob")] - public string? Blob { get; set; } + /// Deprecated. This field is no longer populated. + [EditorBrowsable(EditorBrowsableState.Never)] +#if NET5_0_OR_GREATER + [Obsolete("This member is deprecated and will be removed in a future version.", DiagnosticId = "GHCP001")] +#endif + [JsonPropertyName("enterpriseName")] + public string? EnterpriseName { get; set; } - /// MIME type of the content. - [JsonPropertyName("mimeType")] - public string? MimeType { get; set; } + /// Filtered server name. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; - /// Text content (e.g. HTML). - [JsonPropertyName("text")] - public string? Text { get; set; } + /// Human-readable filter reason. + [JsonPropertyName("reason")] + public string Reason { get; set; } = string.Empty; - /// The resource URI (typically ui://...). - [JsonPropertyName("uri")] - public string Uri { get; set; } = string.Empty; + /// PII-free filter reason. + [JsonPropertyName("redactedReason")] + public string? RedactedReason { get; set; } } -/// Resource contents returned by the MCP server. +/// MCP server startup filtering result. [Experimental(Diagnostics.Experimental)] -public sealed class McpAppsReadResourceResult +internal sealed class McpStartServersResult { - /// Resource contents returned by the server. - [JsonPropertyName("contents")] - public IList Contents { get => field ??= []; set; } + /// Non-default servers allowed by policy. + [JsonPropertyName("allowedServers")] + public IList? AllowedServers { get; set; } + + /// Servers filtered out before startup. + [JsonPropertyName("filteredServers")] + public IList FilteredServers { get => field ??= []; set; } } -/// MCP server and resource URI to fetch. +/// Opaque MCP reload configuration. [Experimental(Diagnostics.Experimental)] -internal sealed class McpAppsReadResourceRequest +internal sealed class McpReloadWithConfigRequest { - /// Name of the MCP server hosting the resource. - [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] - [MinLength(1)] - [JsonPropertyName("serverName")] - public string ServerName { get; set; } = string.Empty; + /// Opaque runtime MCP reload configuration. Marked internal: an in-process runtime shape (reloadMcpServers throws over the wire). + [JsonInclude] + [JsonPropertyName("config")] + internal JsonElement Config { get; set; } /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; - - /// Resource URI (typically ui://...). - [JsonPropertyName("uri")] - public string Uri { get; set; } = string.Empty; } -/// App-callable tools from the named 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. [Experimental(Diagnostics.Experimental)] -public sealed class McpAppsListToolsResult +public sealed class McpExecuteSamplingResult { - /// App-callable tools from the server. - [JsonPropertyName("tools")] - public IList> Tools { get => field ??= []; set; } } -/// MCP server to list app-callable tools for. +/// Outcome of an MCP sampling execution: success result, failure error, or cancellation. [Experimental(Diagnostics.Experimental)] -internal sealed class McpAppsListToolsRequest +public sealed class McpSamplingExecutionResult { - /// **Required.** Server whose ui:// view issued the request. Per SEP-1865 ('callable by the app from this server only'), the call is rejected when this differs from `serverName`, and rejected outright when missing. - [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] - [MinLength(1)] - [JsonPropertyName("originServerName")] - public string OriginServerName { get; set; } = string.Empty; + /// 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. + [JsonPropertyName("action")] + public McpSamplingExecutionAction Action { get; set; } - /// MCP server hosting the app. - [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] - [MinLength(1)] - [JsonPropertyName("serverName")] - public string ServerName { get; set; } = string.Empty; + /// Error description, present when action='failure'. + [JsonPropertyName("error")] + public string? Error { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// 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. + [JsonPropertyName("result")] + public McpExecuteSamplingResult? Result { get; set; } } -/// MCP server, tool name, and arguments to invoke from an MCP App view. +/// 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. [Experimental(Diagnostics.Experimental)] -internal sealed class McpAppsCallToolRequest +public sealed class McpExecuteSamplingRequest { - /// Tool arguments. - [JsonPropertyName("arguments")] - public IDictionary? Arguments { get; set; } +} - /// **Required.** Server whose ui:// view issued the request. Per SEP-1865 ('callable by the app from this server only'), the call is rejected when this differs from `serverName`, and rejected outright when missing. - [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] - [MinLength(1)] - [JsonPropertyName("originServerName")] - public string OriginServerName { get; set; } = string.Empty; +/// Identifiers and raw MCP CreateMessageRequest params used to run a sampling inference. +[Experimental(Diagnostics.Experimental)] +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 JsonElement McpRequestId { get; set; } - /// MCP server hosting the tool. - [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] - [MinLength(1)] + /// 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")] + public McpExecuteSamplingRequest Request { get => field ??= new(); set; } + + /// Caller-provided unique identifier for this sampling execution. Use this same ID with cancelSamplingExecution to cancel the in-flight call. Must be unique within the session for the lifetime of the call. + [JsonPropertyName("requestId")] + public string RequestId { get; set; } = string.Empty; + + /// Name of the MCP server that initiated the sampling request. [JsonPropertyName("serverName")] public string ServerName { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; - - /// MCP tool name. - [JsonPropertyName("toolName")] - public string ToolName { get; set; } = string.Empty; } -/// Host context advertised to MCP App guests. +/// Indicates whether an in-flight sampling execution with the given requestId was found and cancelled. [Experimental(Diagnostics.Experimental)] -public sealed class McpAppsSetHostContextDetails +public sealed class McpCancelSamplingExecutionResult { - /// Display modes the host supports. - [JsonPropertyName("availableDisplayModes")] - public IList? AvailableDisplayModes { get; set; } - - /// Current display mode (SEP-1865). - [JsonPropertyName("displayMode")] - public McpAppsSetHostContextDetailsDisplayMode? DisplayMode { get; set; } - - /// BCP-47 locale, e.g. 'en-US'. - [JsonPropertyName("locale")] - public string? Locale { get; set; } - - /// Platform type for responsive design. - [JsonPropertyName("platform")] - public McpAppsSetHostContextDetailsPlatform? Platform { get; set; } - - /// UI theme preference per SEP-1865. - [JsonPropertyName("theme")] - public McpAppsSetHostContextDetailsTheme? Theme { get; set; } - - /// IANA timezone, e.g. 'America/New_York'. - [JsonPropertyName("timeZone")] - public string? TimeZone { get; set; } - - /// Host application identifier. - [JsonPropertyName("userAgent")] - public string? UserAgent { get; set; } + /// True if an in-flight execution with the given requestId was found and signalled to cancel. False when no such execution is in flight (already completed, never started, or cancelled by another caller). + [JsonPropertyName("cancelled")] + public bool Cancelled { get; set; } } -/// Host context to advertise to MCP App guests. +/// The requestId previously passed to executeSampling that should be cancelled. [Experimental(Diagnostics.Experimental)] -internal sealed class McpAppsSetHostContextRequest +internal sealed class McpCancelSamplingExecutionParams { - /// Host context advertised to MCP App guests. - [JsonPropertyName("context")] - public McpAppsSetHostContextDetails Context { get => field ??= new(); set; } + /// The requestId previously passed to executeSampling that should be cancelled. + [JsonPropertyName("requestId")] + public string RequestId { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Current host context. +/// Env-value mode recorded on the session after the update. [Experimental(Diagnostics.Experimental)] -public sealed class McpAppsHostContextDetails +public sealed class McpSetEnvValueModeResult { - /// Display modes the host supports. - [JsonPropertyName("availableDisplayModes")] - public IList? AvailableDisplayModes { get; set; } - - /// Current display mode (SEP-1865). - [JsonPropertyName("displayMode")] - public McpAppsHostContextDetailsDisplayMode? DisplayMode { get; set; } - - /// BCP-47 locale, e.g. 'en-US'. - [JsonPropertyName("locale")] - public string? Locale { get; set; } - - /// Platform type for responsive design. - [JsonPropertyName("platform")] - public McpAppsHostContextDetailsPlatform? Platform { get; set; } - - /// UI theme preference per SEP-1865. - [JsonPropertyName("theme")] - public McpAppsHostContextDetailsTheme? Theme { get; set; } + /// Mode recorded on the session after the update. + [JsonPropertyName("mode")] + public McpSetEnvValueModeDetails Mode { get; set; } +} - /// IANA timezone, e.g. 'America/New_York'. - [JsonPropertyName("timeZone")] - public string? TimeZone { get; set; } +/// Mode controlling how MCP server env values are resolved (`direct` or `indirect`). +[Experimental(Diagnostics.Experimental)] +internal sealed class McpSetEnvValueModeParams +{ + /// 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". + [JsonPropertyName("mode")] + public McpSetEnvValueModeDetails Mode { get; set; } - /// Host application identifier. - [JsonPropertyName("userAgent")] - public string? UserAgent { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Current host context advertised to MCP App guests. +/// Indicates whether the auto-managed `github` MCP server was removed (false when nothing to remove). [Experimental(Diagnostics.Experimental)] -public sealed class McpAppsHostContext +public sealed class McpRemoveGitHubResult { - /// Current host context. - [JsonPropertyName("context")] - public McpAppsHostContextDetails Context { get => field ??= new(); set; } + /// True when the auto-managed `github` MCP server was removed; false when no removal happened (e.g. user has explicitly configured a `github` server, or the server was not registered). + [JsonPropertyName("removed")] + public bool Removed { get; set; } } /// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionMcpAppsGetHostContextRequest +internal sealed class SessionMcpRemoveGitHubRequest { /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Capability negotiation snapshot. +/// Result of configuring GitHub MCP. [Experimental(Diagnostics.Experimental)] -public sealed class McpAppsDiagnoseCapability +internal sealed class McpConfigureGitHubResult { - /// Whether the runtime advertises `extensions.io.modelcontextprotocol/ui` to MCP servers. - [JsonPropertyName("advertised")] - public bool Advertised { get; set; } + /// Whether GitHub MCP configuration changed. + [JsonPropertyName("changed")] + public bool Changed { get; set; } +} - /// Whether the MCP_APPS feature flag (or COPILOT_MCP_APPS env override) is on. - [JsonPropertyName("featureFlagEnabled")] - public bool FeatureFlagEnabled { get; set; } +/// Opaque auth info used to configure GitHub MCP. +[Experimental(Diagnostics.Experimental)] +internal sealed class McpConfigureGitHubRequest +{ + /// Opaque runtime auth info for GitHub MCP configuration. Marked internal: an in-process runtime shape (configureGitHubMcp is a no-op over the wire). + [JsonInclude] + [JsonPropertyName("authInfo")] + internal JsonElement AuthInfo { get; set; } - /// Whether the session has the `mcp-apps` capability. - [JsonPropertyName("sessionHasMcpApps")] - public bool SessionHasMcpApps { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// What the server returned for this session. +/// Server name and optional configuration for an individual MCP server start. Omit `config` for a config-free start-by-name of an already-configured server. [Experimental(Diagnostics.Experimental)] -public sealed class McpAppsDiagnoseServer +internal sealed class McpStartServerRequest { - /// Whether the named server is currently connected. - [JsonPropertyName("connected")] - public bool Connected { get; set; } - - /// Up to 5 tool names with `_meta.ui` for quick inspection. - [JsonPropertyName("sampleToolNames")] - public IList SampleToolNames { get => field ??= []; set; } + /// MCP server configuration (stdio process or remote HTTP/SSE). Omit to start the server with its already-registered configuration (config-free start-by-name). + [JsonPropertyName("config")] + public JsonElement? Config { get; set; } - /// Total tools returned by the server's tools/list. - [JsonPropertyName("toolCount")] - public double ToolCount { get; set; } + /// Name of the MCP server to start. + [JsonPropertyName("serverName")] + public string ServerName { get; set; } = string.Empty; - /// Tools whose `_meta.ui` is populated (resourceUri and/or visibility set). - [JsonPropertyName("toolsWithUiMeta")] - public double ToolsWithUiMeta { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Diagnostic snapshot of MCP Apps wiring for the named server. +/// Server name and optional replacement configuration for an individual MCP server restart. Omit `config` for a config-free restart-by-name of an already-configured server. [Experimental(Diagnostics.Experimental)] -public sealed class McpAppsDiagnoseResult +internal sealed class McpRestartServerRequest { - /// Capability negotiation snapshot. - [JsonPropertyName("capability")] - public McpAppsDiagnoseCapability Capability { get => field ??= new(); set; } + /// Replacement MCP server configuration (stdio process or remote HTTP/SSE). Omit to restart the server with its already-registered configuration (config-free restart-by-name). + [JsonPropertyName("config")] + public JsonElement? Config { get; set; } - /// What the server returned for this session. - [JsonPropertyName("server")] - public McpAppsDiagnoseServer Server { get => field ??= new(); set; } + /// Name of the MCP server to restart. + [JsonPropertyName("serverName")] + public string ServerName { get; set; } = string.Empty; + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// MCP server to diagnose MCP Apps wiring for. +/// Server name for an individual MCP server stop. [Experimental(Diagnostics.Experimental)] -internal sealed class McpAppsDiagnoseRequest +internal sealed class McpStopServerRequest { - /// MCP server to probe. - [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] - [MinLength(1)] + /// Name of the MCP server to stop. [JsonPropertyName("serverName")] public string ServerName { get; set; } = string.Empty; @@ -6928,173 +7247,187 @@ internal sealed class McpAppsDiagnoseRequest public string SessionId { get; set; } = string.Empty; } -/// MCP resource content with URI, optional MIME type, text or base64 blob, and resource metadata. +/// Registration parameters for an external MCP client. [Experimental(Diagnostics.Experimental)] -public sealed class McpResourceContent +internal sealed class McpRegisterExternalClientRequest { - /// Resource-level metadata (CSP, permissions, etc.). - [JsonPropertyName("_meta")] - public IDictionary? Meta { get; set; } + /// In-process MCP Client instance. Marked internal: cannot be serialized across the JSON-RPC boundary. + [JsonInclude] + [JsonPropertyName("client")] + internal JsonElement Client { get; set; } - /// Base64-encoded binary content. - [JsonPropertyName("blob")] - public string? Blob { get; set; } + /// In-process server config (MCPServerConfig) paired with the in-process client/transport. Marked internal alongside its companions. + [JsonInclude] + [JsonPropertyName("config")] + internal JsonElement Config { get; set; } - /// MIME type of the content. - [JsonPropertyName("mimeType")] - public string? MimeType { get; set; } + /// Logical server name for the external client. + [JsonPropertyName("serverName")] + public string ServerName { get; set; } = string.Empty; - /// Text content (e.g. HTML). - [JsonPropertyName("text")] - public string? Text { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; - /// The resource URI. - [JsonPropertyName("uri")] - public string Uri { get; set; } = string.Empty; + /// In-process MCP Transport instance. Marked internal: cannot be serialized across the JSON-RPC boundary. + [JsonInclude] + [JsonPropertyName("transport")] + internal JsonElement Transport { get; set; } } -/// Resource contents returned by the MCP server. +/// Server name identifying the external client to remove. [Experimental(Diagnostics.Experimental)] -public sealed class McpResourcesReadResult +internal sealed class McpUnregisterExternalClientRequest { - /// Resource contents returned by the server. - [JsonPropertyName("contents")] - public IList Contents { get => field ??= []; set; } + /// Server name of the external client to unregister. + [JsonPropertyName("serverName")] + public string ServerName { get; set; } = string.Empty; + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// MCP server and resource URI to fetch. +/// Whether the named MCP server is running. [Experimental(Diagnostics.Experimental)] -internal sealed class McpResourcesReadRequest +public sealed class McpIsServerRunningResult { - /// Name of the MCP server hosting the resource. - [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] - [MinLength(1)] + /// True if the server has an active client and transport. + [JsonPropertyName("running")] + public bool Running { get; set; } +} + +/// Server name to check running status for. +[Experimental(Diagnostics.Experimental)] +internal sealed class McpIsServerRunningRequest +{ + /// Name of the MCP server to check. [JsonPropertyName("serverName")] public string ServerName { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; - - /// Resource URI. - [JsonPropertyName("uri")] - public string Uri { get; set; } = string.Empty; } -/// Standard MCP resource annotations plus preserved non-standard annotation fields. +/// Indicates whether the pending MCP OAuth response was accepted. [Experimental(Diagnostics.Experimental)] -public sealed class McpResourceAnnotations +public sealed class McpOauthHandlePendingResult { - /// Server-provided non-standard annotation fields preserved from the MCP response. - [JsonPropertyName("additionalProperties")] - public IDictionary? AdditionalProperties { get; set; } - - /// Intended audience roles for this resource. - [JsonPropertyName("audience")] - public IList? Audience { get; set; } - - /// Last-modified timestamp hint. - [JsonPropertyName("lastModified")] - public string? LastModified { get; set; } - - /// Priority hint for model/client use. - [JsonPropertyName("priority")] - public double? Priority { get; set; } + /// Whether the response was accepted. False if the request was unknown, timed out, or already resolved. + [JsonPropertyName("success")] + public bool Success { get; set; } } -/// A resource icon descriptor plus preserved non-standard icon fields. +/// Host response to the pending OAuth request. +/// Polymorphic base type discriminated by kind. [Experimental(Diagnostics.Experimental)] -public sealed class McpResourceIcon +[JsonPolymorphic( + TypeDiscriminatorPropertyName = "kind", + UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] +[JsonDerivedType(typeof(McpOauthPendingRequestResponseToken), "token")] +[JsonDerivedType(typeof(McpOauthPendingRequestResponseCancelled), "cancelled")] +public partial class McpOauthPendingRequestResponse { - /// Server-provided non-standard icon fields preserved from the MCP response. - [JsonPropertyName("additionalProperties")] - public IDictionary? AdditionalProperties { get; set; } + /// The type discriminator. + [JsonPropertyName("kind")] + public virtual string Kind { get; set; } = string.Empty; +} - /// Icon MIME type, when known. - [JsonPropertyName("mimeType")] - public string? MimeType { get; set; } - /// Icon sizes hint. - [JsonPropertyName("sizes")] - public string? Sizes { get; set; } +/// The token variant of . +[Experimental(Diagnostics.Experimental)] +public partial class McpOauthPendingRequestResponseToken : McpOauthPendingRequestResponse +{ + /// + [JsonIgnore] + public override string Kind => "token"; - /// Icon URI. - [JsonPropertyName("src")] - public string Src { get; set; } = string.Empty; + /// Access token acquired by the SDK host. + [JsonPropertyName("accessToken")] + public required string AccessToken { get; set; } - /// Theme hint for this icon. - [JsonPropertyName("theme")] - public string? Theme { get; set; } + /// Token lifetime in seconds, if known. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("expiresIn")] + public long? ExpiresIn { get; set; } + + /// OAuth token type. Defaults to Bearer when omitted. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("tokenType")] + public string? TokenType { get; set; } } -/// An MCP resource descriptor (spec `Resource`): URI, name, and optional title, description, MIME type, size, icons, annotations, and metadata. Server-provided fields outside the standard descriptor shape are exposed under `additionalProperties`. +/// The cancelled variant of . [Experimental(Diagnostics.Experimental)] -public sealed class McpResource +public partial class McpOauthPendingRequestResponseCancelled : McpOauthPendingRequestResponse { - /// Resource-level metadata. - [JsonPropertyName("_meta")] - public IDictionary? Meta { get; set; } + /// + [JsonIgnore] + public override string Kind => "cancelled"; +} - /// Server-provided non-standard descriptor fields preserved from the MCP response. - [JsonPropertyName("additionalProperties")] - public IDictionary? AdditionalProperties { get; set; } +/// Pending MCP OAuth request ID and host-provided token or cancellation response. +[Experimental(Diagnostics.Experimental)] +internal sealed class McpOauthHandlePendingRequest +{ + /// OAuth request identifier from the mcp.oauth_required event. + [JsonPropertyName("requestId")] + public string RequestId { get; set; } = string.Empty; - /// Model/client annotations associated with this resource. - [JsonPropertyName("annotations")] - public McpResourceAnnotations? Annotations { get; set; } + /// Host response to the pending OAuth request. + [JsonPropertyName("result")] + public McpOauthPendingRequestResponse Result { get => field ??= new(); set; } - /// Optional description of what this resource represents. - [JsonPropertyName("description")] - public string? Description { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// Icons associated with this resource. - [JsonPropertyName("icons")] - public IList? Icons { get; set; } - - /// MIME type of the resource, if known. - [JsonPropertyName("mimeType")] - public string? MimeType { get; set; } +/// OAuth authorization URL the caller should open, or empty when cached tokens already authenticated the server. +[Experimental(Diagnostics.Experimental)] +public sealed class McpOauthLoginResult +{ + /// URL the caller should open in a browser to complete OAuth. Omitted when cached tokens were still valid and no browser interaction was needed — the server is already reconnected in that case. When present, the runtime starts the callback listener before returning and continues the flow in the background; completion is signaled via session.mcp_server_status_changed. + [Url] + [StringSyntax(StringSyntaxAttribute.Uri)] + [JsonPropertyName("authorizationUrl")] + public string? AuthorizationUrl { get; set; } +} - /// The programmatic name of the resource. - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; +/// Remote MCP server name and optional overrides controlling reauthentication, OAuth client display name, callback success-page copy, and static OAuth client selection. +[Experimental(Diagnostics.Experimental)] +internal sealed class McpOauthLoginRequest +{ + /// Optional override for the body text shown on the OAuth loopback callback success page. When omitted, the runtime applies a neutral fallback; callers driving interactive auth should pass surface-specific copy telling the user where to return. + [JsonPropertyName("callbackSuccessMessage")] + public string? CallbackSuccessMessage { get; set; } - /// Resource size in bytes, when known. - [JsonPropertyName("size")] - public long? Size { get; set; } + /// Optional OAuth client ID override for this login. When set, the runtime uses this pre-registered static client instead of dynamic client registration. + [JsonPropertyName("clientId")] + public string? ClientId { get; set; } - /// Optional human-readable display title. - [JsonPropertyName("title")] - public string? Title { get; set; } + /// Optional override for the OAuth client display name shown on the consent screen. Applies to newly registered dynamic clients only — existing registrations keep the name they were created with. When omitted, the runtime applies a neutral fallback; callers driving interactive auth should pass their own surface-specific label so the consent screen matches the product the user sees. + [JsonPropertyName("clientName")] + public string? ClientName { get; set; } - /// The resource URI (e.g. ui://... or file:///...). - [JsonPropertyName("uri")] - public string Uri { get; set; } = string.Empty; -} + /// Optional OAuth client secret override for this login. The runtime treats this as an ephemeral host-owned secret, uses it for this authentication attempt and does not persist it. + [JsonPropertyName("clientSecret")] + public string? ClientSecret { get; set; } -/// One page of resources advertised by the named MCP server. -[Experimental(Diagnostics.Experimental)] -public sealed class McpResourcesListResult -{ - /// Opaque cursor for the next page, if the server has more resources. - [JsonPropertyName("nextCursor")] - public string? NextCursor { get; set; } + /// When true, clears any cached OAuth token for the server and runs a full new authorization. Use when the user explicitly wants to switch accounts or believes their session is stuck. + [JsonPropertyName("forceReauth")] + public bool? ForceReauth { get; set; } - /// Resources advertised by the server (proxied MCP `resources/list`). - [JsonPropertyName("resources")] - public IList Resources { get => field ??= []; set; } -} + /// Optional OAuth grant type override for this login. Defaults to the server configuration, or authorization_code when no grant type is specified. + [JsonPropertyName("grantType")] + public McpOauthLoginGrantType? GrantType { get; set; } -/// MCP server whose resources to enumerate. -[Experimental(Diagnostics.Experimental)] -internal sealed class McpResourcesListRequest -{ - /// Opaque MCP pagination cursor from a prior `nextCursor` value. - [JsonPropertyName("cursor")] - public string? Cursor { get; set; } + /// Optional override indicating whether the static OAuth client is public. When false, the runtime treats it as confidential and uses the per-login clientSecret if provided, otherwise retrieving the client secret from the MCP OAuth secret store. + [JsonPropertyName("publicClient")] + public bool? PublicClient { get; set; } - /// Name of the MCP server whose resources to enumerate. + /// Name of the remote MCP server to authenticate. [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] [MinLength(1)] @@ -7106,5942 +7439,8556 @@ internal sealed class McpResourcesListRequest public string SessionId { get; set; } = string.Empty; } -/// An MCP resource template descriptor (spec `ResourceTemplate`): an RFC 6570 URI template, name, and optional title, description, MIME type, icons, annotations, and metadata. Server-provided fields outside the standard descriptor shape are exposed under `additionalProperties`. +/// Indicates whether the pending MCP OAuth response was accepted. [Experimental(Diagnostics.Experimental)] -public sealed class McpResourceTemplate +public sealed class McpOauthRespondResult { - /// Resource-template-level metadata. - [JsonPropertyName("_meta")] - public IDictionary? Meta { get; set; } - - /// Server-provided non-standard descriptor fields preserved from the MCP response. - [JsonPropertyName("additionalProperties")] - public IDictionary? AdditionalProperties { get; set; } + /// Whether the response was accepted. False if the request was unknown, timed out, or already resolved. + [JsonPropertyName("success")] + public bool Success { get; set; } +} - /// Model/client annotations associated with this template. - [JsonPropertyName("annotations")] - public McpResourceAnnotations? Annotations { get; set; } +/// Pending MCP OAuth request id to respond to. +[Experimental(Diagnostics.Experimental)] +internal sealed class McpOauthRespondRequest +{ + /// OAuth request identifier from the mcp.oauth_required event. + [JsonPropertyName("requestId")] + public string RequestId { get; set; } = string.Empty; - /// Optional description of what this template is for. - [JsonPropertyName("description")] - public string? Description { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// Icons associated with resources matching this template. - [JsonPropertyName("icons")] - public IList? Icons { get; set; } +/// Indicates whether the pending MCP headers refresh response was accepted. +[Experimental(Diagnostics.Experimental)] +public sealed class McpHeadersHandlePendingHeadersRefreshRequestResult +{ + /// Whether the response was accepted. False if the request was unknown, timed out, or already resolved. + [JsonPropertyName("success")] + public bool Success { get; set; } +} - /// MIME type for resources matching this template, if uniform. - [JsonPropertyName("mimeType")] - public string? MimeType { get; set; } +/// Host response: supply dynamic headers or decline this refresh. +/// Polymorphic base type discriminated by kind. +[Experimental(Diagnostics.Experimental)] +[JsonPolymorphic( + TypeDiscriminatorPropertyName = "kind", + UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] +[JsonDerivedType(typeof(McpHeadersHandlePendingHeadersRefreshRequestHeaders), "headers")] +[JsonDerivedType(typeof(McpHeadersHandlePendingHeadersRefreshRequestNone), "none")] +public partial class McpHeadersHandlePendingHeadersRefreshRequest +{ + /// The type discriminator. + [JsonPropertyName("kind")] + public virtual string Kind { get; set; } = string.Empty; +} - /// The programmatic name of the resource template. - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; - /// Optional human-readable display title. - [JsonPropertyName("title")] - public string? Title { get; set; } +/// The headers variant of . +[Experimental(Diagnostics.Experimental)] +public partial class McpHeadersHandlePendingHeadersRefreshRequestHeaders : McpHeadersHandlePendingHeadersRefreshRequest +{ + /// + [JsonIgnore] + public override string Kind => "headers"; - /// An RFC 6570 URI template for constructing resource URIs. - [JsonPropertyName("uriTemplate")] - public string UriTemplate { get; set; } = string.Empty; + /// Headers to overlay onto the MCP request. Dynamic headers override static config headers but do not replace SDK-managed request headers. + [JsonPropertyName("headers")] + public required IDictionary Headers { get; set; } } -/// One page of resource templates advertised by the named MCP server. +/// The none variant of . [Experimental(Diagnostics.Experimental)] -public sealed class McpResourcesListTemplatesResult +public partial class McpHeadersHandlePendingHeadersRefreshRequestNone : McpHeadersHandlePendingHeadersRefreshRequest { - /// Opaque cursor for the next page, if the server has more resource templates. - [JsonPropertyName("nextCursor")] - public string? NextCursor { get; set; } - - /// Resource templates advertised by the server (proxied MCP `resources/templates/list`). - [JsonPropertyName("resourceTemplates")] - public IList ResourceTemplates { get => field ??= []; set; } + /// + [JsonIgnore] + public override string Kind => "none"; } -/// MCP server whose resource templates to enumerate. +/// MCP headers refresh request id and the host response. [Experimental(Diagnostics.Experimental)] -internal sealed class McpResourcesListTemplatesRequest +internal sealed class McpHeadersHandlePendingHeadersRefreshRequestRequest { - /// Opaque MCP pagination cursor from a prior `nextCursor` value. - [JsonPropertyName("cursor")] - public string? Cursor { get; set; } + /// Headers refresh request identifier from mcp.headers_refresh_required. + [JsonPropertyName("requestId")] + public string RequestId { get; set; } = string.Empty; - /// Name of the MCP server whose resource templates to enumerate. - [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] - [MinLength(1)] - [JsonPropertyName("serverName")] - public string ServerName { get; set; } = string.Empty; + /// Host response: supply dynamic headers or decline this refresh. + [JsonPropertyName("result")] + public McpHeadersHandlePendingHeadersRefreshRequest Result { get => field ??= new(); set; } /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Session plugin metadata, with name, marketplace, optional version, and enabled state. +/// MCP Apps resource content with URI, optional MIME type, text or base64 blob, and resource metadata. [Experimental(Diagnostics.Experimental)] -public sealed class Plugin +public sealed class McpAppsResourceContent { - /// Whether the plugin is currently enabled. - [JsonPropertyName("enabled")] - public bool Enabled { get; set; } + /// Resource-level metadata (CSP, permissions, etc.). + [JsonPropertyName("_meta")] + public IDictionary? Meta { get; set; } - /// Marketplace the plugin came from. - [JsonPropertyName("marketplace")] - public string Marketplace { get; set; } = string.Empty; + /// Base64-encoded binary content. + [JsonPropertyName("blob")] + public string? Blob { get; set; } - /// Plugin name. - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; + /// MIME type of the content. + [JsonPropertyName("mimeType")] + public string? MimeType { get; set; } - /// Installed version. - [JsonPropertyName("version")] - public string? Version { get; set; } + /// Text content (e.g. HTML). + [JsonPropertyName("text")] + public string? Text { get; set; } + + /// The resource URI (typically ui://...). + [JsonPropertyName("uri")] + public string Uri { get; set; } = string.Empty; } -/// Plugins installed for the session, with their enabled state and version metadata. +/// Resource contents returned by the MCP server. [Experimental(Diagnostics.Experimental)] -public sealed class PluginList +public sealed class McpAppsReadResourceResult { - /// Installed plugins. - [JsonPropertyName("plugins")] - public IList Plugins { get => field ??= []; set; } + /// Resource contents returned by the server. + [JsonPropertyName("contents")] + public IList Contents { get => field ??= []; set; } } -/// Identifies the target session. +/// MCP server and resource URI to fetch. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionPluginsListRequest +internal sealed class McpAppsReadResourceRequest { + /// Name of the MCP server hosting the resource. + [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] + [MinLength(1)] + [JsonPropertyName("serverName")] + public string ServerName { get; set; } = string.Empty; + /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; + + /// Resource URI (typically ui://...). + [JsonPropertyName("uri")] + public string Uri { get; set; } = string.Empty; } -/// Optional flags controlling which side effects the reload performs. +/// App-callable tools from the named MCP server. [Experimental(Diagnostics.Experimental)] -public sealed class PluginsReloadRequest +public sealed class McpAppsListToolsResult { - /// When true, skip repo-level hooks during the hook reload. Use before folder trust is confirmed; load them post-trust via `sessions.loadDeferredRepoHooks`. - [JsonPropertyName("deferRepoHooks")] - public bool? DeferRepoHooks { get; set; } - - /// Re-run custom-agent discovery after refreshing plugins. Defaults to true. - [JsonPropertyName("reloadCustomAgents")] - public bool? ReloadCustomAgents { get; set; } - - /// Re-discover and relaunch subprocess extensions (including plugin-shipped extensions) after refreshing plugins. Defaults to true. Has no effect when the session has no active extension controller (e.g. extensions were not requested for the session). - [JsonPropertyName("reloadExtensions")] - public bool? ReloadExtensions { get; set; } + /// App-callable tools from the server. + [JsonPropertyName("tools")] + public IList> Tools { get => field ??= []; set; } +} - /// Re-load user, plugin, and (subject to `deferRepoHooks`) repo hooks. Defaults to true. Has no effect when the host has not registered a hook reloader (e.g. remote sessions). - [JsonPropertyName("reloadHooks")] - public bool? ReloadHooks { get; set; } - - /// Reload MCP server connections after refreshing plugins. Defaults to true. - [JsonPropertyName("reloadMcp")] - public bool? ReloadMcp { get; set; } -} - -/// Optional flags controlling which side effects the reload performs. +/// MCP server to list app-callable tools for. [Experimental(Diagnostics.Experimental)] -internal sealed class PluginsReloadRequestWithSession +internal sealed class McpAppsListToolsRequest { - /// When true, skip repo-level hooks during the hook reload. Use before folder trust is confirmed; load them post-trust via `sessions.loadDeferredRepoHooks`. - [JsonPropertyName("deferRepoHooks")] - public bool? DeferRepoHooks { get; set; } - - /// Re-run custom-agent discovery after refreshing plugins. Defaults to true. - [JsonPropertyName("reloadCustomAgents")] - public bool? ReloadCustomAgents { get; set; } - - /// Re-discover and relaunch subprocess extensions (including plugin-shipped extensions) after refreshing plugins. Defaults to true. Has no effect when the session has no active extension controller (e.g. extensions were not requested for the session). - [JsonPropertyName("reloadExtensions")] - public bool? ReloadExtensions { get; set; } - - /// Re-load user, plugin, and (subject to `deferRepoHooks`) repo hooks. Defaults to true. Has no effect when the host has not registered a hook reloader (e.g. remote sessions). - [JsonPropertyName("reloadHooks")] - public bool? ReloadHooks { get; set; } + /// **Required.** Server whose ui:// view issued the request. Per SEP-1865 ('callable by the app from this server only'), the call is rejected when this differs from `serverName`, and rejected outright when missing. + [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] + [MinLength(1)] + [JsonPropertyName("originServerName")] + public string OriginServerName { get; set; } = string.Empty; - /// Reload MCP server connections after refreshing plugins. Defaults to true. - [JsonPropertyName("reloadMcp")] - public bool? ReloadMcp { get; set; } + /// MCP server hosting the app. + [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] + [MinLength(1)] + [JsonPropertyName("serverName")] + public string ServerName { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Short-lived, rotating credential the caller must send on every request, in addition to `apiKey` if one is present. Omitted when the endpoint does not require one. +/// MCP server, tool name, and arguments to invoke from an MCP App view. [Experimental(Diagnostics.Experimental)] -public sealed class ProviderSessionToken +internal sealed class McpAppsCallToolRequest { - /// When the token expires, if known. Callers should refresh by calling `getEndpoint` again before this time, or reactively on any 401/403 response from `baseUrl`. - [JsonPropertyName("expiresAt")] - public DateTimeOffset? ExpiresAt { get; set; } + /// Tool arguments. + [JsonPropertyName("arguments")] + public IDictionary? Arguments { get; set; } - /// HTTP header name the token must be sent under. - [JsonPropertyName("header")] - public string Header { get; set; } = string.Empty; + /// **Required.** Server whose ui:// view issued the request. Per SEP-1865 ('callable by the app from this server only'), the call is rejected when this differs from `serverName`, and rejected outright when missing. + [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] + [MinLength(1)] + [JsonPropertyName("originServerName")] + public string OriginServerName { get; set; } = string.Empty; - /// The model the token is bound to, when applicable. When set, the token is only valid for requests against this model. - [JsonPropertyName("model")] - public string? Model { get; set; } + /// MCP server hosting the tool. + [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] + [MinLength(1)] + [JsonPropertyName("serverName")] + public string ServerName { get; set; } = string.Empty; - /// The short-lived token value. - [JsonPropertyName("token")] - public string Token { get; set; } = string.Empty; + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; + + /// MCP tool name. + [JsonPropertyName("toolName")] + public string ToolName { get; set; } = string.Empty; } -/// A snapshot of the provider endpoint the session is currently configured to talk to. +/// Host context advertised to MCP App guests. [Experimental(Diagnostics.Experimental)] -public sealed class ProviderEndpoint +public sealed class McpAppsSetHostContextDetails { - /// A credential the caller should use with this endpoint. Omitted only when the endpoint accepts unauthenticated requests. - [JsonPropertyName("apiKey")] - public string? ApiKey { get; set; } - - /// Base URL to pass to the LLM client library. - [Url] - [StringSyntax(StringSyntaxAttribute.Uri)] - [JsonPropertyName("baseUrl")] - public string BaseUrl { get; set; } = string.Empty; + /// Display modes the host supports. + [JsonPropertyName("availableDisplayModes")] + public IList? AvailableDisplayModes { get; set; } - /// HTTP headers the caller must include on every outbound request. - [JsonPropertyName("headers")] - public IDictionary Headers { get => field ??= new Dictionary(); set; } + /// Current display mode (SEP-1865). + [JsonPropertyName("displayMode")] + public McpAppsSetHostContextDetailsDisplayMode? DisplayMode { get; set; } - /// Short-lived, rotating credential the caller must send on every request, in addition to `apiKey` if one is present. Omitted when the endpoint does not require one. - [JsonPropertyName("sessionToken")] - public ProviderSessionToken? SessionToken { get; set; } + /// BCP-47 locale, e.g. 'en-US'. + [JsonPropertyName("locale")] + public string? Locale { get; set; } - /// Transport to be used for provider requests. - [JsonPropertyName("transport")] - public ProviderEndpointTransport? Transport { get; set; } + /// Platform type for responsive design. + [JsonPropertyName("platform")] + public McpAppsSetHostContextDetailsPlatform? Platform { get; set; } - /// Provider family. Matches the `type` field of a BYOK provider config. - [JsonPropertyName("type")] - public ProviderEndpointType Type { get; set; } + /// UI theme preference per SEP-1865. + [JsonPropertyName("theme")] + public McpAppsSetHostContextDetailsTheme? Theme { get; set; } - /// Wire API to be used, when required for the provider type. - [JsonPropertyName("wireApi")] - public ProviderEndpointWireApi? WireApi { get; set; } -} + /// IANA timezone, e.g. 'America/New_York'. + [JsonPropertyName("timeZone")] + public string? TimeZone { get; set; } -/// Optional model identifier to scope the endpoint snapshot to. -[Experimental(Diagnostics.Experimental)] -public sealed class ProviderGetEndpointRequest -{ - /// Model identifier the caller intends to use against the returned endpoint. Used to pick the correct wire shape. Omit to use whichever model the session is currently using. - [JsonPropertyName("modelId")] - public string? ModelId { get; set; } + /// Host application identifier. + [JsonPropertyName("userAgent")] + public string? UserAgent { get; set; } } -/// Optional model identifier to scope the endpoint snapshot to. +/// Host context to advertise to MCP App guests. [Experimental(Diagnostics.Experimental)] -internal sealed class ProviderGetEndpointRequestWithSession +internal sealed class McpAppsSetHostContextRequest { - /// Model identifier the caller intends to use against the returned endpoint. Used to pick the correct wire shape. Omit to use whichever model the session is currently using. - [JsonPropertyName("modelId")] - public string? ModelId { get; set; } + /// Host context advertised to MCP App guests. + [JsonPropertyName("context")] + public McpAppsSetHostContextDetails Context { get => field ??= new(); set; } /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// The selectable model entries synthesized for the models added by this call. -[Experimental(Diagnostics.Experimental)] -public sealed class ProviderAddResult -{ - /// Synthesized selectable model entries for the newly added BYOK models, each under its provider-qualified selection id (`provider/id`). Empty when only providers were added. - [JsonPropertyName("models")] - public IList Models { get => field ??= []; set; } -} - -/// A BYOK model definition referencing a named provider. +/// Current host context. [Experimental(Diagnostics.Experimental)] -public sealed class ProviderModelConfig +public sealed class McpAppsHostContextDetails { - /// Optional capability overrides (vision, tool_calls, reasoning, etc.). - [JsonPropertyName("capabilities")] - public ModelCapabilitiesOverride? Capabilities { get; set; } - - /// Provider-local model id, unique within its provider. The session-wide selection id (shown in the model list and passed to switchTo) is the provider-qualified `provider/id`. - [JsonPropertyName("id")] - public string Id { get; set; } = string.Empty; + /// Display modes the host supports. + [JsonPropertyName("availableDisplayModes")] + public IList? AvailableDisplayModes { get; set; } - /// Maximum context window tokens for the model. - [JsonPropertyName("maxContextWindowTokens")] - public double? MaxContextWindowTokens { get; set; } + /// Current display mode (SEP-1865). + [JsonPropertyName("displayMode")] + public McpAppsHostContextDetailsDisplayMode? DisplayMode { get; set; } - /// Maximum output tokens for the model. - [JsonPropertyName("maxOutputTokens")] - public double? MaxOutputTokens { get; set; } + /// BCP-47 locale, e.g. 'en-US'. + [JsonPropertyName("locale")] + public string? Locale { get; set; } - /// Maximum prompt/input tokens for the model. - [JsonPropertyName("maxPromptTokens")] - public double? MaxPromptTokens { get; set; } + /// Platform type for responsive design. + [JsonPropertyName("platform")] + public McpAppsHostContextDetailsPlatform? Platform { get; set; } - /// Well-known base model id used for behavior/capability/config lookup. Defaults to `id`. - [JsonPropertyName("modelId")] - public string? ModelId { get; set; } + /// UI theme preference per SEP-1865. + [JsonPropertyName("theme")] + public McpAppsHostContextDetailsTheme? Theme { get; set; } - /// Display name for model pickers. Defaults to the provider-qualified selection id (`provider/id`). - [JsonPropertyName("name")] - public string? Name { get; set; } + /// IANA timezone, e.g. 'America/New_York'. + [JsonPropertyName("timeZone")] + public string? TimeZone { get; set; } - /// Name of the NamedProviderConfig that serves this model. - [JsonPropertyName("provider")] - public string Provider { get; set; } = string.Empty; + /// Host application identifier. + [JsonPropertyName("userAgent")] + public string? UserAgent { get; set; } +} - /// The model name sent to the provider API for inference. Defaults to `id`. - [JsonPropertyName("wireModel")] - public string? WireModel { get; set; } +/// Current host context advertised to MCP App guests. +[Experimental(Diagnostics.Experimental)] +public sealed class McpAppsHostContext +{ + /// Current host context. + [JsonPropertyName("context")] + public McpAppsHostContextDetails Context { get => field ??= new(); set; } } -/// Azure-specific provider options. +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -public sealed class ProviderConfigAzure +internal sealed class SessionMcpAppsGetHostContextRequest { - /// API version. When set, uses the versioned deployment route. When omitted, uses the GA versionless v1 route. - [JsonPropertyName("apiVersion")] - public string? ApiVersion { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// A named BYOK provider connection (transport + credentials). +/// Capability negotiation snapshot. [Experimental(Diagnostics.Experimental)] -public sealed class NamedProviderConfig +public sealed class McpAppsDiagnoseCapability { - /// API key. Optional for local providers like Ollama. - [JsonPropertyName("apiKey")] - public string? ApiKey { get; set; } + /// Whether the runtime advertises `extensions.io.modelcontextprotocol/ui` to MCP servers. + [JsonPropertyName("advertised")] + public bool Advertised { get; set; } - /// Azure-specific provider options. - [JsonPropertyName("azure")] - public ProviderConfigAzure? Azure { get; set; } + /// Whether the MCP_APPS feature flag (or COPILOT_MCP_APPS env override) is on. + [JsonPropertyName("featureFlagEnabled")] + public bool FeatureFlagEnabled { get; set; } - /// API endpoint URL. - [JsonPropertyName("baseUrl")] - public string BaseUrl { get; set; } = string.Empty; + /// Whether the session has the `mcp-apps` capability. + [JsonPropertyName("sessionHasMcpApps")] + public bool SessionHasMcpApps { get; set; } +} - /// Bearer token for authentication. Sets the Authorization header directly. Takes precedence over apiKey when both are set. - [JsonPropertyName("bearerToken")] - public string? BearerToken { get; set; } +/// What the server returned for this session. +[Experimental(Diagnostics.Experimental)] +public sealed class McpAppsDiagnoseServer +{ + /// Whether the named server is currently connected. + [JsonPropertyName("connected")] + public bool Connected { get; set; } - /// When true, the SDK client supplies bearer tokens on demand: the runtime calls the client-session `providerToken.getToken` callback before each request and applies the returned token as an `Authorization: Bearer <token>` header. This is the bearer/OAuth scheme used by Azure AD / managed-identity tokens and provider OAuth access tokens (including Anthropic's), not a provider-specific API-key header such as Anthropic's `x-api-key`. The token-acquiring function itself stays on the SDK side and is never serialized; only this flag crosses the wire. When set alongside `apiKey`/`bearerToken`, the callback takes precedence: the runtime applies the token returned by `providerToken.getToken` as the `Authorization: Bearer` header for each request and does not send the static credential. - [JsonPropertyName("hasBearerTokenProvider")] - public bool? HasBearerTokenProvider { get; set; } - - /// Custom HTTP headers to include in all outbound requests to the provider. - [JsonPropertyName("headers")] - public IDictionary? Headers { get; set; } + /// Up to 5 tool names with `_meta.ui` for quick inspection. + [JsonPropertyName("sampleToolNames")] + public IList SampleToolNames { get => field ??= []; set; } - /// Stable identifier referenced by BYOK model definitions. Must not contain '/'. - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; + /// Total tools returned by the server's tools/list. + [JsonPropertyName("toolCount")] + public double ToolCount { get; set; } - /// Provider transport. Defaults to "http". - [JsonPropertyName("transport")] - public ProviderConfigTransport? Transport { get; set; } + /// Tools whose `_meta.ui` is populated (resourceUri and/or visibility set). + [JsonPropertyName("toolsWithUiMeta")] + public double ToolsWithUiMeta { get; set; } +} - /// Provider type. Defaults to "openai" for generic OpenAI-compatible APIs. - [JsonPropertyName("type")] - public ProviderConfigType? Type { get; set; } +/// Diagnostic snapshot of MCP Apps wiring for the named server. +[Experimental(Diagnostics.Experimental)] +public sealed class McpAppsDiagnoseResult +{ + /// Capability negotiation snapshot. + [JsonPropertyName("capability")] + public McpAppsDiagnoseCapability Capability { get => field ??= new(); set; } - /// Wire API format (openai/azure only). Defaults to "completions". - [JsonPropertyName("wireApi")] - public ProviderConfigWireApi? WireApi { get; set; } + /// What the server returned for this session. + [JsonPropertyName("server")] + public McpAppsDiagnoseServer Server { get => field ??= new(); set; } } -/// BYOK providers and/or models to add to the session's registry at runtime. Both fields are optional; provide providers, models, or both. +/// MCP server to diagnose MCP Apps wiring for. [Experimental(Diagnostics.Experimental)] -internal sealed class ProviderAddRequest +internal sealed class McpAppsDiagnoseRequest { - /// BYOK model definitions to register. Each must reference a provider that is already registered or included in this same call. Selection ids (`provider/id`) must be unique across the registry. - [JsonPropertyName("models")] - public IList? Models { get; set; } - - /// Named BYOK provider connections to register, additive to any providers already in the registry. Each name must be unique across the registry and must not contain '/'. - [JsonPropertyName("providers")] - public IList? Providers { get; set; } + /// MCP server to probe. + [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] + [MinLength(1)] + [JsonPropertyName("serverName")] + public string ServerName { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Indicates whether the session options patch was applied successfully. +/// MCP resource content with URI, optional MIME type, text or base64 blob, and resource metadata. [Experimental(Diagnostics.Experimental)] -public sealed class SessionUpdateOptionsResult +public sealed class McpResourceContent { - /// Number of hooks loaded from installed plugins, returned when installedPlugins is updated. - [JsonPropertyName("pluginHookCount")] - public long? PluginHookCount { get; set; } + /// Resource-level metadata (CSP, permissions, etc.). + [JsonPropertyName("_meta")] + public IDictionary? Meta { get; set; } - /// Whether the operation succeeded. - [JsonPropertyName("success")] - public bool Success { get; set; } + /// Base64-encoded binary content. + [JsonPropertyName("blob")] + public string? Blob { get; set; } + + /// MIME type of the content. + [JsonPropertyName("mimeType")] + public string? MimeType { get; set; } + + /// Text content (e.g. HTML). + [JsonPropertyName("text")] + public string? Text { get; set; } + + /// The resource URI. + [JsonPropertyName("uri")] + public string Uri { get; set; } = string.Empty; } -/// Source descriptor for a `session.options.update` content-exclusion rule, with source name and type. +/// Resource contents returned by the MCP server. [Experimental(Diagnostics.Experimental)] -public sealed class OptionsUpdateAdditionalContentExclusionPolicyRuleSource +public sealed class McpResourcesReadResult { - /// Gets or sets the name value. - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; - - /// Gets or sets the type value. - [JsonPropertyName("type")] - public string Type { get; set; } = string.Empty; + /// Resource contents returned by the server. + [JsonPropertyName("contents")] + public IList Contents { get => field ??= []; set; } } -/// Single content-exclusion rule supplied to `session.options.update`, with paths, match conditions, and source. +/// MCP server and resource URI to fetch. [Experimental(Diagnostics.Experimental)] -public sealed class OptionsUpdateAdditionalContentExclusionPolicyRule +internal sealed class McpResourcesReadRequest { - /// Gets or sets the ifAnyMatch value. - [JsonPropertyName("ifAnyMatch")] - public IList? IfAnyMatch { get; set; } - - /// Gets or sets the ifNoneMatch value. - [JsonPropertyName("ifNoneMatch")] - public IList? IfNoneMatch { get; set; } + /// Name of the MCP server hosting the resource. + [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] + [MinLength(1)] + [JsonPropertyName("serverName")] + public string ServerName { get; set; } = string.Empty; - /// Gets or sets the paths value. - [JsonPropertyName("paths")] - public IList Paths { get => field ??= []; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; - /// Source descriptor for a `session.options.update` content-exclusion rule, with source name and type. - [JsonPropertyName("source")] - public OptionsUpdateAdditionalContentExclusionPolicyRuleSource Source { get => field ??= new(); set; } + /// Resource URI. + [JsonPropertyName("uri")] + public string Uri { get; set; } = string.Empty; } -/// Content-exclusion policy supplied to `session.options.update`, with rules, last-updated data, and scope. +/// Standard MCP resource annotations plus preserved non-standard annotation fields. [Experimental(Diagnostics.Experimental)] -public sealed class OptionsUpdateAdditionalContentExclusionPolicy +public sealed class McpResourceAnnotations { - /// Gets or sets the last_updated_at value. - [JsonPropertyName("last_updated_at")] - public JsonElement LastUpdatedAt { get; set; } + /// Server-provided non-standard annotation fields preserved from the MCP response. + [JsonPropertyName("additionalProperties")] + public IDictionary? AdditionalProperties { get; set; } - /// Gets or sets the rules value. - [JsonPropertyName("rules")] - public IList Rules { get => field ??= []; set; } + /// Intended audience roles for this resource. + [JsonPropertyName("audience")] + public IList? Audience { get; set; } - /// Allowed values for the `OptionsUpdateAdditionalContentExclusionPolicyScope` enumeration. - [JsonPropertyName("scope")] - public OptionsUpdateAdditionalContentExclusionPolicyScope Scope { get; set; } + /// Last-modified timestamp hint. + [JsonPropertyName("lastModified")] + public string? LastModified { get; set; } + + /// Priority hint for model/client use. + [JsonPropertyName("priority")] + public double? Priority { get; set; } } -/// Options scoped to the built-in CAPI (Copilot API) provider. +/// A resource icon descriptor plus preserved non-standard icon fields. [Experimental(Diagnostics.Experimental)] -public sealed class CapiSessionOptions +public sealed class McpResourceIcon { - /// Whether to use WebSocket transport for the CAPI Responses API. Enabled by default when the model advertises `ws:/responses` support; set to `false` to force the HTTP Responses transport in environments where WebSockets are blocked (e.g. behind a proxy). Setting this to `false` is equivalent to the `COPILOT_CLI_DISABLE_WEBSOCKET_RESPONSES` environment variable. - [JsonPropertyName("enableWebSocketResponses")] - public bool? EnableWebSocketResponses { get; set; } + /// Server-provided non-standard icon fields preserved from the MCP response. + [JsonPropertyName("additionalProperties")] + public IDictionary? AdditionalProperties { get; set; } + + /// Icon MIME type, when known. + [JsonPropertyName("mimeType")] + public string? MimeType { get; set; } + + /// Icon sizes hint. + [JsonPropertyName("sizes")] + public string? Sizes { get; set; } + + /// Icon URI. + [JsonPropertyName("src")] + public string Src { get; set; } = string.Empty; + + /// Theme hint for this icon. + [JsonPropertyName("theme")] + public string? Theme { get; set; } } -/// Installed plugin record for a session, with marketplace, version, install time, enabled state, cache path, and source. +/// An MCP resource descriptor (spec `Resource`): URI, name, and optional title, description, MIME type, size, icons, annotations, and metadata. Server-provided fields outside the standard descriptor shape are exposed under `additionalProperties`. [Experimental(Diagnostics.Experimental)] -public sealed class SessionInstalledPlugin +public sealed class McpResource { - /// Path where the plugin is cached locally. - [JsonPropertyName("cache_path")] - public string? CachePath { get; set; } + /// Resource-level metadata. + [JsonPropertyName("_meta")] + public IDictionary? Meta { get; set; } - /// Whether the plugin is currently enabled. - [JsonPropertyName("enabled")] - public bool Enabled { get; set; } + /// Server-provided non-standard descriptor fields preserved from the MCP response. + [JsonPropertyName("additionalProperties")] + public IDictionary? AdditionalProperties { get; set; } - /// Installation timestamp (ISO-8601). - [JsonPropertyName("installed_at")] - public string InstalledAt { get; set; } = string.Empty; + /// Model/client annotations associated with this resource. + [JsonPropertyName("annotations")] + public McpResourceAnnotations? Annotations { get; set; } - /// Marketplace the plugin came from (empty string for direct repo installs). - [JsonPropertyName("marketplace")] - public string Marketplace { get; set; } = string.Empty; + /// Optional description of what this resource represents. + [JsonPropertyName("description")] + public string? Description { get; set; } - /// Plugin name. + /// Icons associated with this resource. + [JsonPropertyName("icons")] + public IList? Icons { get; set; } + + /// MIME type of the resource, if known. + [JsonPropertyName("mimeType")] + public string? MimeType { get; set; } + + /// The programmatic name of the resource. [JsonPropertyName("name")] public string Name { get; set; } = string.Empty; - /// Source descriptor for direct repo installs (when marketplace is empty). - [JsonPropertyName("source")] - public JsonElement? Source { get; set; } + /// Resource size in bytes, when known. + [JsonPropertyName("size")] + public long? Size { get; set; } - /// Installed version, if known. - [JsonPropertyName("version")] - public string? Version { get; set; } + /// Optional human-readable display title. + [JsonPropertyName("title")] + public string? Title { get; set; } + + /// The resource URI (e.g. ui://... or file:///...). + [JsonPropertyName("uri")] + public string Uri { get; set; } = string.Empty; } -/// Custom model-provider configuration (BYOK). +/// One page of resources advertised by the named MCP server. [Experimental(Diagnostics.Experimental)] -public sealed class ProviderConfig +public sealed class McpResourcesListResult { - /// API key. Optional for local providers like Ollama. - [JsonPropertyName("apiKey")] - public string? ApiKey { get; set; } - - /// Azure-specific provider options. - [JsonPropertyName("azure")] - public ProviderConfigAzure? Azure { get; set; } + /// Opaque cursor for the next page, if the server has more resources. + [JsonPropertyName("nextCursor")] + public string? NextCursor { get; set; } - /// API endpoint URL. - [JsonPropertyName("baseUrl")] - public string BaseUrl { get; set; } = string.Empty; + /// Resources advertised by the server (proxied MCP `resources/list`). + [JsonPropertyName("resources")] + public IList Resources { get => field ??= []; set; } +} - /// Bearer token for authentication. Sets the Authorization header directly. Takes precedence over apiKey when both are set. - [JsonPropertyName("bearerToken")] - public string? BearerToken { get; set; } +/// MCP server whose resources to enumerate. +[Experimental(Diagnostics.Experimental)] +internal sealed class McpResourcesListRequest +{ + /// Opaque MCP pagination cursor from a prior `nextCursor` value. + [JsonPropertyName("cursor")] + public string? Cursor { get; set; } - /// When true, the SDK client supplies bearer tokens on demand: the runtime calls the client-session `providerToken.getToken` callback before each request and applies the returned token as an `Authorization: Bearer <token>` header. This is the bearer/OAuth scheme used by Azure AD / managed-identity tokens and provider OAuth access tokens (including Anthropic's), not a provider-specific API-key header such as Anthropic's `x-api-key`. The token-acquiring function itself stays on the SDK side and is never serialized; only this flag crosses the wire. When set alongside `apiKey`/`bearerToken`, the callback takes precedence: the runtime applies the token returned by `providerToken.getToken` as the `Authorization: Bearer` header for each request and does not send the static credential. - [JsonPropertyName("hasBearerTokenProvider")] - public bool? HasBearerTokenProvider { get; set; } + /// Name of the MCP server whose resources to enumerate. + [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] + [MinLength(1)] + [JsonPropertyName("serverName")] + public string ServerName { get; set; } = string.Empty; - /// Custom HTTP headers to include in all outbound requests to the provider. - [JsonPropertyName("headers")] - public IDictionary? Headers { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// Maximum context window tokens for the model. - [JsonPropertyName("maxContextWindowTokens")] - public double? MaxContextWindowTokens { get; set; } +/// An MCP resource template descriptor (spec `ResourceTemplate`): an RFC 6570 URI template, name, and optional title, description, MIME type, icons, annotations, and metadata. Server-provided fields outside the standard descriptor shape are exposed under `additionalProperties`. +[Experimental(Diagnostics.Experimental)] +public sealed class McpResourceTemplate +{ + /// Resource-template-level metadata. + [JsonPropertyName("_meta")] + public IDictionary? Meta { get; set; } - /// Maximum output tokens for the model. - [JsonPropertyName("maxOutputTokens")] - public double? MaxOutputTokens { get; set; } + /// Server-provided non-standard descriptor fields preserved from the MCP response. + [JsonPropertyName("additionalProperties")] + public IDictionary? AdditionalProperties { get; set; } - /// Maximum prompt/input tokens for the model. - [JsonPropertyName("maxPromptTokens")] - public double? MaxPromptTokens { get; set; } + /// Model/client annotations associated with this template. + [JsonPropertyName("annotations")] + public McpResourceAnnotations? Annotations { get; set; } - /// Well-known model ID used for capability lookup. When set, agent behavior config and token limits are inferred from this model. - [JsonPropertyName("modelId")] - public string? ModelId { get; set; } + /// Optional description of what this template is for. + [JsonPropertyName("description")] + public string? Description { get; set; } - /// Provider transport. Defaults to "http". - [JsonPropertyName("transport")] - public ProviderConfigTransport? Transport { get; set; } + /// Icons associated with resources matching this template. + [JsonPropertyName("icons")] + public IList? Icons { get; set; } - /// Provider type. Defaults to "openai" for generic OpenAI-compatible APIs. - [JsonPropertyName("type")] - public ProviderConfigType? Type { get; set; } + /// MIME type for resources matching this template, if uniform. + [JsonPropertyName("mimeType")] + public string? MimeType { get; set; } - /// Wire API format (openai/azure only). Defaults to "completions". - [JsonPropertyName("wireApi")] - public ProviderConfigWireApi? WireApi { get; set; } + /// The programmatic name of the resource template. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; - /// The model identifier sent to the provider API for inference (the "wire" model), as opposed to modelId which is the well-known base. - [JsonPropertyName("wireModel")] - public string? WireModel { get; set; } + /// Optional human-readable display title. + [JsonPropertyName("title")] + public string? Title { get; set; } + + /// An RFC 6570 URI template for constructing resource URIs. + [JsonPropertyName("uriTemplate")] + public string UriTemplate { get; set; } = string.Empty; } -/// macOS seatbelt experimental options. +/// One page of resource templates advertised by the named MCP server. [Experimental(Diagnostics.Experimental)] -public sealed class SandboxConfigUserPolicyExperimentalSeatbelt +public sealed class McpResourcesListTemplatesResult { - /// Whether the macOS seatbelt profile may access the keychain. - [JsonPropertyName("keychainAccess")] - public bool? KeychainAccess { get; set; } + /// Opaque cursor for the next page, if the server has more resource templates. + [JsonPropertyName("nextCursor")] + public string? NextCursor { get; set; } + + /// Resource templates advertised by the server (proxied MCP `resources/templates/list`). + [JsonPropertyName("resourceTemplates")] + public IList ResourceTemplates { get => field ??= []; set; } } -/// Platform-specific experimental policy fields. +/// MCP server whose resource templates to enumerate. [Experimental(Diagnostics.Experimental)] -public sealed class SandboxConfigUserPolicyExperimental +internal sealed class McpResourcesListTemplatesRequest { - /// macOS seatbelt experimental options. - [JsonPropertyName("seatbelt")] - public SandboxConfigUserPolicyExperimentalSeatbelt? Seatbelt { get; set; } + /// Opaque MCP pagination cursor from a prior `nextCursor` value. + [JsonPropertyName("cursor")] + public string? Cursor { get; set; } + + /// Name of the MCP server whose resource templates to enumerate. + [RegularExpression("^[^\\x00-\\x1f/\\x7f-\\x9f}]+(?:\\/[^\\x00-\\x1f/\\x7f-\\x9f}]+)*$")] + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] + [MinLength(1)] + [JsonPropertyName("serverName")] + public string ServerName { get; set; } = string.Empty; + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Filesystem rules to merge into the base policy. +/// Session plugin metadata, with name, marketplace, optional version, and enabled state. [Experimental(Diagnostics.Experimental)] -public sealed class SandboxConfigUserPolicyFilesystem +public sealed class Plugin { - /// Whether to clear the policy when the session exits. - [JsonPropertyName("clearPolicyOnExit")] - public bool? ClearPolicyOnExit { get; set; } + /// Whether the plugin is currently enabled. + [JsonPropertyName("enabled")] + public bool Enabled { get; set; } - /// Paths explicitly denied. - [JsonPropertyName("deniedPaths")] - public IList? DeniedPaths { get; set; } + /// Marketplace the plugin came from. + [JsonPropertyName("marketplace")] + public string Marketplace { get; set; } = string.Empty; - /// Paths granted read-only access. - [JsonPropertyName("readonlyPaths")] - public IList? ReadonlyPaths { get; set; } + /// Plugin name. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; - /// Paths granted read/write access. - [JsonPropertyName("readwritePaths")] - public IList? ReadwritePaths { get; set; } + /// Installed version. + [JsonPropertyName("version")] + public string? Version { get; set; } } -/// Network rules to merge into the base policy. +/// Plugins installed for the session, with their enabled state and version metadata. [Experimental(Diagnostics.Experimental)] -public sealed class SandboxConfigUserPolicyNetwork +public sealed class PluginList { - /// Whether traffic to local/loopback addresses is allowed. - [JsonPropertyName("allowLocalNetwork")] - public bool? AllowLocalNetwork { get; set; } - - /// Whether outbound network traffic is allowed at all. - [JsonPropertyName("allowOutbound")] - public bool? AllowOutbound { get; set; } + /// Installed plugins. + [JsonPropertyName("plugins")] + public IList Plugins { get => field ??= []; set; } } -/// macOS seatbelt-specific options. +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -public sealed class SandboxConfigUserPolicySeatbelt +internal sealed class SessionPluginsListRequest { - /// Whether the macOS seatbelt profile may access the keychain. - [JsonPropertyName("keychainAccess")] - public bool? KeychainAccess { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// User-managed sandbox policy fragment merged into the auto-discovered base policy. +/// RPC data type for SessionPluginsReload operations. [Experimental(Diagnostics.Experimental)] -public sealed class SandboxConfigUserPolicy +public sealed class SessionPluginsReloadRequest { - /// Deprecated legacy location for `seatbelt`; read only when the top-level `seatbelt` is absent. - [JsonPropertyName("experimental")] - public SandboxConfigUserPolicyExperimental? Experimental { get; set; } + /// When true, skip repo-level hooks during the hook reload. Use before folder trust is confirmed; load them post-trust via `sessions.loadDeferredRepoHooks`. + [JsonPropertyName("deferRepoHooks")] + public bool? DeferRepoHooks { get; set; } - /// Filesystem rules to merge into the base policy. - [JsonPropertyName("filesystem")] - public SandboxConfigUserPolicyFilesystem? Filesystem { get; set; } + /// Re-run custom-agent discovery after refreshing plugins. Defaults to true. + [JsonPropertyName("reloadCustomAgents")] + public bool? ReloadCustomAgents { get; set; } - /// Network rules to merge into the base policy. - [JsonPropertyName("network")] - public SandboxConfigUserPolicyNetwork? Network { get; set; } + /// Re-discover and relaunch subprocess extensions (including plugin-shipped extensions) after refreshing plugins. Defaults to true. Has no effect when the session has no active extension controller (e.g. extensions were not requested for the session). + [JsonPropertyName("reloadExtensions")] + public bool? ReloadExtensions { get; set; } - /// macOS seatbelt options to merge into the base policy. - [JsonPropertyName("seatbelt")] - public SandboxConfigUserPolicySeatbelt? Seatbelt { get; set; } + /// Re-load user, plugin, and (subject to `deferRepoHooks`) repo hooks. Defaults to true. Has no effect when the host has not registered a hook reloader (e.g. remote sessions). + [JsonPropertyName("reloadHooks")] + public bool? ReloadHooks { get; set; } + + /// Reload MCP server connections after refreshing plugins. Defaults to true. + [JsonPropertyName("reloadMcp")] + public bool? ReloadMcp { get; set; } } -/// Resolved sandbox configuration. +/// RPC data type for SessionPluginsReloadRequestWithSession operations. [Experimental(Diagnostics.Experimental)] -public sealed class SandboxConfig +internal sealed class SessionPluginsReloadRequestWithSession { - /// Whether to auto-add the current working directory to readwritePaths. Default: true. - [JsonPropertyName("addCurrentWorkingDirectory")] - public bool? AddCurrentWorkingDirectory { get; set; } + /// When true, skip repo-level hooks during the hook reload. Use before folder trust is confirmed; load them post-trust via `sessions.loadDeferredRepoHooks`. + [JsonPropertyName("deferRepoHooks")] + public bool? DeferRepoHooks { get; set; } - /// Whether sandboxing is enabled for the session. - [JsonPropertyName("enabled")] - public bool Enabled { get; set; } + /// Re-run custom-agent discovery after refreshing plugins. Defaults to true. + [JsonPropertyName("reloadCustomAgents")] + public bool? ReloadCustomAgents { get; set; } - /// Whether to export `GH_TOKEN` so the `gh` CLI authenticates inside the sandbox without the OS keyring the sandbox blocks. Default: false (opt-in). - [JsonPropertyName("ghAuth")] - public bool? GhAuth { get; set; } + /// Re-discover and relaunch subprocess extensions (including plugin-shipped extensions) after refreshing plugins. Defaults to true. Has no effect when the session has no active extension controller (e.g. extensions were not requested for the session). + [JsonPropertyName("reloadExtensions")] + public bool? ReloadExtensions { get; set; } - /// Whether to inject the Copilot GitHub token as an `http.<host>.extraheader` so authenticated HTTPS git works inside the sandbox without the shell-based credential helper the sandbox blocks. Default: false (opt-in). - [JsonPropertyName("gitAuth")] - public bool? GitAuth { get; set; } + /// Re-load user, plugin, and (subject to `deferRepoHooks`) repo hooks. Defaults to true. Has no effect when the host has not registered a hook reloader (e.g. remote sessions). + [JsonPropertyName("reloadHooks")] + public bool? ReloadHooks { get; set; } - /// User-managed sandbox policy fragment merged into the auto-discovered base policy. - [JsonPropertyName("userPolicy")] - public SandboxConfigUserPolicy? UserPolicy { get; set; } + /// Reload MCP server connections after refreshing plugins. Defaults to true. + [JsonPropertyName("reloadMcp")] + public bool? ReloadMcp { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Patch of mutable session options to apply to the running session. +/// Short-lived, rotating credential the caller must send on every request, in addition to `apiKey` if one is present. Omitted when the endpoint does not require one. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionUpdateOptionsParams +public sealed class ProviderSessionToken { - /// Additional content-exclusion policies to merge into the session's policy set. - [Experimental(Diagnostics.Experimental)] - [JsonPropertyName("additionalContentExclusionPolicies")] - public IList? AdditionalContentExclusionPolicies { get; set; } + /// When the token expires, if known. Callers should refresh by calling `getEndpoint` again before this time, or reactively on any 401/403 response from `baseUrl`. + [JsonPropertyName("expiresAt")] + public DateTimeOffset? ExpiresAt { get; set; } - /// Runtime context discriminator (e.g., `cli`, `actions`). - [JsonPropertyName("agentContext")] - public string? AgentContext { get; set; } + /// HTTP header name the token must be sent under. + [JsonPropertyName("header")] + public string Header { get; set; } = string.Empty; - /// Whether to include instructions from every MCP server in the system prompt instead of only allowlisted servers. - [JsonPropertyName("allowAllMcpServerInstructions")] - public bool? AllowAllMcpServerInstructions { get; set; } + /// The model the token is bound to, when applicable. When set, the token is only valid for requests against this model. + [JsonPropertyName("model")] + public string? Model { get; set; } - /// Whether to disable the `ask_user` tool (encourages autonomous behavior). - [JsonPropertyName("askUserDisabled")] - public bool? AskUserDisabled { get; set; } - - /// Allowlist of tool names available to this session. - [JsonPropertyName("availableTools")] - public IList? AvailableTools { get; set; } - - /// Options scoped to the built-in CAPI (Copilot API) provider. - [JsonPropertyName("capi")] - public CapiSessionOptions? Capi { get; set; } + /// The short-lived token value. + [JsonPropertyName("token")] + public string Token { get; set; } = string.Empty; +} - /// Identifier of the client driving the session. - [JsonPropertyName("clientName")] - public string? ClientName { get; set; } +/// A snapshot of the provider endpoint the session is currently configured to talk to. +[Experimental(Diagnostics.Experimental)] +public sealed class ProviderEndpoint +{ + /// A credential the caller should use with this endpoint. Omitted only when the endpoint accepts unauthenticated requests. + [JsonPropertyName("apiKey")] + public string? ApiKey { get; set; } - /// Whether to include the `Co-authored-by` trailer in commit messages. - [JsonPropertyName("coauthorEnabled")] - public bool? CoauthorEnabled { get; set; } + /// Base URL to pass to the LLM client library. + [Url] + [StringSyntax(StringSyntaxAttribute.Uri)] + [JsonPropertyName("baseUrl")] + public string BaseUrl { get; set; } = string.Empty; - /// Context tier for models with tiered pricing. The session uses this to derive effective `modelCapabilitiesOverrides` so compaction, truncation, token display, and request limits honor the selected tier. - [JsonPropertyName("contextTier")] - public OptionsUpdateContextTier? ContextTier { get; set; } + /// HTTP headers the caller must include on every outbound request. + [JsonPropertyName("headers")] + public IDictionary Headers { get => field ??= new Dictionary(); set; } - /// Whether to allow auto-mode continuation across turns. - [JsonPropertyName("continueOnAutoMode")] - public bool? ContinueOnAutoMode { get; set; } + /// Short-lived, rotating credential the caller must send on every request, in addition to `apiKey` if one is present. Omitted when the endpoint does not require one. + [JsonPropertyName("sessionToken")] + public ProviderSessionToken? SessionToken { get; set; } - /// Override URL for the Copilot API endpoint. - [JsonPropertyName("copilotUrl")] - public string? CopilotUrl { get; set; } + /// Transport to be used for provider requests. + [JsonPropertyName("transport")] + public ProviderEndpointTransport? Transport { get; set; } - /// Whether to default custom agents to local-only execution. - [JsonPropertyName("customAgentsLocalOnly")] - public bool? CustomAgentsLocalOnly { get; set; } + /// Provider family. Matches the `type` field of a BYOK provider config. + [JsonPropertyName("type")] + public ProviderEndpointType Type { get; set; } - /// Instruction source IDs to exclude from the system prompt. - [JsonPropertyName("disabledInstructionSources")] - public IList? DisabledInstructionSources { get; set; } + /// Wire API to be used, when required for the provider type. + [JsonPropertyName("wireApi")] + public ProviderEndpointWireApi? WireApi { get; set; } +} - /// Skill IDs that should be excluded from this session. - [JsonPropertyName("disabledSkills")] - public IList? DisabledSkills { get; set; } +/// RPC data type for SessionProviderGetEndpoint operations. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionProviderGetEndpointRequest +{ + /// Model identifier the caller intends to use against the returned endpoint. Used to pick the correct wire shape. Omit to use whichever model the session is currently using. + [JsonPropertyName("modelId")] + public string? ModelId { get; set; } +} - /// Whether to enable loading of `.github/hooks/` filesystem hooks. Separate from the SDK callback hook mechanism. - [JsonPropertyName("enableFileHooks")] - public bool? EnableFileHooks { get; set; } +/// RPC data type for SessionProviderGetEndpointRequestWithSession operations. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionProviderGetEndpointRequestWithSession +{ + /// Model identifier the caller intends to use against the returned endpoint. Used to pick the correct wire shape. Omit to use whichever model the session is currently using. + [JsonPropertyName("modelId")] + public string? ModelId { get; set; } - /// Whether to enable host git operations (context resolution, child repo scanning, git info in system prompt). - [JsonPropertyName("enableHostGitOperations")] - public bool? EnableHostGitOperations { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// Whether to discover custom instructions on demand after successful file views (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md surfacing). Combined with `skipCustomInstructions` and the runtime-side `ON_DEMAND_INSTRUCTIONS` feature flag. - [JsonPropertyName("enableOnDemandInstructionDiscovery")] - public bool? EnableOnDemandInstructionDiscovery { get; set; } +/// The selectable model entries synthesized for the models added by this call. +[Experimental(Diagnostics.Experimental)] +public sealed class ProviderAddResult +{ + /// Synthesized selectable model entries for the newly added BYOK models, each under its provider-qualified selection id (`provider/id`). Empty when only providers were added. + [JsonPropertyName("models")] + public IList Models { get => field ??= []; set; } +} - /// Whether to surface reasoning-summary events from the model. - [JsonPropertyName("enableReasoningSummaries")] - public bool? EnableReasoningSummaries { get; set; } +/// A BYOK model definition referencing a named provider. +[Experimental(Diagnostics.Experimental)] +public sealed class ProviderModelConfig +{ + /// Optional capability overrides (vision, tool_calls, reasoning, etc.). + [JsonPropertyName("capabilities")] + public ModelCapabilitiesOverride? Capabilities { get; set; } - /// Whether shell-script safety heuristics are enabled. - [JsonPropertyName("enableScriptSafety")] - public bool? EnableScriptSafety { get; set; } + /// Provider-local model id, unique within its provider. The session-wide selection id (shown in the model list and passed to switchTo) is the provider-qualified `provider/id`. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; - /// Whether to enable cross-session store writes and reads. - [JsonPropertyName("enableSessionStore")] - public bool? EnableSessionStore { get; set; } + /// Maximum context window tokens for the model. + [JsonPropertyName("maxContextWindowTokens")] + public double? MaxContextWindowTokens { get; set; } - /// Whether to enable skill directory scanning and loading. Falls back to enableConfigDiscovery when unset. - [JsonPropertyName("enableSkills")] - public bool? EnableSkills { get; set; } + /// Maximum output tokens for the model. + [JsonPropertyName("maxOutputTokens")] + public double? MaxOutputTokens { get; set; } - /// Whether to stream model responses. - [JsonPropertyName("enableStreaming")] - public bool? EnableStreaming { get; set; } + /// Maximum prompt/input tokens for the model. + [JsonPropertyName("maxPromptTokens")] + public double? MaxPromptTokens { get; set; } - /// How env values are passed to MCP servers (`direct` inlines literal values; `indirect` resolves at launch). - [JsonPropertyName("envValueMode")] - public OptionsUpdateEnvValueMode? EnvValueMode { get; set; } + /// Well-known base model id used for behavior/capability/config lookup. Defaults to `id`. + [JsonPropertyName("modelId")] + public string? ModelId { get; set; } - /// Override directory for the session-events log. When unset, the runtime's default events log directory is used. - [JsonPropertyName("eventsLogDirectory")] - public string? EventsLogDirectory { get; set; } + /// Display name for model pickers. Defaults to the provider-qualified selection id (`provider/id`). + [JsonPropertyName("name")] + public string? Name { get; set; } - /// Built-in subagent names to exclude from this session. Excluded built-ins are hidden from agent discovery and cannot be dispatched unless a custom agent with the same name is available. - [JsonPropertyName("excludedBuiltinAgents")] - public IList? ExcludedBuiltinAgents { get; set; } + /// Name of the NamedProviderConfig that serves this model. + [JsonPropertyName("provider")] + public string Provider { get; set; } = string.Empty; - /// Denylist of tool names for this session. - [JsonPropertyName("excludedTools")] - public IList? ExcludedTools { get; set; } + /// The model name sent to the provider API for inference. Defaults to `id`. + [JsonPropertyName("wireModel")] + public string? WireModel { get; set; } +} - /// Map of feature-flag IDs to their boolean enabled state. - [JsonPropertyName("featureFlags")] - public IDictionary? FeatureFlags { get; set; } +/// Azure-specific provider options. +[Experimental(Diagnostics.Experimental)] +public sealed class ProviderConfigAzure +{ + /// API version. When set, uses the versioned deployment route. When omitted, uses the GA versionless v1 route. + [JsonPropertyName("apiVersion")] + public string? ApiVersion { get; set; } +} - /// Built-in subagent names to include in this session. When specified, only these built-ins are available, subject to runtime availability and exclusions. Custom agents with the same name remain available. Set to null to remove the allowlist restriction. - [JsonPropertyName("includedBuiltinAgents")] - public IList? IncludedBuiltinAgents { get; set; } +/// A named BYOK provider connection (transport + credentials). +[Experimental(Diagnostics.Experimental)] +public sealed class NamedProviderConfig +{ + /// API key. Optional for local providers like Ollama. + [JsonPropertyName("apiKey")] + public string? ApiKey { get; set; } - /// Full set of installed plugins for the session. Replaces the existing list; the runtime invalidates the skills cache only when the list materially changes. - [JsonPropertyName("installedPlugins")] - public IList? InstalledPlugins { get; set; } + /// Azure-specific provider options. + [JsonPropertyName("azure")] + public ProviderConfigAzure? Azure { get; set; } - /// Stable integration identifier used for analytics and rate-limit attribution. - [JsonPropertyName("integrationId")] - public string? IntegrationId { get; set; } + /// API endpoint URL. + [JsonPropertyName("baseUrl")] + public string BaseUrl { get; set; } = string.Empty; - /// Whether experimental capabilities are enabled. - [JsonPropertyName("isExperimentalMode")] - public bool? IsExperimentalMode { get; set; } + /// Bearer token for authentication. Sets the Authorization header directly. Takes precedence over apiKey when both are set. + [JsonPropertyName("bearerToken")] + public string? BearerToken { get; set; } - /// Whether interactive shell sessions are logged. - [JsonPropertyName("logInteractiveShells")] - public bool? LogInteractiveShells { get; set; } + /// When true, the SDK client supplies bearer tokens on demand: the runtime calls the client-session `providerToken.getToken` callback before each request and applies the returned token as an `Authorization: Bearer <token>` header. This is the bearer/OAuth scheme used by Azure AD / managed-identity tokens and provider OAuth access tokens (including Anthropic's), not a provider-specific API-key header such as Anthropic's `x-api-key`. The token-acquiring function itself stays on the SDK side and is never serialized; only this flag crosses the wire. When set alongside `apiKey`/`bearerToken`, the callback takes precedence: the runtime applies the token returned by `providerToken.getToken` as the `Authorization: Bearer` header for each request and does not send the static credential. + [JsonPropertyName("hasBearerTokenProvider")] + public bool? HasBearerTokenProvider { get; set; } - /// Identifier sent to LSP-style integrations. - [JsonPropertyName("lspClientName")] - public string? LspClientName { get; set; } + /// Custom HTTP headers to include in all outbound requests to the provider. + [JsonPropertyName("headers")] + public IDictionary? Headers { get; set; } - /// 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). - [JsonPropertyName("manageScheduleEnabled")] - public bool? ManageScheduleEnabled { get; set; } + /// Stable identifier referenced by BYOK model definitions. Must not contain '/'. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; - /// Maximum decoded byte size of a single model-facing binary tool result (e.g. an image) persisted inline in session events and re-presented to the model on later turns / resume. Larger results are persisted as a metadata-only marker and shown to the model as a short text note. Defaults to 10 MB. - [JsonPropertyName("maxInlineBinaryBytes")] - public long? MaxInlineBinaryBytes { get; set; } + /// Provider transport. Defaults to "http". + [JsonPropertyName("transport")] + public ProviderConfigTransport? Transport { get; set; } - /// The model ID to use for assistant turns. - [JsonPropertyName("model")] - public string? Model { get; set; } + /// Provider type. Defaults to "openai" for generic OpenAI-compatible APIs. + [JsonPropertyName("type")] + public ProviderConfigType? Type { get; set; } - /// Per-property model capability overrides for the selected model. - [JsonPropertyName("modelCapabilitiesOverrides")] - public ModelCapabilitiesOverride? ModelCapabilitiesOverrides { get; set; } + /// Wire API format (openai/azure only). Defaults to "completions". + [JsonPropertyName("wireApi")] + public ProviderConfigWireApi? WireApi { get; set; } +} - /// Organization-level custom instructions to inject into the system prompt. - [JsonPropertyName("organizationCustomInstructions")] - public string? OrganizationCustomInstructions { get; set; } +/// BYOK providers and/or models to add to the session's registry at runtime. Both fields are optional; provide providers, models, or both. +[Experimental(Diagnostics.Experimental)] +internal sealed class ProviderAddRequest +{ + /// BYOK model definitions to register. Each must reference a provider that is already registered or included in this same call. Selection ids (`provider/id`) must be unique across the registry. + [JsonPropertyName("models")] + public IList? Models { get; set; } - /// Custom model-provider configuration (BYOK). - [JsonPropertyName("provider")] - public ProviderConfig? Provider { get; set; } + /// Named BYOK provider connections to register, additive to any providers already in the registry. Each name must be unique across the registry and must not contain '/'. + [JsonPropertyName("providers")] + public IList? Providers { get; set; } - /// Reasoning effort for the selected model (model-defined enum). - [JsonPropertyName("reasoningEffort")] - public string? ReasoningEffort { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// Reasoning summary mode for supported model clients. +/// Indicates whether the session options patch was applied successfully. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionUpdateOptionsResult +{ + /// Number of hooks loaded from installed plugins, returned when installedPlugins is updated. + [JsonPropertyName("pluginHookCount")] + public long? PluginHookCount { get; set; } + + /// Whether the operation succeeded. + [JsonPropertyName("success")] + public bool Success { get; set; } +} + +/// Source descriptor for a `session.options.update` content-exclusion rule, with source name and type. +[Experimental(Diagnostics.Experimental)] +public sealed class OptionsUpdateAdditionalContentExclusionPolicyRuleSource +{ + /// Gets or sets the name value. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; + + /// Gets or sets the type value. + [JsonPropertyName("type")] + public string Type { get; set; } = string.Empty; +} + +/// Single content-exclusion rule supplied to `session.options.update`, with paths, match conditions, and source. +[Experimental(Diagnostics.Experimental)] +public sealed class OptionsUpdateAdditionalContentExclusionPolicyRule +{ + /// Gets or sets the ifAnyMatch value. + [JsonPropertyName("ifAnyMatch")] + public IList? IfAnyMatch { get; set; } + + /// Gets or sets the ifNoneMatch value. + [JsonPropertyName("ifNoneMatch")] + public IList? IfNoneMatch { get; set; } + + /// Gets or sets the paths value. + [JsonPropertyName("paths")] + public IList Paths { get => field ??= []; set; } + + /// Source descriptor for a `session.options.update` content-exclusion rule, with source name and type. + [JsonPropertyName("source")] + public OptionsUpdateAdditionalContentExclusionPolicyRuleSource Source { get => field ??= new(); set; } +} + +/// Content-exclusion policy supplied to `session.options.update`, with rules, last-updated data, and scope. +[Experimental(Diagnostics.Experimental)] +public sealed class OptionsUpdateAdditionalContentExclusionPolicy +{ + /// Gets or sets the last_updated_at value. + [JsonPropertyName("last_updated_at")] + public JsonElement LastUpdatedAt { get; set; } + + /// Gets or sets the rules value. + [JsonPropertyName("rules")] + public IList Rules { get => field ??= []; set; } + + /// Allowed values for the `OptionsUpdateAdditionalContentExclusionPolicyScope` enumeration. + [JsonPropertyName("scope")] + public OptionsUpdateAdditionalContentExclusionPolicyScope Scope { get; set; } +} + +/// Options scoped to the built-in CAPI (Copilot API) provider. +[Experimental(Diagnostics.Experimental)] +public sealed class CapiSessionOptions +{ + /// Whether to use WebSocket transport for the CAPI Responses API. Enabled by default when the model advertises `ws:/responses` support; set to `false` to force the HTTP Responses transport in environments where WebSockets are blocked (e.g. behind a proxy). Setting this to `false` is equivalent to the `COPILOT_CLI_DISABLE_WEBSOCKET_RESPONSES` environment variable. + [JsonPropertyName("enableWebSocketResponses")] + public bool? EnableWebSocketResponses { get; set; } +} + +/// Installed plugin record for a session, with marketplace, version, install time, enabled state, cache path, and source. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionInstalledPlugin +{ + /// Path where the plugin is cached locally. + [JsonPropertyName("cache_path")] + public string? CachePath { get; set; } + + /// Whether the plugin is currently enabled. + [JsonPropertyName("enabled")] + public bool Enabled { get; set; } + + /// Installation timestamp (ISO-8601). + [JsonPropertyName("installed_at")] + public string InstalledAt { get; set; } = string.Empty; + + /// Marketplace the plugin came from (empty string for direct repo installs). + [JsonPropertyName("marketplace")] + public string Marketplace { get; set; } = string.Empty; + + /// Plugin name. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; + + /// Source descriptor for direct repo installs (when marketplace is empty). + [JsonPropertyName("source")] + public JsonElement? Source { get; set; } + + /// Installed version, if known. + [JsonPropertyName("version")] + public string? Version { get; set; } +} + +/// Custom model-provider configuration (BYOK). +[Experimental(Diagnostics.Experimental)] +public sealed class ProviderConfig +{ + /// API key. Optional for local providers like Ollama. + [JsonPropertyName("apiKey")] + public string? ApiKey { get; set; } + + /// Azure-specific provider options. + [JsonPropertyName("azure")] + public ProviderConfigAzure? Azure { get; set; } + + /// API endpoint URL. + [JsonPropertyName("baseUrl")] + public string BaseUrl { get; set; } = string.Empty; + + /// Bearer token for authentication. Sets the Authorization header directly. Takes precedence over apiKey when both are set. + [JsonPropertyName("bearerToken")] + public string? BearerToken { get; set; } + + /// When true, the SDK client supplies bearer tokens on demand: the runtime calls the client-session `providerToken.getToken` callback before each request and applies the returned token as an `Authorization: Bearer <token>` header. This is the bearer/OAuth scheme used by Azure AD / managed-identity tokens and provider OAuth access tokens (including Anthropic's), not a provider-specific API-key header such as Anthropic's `x-api-key`. The token-acquiring function itself stays on the SDK side and is never serialized; only this flag crosses the wire. When set alongside `apiKey`/`bearerToken`, the callback takes precedence: the runtime applies the token returned by `providerToken.getToken` as the `Authorization: Bearer` header for each request and does not send the static credential. + [JsonPropertyName("hasBearerTokenProvider")] + public bool? HasBearerTokenProvider { get; set; } + + /// Custom HTTP headers to include in all outbound requests to the provider. + [JsonPropertyName("headers")] + public IDictionary? Headers { get; set; } + + /// Maximum context window tokens for the model. + [JsonPropertyName("maxContextWindowTokens")] + public double? MaxContextWindowTokens { get; set; } + + /// Maximum output tokens for the model. + [JsonPropertyName("maxOutputTokens")] + public double? MaxOutputTokens { get; set; } + + /// Maximum prompt/input tokens for the model. + [JsonPropertyName("maxPromptTokens")] + public double? MaxPromptTokens { get; set; } + + /// Well-known model ID used for capability lookup. When set, agent behavior config and token limits are inferred from this model. + [JsonPropertyName("modelId")] + public string? ModelId { get; set; } + + /// Provider transport. Defaults to "http". + [JsonPropertyName("transport")] + public ProviderConfigTransport? Transport { get; set; } + + /// Provider type. Defaults to "openai" for generic OpenAI-compatible APIs. + [JsonPropertyName("type")] + public ProviderConfigType? Type { get; set; } + + /// Wire API format (openai/azure only). Defaults to "completions". + [JsonPropertyName("wireApi")] + public ProviderConfigWireApi? WireApi { get; set; } + + /// The model identifier sent to the provider API for inference (the "wire" model), as opposed to modelId which is the well-known base. + [JsonPropertyName("wireModel")] + public string? WireModel { get; set; } +} + +/// macOS seatbelt experimental options. +[Experimental(Diagnostics.Experimental)] +public sealed class SandboxConfigUserPolicyExperimentalSeatbelt +{ + /// Whether the macOS seatbelt profile may access the keychain. + [JsonPropertyName("keychainAccess")] + public bool? KeychainAccess { get; set; } +} + +/// Platform-specific experimental policy fields. +[Experimental(Diagnostics.Experimental)] +public sealed class SandboxConfigUserPolicyExperimental +{ + /// macOS seatbelt experimental options. + [JsonPropertyName("seatbelt")] + public SandboxConfigUserPolicyExperimentalSeatbelt? Seatbelt { get; set; } +} + +/// Filesystem rules to merge into the base policy. +[Experimental(Diagnostics.Experimental)] +public sealed class SandboxConfigUserPolicyFilesystem +{ + /// Whether to clear the policy when the session exits. + [JsonPropertyName("clearPolicyOnExit")] + public bool? ClearPolicyOnExit { get; set; } + + /// Paths explicitly denied. + [JsonPropertyName("deniedPaths")] + public IList? DeniedPaths { get; set; } + + /// Paths granted read-only access. + [JsonPropertyName("readonlyPaths")] + public IList? ReadonlyPaths { get; set; } + + /// Paths granted read/write access. + [JsonPropertyName("readwritePaths")] + public IList? ReadwritePaths { get; set; } +} + +/// HTTP proxy configuration for sandboxed traffic. +[Experimental(Diagnostics.Experimental)] +public sealed class SandboxConfigUserPolicyNetworkProxy +{ + /// Optional password for proxy authentication, combined with the URL at spawn time. The persisted value may be a literal password, a `${secret:…}` reference resolved from the OS keychain, or a `${VAR}`/`$VAR` environment reference; it is resolved just before the sandboxed process routes through the proxy. The /sandbox dialog stores a real password in the OS keychain and persists only a `${secret:…}` placeholder (never plaintext in settings.json); the field is masked in the dialog and redacted by /settings show. + [JsonPropertyName("password")] + public string? Password { get; set; } + + /// Proxy URL (e.g. http://proxy.example.com:8080). The port is optional and defaults to the scheme's standard port when omitted. Credentials must not be embedded here — a `user:pass@` authority is rejected; put them in the separate `username`/`password` fields. A credential-free http:// loopback URL is routed through the localhost proxy automatically; loopback covers localhost and any *.localhost subdomain, the whole 127.0.0.0/8 range, ::1, and IPv4-mapped loopback (::ffff:127.0.0.1). An https:// URL, or one with a username/password set, is used as-is. + [JsonPropertyName("url")] + public string Url { get; set; } = string.Empty; + + /// Optional username for proxy authentication. Combined with the URL (and `password`) into `user:pass@host` when the sandboxed process routes through the proxy. + [JsonPropertyName("username")] + public string? Username { get; set; } +} + +/// Network rules to merge into the base policy. +[Experimental(Diagnostics.Experimental)] +public sealed class SandboxConfigUserPolicyNetwork +{ + /// Whether traffic to local/loopback addresses is allowed. + [JsonPropertyName("allowLocalNetwork")] + public bool? AllowLocalNetwork { get; set; } + + /// Whether outbound network traffic is allowed at all. + [JsonPropertyName("allowOutbound")] + public bool? AllowOutbound { get; set; } + + /// HTTP proxy the sandboxed process routes traffic through. Enforced on Windows and cooperative (honored by well-behaved tools, not strictly enforced) on Linux and macOS. Credentials go in the separate `username`/`password` fields. A credential-free http:// loopback proxy URL is routed through the localhost proxy automatically; an https:// or authenticated loopback URL is used as-is. + [JsonPropertyName("proxy")] + public SandboxConfigUserPolicyNetworkProxy? Proxy { get; set; } +} + +/// macOS seatbelt-specific options. +[Experimental(Diagnostics.Experimental)] +public sealed class SandboxConfigUserPolicySeatbelt +{ + /// Whether the macOS seatbelt profile may access the keychain. + [JsonPropertyName("keychainAccess")] + public bool? KeychainAccess { get; set; } +} + +/// User-managed sandbox policy fragment merged into the auto-discovered base policy. +[Experimental(Diagnostics.Experimental)] +public sealed class SandboxConfigUserPolicy +{ + /// Deprecated legacy location for `seatbelt`; read only when the top-level `seatbelt` is absent. + [JsonPropertyName("experimental")] + public SandboxConfigUserPolicyExperimental? Experimental { get; set; } + + /// Filesystem rules to merge into the base policy. + [JsonPropertyName("filesystem")] + public SandboxConfigUserPolicyFilesystem? Filesystem { get; set; } + + /// Network rules to merge into the base policy. + [JsonPropertyName("network")] + public SandboxConfigUserPolicyNetwork? Network { get; set; } + + /// macOS seatbelt options to merge into the base policy. + [JsonPropertyName("seatbelt")] + public SandboxConfigUserPolicySeatbelt? Seatbelt { get; set; } +} + +/// Resolved sandbox configuration. +[Experimental(Diagnostics.Experimental)] +public sealed class SandboxConfig +{ + /// Whether to auto-add the current working directory to readwritePaths. Default: true. + [JsonPropertyName("addCurrentWorkingDirectory")] + public bool? AddCurrentWorkingDirectory { get; set; } + + /// Whether sandboxing is enabled for the session. + [JsonPropertyName("enabled")] + public bool Enabled { get; set; } + + /// Whether to export `GH_TOKEN` so the `gh` CLI authenticates inside the sandbox without the OS keyring the sandbox blocks. Default: false (opt-in). + [JsonPropertyName("ghAuth")] + public bool? GhAuth { get; set; } + + /// Whether to inject the Copilot GitHub token as an `http.<host>.extraheader` so authenticated HTTPS git works inside the sandbox without the shell-based credential helper the sandbox blocks. Default: false (opt-in). + [JsonPropertyName("gitAuth")] + public bool? GitAuth { get; set; } + + /// User-managed sandbox policy fragment merged into the auto-discovered base policy. + [JsonPropertyName("userPolicy")] + public SandboxConfigUserPolicy? UserPolicy { get; set; } +} + +/// A host-provided script sourced before each built-in shell command when its shell target matches the active shell. +[Experimental(Diagnostics.Experimental)] +public sealed class ShellInitScript +{ + /// Path to the script to source. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; + + /// Built-in shell that may source this script. + [JsonPropertyName("shell")] + public ShellInitScriptShell Shell { get; set; } +} + +/// Per-session settings for built-in shell tools. +[Experimental(Diagnostics.Experimental)] +public sealed class ShellOptions +{ + /// Controls automatic non-interactive profile loading where supported. Explicit initScripts are unaffected. + [JsonPropertyName("initProfile")] + public ShellInitProfile? InitProfile { get; set; } + + /// + /// Ordered host-provided script paths sourced before each built-in shell command when the + /// entry's shell target matches the active shell. Use these for rc files, environment setup scripts, + /// or other custom scripts. A script that returns a nonzero status is reported, and later scripts + /// and the user command continue while the shell remains running. Because scripts are sourced into + /// the command shell, `exit`, `exec`, failures under `set -e`, or other shell-terminating behavior + /// can prevent continuation. Script standard output is preserved; Bash script stderr is discarded, + /// PowerShell exception messages are replaced, and runtime-generated failure notices omit + /// configured script paths. When sandboxing is enabled, each script must already be readable under + /// the active sandbox filesystem policy. Pass an empty array to clear the list. + /// + [JsonPropertyName("initScripts")] + public IList? InitScripts { get; set; } + + /// + /// Flags passed to the active built-in shell process on startup, replacing its default flags. + /// When omitted, the built-in Bash shell uses `--norc --noprofile`, + /// and the built-in PowerShell shell uses `-NoProfile -NoLogo`. + /// + [JsonPropertyName("processFlags")] + public IList? ProcessFlags { get; set; } +} + +/// Patch of mutable session options to apply to the running session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionUpdateOptionsParams +{ + /// Additional content-exclusion policies to merge into the session's policy set. + [Experimental(Diagnostics.Experimental)] + [JsonPropertyName("additionalContentExclusionPolicies")] + public IList? AdditionalContentExclusionPolicies { get; set; } + + /// Runtime context discriminator (e.g., `cli`, `actions`). + [JsonPropertyName("agentContext")] + public string? AgentContext { get; set; } + + /// Whether to include instructions from every MCP server in the system prompt instead of only allowlisted servers. + [JsonPropertyName("allowAllMcpServerInstructions")] + public bool? AllowAllMcpServerInstructions { get; set; } + + /// Whether to disable the `ask_user` tool (encourages autonomous behavior). + [JsonPropertyName("askUserDisabled")] + public bool? AskUserDisabled { get; set; } + + /// Allowlist of tool names available to this session. + [JsonPropertyName("availableTools")] + public IList? AvailableTools { get; set; } + + /// Options scoped to the built-in CAPI (Copilot API) provider. + [JsonPropertyName("capi")] + public CapiSessionOptions? Capi { get; set; } + + /// Identifier of the client driving the session. + [JsonPropertyName("clientName")] + public string? ClientName { get; set; } + + /// Whether to include the `Co-authored-by` trailer in commit messages. + [JsonPropertyName("coauthorEnabled")] + public bool? CoauthorEnabled { get; set; } + + /// Context tier for models with tiered pricing. The session uses this to derive effective `modelCapabilitiesOverrides` so compaction, truncation, token display, and request limits honor the selected tier. + [JsonPropertyName("contextTier")] + public OptionsUpdateContextTier? ContextTier { get; set; } + + /// Whether to allow auto-mode continuation across turns. + [JsonPropertyName("continueOnAutoMode")] + public bool? ContinueOnAutoMode { get; set; } + + /// Override URL for the Copilot API endpoint. + [JsonPropertyName("copilotUrl")] + public string? CopilotUrl { get; set; } + + /// Whether to default custom agents to local-only execution. + [JsonPropertyName("customAgentsLocalOnly")] + public bool? CustomAgentsLocalOnly { get; set; } + + /// Instruction source IDs to exclude from the system prompt. + [JsonPropertyName("disabledInstructionSources")] + public IList? DisabledInstructionSources { get; set; } + + /// Skill IDs that should be excluded from this session. + [JsonPropertyName("disabledSkills")] + public IList? DisabledSkills { get; set; } + + /// Whether to enable loading of `.github/hooks/` filesystem hooks. Separate from the SDK callback hook mechanism. + [JsonPropertyName("enableFileHooks")] + public bool? EnableFileHooks { get; set; } + + /// Whether to enable host git operations (context resolution, child repo scanning, git info in system prompt). + [JsonPropertyName("enableHostGitOperations")] + public bool? EnableHostGitOperations { get; set; } + + /// Whether to discover custom instructions on demand after successful file views (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md surfacing). Combined with `skipCustomInstructions`. + [JsonPropertyName("enableOnDemandInstructionDiscovery")] + public bool? EnableOnDemandInstructionDiscovery { get; set; } + + /// Whether to surface reasoning-summary events from the model. + [JsonPropertyName("enableReasoningSummaries")] + public bool? EnableReasoningSummaries { get; set; } + + /// Whether shell-script safety heuristics are enabled. + [JsonPropertyName("enableScriptSafety")] + public bool? EnableScriptSafety { get; set; } + + /// Whether to enable cross-session store writes and reads. + [JsonPropertyName("enableSessionStore")] + public bool? EnableSessionStore { get; set; } + + /// Whether to enable skill directory scanning and loading. Falls back to enableConfigDiscovery when unset. + [JsonPropertyName("enableSkills")] + public bool? EnableSkills { get; set; } + + /// Whether to stream model responses. + [JsonPropertyName("enableStreaming")] + public bool? EnableStreaming { get; set; } + + /// How env values are passed to MCP servers (`direct` inlines literal values; `indirect` resolves at launch). + [JsonPropertyName("envValueMode")] + public OptionsUpdateEnvValueMode? EnvValueMode { get; set; } + + /// Override directory for the session-events log. When unset, the runtime's default events log directory is used. + [JsonPropertyName("eventsLogDirectory")] + public string? EventsLogDirectory { get; set; } + + /// Whether subagent callback events should be forwarded into the session event log sink. + [JsonPropertyName("eventsLogIncludesSubagents")] + public bool? EventsLogIncludesSubagents { get; set; } + + /// Built-in subagent names to exclude from this session. Excluded built-ins are hidden from agent discovery and cannot be dispatched unless a custom agent with the same name is available. + [JsonPropertyName("excludedBuiltinAgents")] + public IList? ExcludedBuiltinAgents { get; set; } + + /// Denylist of tool names for this session. + [JsonPropertyName("excludedTools")] + public IList? ExcludedTools { get; set; } + + /// Map of feature-flag IDs to their boolean enabled state. + [JsonPropertyName("featureFlags")] + public IDictionary? FeatureFlags { get; set; } + + /// Built-in subagent names to include in this session. When specified, only these built-ins are available, subject to runtime availability and exclusions. Custom agents with the same name remain available. Set to null to remove the allowlist restriction. + [JsonPropertyName("includedBuiltinAgents")] + public IList? IncludedBuiltinAgents { get; set; } + + /// Full set of installed plugins for the session. Replaces the existing list; the runtime invalidates the skills cache only when the list materially changes. + [JsonPropertyName("installedPlugins")] + public IList? InstalledPlugins { get; set; } + + /// Stable integration identifier used for analytics and rate-limit attribution. + [JsonPropertyName("integrationId")] + public string? IntegrationId { get; set; } + + /// Whether experimental capabilities are enabled. + [JsonPropertyName("isExperimentalMode")] + public bool? IsExperimentalMode { get; set; } + + /// Whether interactive shell sessions are logged. + [JsonPropertyName("logInteractiveShells")] + public bool? LogInteractiveShells { get; set; } + + /// Identifier sent to LSP-style integrations. + [JsonPropertyName("lspClientName")] + public string? LspClientName { get; set; } + + /// 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). + [JsonPropertyName("manageScheduleEnabled")] + public bool? ManageScheduleEnabled { get; set; } + + /// Maximum decoded byte size of a single model-facing binary tool result (e.g. an image) persisted inline in session events and re-presented to the model on later turns / resume. Larger results are persisted as a metadata-only marker and shown to the model as a short text note. Defaults to 10 MB. + [JsonPropertyName("maxInlineBinaryBytes")] + public long? MaxInlineBinaryBytes { get; set; } + + /// The model ID to use for assistant turns. + [JsonPropertyName("model")] + public string? Model { get; set; } + + /// Per-property model capability overrides for the selected model. + [JsonPropertyName("modelCapabilitiesOverrides")] + public ModelCapabilitiesOverride? ModelCapabilitiesOverrides { get; set; } + + /// Organization-level custom instructions to inject into the system prompt. + [JsonPropertyName("organizationCustomInstructions")] + public string? OrganizationCustomInstructions { get; set; } + + /// Custom model-provider configuration (BYOK). + [JsonPropertyName("provider")] + public ProviderConfig? Provider { get; set; } + + /// Reasoning effort for the selected model (model-defined enum). + [JsonPropertyName("reasoningEffort")] + public string? ReasoningEffort { get; set; } + + /// Reasoning summary mode for supported model clients. [JsonPropertyName("reasoningSummary")] public OptionsUpdateReasoningSummary? ReasoningSummary { get; set; } - /// Whether the session is running in an interactive UI. - [JsonPropertyName("runningInInteractiveMode")] - public bool? RunningInInteractiveMode { get; set; } + /// Whether the session is running in an interactive UI. + [JsonPropertyName("runningInInteractiveMode")] + public bool? RunningInInteractiveMode { get; set; } + + /// Resolved sandbox configuration. + [JsonPropertyName("sandboxConfig")] + public SandboxConfig? SandboxConfig { get; set; } + + /// Replaces the session's capability set with the given list. Use to enable or disable capabilities mid-session (e.g., remove `memory` for reproducible scripted runs). Omit the field to leave the existing capability set unchanged. + [JsonPropertyName("sessionCapabilities")] + public IList? SessionCapabilities { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; + + /// Optional session limits. Pass null to clear the session limits. + [JsonPropertyName("sessionLimits")] + public SessionLimitsConfig? SessionLimits { get; set; } + + /// Per-session settings for built-in shell tools. + [JsonPropertyName("shell")] + public ShellOptions? Shell { get; set; } + + /// Use shell.initProfile instead. Shell init profile (`None` or `NonInteractive`). + [EditorBrowsable(EditorBrowsableState.Never)] +#if NET5_0_OR_GREATER + [Obsolete("This member is deprecated and will be removed in a future version.", DiagnosticId = "GHCP001")] +#endif + [JsonPropertyName("shellInitProfile")] + public string? ShellInitProfile { get; set; } + + /// PowerShell process flags applied to built-in and user-requested shell commands. + [JsonPropertyName("shellProcessFlags")] + public IList? ShellProcessFlags { get; set; } + + /// Additional directories to search for skills. + [JsonPropertyName("skillDirectories")] + public IList? SkillDirectories { get; set; } + + /// Whether to skip loading custom instruction sources. + [JsonPropertyName("skipCustomInstructions")] + public bool? SkipCustomInstructions { get; set; } + + /// Whether to skip embedding retrieval pipeline initialization and execution. + [JsonPropertyName("skipEmbeddingRetrieval")] + public bool? SkipEmbeddingRetrieval { get; set; } + + /// When true, the selected custom agent's prompt is not injected into the user message (skill context is still injected). Used by automation triggers where the agent prompt is already in the problem statement. + [JsonPropertyName("suppressCustomAgentPrompt")] + public bool? SuppressCustomAgentPrompt { get; set; } + + /// Controls how availableTools (allowlist) and excludedTools (denylist) combine when both are set. + [JsonPropertyName("toolFilterPrecedence")] + public OptionsUpdateToolFilterPrecedence? ToolFilterPrecedence { get; set; } + + /// Optional path for trajectory output. + [JsonPropertyName("trajectoryFile")] + public string? TrajectoryFile { get; set; } + + /// Output verbosity level for supported models. + [JsonPropertyName("verbosity")] + public Verbosity? Verbosity { get; set; } + + /// Absolute working-directory path for shell tools. + [JsonPropertyName("workingDirectory")] + public string? WorkingDirectory { get; set; } +} + +/// Parameters for (re)loading the merged LSP configuration set. +[Experimental(Diagnostics.Experimental)] +internal sealed class LspInitializeRequest +{ + /// Force re-initialization even when LSP configs were already loaded for the working directory. + [JsonPropertyName("force")] + public bool? Force { get; set; } + + /// Git root used as the boundary when traversing for project-level LSP configs (supports monorepos). + [JsonPropertyName("gitRoot")] + public string? GitRoot { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; + + /// Working directory used to load project-level LSP configs. Defaults to the session working directory when omitted. + [JsonPropertyName("workingDirectory")] + public string? WorkingDirectory { get; set; } +} + +/// Discovered extension metadata, including source-qualified ID, name, discovery source, status, and optional process ID. +[Experimental(Diagnostics.Experimental)] +public sealed class Extension +{ + /// Source-qualified ID (e.g., 'project:my-ext', 'user:auth-helper', 'plugin:my-plugin:my-ext'). + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; + + /// Extension name (directory name). + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; + + /// Process ID if the extension is running. + [JsonPropertyName("pid")] + public long? Pid { get; set; } + + /// Discovery source: project (.github/extensions/), user (~/.copilot/extensions/), plugin (installed plugin), or session (session-state/<id>/extensions/). + [JsonPropertyName("source")] + public ExtensionSource Source { get; set; } + + /// Current status: running, disabled, failed, or starting. + [JsonPropertyName("status")] + public ExtensionStatus Status { get; set; } +} + +/// Extensions discovered for the session, with their current status. +[Experimental(Diagnostics.Experimental)] +public sealed class ExtensionList +{ + /// Discovered extensions and their current status. + [JsonPropertyName("extensions")] + public IList Extensions { get => field ??= []; set; } +} + +/// Identifies the target session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionExtensionsListRequest +{ + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Source-qualified extension identifier to enable for the session. +[Experimental(Diagnostics.Experimental)] +internal sealed class ExtensionsEnableRequest +{ + /// Source-qualified extension ID to enable. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Source-qualified extension identifier to disable for the session. +[Experimental(Diagnostics.Experimental)] +internal sealed class ExtensionsDisableRequest +{ + /// Source-qualified extension ID to disable. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Identifies the target session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionExtensionsReloadRequest +{ + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Attachment union accepted by push input, covering files, directories, GitHub objects, blobs, snippets, and extension context. +/// Polymorphic base type discriminated by type. +[Experimental(Diagnostics.Experimental)] +[JsonPolymorphic( + TypeDiscriminatorPropertyName = "type", + UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] +[JsonDerivedType(typeof(PushAttachmentFile), "file")] +[JsonDerivedType(typeof(PushAttachmentDirectory), "directory")] +[JsonDerivedType(typeof(PushAttachmentSelection), "selection")] +[JsonDerivedType(typeof(PushAttachmentGitHubReference), "github_reference")] +[JsonDerivedType(typeof(PushAttachmentGitHubCommit), "github_commit")] +[JsonDerivedType(typeof(PushAttachmentGitHubRelease), "github_release")] +[JsonDerivedType(typeof(PushAttachmentGitHubActionsJob), "github_actions_job")] +[JsonDerivedType(typeof(PushAttachmentGitHubRepository), "github_repository")] +[JsonDerivedType(typeof(PushAttachmentGitHubFileDiff), "github_file_diff")] +[JsonDerivedType(typeof(PushAttachmentGitHubTreeComparison), "github_tree_comparison")] +[JsonDerivedType(typeof(PushAttachmentGitHubUrl), "github_url")] +[JsonDerivedType(typeof(PushAttachmentGitHubFile), "github_file")] +[JsonDerivedType(typeof(PushAttachmentGitHubSnippet), "github_snippet")] +[JsonDerivedType(typeof(PushAttachmentBlob), "blob")] +[JsonDerivedType(typeof(PushAttachmentExtensionContext), "extension_context")] +public partial class PushAttachment +{ + /// The type discriminator. + [JsonPropertyName("type")] + public virtual string Type { get; set; } = string.Empty; +} + + +/// Optional line range to scope the attachment to a specific section of the file. +[Experimental(Diagnostics.Experimental)] +public sealed class PushAttachmentFileLineRange +{ + /// End line number (1-based, inclusive). + [JsonPropertyName("end")] + public long End { get; set; } + + /// Start line number (1-based). + [JsonPropertyName("start")] + public long Start { get; set; } +} + +/// File attachment. +/// The file variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentFile : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "file"; + + /// User-facing display name for the attachment. + [JsonPropertyName("displayName")] + public required string DisplayName { get; set; } + + /// Optional line range to scope the attachment to a specific section of the file. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("lineRange")] + public PushAttachmentFileLineRange? LineRange { get; set; } + + /// Absolute file path. + [JsonPropertyName("path")] + public required string Path { get; set; } +} + +/// Directory attachment. +/// The directory variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentDirectory : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "directory"; + + /// User-facing display name for the attachment. + [JsonPropertyName("displayName")] + public required string DisplayName { get; set; } + + /// Absolute directory path. + [JsonPropertyName("path")] + public required string Path { get; set; } +} + +/// End position of the selection. +[Experimental(Diagnostics.Experimental)] +public sealed class PushAttachmentSelectionDetailsEnd +{ + /// End character offset within the line (0-based). + [JsonPropertyName("character")] + public long Character { get; set; } + + /// End line number (0-based). + [JsonPropertyName("line")] + public long Line { get; set; } +} + +/// Start position of the selection. +[Experimental(Diagnostics.Experimental)] +public sealed class PushAttachmentSelectionDetailsStart +{ + /// Start character offset within the line (0-based). + [JsonPropertyName("character")] + public long Character { get; set; } + + /// Start line number (0-based). + [JsonPropertyName("line")] + public long Line { get; set; } +} + +/// Position range of the selection within the file. +[Experimental(Diagnostics.Experimental)] +public sealed class PushAttachmentSelectionDetails +{ + /// End position of the selection. + [JsonPropertyName("end")] + public PushAttachmentSelectionDetailsEnd End { get => field ??= new(); set; } + + /// Start position of the selection. + [JsonPropertyName("start")] + public PushAttachmentSelectionDetailsStart Start { get => field ??= new(); set; } +} + +/// Code selection attachment from an editor. +/// The selection variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentSelection : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "selection"; + + /// User-facing display name for the selection. + [JsonPropertyName("displayName")] + public required string DisplayName { get; set; } + + /// Absolute path to the file containing the selection. + [JsonPropertyName("filePath")] + public required string FilePath { get; set; } + + /// Position range of the selection within the file. + [JsonPropertyName("selection")] + public required PushAttachmentSelectionDetails Selection { get; set; } + + /// The selected text content. + [JsonPropertyName("text")] + public required string Text { get; set; } +} + +/// GitHub issue, pull request, or discussion reference. +/// The github_reference variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentGitHubReference : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "github_reference"; + + /// Issue, pull request, or discussion number. + [JsonPropertyName("number")] + public required long Number { get; set; } + + /// Type of GitHub reference. + [JsonPropertyName("referenceType")] + public required PushAttachmentGitHubReferenceType ReferenceType { get; set; } + + /// Current state of the referenced item (e.g., open, closed, merged). + [JsonPropertyName("state")] + public required string State { get; set; } + + /// Title of the referenced item. + [JsonPropertyName("title")] + public required string Title { get; set; } + + /// URL to the referenced item on GitHub. + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// Pointer to a GitHub repository. +[Experimental(Diagnostics.Experimental)] +public sealed class PushGitHubRepoRef +{ + /// Numeric GitHub repository id. + [JsonPropertyName("id")] + public long? Id { get; set; } + + /// Repository name (without owner). + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; + + /// Repository owner login (user or organization). + [JsonPropertyName("owner")] + public string Owner { get; set; } = string.Empty; +} + +/// Pointer to a GitHub commit. +/// The github_commit variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentGitHubCommit : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "github_commit"; + + /// First line of the commit message. + [JsonPropertyName("message")] + public required string Message { get; set; } + + /// Full commit SHA. + [JsonPropertyName("oid")] + public required string Oid { get; set; } + + /// Repository the commit belongs to. + [JsonPropertyName("repo")] + public required PushGitHubRepoRef Repo { get; set; } + + /// URL to the commit on GitHub. + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// Pointer to a GitHub release. +/// The github_release variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentGitHubRelease : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "github_release"; + + /// Human-readable release name. + [JsonPropertyName("name")] + public required string Name { get; set; } + + /// Repository the release belongs to. + [JsonPropertyName("repo")] + public required PushGitHubRepoRef Repo { get; set; } + + /// Git tag the release is anchored to. + [JsonPropertyName("tagName")] + public required string TagName { get; set; } + + /// URL to the release on GitHub. + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// Pointer to a GitHub Actions job. +/// The github_actions_job variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentGitHubActionsJob : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "github_actions_job"; + + /// Terminal conclusion of the job when finished (e.g., success, failure, cancelled). Absent for in-progress jobs. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("conclusion")] + public string? Conclusion { get; set; } + + /// Job id within the workflow run. + [JsonPropertyName("jobId")] + public required long JobId { get; set; } + + /// Display name of the job. + [JsonPropertyName("jobName")] + public required string JobName { get; set; } + + /// Repository the workflow run belongs to. + [JsonPropertyName("repo")] + public required PushGitHubRepoRef Repo { get; set; } + + /// URL to the job on GitHub. + [JsonPropertyName("url")] + public required string Url { get; set; } + + /// Display name of the workflow the job ran in. + [JsonPropertyName("workflowName")] + public required string WorkflowName { get; set; } +} + +/// Pointer to a GitHub repository. +/// The github_repository variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentGitHubRepository : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "github_repository"; + + /// Short description of the repository. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("description")] + public string? Description { get; set; } + + /// Git ref this attachment is anchored at (branch, tag, or commit). When absent the default branch is implied. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("ref")] + public string? Ref { get; set; } + + /// Repository pointer. + [JsonPropertyName("repo")] + public required PushGitHubRepoRef Repo { get; set; } + + /// URL to the repository on GitHub. + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// One side of a file diff (head or base). +[Experimental(Diagnostics.Experimental)] +public sealed class PushAttachmentGitHubFileDiffSide +{ + /// Repository-relative path to the file. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; + + /// Git ref (branch, tag, or commit SHA) the file is read at. + [JsonPropertyName("ref")] + public string Ref { get; set; } = string.Empty; + + /// Repository the file lives in. + [JsonPropertyName("repo")] + public PushGitHubRepoRef Repo { get => field ??= new(); set; } +} + +/// Pointer to a single-file diff. At least one of `head` and `base` must be present. +/// The github_file_diff variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentGitHubFileDiff : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "github_file_diff"; + + /// File location on the base side of the diff. Absent for additions. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("base")] + public PushAttachmentGitHubFileDiffSide? Base { get; set; } + + /// File location on the head side of the diff. Absent for deletions. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("head")] + public PushAttachmentGitHubFileDiffSide? Head { get; set; } + + /// URL to the diff on GitHub (e.g., a commit, compare, or PR-file URL). + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// One side of a tree comparison (head or base). +[Experimental(Diagnostics.Experimental)] +public sealed class PushAttachmentGitHubTreeComparisonSide +{ + /// Repository the revision belongs to. + [JsonPropertyName("repo")] + public PushGitHubRepoRef Repo { get => field ??= new(); set; } + + /// Git revision (branch, tag, or commit SHA). + [JsonPropertyName("revision")] + public string Revision { get; set; } = string.Empty; +} + +/// Pointer to a comparison between two git revisions. +/// The github_tree_comparison variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentGitHubTreeComparison : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "github_tree_comparison"; + + /// Base side of the comparison. + [JsonPropertyName("base")] + public required PushAttachmentGitHubTreeComparisonSide Base { get; set; } + + /// Head side of the comparison. + [JsonPropertyName("head")] + public required PushAttachmentGitHubTreeComparisonSide Head { get; set; } + + /// URL to the comparison on GitHub. + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// Generic GitHub URL reference. +/// The github_url variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentGitHubUrl : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "github_url"; + + /// URL to the GitHub resource. + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// Pointer to a file in a GitHub repository at a specific ref. +/// The github_file variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentGitHubFile : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "github_file"; + + /// Repository-relative path to the file. + [JsonPropertyName("path")] + public required string Path { get; set; } + + /// Git ref the file is read at (branch, tag, or commit SHA). + [JsonPropertyName("ref")] + public required string Ref { get; set; } + + /// Repository the file lives in. + [JsonPropertyName("repo")] + public required PushGitHubRepoRef Repo { get; set; } + + /// URL to the file on GitHub. + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// Pointer to a line range inside a file in a GitHub repository. +/// The github_snippet variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentGitHubSnippet : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "github_snippet"; + + /// Line range the snippet covers. + [JsonPropertyName("lineRange")] + public required PushAttachmentFileLineRange LineRange { get; set; } + + /// Repository-relative path to the file. + [JsonPropertyName("path")] + public required string Path { get; set; } + + /// Git ref the file is read at (branch, tag, or commit SHA). + [JsonPropertyName("ref")] + public required string Ref { get; set; } + + /// Repository the file lives in. + [JsonPropertyName("repo")] + public required PushGitHubRepoRef Repo { get; set; } + + /// URL to the snippet on GitHub (with line anchor). + [JsonPropertyName("url")] + public required string Url { get; set; } +} + +/// Blob attachment with inline base64-encoded data. +/// The blob variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentBlob : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "blob"; + + /// Base64-encoded content. + [Base64String] + [JsonPropertyName("data")] + public required string Data { get; set; } + + /// User-facing display name for the attachment. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("displayName")] + public string? DisplayName { get; set; } + + /// MIME type of the inline data. + [JsonPropertyName("mimeType")] + public required string MimeType { get; set; } +} + +/// Slim input shape for extension_context attachments; identity fields are runtime-derived. +/// The extension_context variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PushAttachmentExtensionContext : PushAttachment +{ + /// + [JsonIgnore] + public override string Type => "extension_context"; + + /// Caller-supplied JSON payload (required, may be null but not undefined). + [JsonPropertyName("payload")] + public required JsonElement Payload { get; set; } + + /// Human-readable composer pill label. + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] + [MinLength(1)] + [JsonPropertyName("title")] + public required string Title { get; set; } +} + +/// Parameters for session.extensions.sendAttachmentsToMessage. +[Experimental(Diagnostics.Experimental)] +internal sealed class SendAttachmentsToMessageParams +{ + /// Attachments to push into the next user-message turn. extension_context entries take the slim shape; standard variants take their full AttachmentSchema shape. + [JsonPropertyName("attachments")] + public IList Attachments { get => field ??= []; set; } + + /// Optional canvas instance binding the push for provenance. When supplied, the runtime resolves the canvas, verifies it is owned by the calling extension, and stamps canvasId/instanceId onto each extension_context entry. When omitted, no resolution runs and those fields stay unset on the attachment. + [JsonPropertyName("instanceId")] + public string? InstanceId { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Indicates whether the external tool call result was handled successfully. +[Experimental(Diagnostics.Experimental)] +public sealed class HandlePendingToolCallResult +{ + /// Whether the tool call result was handled successfully. + [JsonPropertyName("success")] + public bool Success { get; set; } +} + +/// Pending external tool call request ID, with the tool result or an error describing why it failed. +[Experimental(Diagnostics.Experimental)] +internal sealed class HandlePendingToolCallRequest +{ + /// Error message if the tool call failed. + [JsonPropertyName("error")] + public string? Error { get; set; } + + /// Request ID of the pending tool call. + [JsonPropertyName("requestId")] + public string RequestId { get; set; } = string.Empty; + + /// Tool call result (string or expanded result object). + [JsonPropertyName("result")] + public JsonElement? Result { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Resolve, build, and validate the runtime tool list for this session. Subagent sessions and consumer flows that need an initialized tool set before `send` invoke this. Default base-class implementation is a no-op for sessions that don't support tool validation. +[Experimental(Diagnostics.Experimental)] +public sealed class ToolsInitializeAndValidateResult +{ +} + +/// Identifies the target session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionToolsInitializeAndValidateRequest +{ + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Lightweight metadata for a currently initialized session tool. +[Experimental(Diagnostics.Experimental)] +public sealed class CurrentToolMetadata +{ + /// Whether the tool is loaded on demand via tool search. + [JsonPropertyName("deferLoading")] + public bool? DeferLoading { get; set; } + + /// Tool description. + [JsonPropertyName("description")] + public string Description { get; set; } = string.Empty; + + /// JSON Schema for tool input. + [JsonPropertyName("input_schema")] + public IDictionary? InputSchema { get; set; } + + /// MCP server name for MCP-backed tools. + [JsonPropertyName("mcpServerName")] + public string? McpServerName { get; set; } + + /// Raw MCP tool name for MCP-backed tools. + [JsonPropertyName("mcpToolName")] + public string? McpToolName { get; set; } + + /// Model-facing tool name. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; + + /// Optional MCP/config namespaced tool name. + [JsonPropertyName("namespacedName")] + public string? NamespacedName { get; set; } +} + +/// Current lightweight tool metadata snapshot for the session. +[Experimental(Diagnostics.Experimental)] +public sealed class ToolsGetCurrentMetadataResult +{ + /// Current tool metadata, or null when tools have not been initialized yet. + [JsonPropertyName("tools")] + public IList? Tools { get; set; } +} + +/// Identifies the target session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionToolsGetCurrentMetadataRequest +{ + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Empty result after applying subagent settings. +[Experimental(Diagnostics.Experimental)] +public sealed class ToolsUpdateSubagentSettingsResult +{ +} + +/// Subagent model, reasoning effort, and context tier settings. +[Experimental(Diagnostics.Experimental)] +public sealed class SubagentSettingsEntry +{ + /// Context tier override for matching subagents. + [JsonPropertyName("contextTier")] + public SubagentSettingsEntryContextTier? ContextTier { get; set; } + + /// Reasoning effort override for matching subagents. + [JsonPropertyName("effortLevel")] + public string? EffortLevel { get; set; } + + /// Model override for matching subagents. + [JsonPropertyName("model")] + public string? Model { get; set; } +} + +/// Configured per-agent subagent overrides. +public sealed class UpdateSubagentSettingsRequestSubagents +{ + /// Per-agent settings keyed by subagent agent_type. + [JsonPropertyName("agents")] + public IDictionary? Agents { get; set; } + + /// Names of subagents the user has turned off; they cannot be dispatched. + [JsonPropertyName("disabledSubagents")] + public IList? DisabledSubagents { get; set; } + + /// Maximum number of subagents that can run concurrently; applies to usage-based billing users only. + [JsonPropertyName("maxConcurrency")] + public int? MaxConcurrency { get; set; } + + /// Maximum subagent nesting depth; applies to usage-based billing users only. + [JsonPropertyName("maxDepth")] + public int? MaxDepth { get; set; } +} + +/// Subagent settings to apply to the current session. +[Experimental(Diagnostics.Experimental)] +internal sealed class UpdateSubagentSettingsRequest +{ + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; + + /// Subagent settings to apply, or null to clear the live session override. + [JsonPropertyName("subagents")] + public UpdateSubagentSettingsRequestSubagents? Subagents { get; set; } +} + +/// RPC data type for SessionCommandsList operations. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionCommandsListRequest +{ + /// Include runtime built-in commands. + [JsonPropertyName("includeBuiltins")] + public bool? IncludeBuiltins { get; set; } + + /// Include commands registered by protocol clients, including SDK clients and extensions. + [JsonPropertyName("includeClientCommands")] + public bool? IncludeClientCommands { get; set; } + + /// Include enabled user-invocable skills and commands. + [JsonPropertyName("includeSkills")] + public bool? IncludeSkills { get; set; } +} + +/// RPC data type for SessionCommandsListRequestWithSession operations. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionCommandsListRequestWithSession +{ + /// Include runtime built-in commands. + [JsonPropertyName("includeBuiltins")] + public bool? IncludeBuiltins { get; set; } + + /// Include commands registered by protocol clients, including SDK clients and extensions. + [JsonPropertyName("includeClientCommands")] + public bool? IncludeClientCommands { get; set; } + + /// Include enabled user-invocable skills and commands. + [JsonPropertyName("includeSkills")] + public bool? IncludeSkills { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Result of invoking the slash command (text output, prompt to send to the agent, completion, or subcommand selection). +/// Polymorphic base type discriminated by kind. +[Experimental(Diagnostics.Experimental)] +[JsonPolymorphic( + TypeDiscriminatorPropertyName = "kind", + UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] +[JsonDerivedType(typeof(SlashCommandInvocationResultText), "text")] +[JsonDerivedType(typeof(SlashCommandInvocationResultAgentPrompt), "agent-prompt")] +[JsonDerivedType(typeof(SlashCommandInvocationResultCompleted), "completed")] +[JsonDerivedType(typeof(SlashCommandInvocationResultSelectSubcommand), "select-subcommand")] +public partial class SlashCommandInvocationResult +{ + /// The type discriminator. + [JsonPropertyName("kind")] + public virtual string Kind { get; set; } = string.Empty; +} + + +/// Slash-command invocation result containing text output plus Markdown/ANSI rendering flags. +/// The text variant of . +[Experimental(Diagnostics.Experimental)] +public partial class SlashCommandInvocationResultText : SlashCommandInvocationResult +{ + /// + [JsonIgnore] + public override string Kind => "text"; + + /// Whether text contains Markdown. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("markdown")] + public bool? Markdown { get; set; } + + /// Whether ANSI sequences should be preserved. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("preserveAnsi")] + public bool? PreserveAnsi { get; set; } + + /// True when the invocation mutated user runtime settings; consumers caching settings should refresh. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("runtimeSettingsChanged")] + public bool? RuntimeSettingsChanged { get; set; } + + /// Text output for the client to render. + [JsonPropertyName("text")] + public required string Text { get; set; } +} + +/// Slash-command invocation result that submits an agent prompt, with display prompt, optional mode, optional user-facing notice, and settings-change flag. +/// The agent-prompt variant of . +[Experimental(Diagnostics.Experimental)] +public partial class SlashCommandInvocationResultAgentPrompt : SlashCommandInvocationResult +{ + /// + [JsonIgnore] + public override string Kind => "agent-prompt"; + + /// Prompt text to display to the user. + [JsonPropertyName("displayPrompt")] + public required string DisplayPrompt { get; set; } + + /// Optional target session mode for the agent prompt. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("mode")] + public SessionMode? Mode { get; set; } + + /// Optional user-facing notice to show before the prompt is submitted. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("notice")] + public string? Notice { get; set; } + + /// Prompt to submit to the agent. + [JsonPropertyName("prompt")] + public required string Prompt { get; set; } + + /// True when the invocation mutated user runtime settings; consumers caching settings should refresh. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("runtimeSettingsChanged")] + public bool? RuntimeSettingsChanged { get; set; } +} + +/// Slash-command invocation result indicating completion, with optional message and settings-change flag. +/// The completed variant of . +[Experimental(Diagnostics.Experimental)] +public partial class SlashCommandInvocationResultCompleted : SlashCommandInvocationResult +{ + /// + [JsonIgnore] + public override string Kind => "completed"; + + /// Optional user-facing message describing the completed command. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("message")] + public string? Message { get; set; } + + /// True when the invocation mutated user runtime settings; consumers caching settings should refresh. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("runtimeSettingsChanged")] + public bool? RuntimeSettingsChanged { get; set; } +} + +/// Selectable slash-command subcommand option with name, description, and optional group label. +[Experimental(Diagnostics.Experimental)] +public sealed class SlashCommandSelectSubcommandOption +{ + /// Human-readable description of the subcommand. + [JsonPropertyName("description")] + public string Description { get; set; } = string.Empty; + + /// Optional group label for organizing options. + [JsonPropertyName("group")] + public string? Group { get; set; } + + /// Subcommand name to invoke. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; +} + +/// Slash-command invocation result asking the client to present subcommand options for a parent command. +/// The select-subcommand variant of . +[Experimental(Diagnostics.Experimental)] +public partial class SlashCommandInvocationResultSelectSubcommand : SlashCommandInvocationResult +{ + /// + [JsonIgnore] + public override string Kind => "select-subcommand"; + + /// Parent command name that requires subcommand selection. + [JsonPropertyName("command")] + public required string Command { get; set; } + + /// Available subcommand options for the client to present. + [JsonPropertyName("options")] + public required IList Options { get; set; } + + /// True when the invocation mutated user runtime settings; consumers caching settings should refresh. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("runtimeSettingsChanged")] + public bool? RuntimeSettingsChanged { get; set; } + + /// Human-readable title for the selection UI. + [JsonPropertyName("title")] + public required string Title { get; set; } +} + +/// Slash command name and optional raw input string to invoke. +[Experimental(Diagnostics.Experimental)] +internal sealed class CommandsInvokeRequest +{ + /// Raw input after the command name. + [JsonPropertyName("input")] + public string? Input { get; set; } + + /// Command name. Leading slashes are stripped and the name is matched case-insensitively. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Indicates whether the pending client-handled command was completed successfully. +[Experimental(Diagnostics.Experimental)] +public sealed class CommandsHandlePendingCommandResult +{ + /// Whether the command was handled successfully. + [JsonPropertyName("success")] + public bool Success { get; set; } +} + +/// Pending command request ID and an optional error if the client handler failed. +[Experimental(Diagnostics.Experimental)] +internal sealed class CommandsHandlePendingCommandRequest +{ + /// Error message if the command handler failed. + [JsonPropertyName("error")] + public string? Error { get; set; } + + /// Request ID from the command invocation event. + [JsonPropertyName("requestId")] + public string RequestId { get; set; } = string.Empty; + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Error message produced while executing the command, if any. +[Experimental(Diagnostics.Experimental)] +public sealed class ExecuteCommandResult +{ + /// Error message produced while executing the command, if any. Omitted when the handler succeeded. + [JsonPropertyName("error")] + public string? Error { get; set; } +} + +/// Slash command name and argument string to execute synchronously. +[Experimental(Diagnostics.Experimental)] +internal sealed class ExecuteCommandParams +{ + /// Argument string to pass to the command (empty string if none). + [JsonPropertyName("args")] + public string Args { get; set; } = string.Empty; + + /// Name of the slash command to invoke (without the leading '/'). + [JsonPropertyName("commandName")] + public string CommandName { get; set; } = string.Empty; + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Indicates whether the command was accepted into the local execution queue. +[Experimental(Diagnostics.Experimental)] +public sealed class EnqueueCommandResult +{ + /// True when the command was accepted into the local execution queue. False when the call targets a session that does not support local command queueing (e.g. remote sessions). + [JsonPropertyName("queued")] + public bool Queued { get; set; } +} + +/// Slash-prefixed command string to enqueue for FIFO processing. +[Experimental(Diagnostics.Experimental)] +internal sealed class EnqueueCommandParams +{ + /// Slash-prefixed command string to enqueue, e.g. '/compact' or '/model gpt-4'. Queued FIFO with any in-flight items; if the session is idle, processing kicks off immediately. + [JsonPropertyName("command")] + public string Command { get; set; } = string.Empty; + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Indicates whether the queued-command response was matched to a pending request. +[Experimental(Diagnostics.Experimental)] +public sealed class CommandsRespondToQueuedCommandResult +{ + /// Whether a pending queued command with the given request ID was found and resolved. False when the request was already resolved, cancelled, or unknown. + [JsonPropertyName("success")] + public bool Success { get; set; } +} + +/// Result of the queued command execution. +/// Data type discriminated by handled. +[Experimental(Diagnostics.Experimental)] +public partial class QueuedCommandResult +{ + /// The boolean discriminator. + [JsonPropertyName("handled")] + public bool Handled { get; set; } + + /// When true, the runtime will not process subsequent queued commands until a new request comes in. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("stopProcessingQueue")] + public bool? StopProcessingQueue { get; set; } +} + +/// Queued-command request ID and the result indicating whether the host executed it (and whether to stop processing further queued commands). +[Experimental(Diagnostics.Experimental)] +internal sealed class CommandsRespondToQueuedCommandRequest +{ + /// Request ID from the `command.queued` event the host is responding to. + [JsonPropertyName("requestId")] + public string RequestId { get; set; } = string.Empty; + + /// Result of the queued command execution. + [JsonPropertyName("result")] + public QueuedCommandResult Result { get => field ??= new(); set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Telemetry engagement ID for the session, when available. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionTelemetryEngagement +{ + /// Current telemetry engagement ID, when available. + [JsonPropertyName("engagementId")] + public string? EngagementId { get; set; } +} + +/// Identifies the target session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionTelemetryGetEngagementIdRequest +{ + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Feature override key/value pairs to attach to subsequent telemetry events from this session. +[Experimental(Diagnostics.Experimental)] +internal sealed class TelemetrySetFeatureOverridesRequest +{ + /// Override key/value pairs to attach to subsequent telemetry events from this session. Replaces any previously-set overrides. + [JsonPropertyName("features")] + public IDictionary Features { get => field ??= new Dictionary(); set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Transient answer generated from current conversation context. +[Experimental(Diagnostics.Experimental)] +public sealed class UIEphemeralQueryResult +{ + /// Full assistant response text. + [JsonPropertyName("answer")] + public string Answer { get; set; } = string.Empty; +} + +/// Transient question to answer without adding it to conversation history. +[Experimental(Diagnostics.Experimental)] +internal sealed class UIEphemeralQueryRequest +{ + /// In-process `AbortSignal` forwarded to the model client to cancel an in-flight request. Marked internal: excluded from the public SDK surface. Replaced by an explicit cancellation token + cancel RPC in the SDK migration. + [JsonInclude] + [JsonPropertyName("abortSignal")] + internal JsonElement? AbortSignal { get; set; } + + /// In-process streaming callback `(text) => void` invoked with each token as the model emits it. Marked internal: excluded from the public SDK surface. In a process-separated SDK this is replaced by a streaming RPC that yields chunks and a final answer. + [JsonInclude] + [JsonPropertyName("onChunk")] + internal JsonElement? OnChunk { get; set; } + + /// Question to answer from the current conversation context. + [JsonPropertyName("question")] + public string Question { get; set; } = string.Empty; + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// The elicitation response (accept with form values, decline, or cancel). +[Experimental(Diagnostics.Experimental)] +public sealed class UIElicitationResponse +{ + /// The user's response: accept (submitted), decline (rejected), or cancel (dismissed). + [JsonPropertyName("action")] + public UIElicitationResponseAction Action { get; set; } + + /// The form values submitted by the user (present when action is 'accept'). + [JsonPropertyName("content")] + public IDictionary? Content { get; set; } +} + +/// JSON Schema describing the form fields to present to the user. +[Experimental(Diagnostics.Experimental)] +public sealed class UIElicitationSchema +{ + /// Form field definitions, keyed by field name. + [JsonPropertyName("properties")] + public IDictionary Properties { get => field ??= new Dictionary(); set; } + + /// List of required field names. + [JsonPropertyName("required")] + public IList? Required { get; set; } + + /// Schema type indicator (always 'object'). + [JsonPropertyName("type")] + public string Type { get; set; } = string.Empty; +} + +/// Prompt message and JSON schema describing the form fields to elicit from the user. +[Experimental(Diagnostics.Experimental)] +internal sealed class UIElicitationRequest +{ + /// Message describing what information is needed from the user. + [JsonPropertyName("message")] + public string Message { get; set; } = string.Empty; + + /// JSON Schema describing the form fields to present to the user. + [JsonPropertyName("requestedSchema")] + public UIElicitationSchema RequestedSchema { get => field ??= new(); set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Indicates whether the elicitation response was accepted; false if it was already resolved by another client. +[Experimental(Diagnostics.Experimental)] +public sealed class UIElicitationResult +{ + /// Whether the response was accepted. False if the request was already resolved by another client. + [JsonPropertyName("success")] + public bool Success { get; set; } +} + +/// Pending elicitation request ID and the user's response (accept/decline/cancel + form values). +[Experimental(Diagnostics.Experimental)] +internal sealed class UIHandlePendingElicitationRequest +{ + /// The unique request ID from the elicitation.requested event. + [JsonPropertyName("requestId")] + public string RequestId { get; set; } = string.Empty; + + /// The elicitation response (accept with form values, decline, or cancel). + [JsonPropertyName("result")] + public UIElicitationResponse Result { get => field ??= new(); set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Indicates whether the pending UI request was resolved by this call. +[Experimental(Diagnostics.Experimental)] +public sealed class UIHandlePendingResult +{ + /// True if the request was still pending and was resolved by this call. False if the request ID was unknown, already resolved by another client (e.g. GitHub), expired, or otherwise no longer pending. + [JsonPropertyName("success")] + public bool Success { get; set; } +} + +/// User response for a pending user-input request, with answer text and whether it was typed freeform. +[Experimental(Diagnostics.Experimental)] +public sealed class UIUserInputResponse +{ + /// The user's answer text. + [JsonPropertyName("answer")] + public string Answer { get; set; } = string.Empty; + + /// True if the user typed a freeform response, false if they selected a presented choice. Used by telemetry to differentiate between free text input and choice selection. + [JsonPropertyName("wasFreeform")] + public bool WasFreeform { get; set; } +} + +/// Request ID of a pending `user_input.requested` event and the user's response. +[Experimental(Diagnostics.Experimental)] +internal sealed class UIHandlePendingUserInputRequest +{ + /// The unique request ID from the user_input.requested event. + [JsonPropertyName("requestId")] + public string RequestId { get; set; } = string.Empty; + + /// User response for a pending user-input request, with answer text and whether it was typed freeform. + [JsonPropertyName("response")] + public UIUserInputResponse Response { get => field ??= new(); set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Optional sampling result payload. Omit to reject/cancel the sampling request without providing a result. +[Experimental(Diagnostics.Experimental)] +public sealed class UIHandlePendingSamplingResponse +{ +} + +/// Request ID of a pending `sampling.requested` event and an optional sampling result payload (omit to reject). +[Experimental(Diagnostics.Experimental)] +internal sealed class UIHandlePendingSamplingRequest +{ + /// The unique request ID from the sampling.requested event. + [JsonPropertyName("requestId")] + public string RequestId { get; set; } = string.Empty; + + /// Optional sampling result payload. Omit to reject/cancel the sampling request without providing a result. + [JsonPropertyName("response")] + public UIHandlePendingSamplingResponse? Response { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Request ID of a pending `auto_mode_switch.requested` event and the user's response. +[Experimental(Diagnostics.Experimental)] +internal sealed class UIHandlePendingAutoModeSwitchRequest +{ + /// The unique request ID from the auto_mode_switch.requested event. + [JsonPropertyName("requestId")] + public string RequestId { get; set; } = string.Empty; + + /// User's choice for auto-mode switching: yes (allow this turn), yes_always (allow + persist as setting), or no (decline). + [JsonPropertyName("response")] + public UIAutoModeSwitchResponse Response { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// The user's selected action for an exhausted session limit. +[Experimental(Diagnostics.Experimental)] +public sealed class UISessionLimitsExhaustedResponse +{ + /// Action selected by the user. + [JsonPropertyName("action")] + public UISessionLimitsExhaustedResponseAction Action { get; set; } + + /// AI Credits to add to the current max when action is 'add'. + [JsonPropertyName("additionalAiCredits")] + public double? AdditionalAiCredits { get; set; } + + /// New absolute max AI Credits when action is 'set'. + [JsonPropertyName("maxAiCredits")] + public double? MaxAiCredits { get; set; } +} + +/// Request ID of a pending `session_limits_exhausted.requested` event and the user's selected limit action. +[Experimental(Diagnostics.Experimental)] +internal sealed class UIHandlePendingSessionLimitsExhaustedRequest +{ + /// The unique request ID from the session_limits_exhausted.requested event. + [JsonPropertyName("requestId")] + public string RequestId { get; set; } = string.Empty; + + /// The selected session-limit action. + [JsonPropertyName("response")] + public UISessionLimitsExhaustedResponse Response { get => field ??= new(); set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// User response for a pending exit-plan-mode request, with approval state, selected action, auto-approve flag, and feedback. +[Experimental(Diagnostics.Experimental)] +public sealed class UIExitPlanModeResponse +{ + /// Whether the plan was approved. + [JsonPropertyName("approved")] + public bool Approved { get; set; } + + /// Whether subsequent edits should be auto-approved without confirmation. + [JsonPropertyName("autoApproveEdits")] + public bool? AutoApproveEdits { get; set; } + + /// When true, the agent is instructed to end its turn without starting implementation so the client can restore the session model and auto-submit a fresh implementation turn on it. Set only when a distinct plan configuration (a different model, reasoning effort, or context tier) actually ran the planning turn. + [JsonPropertyName("deferImplementation")] + public bool? DeferImplementation { get; set; } + + /// Feedback from the user when they declined the plan or requested changes. + [JsonPropertyName("feedback")] + public string? Feedback { get; set; } + + /// The action the user selected. Defaults to 'autopilot' when autoApproveEdits is true, otherwise 'interactive'. + [JsonPropertyName("selectedAction")] + public UIExitPlanModeAction? SelectedAction { get; set; } +} + +/// Request ID of a pending `exit_plan_mode.requested` event and the user's response. +[Experimental(Diagnostics.Experimental)] +internal sealed class UIHandlePendingExitPlanModeRequest +{ + /// The unique request ID from the exit_plan_mode.requested event. + [JsonPropertyName("requestId")] + public string RequestId { get; set; } = string.Empty; + + /// User response for a pending exit-plan-mode request, with approval state, selected action, auto-approve flag, and feedback. + [JsonPropertyName("response")] + public UIExitPlanModeResponse Response { get => field ??= new(); set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Register an in-process handler for `auto_mode_switch.requested` events. The caller still attaches the actual listener via the standard event-subscription mechanism; this registration solely tells the server bridge to skip its own dispatch (so a remote client doesn't race the in-process handler for the same requestId). +[Experimental(Diagnostics.Experimental)] +public sealed class UIRegisterDirectAutoModeSwitchHandlerResult +{ + /// Opaque handle representing the registration. Pass this same handle to `unregisterDirectAutoModeSwitchHandler` when the in-process handler is no longer active. Multiple registrations are reference-counted; the server bridge will only dispatch auto-mode-switch requests when no handles are active. + [JsonPropertyName("handle")] + public string Handle { get; set; } = string.Empty; +} + +/// Identifies the target session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionUiRegisterDirectAutoModeSwitchHandlerRequest +{ + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Indicates whether the handle was active and the registration count was decremented. +[Experimental(Diagnostics.Experimental)] +public sealed class UIUnregisterDirectAutoModeSwitchHandlerResult +{ + /// True if the handle was active and decremented the counter; false if the handle was unknown. + [JsonPropertyName("unregistered")] + public bool Unregistered { get; set; } +} + +/// Opaque handle previously returned by `registerDirectAutoModeSwitchHandler` to release. +[Experimental(Diagnostics.Experimental)] +internal sealed class UIUnregisterDirectAutoModeSwitchHandlerRequest +{ + /// Handle previously returned by `registerDirectAutoModeSwitchHandler`. + [JsonPropertyName("handle")] + public string Handle { get; set; } = string.Empty; + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Indicates whether the operation succeeded. +[Experimental(Diagnostics.Experimental)] +public sealed class PermissionsConfigureResult +{ + /// Whether the operation succeeded. + [JsonPropertyName("success")] + public bool Success { get; set; } +} + +/// Source descriptor for a `session.permissions.configure` content-exclusion rule, with source name and type. +[Experimental(Diagnostics.Experimental)] +public sealed class PermissionsConfigureAdditionalContentExclusionPolicyRuleSource +{ + /// Gets or sets the name value. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; + + /// Gets or sets the type value. + [JsonPropertyName("type")] + public string Type { get; set; } = string.Empty; +} + +/// Single content-exclusion rule supplied to `session.permissions.configure`, with paths, match conditions, and source. +[Experimental(Diagnostics.Experimental)] +public sealed class PermissionsConfigureAdditionalContentExclusionPolicyRule +{ + /// Gets or sets the ifAnyMatch value. + [JsonPropertyName("ifAnyMatch")] + public IList? IfAnyMatch { get; set; } + + /// Gets or sets the ifNoneMatch value. + [JsonPropertyName("ifNoneMatch")] + public IList? IfNoneMatch { get; set; } + + /// Gets or sets the paths value. + [JsonPropertyName("paths")] + public IList Paths { get => field ??= []; set; } + + /// Source descriptor for a `session.permissions.configure` content-exclusion rule, with source name and type. + [JsonPropertyName("source")] + public PermissionsConfigureAdditionalContentExclusionPolicyRuleSource Source { get => field ??= new(); set; } +} + +/// Content-exclusion policy supplied to `session.permissions.configure`, with rules, last-updated data, and scope. +[Experimental(Diagnostics.Experimental)] +public sealed class PermissionsConfigureAdditionalContentExclusionPolicy +{ + /// Gets or sets the last_updated_at value. + [JsonPropertyName("last_updated_at")] + public JsonElement LastUpdatedAt { get; set; } + + /// Gets or sets the rules value. + [JsonPropertyName("rules")] + public IList Rules { get => field ??= []; set; } + + /// Allowed values for the `PermissionsConfigureAdditionalContentExclusionPolicyScope` enumeration. + [JsonPropertyName("scope")] + public PermissionsConfigureAdditionalContentExclusionPolicyScope Scope { get; set; } +} + +/// If specified, replaces the session's path-permission policy. The runtime constructs the appropriate PathManager based on these inputs (rooted at the session's working directory). Omit to leave the current path policy unchanged. +[Experimental(Diagnostics.Experimental)] +public sealed class PermissionPathsConfig +{ + /// Additional directories to allow tool access to (in addition to the session's working directory). When `unrestricted` is true, these are still pre-populated on the UnrestrictedPathManager so they remain visible via getDirectories() (e.g. for @-mention completion). + [JsonPropertyName("additionalDirectories")] + public IList? AdditionalDirectories { get; set; } + + /// Whether to include the system temp directory in the allowed list (defaults to true). Ignored when `unrestricted` is true. + [JsonPropertyName("includeTempDirectory")] + public bool? IncludeTempDirectory { get; set; } + + /// If true, the runtime allows access to all paths without prompting. Equivalent to constructing an UnrestrictedPathManager. + [JsonPropertyName("unrestricted")] + public bool? Unrestricted { get; set; } + + /// Workspace root path (special-cased to be allowed even before the directory exists). Ignored when `unrestricted` is true. + [JsonPropertyName("workspacePath")] + public string? WorkspacePath { get; set; } +} + +/// If specified, replaces the session's approved/denied permission rules. Omit to leave the current rules unchanged. +[Experimental(Diagnostics.Experimental)] +public sealed class PermissionRulesSet +{ + /// Rules that auto-approve matching requests. + [JsonPropertyName("approved")] + public IList Approved { get => field ??= []; set; } + + /// Rules that auto-deny matching requests. + [JsonPropertyName("denied")] + public IList Denied { get => field ??= []; set; } +} + +/// If specified, replaces the session's URL-permission policy. The runtime constructs a fresh DefaultUrlManager based on these inputs. Omit to leave the current URL policy unchanged. +[Experimental(Diagnostics.Experimental)] +public sealed class PermissionUrlsConfig +{ + /// Initial list of allowed URL/domain patterns. Patterns may include path components. Ignored when `unrestricted` is true. + [JsonPropertyName("initialAllowed")] + public IList? InitialAllowed { get; set; } + + /// If true, the runtime allows access to all URLs without prompting. Initial allow-list is ignored when this is true. + [JsonPropertyName("unrestricted")] + public bool? Unrestricted { get; set; } +} + +/// Patch of permission policy fields to apply (omit a field to leave it unchanged). +[Experimental(Diagnostics.Experimental)] +internal sealed class PermissionsConfigureParams +{ + /// If specified, replaces the host-supplied GitHub Content Exclusion policies on the session (combined with natively-discovered policies when evaluating tool/file access). Omit to leave the current policies unchanged. + [JsonPropertyName("additionalContentExclusionPolicies")] + public IList? AdditionalContentExclusionPolicies { get; set; } + + /// If specified, sets whether path/URL read permission requests are auto-approved. Omit to leave the current value unchanged. + [JsonPropertyName("approveAllReadPermissionRequests")] + public bool? ApproveAllReadPermissionRequests { get; set; } + + /// If specified, sets whether tool permission requests are auto-approved without prompting. Omit to leave the current value unchanged. + [JsonPropertyName("approveAllToolPermissionRequests")] + public bool? ApproveAllToolPermissionRequests { get; set; } + + /// If specified, replaces the session's path-permission policy. The runtime constructs the appropriate PathManager based on these inputs (rooted at the session's working directory). Omit to leave the current path policy unchanged. + [JsonPropertyName("paths")] + public PermissionPathsConfig? Paths { get; set; } + + /// If specified, replaces the session's approved/denied permission rules. Omit to leave the current rules unchanged. + [JsonPropertyName("rules")] + public PermissionRulesSet? Rules { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; + + /// If specified, replaces the session's URL-permission policy. The runtime constructs a fresh DefaultUrlManager based on these inputs. Omit to leave the current URL policy unchanged. + [JsonPropertyName("urls")] + public PermissionUrlsConfig? Urls { get; set; } +} + +/// Indicates whether the permission decision was applied; false when the request was already resolved. +[Experimental(Diagnostics.Experimental)] +public sealed class PermissionRequestResult +{ + /// Whether the permission request was handled successfully. + [JsonPropertyName("success")] + public bool Success { get; set; } +} + +/// The client's response to the pending permission prompt. +/// Polymorphic base type discriminated by kind. +[Experimental(Diagnostics.Experimental)] +[JsonPolymorphic( + TypeDiscriminatorPropertyName = "kind", + UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] +[JsonDerivedType(typeof(PermissionDecisionApproveOnce), "approve-once")] +[JsonDerivedType(typeof(PermissionDecisionApproveForSession), "approve-for-session")] +[JsonDerivedType(typeof(PermissionDecisionApproveForLocation), "approve-for-location")] +[JsonDerivedType(typeof(PermissionDecisionApprovePermanently), "approve-permanently")] +[JsonDerivedType(typeof(PermissionDecisionReject), "reject")] +[JsonDerivedType(typeof(PermissionDecisionUserNotAvailable), "user-not-available")] +[JsonDerivedType(typeof(PermissionDecisionApproved), "approved")] +[JsonDerivedType(typeof(PermissionDecisionApprovedForSession), "approved-for-session")] +[JsonDerivedType(typeof(PermissionDecisionApprovedForLocation), "approved-for-location")] +[JsonDerivedType(typeof(PermissionDecisionCancelled), "cancelled")] +[JsonDerivedType(typeof(PermissionDecisionDeniedByRules), "denied-by-rules")] +[JsonDerivedType(typeof(PermissionDecisionDeniedNoApprovalRuleAndCouldNotRequestFromUser), "denied-no-approval-rule-and-could-not-request-from-user")] +[JsonDerivedType(typeof(PermissionDecisionDeniedInteractivelyByUser), "denied-interactively-by-user")] +[JsonDerivedType(typeof(PermissionDecisionDeniedByContentExclusionPolicy), "denied-by-content-exclusion-policy")] +[JsonDerivedType(typeof(PermissionDecisionDeniedByPermissionRequestHook), "denied-by-permission-request-hook")] +public partial class PermissionDecision +{ + /// The type discriminator. + [JsonPropertyName("kind")] + public virtual string Kind { get; set; } = string.Empty; +} + + +/// Permission-decision request variant to approve only the current permission request. +/// The approve-once variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PermissionDecisionApproveOnce : PermissionDecision +{ + /// + [JsonIgnore] + public override string Kind => "approve-once"; + + /// True only when a host surfaced this request to a user who approved it. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("approvedInteractively")] + public bool? ApprovedInteractively { get; set; } +} + +/// Session-scoped approval to remember (tool prompts only; omitted for path/url prompts). +/// Polymorphic base type discriminated by kind. +[Experimental(Diagnostics.Experimental)] +[JsonPolymorphic( + TypeDiscriminatorPropertyName = "kind", + UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] +[JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalCommands), "commands")] +[JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalRead), "read")] +[JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalWrite), "write")] +[JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalMcp), "mcp")] +[JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalMcpSampling), "mcp-sampling")] +[JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalMemory), "memory")] +[JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalCustomTool), "custom-tool")] +[JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalExtensionManagement), "extension-management")] +[JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess), "extension-permission-access")] +public partial class PermissionDecisionApproveForSessionApproval +{ + /// The type discriminator. + [JsonPropertyName("kind")] + public virtual string Kind { get; set; } = string.Empty; +} + + +/// Session-scoped approval details for specific command identifiers. +/// The commands variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PermissionDecisionApproveForSessionApprovalCommands : PermissionDecisionApproveForSessionApproval +{ + /// + [JsonIgnore] + public override string Kind => "commands"; + + /// Command identifiers covered by this approval. + [JsonPropertyName("commandIdentifiers")] + public required IList CommandIdentifiers { get; set; } +} + +/// Session-scoped approval details for read-only filesystem operations. +/// The read variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PermissionDecisionApproveForSessionApprovalRead : PermissionDecisionApproveForSessionApproval +{ + /// + [JsonIgnore] + public override string Kind => "read"; +} + +/// Session-scoped approval details for filesystem write operations. +/// The write variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PermissionDecisionApproveForSessionApprovalWrite : PermissionDecisionApproveForSessionApproval +{ + /// + [JsonIgnore] + public override string Kind => "write"; +} + +/// Session-scoped approval details for an MCP server tool, or all tools on the server when `toolName` is null. +/// The mcp variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PermissionDecisionApproveForSessionApprovalMcp : PermissionDecisionApproveForSessionApproval +{ + /// + [JsonIgnore] + public override string Kind => "mcp"; + + /// MCP server name. + [JsonPropertyName("serverName")] + public required string ServerName { get; set; } + + /// MCP tool name, or null to cover every tool on the server. + [JsonPropertyName("toolName")] + public string? ToolName { get; set; } +} + +/// Session-scoped approval details for MCP sampling requests from a server. +/// The mcp-sampling variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PermissionDecisionApproveForSessionApprovalMcpSampling : PermissionDecisionApproveForSessionApproval +{ + /// + [JsonIgnore] + public override string Kind => "mcp-sampling"; - /// Resolved sandbox configuration. - [JsonPropertyName("sandboxConfig")] - public SandboxConfig? SandboxConfig { get; set; } + /// MCP server name. + [JsonPropertyName("serverName")] + public required string ServerName { get; set; } +} - /// Replaces the session's capability set with the given list. Use to enable or disable capabilities mid-session (e.g., remove `memory` for reproducible scripted runs). Omit the field to leave the existing capability set unchanged. - [JsonPropertyName("sessionCapabilities")] - public IList? SessionCapabilities { get; set; } +/// Session-scoped approval details for writes to long-term memory. +/// The memory variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PermissionDecisionApproveForSessionApprovalMemory : PermissionDecisionApproveForSessionApproval +{ + /// + [JsonIgnore] + public override string Kind => "memory"; +} - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; +/// Session-scoped approval details for a custom tool, keyed by tool name. +/// The custom-tool variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PermissionDecisionApproveForSessionApprovalCustomTool : PermissionDecisionApproveForSessionApproval +{ + /// + [JsonIgnore] + public override string Kind => "custom-tool"; - /// Optional session limits. Pass null to clear the session limits. - [JsonPropertyName("sessionLimits")] - public SessionLimitsConfig? SessionLimits { get; set; } + /// Custom tool name. + [JsonPropertyName("toolName")] + public required string ToolName { get; set; } +} - /// Shell init profile (`None` or `NonInteractive`). - [JsonPropertyName("shellInitProfile")] - public string? ShellInitProfile { get; set; } +/// Session-scoped approval details for extension-management operations, optionally narrowed by operation. +/// The extension-management variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PermissionDecisionApproveForSessionApprovalExtensionManagement : PermissionDecisionApproveForSessionApproval +{ + /// + [JsonIgnore] + public override string Kind => "extension-management"; - /// Per-shell process flags (e.g., `pwsh` arguments). - [JsonPropertyName("shellProcessFlags")] - public IList? ShellProcessFlags { get; set; } + /// Optional operation identifier; when omitted, the approval covers all extension management operations. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("operation")] + public string? Operation { get; set; } +} - /// Additional directories to search for skills. - [JsonPropertyName("skillDirectories")] - public IList? SkillDirectories { get; set; } +/// Session-scoped approval details for an extension's permission-gated capability access, keyed by extension name. +/// The extension-permission-access variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess : PermissionDecisionApproveForSessionApproval +{ + /// + [JsonIgnore] + public override string Kind => "extension-permission-access"; - /// Whether to skip loading custom instruction sources. - [JsonPropertyName("skipCustomInstructions")] - public bool? SkipCustomInstructions { get; set; } + /// Extension name. + [JsonPropertyName("extensionName")] + public required string ExtensionName { get; set; } +} - /// Whether to skip embedding retrieval pipeline initialization and execution. - [JsonPropertyName("skipEmbeddingRetrieval")] - public bool? SkipEmbeddingRetrieval { get; set; } +/// Permission-decision request variant to approve for the rest of the session, with optional tool approval or URL domain. +/// The approve-for-session variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PermissionDecisionApproveForSession : PermissionDecision +{ + /// + [JsonIgnore] + public override string Kind => "approve-for-session"; - /// When true, the selected custom agent's prompt is not injected into the user message (skill context is still injected). Used by automation triggers where the agent prompt is already in the problem statement. - [JsonPropertyName("suppressCustomAgentPrompt")] - public bool? SuppressCustomAgentPrompt { get; set; } + /// Session-scoped approval to remember (tool prompts only; omitted for path/url prompts). + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("approval")] + public PermissionDecisionApproveForSessionApproval? Approval { get; set; } - /// Controls how availableTools (allowlist) and excludedTools (denylist) combine when both are set. - [JsonPropertyName("toolFilterPrecedence")] - public OptionsUpdateToolFilterPrecedence? ToolFilterPrecedence { get; set; } + /// URL domain to approve for the rest of the session (URL prompts only). + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("domain")] + public string? Domain { get; set; } +} - /// Optional path for trajectory output. - [JsonPropertyName("trajectoryFile")] - public string? TrajectoryFile { get; set; } +/// Approval to persist for this location. +/// Polymorphic base type discriminated by kind. +[Experimental(Diagnostics.Experimental)] +[JsonPolymorphic( + TypeDiscriminatorPropertyName = "kind", + UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] +[JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalCommands), "commands")] +[JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalRead), "read")] +[JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalWrite), "write")] +[JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalMcp), "mcp")] +[JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalMcpSampling), "mcp-sampling")] +[JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalMemory), "memory")] +[JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalCustomTool), "custom-tool")] +[JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalExtensionManagement), "extension-management")] +[JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess), "extension-permission-access")] +public partial class PermissionDecisionApproveForLocationApproval +{ + /// The type discriminator. + [JsonPropertyName("kind")] + public virtual string Kind { get; set; } = string.Empty; +} - /// Output verbosity level for supported models. - [JsonPropertyName("verbosity")] - public Verbosity? Verbosity { get; set; } - /// Absolute working-directory path for shell tools. - [JsonPropertyName("workingDirectory")] - public string? WorkingDirectory { get; set; } +/// Location-scoped approval details for specific command identifiers. +/// The commands variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PermissionDecisionApproveForLocationApprovalCommands : PermissionDecisionApproveForLocationApproval +{ + /// + [JsonIgnore] + public override string Kind => "commands"; + + /// Command identifiers covered by this approval. + [JsonPropertyName("commandIdentifiers")] + public required IList CommandIdentifiers { get; set; } } -/// Parameters for (re)loading the merged LSP configuration set. +/// Location-scoped approval details for read-only filesystem operations. +/// The read variant of . [Experimental(Diagnostics.Experimental)] -internal sealed class LspInitializeRequest +public partial class PermissionDecisionApproveForLocationApprovalRead : PermissionDecisionApproveForLocationApproval { - /// Force re-initialization even when LSP configs were already loaded for the working directory. - [JsonPropertyName("force")] - public bool? Force { get; set; } + /// + [JsonIgnore] + public override string Kind => "read"; +} - /// Git root used as the boundary when traversing for project-level LSP configs (supports monorepos). - [JsonPropertyName("gitRoot")] - public string? GitRoot { get; set; } +/// Location-scoped approval details for filesystem write operations. +/// The write variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PermissionDecisionApproveForLocationApprovalWrite : PermissionDecisionApproveForLocationApproval +{ + /// + [JsonIgnore] + public override string Kind => "write"; +} - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; +/// Location-scoped approval details for an MCP server tool, or all tools on the server when `toolName` is null. +/// The mcp variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PermissionDecisionApproveForLocationApprovalMcp : PermissionDecisionApproveForLocationApproval +{ + /// + [JsonIgnore] + public override string Kind => "mcp"; - /// Working directory used to load project-level LSP configs. Defaults to the session working directory when omitted. - [JsonPropertyName("workingDirectory")] - public string? WorkingDirectory { get; set; } + /// MCP server name. + [JsonPropertyName("serverName")] + public required string ServerName { get; set; } + + /// MCP tool name, or null to cover every tool on the server. + [JsonPropertyName("toolName")] + public string? ToolName { get; set; } } -/// Discovered extension metadata, including source-qualified ID, name, discovery source, status, and optional process ID. +/// Location-scoped approval details for MCP sampling requests from a server. +/// The mcp-sampling variant of . [Experimental(Diagnostics.Experimental)] -public sealed class Extension +public partial class PermissionDecisionApproveForLocationApprovalMcpSampling : PermissionDecisionApproveForLocationApproval { - /// Source-qualified ID (e.g., 'project:my-ext', 'user:auth-helper', 'plugin:my-plugin:my-ext'). - [JsonPropertyName("id")] - public string Id { get; set; } = string.Empty; + /// + [JsonIgnore] + public override string Kind => "mcp-sampling"; - /// Extension name (directory name). - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; + /// MCP server name. + [JsonPropertyName("serverName")] + public required string ServerName { get; set; } +} - /// Process ID if the extension is running. - [JsonPropertyName("pid")] - public long? Pid { get; set; } +/// Location-scoped approval details for writes to long-term memory. +/// The memory variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PermissionDecisionApproveForLocationApprovalMemory : PermissionDecisionApproveForLocationApproval +{ + /// + [JsonIgnore] + public override string Kind => "memory"; +} - /// Discovery source: project (.github/extensions/), user (~/.copilot/extensions/), plugin (installed plugin), or session (session-state/<id>/extensions/). - [JsonPropertyName("source")] - public ExtensionSource Source { get; set; } +/// Location-scoped approval details for a custom tool, keyed by tool name. +/// The custom-tool variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PermissionDecisionApproveForLocationApprovalCustomTool : PermissionDecisionApproveForLocationApproval +{ + /// + [JsonIgnore] + public override string Kind => "custom-tool"; - /// Current status: running, disabled, failed, or starting. - [JsonPropertyName("status")] - public ExtensionStatus Status { get; set; } + /// Custom tool name. + [JsonPropertyName("toolName")] + public required string ToolName { get; set; } +} + +/// Location-scoped approval details for extension-management operations, optionally narrowed by operation. +/// The extension-management variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PermissionDecisionApproveForLocationApprovalExtensionManagement : PermissionDecisionApproveForLocationApproval +{ + /// + [JsonIgnore] + public override string Kind => "extension-management"; + + /// Optional operation identifier; when omitted, the approval covers all extension management operations. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("operation")] + public string? Operation { get; set; } } -/// Extensions discovered for the session, with their current status. +/// Location-scoped approval details for an extension's permission-gated capability access, keyed by extension name. +/// The extension-permission-access variant of . [Experimental(Diagnostics.Experimental)] -public sealed class ExtensionList +public partial class PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess : PermissionDecisionApproveForLocationApproval { - /// Discovered extensions and their current status. - [JsonPropertyName("extensions")] - public IList Extensions { get => field ??= []; set; } + /// + [JsonIgnore] + public override string Kind => "extension-permission-access"; + + /// Extension name. + [JsonPropertyName("extensionName")] + public required string ExtensionName { get; set; } } -/// Identifies the target session. +/// Permission-decision request variant to approve and persist a permission for a project location, with approval details and location key. +/// The approve-for-location variant of . [Experimental(Diagnostics.Experimental)] -internal sealed class SessionExtensionsListRequest +public partial class PermissionDecisionApproveForLocation : PermissionDecision { - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// + [JsonIgnore] + public override string Kind => "approve-for-location"; + + /// Approval to persist for this location. + [JsonPropertyName("approval")] + public required PermissionDecisionApproveForLocationApproval Approval { get; set; } + + /// Location key (git root or cwd) to persist the approval to. + [JsonPropertyName("locationKey")] + public required string LocationKey { get; set; } } -/// Source-qualified extension identifier to enable for the session. +/// Permission-decision request variant to permanently approve a URL domain across sessions. +/// The approve-permanently variant of . [Experimental(Diagnostics.Experimental)] -internal sealed class ExtensionsEnableRequest +public partial class PermissionDecisionApprovePermanently : PermissionDecision { - /// Source-qualified extension ID to enable. - [JsonPropertyName("id")] - public string Id { get; set; } = string.Empty; + /// + [JsonIgnore] + public override string Kind => "approve-permanently"; - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// URL domain to approve permanently. + [JsonPropertyName("domain")] + public required string Domain { get; set; } } -/// Source-qualified extension identifier to disable for the session. +/// Permission-decision request variant to reject a pending permission request, with optional feedback. +/// The reject variant of . [Experimental(Diagnostics.Experimental)] -internal sealed class ExtensionsDisableRequest +public partial class PermissionDecisionReject : PermissionDecision { - /// Source-qualified extension ID to disable. - [JsonPropertyName("id")] - public string Id { get; set; } = string.Empty; + /// + [JsonIgnore] + public override string Kind => "reject"; - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Optional feedback explaining the rejection. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("feedback")] + public string? Feedback { get; set; } } -/// Identifies the target session. +/// Permission-decision variant indicating no user was available to confirm the request. +/// The user-not-available variant of . [Experimental(Diagnostics.Experimental)] -internal sealed class SessionExtensionsReloadRequest +public partial class PermissionDecisionUserNotAvailable : PermissionDecision { - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// + [JsonIgnore] + public override string Kind => "user-not-available"; } -/// Attachment union accepted by push input, covering files, directories, GitHub objects, blobs, snippets, and extension context. -/// Polymorphic base type discriminated by type. +/// Permission-decision variant indicating the request was approved. +/// The approved variant of . [Experimental(Diagnostics.Experimental)] -[JsonPolymorphic( - TypeDiscriminatorPropertyName = "type", - UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] -[JsonDerivedType(typeof(PushAttachmentFile), "file")] -[JsonDerivedType(typeof(PushAttachmentDirectory), "directory")] -[JsonDerivedType(typeof(PushAttachmentSelection), "selection")] -[JsonDerivedType(typeof(PushAttachmentGitHubReference), "github_reference")] -[JsonDerivedType(typeof(PushAttachmentGitHubCommit), "github_commit")] -[JsonDerivedType(typeof(PushAttachmentGitHubRelease), "github_release")] -[JsonDerivedType(typeof(PushAttachmentGitHubActionsJob), "github_actions_job")] -[JsonDerivedType(typeof(PushAttachmentGitHubRepository), "github_repository")] -[JsonDerivedType(typeof(PushAttachmentGitHubFileDiff), "github_file_diff")] -[JsonDerivedType(typeof(PushAttachmentGitHubTreeComparison), "github_tree_comparison")] -[JsonDerivedType(typeof(PushAttachmentGitHubUrl), "github_url")] -[JsonDerivedType(typeof(PushAttachmentGitHubFile), "github_file")] -[JsonDerivedType(typeof(PushAttachmentGitHubSnippet), "github_snippet")] -[JsonDerivedType(typeof(PushAttachmentBlob), "blob")] -[JsonDerivedType(typeof(PushAttachmentExtensionContext), "extension_context")] -public partial class PushAttachment +public partial class PermissionDecisionApproved : PermissionDecision { - /// The type discriminator. - [JsonPropertyName("type")] - public virtual string Type { get; set; } = string.Empty; + /// + [JsonIgnore] + public override string Kind => "approved"; } - -/// Optional line range to scope the attachment to a specific section of the file. +/// Permission-decision variant indicating approval was remembered for the session, with approval details. +/// The approved-for-session variant of . [Experimental(Diagnostics.Experimental)] -public sealed class PushAttachmentFileLineRange +public partial class PermissionDecisionApprovedForSession : PermissionDecision { - /// End line number (1-based, inclusive). - [JsonPropertyName("end")] - public long End { get; set; } + /// + [JsonIgnore] + public override string Kind => "approved-for-session"; - /// Start line number (1-based). - [JsonPropertyName("start")] - public long Start { get; set; } + /// The approval to add as a session-scoped rule. + [JsonPropertyName("approval")] + public required UserToolSessionApproval Approval { get; set; } } -/// File attachment. -/// The file variant of . +/// Permission-decision variant indicating approval was persisted for a project location, with approval details and location key. +/// The approved-for-location variant of . [Experimental(Diagnostics.Experimental)] -public partial class PushAttachmentFile : PushAttachment +public partial class PermissionDecisionApprovedForLocation : PermissionDecision { /// [JsonIgnore] - public override string Type => "file"; - - /// User-facing display name for the attachment. - [JsonPropertyName("displayName")] - public required string DisplayName { get; set; } + public override string Kind => "approved-for-location"; - /// Optional line range to scope the attachment to a specific section of the file. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("lineRange")] - public PushAttachmentFileLineRange? LineRange { get; set; } + /// The approval to persist for this location. + [JsonPropertyName("approval")] + public required UserToolSessionApproval Approval { get; set; } - /// Absolute file path. - [JsonPropertyName("path")] - public required string Path { get; set; } + /// The location key (git root or cwd) to persist the approval to. + [JsonPropertyName("locationKey")] + public required string LocationKey { get; set; } } -/// Directory attachment. -/// The directory variant of . +/// Permission-decision variant indicating the request was cancelled before use, with an optional reason. +/// The cancelled variant of . [Experimental(Diagnostics.Experimental)] -public partial class PushAttachmentDirectory : PushAttachment +public partial class PermissionDecisionCancelled : PermissionDecision { /// [JsonIgnore] - public override string Type => "directory"; - - /// User-facing display name for the attachment. - [JsonPropertyName("displayName")] - public required string DisplayName { get; set; } + public override string Kind => "cancelled"; - /// Absolute directory path. - [JsonPropertyName("path")] - public required string Path { get; set; } + /// Optional explanation of why the request was cancelled. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("reason")] + public string? Reason { get; set; } } -/// End position of the selection. +/// Permission-decision variant indicating explicit denial by permission rules, with the matching rules. +/// The denied-by-rules variant of . [Experimental(Diagnostics.Experimental)] -public sealed class PushAttachmentSelectionDetailsEnd +public partial class PermissionDecisionDeniedByRules : PermissionDecision { - /// End character offset within the line (0-based). - [JsonPropertyName("character")] - public long Character { get; set; } + /// + [JsonIgnore] + public override string Kind => "denied-by-rules"; - /// End line number (0-based). - [JsonPropertyName("line")] - public long Line { get; set; } + /// Rules that denied the request. + [JsonPropertyName("rules")] + public required IList Rules { get; set; } } -/// Start position of the selection. +/// Permission-decision variant indicating no approval rule matched and user confirmation was unavailable. +/// The denied-no-approval-rule-and-could-not-request-from-user variant of . [Experimental(Diagnostics.Experimental)] -public sealed class PushAttachmentSelectionDetailsStart +public partial class PermissionDecisionDeniedNoApprovalRuleAndCouldNotRequestFromUser : PermissionDecision { - /// Start character offset within the line (0-based). - [JsonPropertyName("character")] - public long Character { get; set; } - - /// Start line number (0-based). - [JsonPropertyName("line")] - public long Line { get; set; } + /// + [JsonIgnore] + public override string Kind => "denied-no-approval-rule-and-could-not-request-from-user"; } -/// Position range of the selection within the file. +/// Permission-decision variant indicating the user denied an interactive prompt, with optional feedback and force-reject flag. +/// The denied-interactively-by-user variant of . [Experimental(Diagnostics.Experimental)] -public sealed class PushAttachmentSelectionDetails +public partial class PermissionDecisionDeniedInteractivelyByUser : PermissionDecision { - /// End position of the selection. - [JsonPropertyName("end")] - public PushAttachmentSelectionDetailsEnd End { get => field ??= new(); set; } + /// + [JsonIgnore] + public override string Kind => "denied-interactively-by-user"; - /// Start position of the selection. - [JsonPropertyName("start")] - public PushAttachmentSelectionDetailsStart Start { get => field ??= new(); set; } + /// Optional feedback from the user explaining the denial. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("feedback")] + public string? Feedback { get; set; } + + /// Whether to force-reject the current agent turn. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("forceReject")] + public bool? ForceReject { get; set; } } -/// Code selection attachment from an editor. -/// The selection variant of . +/// Permission-decision variant indicating denial by content-exclusion policy, with path and message. +/// The denied-by-content-exclusion-policy variant of . [Experimental(Diagnostics.Experimental)] -public partial class PushAttachmentSelection : PushAttachment +public partial class PermissionDecisionDeniedByContentExclusionPolicy : PermissionDecision { /// [JsonIgnore] - public override string Type => "selection"; - - /// User-facing display name for the selection. - [JsonPropertyName("displayName")] - public required string DisplayName { get; set; } - - /// Absolute path to the file containing the selection. - [JsonPropertyName("filePath")] - public required string FilePath { get; set; } - - /// Position range of the selection within the file. - [JsonPropertyName("selection")] - public required PushAttachmentSelectionDetails Selection { get; set; } + public override string Kind => "denied-by-content-exclusion-policy"; - /// The selected text content. - [JsonPropertyName("text")] - public required string Text { get; set; } + /// Human-readable explanation of why the path was excluded. + [JsonPropertyName("message")] + public required string Message { get; set; } + + /// File path that triggered the exclusion. + [JsonPropertyName("path")] + public required string Path { get; set; } } -/// GitHub issue, pull request, or discussion reference. -/// The github_reference variant of . +/// Permission-decision variant indicating denial by a permission request hook, with optional message and interrupt flag. +/// The denied-by-permission-request-hook variant of . [Experimental(Diagnostics.Experimental)] -public partial class PushAttachmentGitHubReference : PushAttachment +public partial class PermissionDecisionDeniedByPermissionRequestHook : PermissionDecision { /// [JsonIgnore] - public override string Type => "github_reference"; + public override string Kind => "denied-by-permission-request-hook"; - /// Issue, pull request, or discussion number. - [JsonPropertyName("number")] - public required long Number { get; set; } + /// Whether to interrupt the current agent turn. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("interrupt")] + public bool? Interrupt { get; set; } - /// Type of GitHub reference. - [JsonPropertyName("referenceType")] - public required PushAttachmentGitHubReferenceType ReferenceType { get; set; } + /// Optional message from the hook explaining the denial. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("message")] + public string? Message { get; set; } +} - /// Current state of the referenced item (e.g., open, closed, merged). - [JsonPropertyName("state")] - public required string State { get; set; } +/// Pending permission request ID and the decision to apply (approve/reject and scope). +[Experimental(Diagnostics.Experimental)] +internal sealed class PermissionDecisionRequest +{ + /// Request ID of the pending permission request. + [JsonPropertyName("requestId")] + public string RequestId { get; set; } = string.Empty; - /// Title of the referenced item. - [JsonPropertyName("title")] - public required string Title { get; set; } + /// The client's response to the pending permission prompt. + [JsonPropertyName("result")] + public PermissionDecision Result { get => field ??= new(); set; } - /// URL to the referenced item on GitHub. - [JsonPropertyName("url")] - public required string Url { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Pointer to a GitHub repository. +/// Pending permission prompt reconstructed from event history, with request ID and user-facing prompt details. [Experimental(Diagnostics.Experimental)] -public sealed class PushGitHubRepoRef +public sealed class PendingPermissionRequest { - /// Numeric GitHub repository id. - [JsonPropertyName("id")] - public long? Id { get; set; } + /// The user-facing permission prompt details (commands, write, read, mcp, url, memory, custom-tool, path, hook). + [JsonPropertyName("request")] + public PermissionPromptRequest Request { get; set; } = null!; - /// Repository name (without owner). - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; + /// Unique identifier for the pending permission request. + [JsonPropertyName("requestId")] + public string RequestId { get; set; } = string.Empty; +} - /// Repository owner login (user or organization). - [JsonPropertyName("owner")] - public string Owner { get; set; } = string.Empty; +/// List of pending permission requests reconstructed from event history. +[Experimental(Diagnostics.Experimental)] +public sealed class PendingPermissionRequestList +{ + /// Pending permission prompts reconstructed from the session's event history. Equivalent to the set of `permission.requested` events that have not yet been followed by a matching `permission.completed` event. Used by clients (e.g. the CLI) to hydrate UI for prompts that were emitted before the client attached to the session. + [JsonPropertyName("items")] + public IList Items { get => field ??= []; set; } } -/// Pointer to a GitHub commit. -/// The github_commit variant of . +/// No parameters; returns currently-pending permission requests for the session. [Experimental(Diagnostics.Experimental)] -public partial class PushAttachmentGitHubCommit : PushAttachment +internal sealed class PermissionsPendingRequestsRequest { - /// - [JsonIgnore] - public override string Type => "github_commit"; + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// First line of the commit message. - [JsonPropertyName("message")] - public required string Message { get; set; } +/// Indicates whether the operation succeeded. +[Experimental(Diagnostics.Experimental)] +public sealed class PermissionsSetApproveAllResult +{ + /// Whether the operation succeeded. + [JsonPropertyName("success")] + public bool Success { get; set; } +} - /// Full commit SHA. - [JsonPropertyName("oid")] - public required string Oid { get; set; } +/// Allow-all toggle for tool permission requests, with an optional telemetry source. +[Experimental(Diagnostics.Experimental)] +internal sealed class PermissionsSetApproveAllRequest +{ + /// Whether to auto-approve all tool permission requests. + [JsonPropertyName("enabled")] + public bool Enabled { get; set; } - /// Repository the commit belongs to. - [JsonPropertyName("repo")] - public required PushGitHubRepoRef Repo { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; - /// URL to the commit on GitHub. - [JsonPropertyName("url")] - public required string Url { get; set; } + /// Optional source for allow-all telemetry. Defaults to `rpc` when omitted for SDK callers. + [JsonPropertyName("source")] + public PermissionsSetApproveAllSource? Source { get; set; } } -/// Pointer to a GitHub release. -/// The github_release variant of . +/// Indicates whether the operation succeeded and reports the post-mutation state. [Experimental(Diagnostics.Experimental)] -public partial class PushAttachmentGitHubRelease : PushAttachment +public sealed class AllowAllPermissionSetResult { - /// - [JsonIgnore] - public override string Type => "github_release"; - - /// Human-readable release name. - [JsonPropertyName("name")] - public required string Name { get; set; } - - /// Repository the release belongs to. - [JsonPropertyName("repo")] - public required PushGitHubRepoRef Repo { get; set; } + /// Authoritative full allow-all state after the mutation. + [JsonPropertyName("enabled")] + public bool Enabled { get; set; } - /// Git tag the release is anchored to. - [JsonPropertyName("tagName")] - public required string TagName { get; set; } + /// Authoritative allow-all mode after the mutation. + [JsonPropertyName("mode")] + public PermissionsAllowAllMode? Mode { get; set; } - /// URL to the release on GitHub. - [JsonPropertyName("url")] - public required string Url { get; set; } + /// Whether the operation succeeded. + [JsonPropertyName("success")] + public bool Success { get; set; } } -/// Pointer to a GitHub Actions job. -/// The github_actions_job variant of . +/// Allow-all mode to apply for the session. [Experimental(Diagnostics.Experimental)] -public partial class PushAttachmentGitHubActionsJob : PushAttachment +internal sealed class PermissionsSetAllowAllRequest { - /// - [JsonIgnore] - public override string Type => "github_actions_job"; + /// Legacy full allow-all toggle. Prefer `mode`; when `mode` is omitted, `enabled: true` is treated as `mode: "on"` and any other value is treated as `mode: "off"`. + [JsonPropertyName("enabled")] + public bool? Enabled { get; set; } - /// Terminal conclusion of the job when finished (e.g., success, failure, cancelled). Absent for in-progress jobs. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("conclusion")] - public string? Conclusion { get; set; } + /// Allow-all mode to apply. `on` enables full allow-all; `auto` enables advisory LLM auto-approval; `off` disables both. + [JsonPropertyName("mode")] + public PermissionsAllowAllMode? Mode { get; set; } - /// Job id within the workflow run. - [JsonPropertyName("jobId")] - public required long JobId { get; set; } + /// Optional model id for the `auto` mode auto-approval LLM judging. Only meaningful when `mode` is `auto`; ignored otherwise. When omitted, the session's active model is used. + [JsonPropertyName("model")] + public string? Model { get; set; } - /// Display name of the job. - [JsonPropertyName("jobName")] - public required string JobName { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; - /// Repository the workflow run belongs to. - [JsonPropertyName("repo")] - public required PushGitHubRepoRef Repo { get; set; } + /// Optional source for allow-all telemetry. Defaults to `rpc` when omitted for SDK callers. + [JsonPropertyName("source")] + public PermissionsSetAllowAllSource? Source { get; set; } +} - /// URL to the job on GitHub. - [JsonPropertyName("url")] - public required string Url { get; set; } +/// Current allow-all permission mode. +[Experimental(Diagnostics.Experimental)] +public sealed class AllowAllPermissionState +{ + /// Whether full allow-all permissions are currently active. + [JsonPropertyName("enabled")] + public bool Enabled { get; set; } - /// Display name of the workflow the job ran in. - [JsonPropertyName("workflowName")] - public required string WorkflowName { get; set; } + /// Current allow-all mode. + [JsonPropertyName("mode")] + public PermissionsAllowAllMode? Mode { get; set; } } -/// Pointer to a GitHub repository. -/// The github_repository variant of . +/// No parameters. [Experimental(Diagnostics.Experimental)] -public partial class PushAttachmentGitHubRepository : PushAttachment +internal sealed class PermissionsGetAllowAllRequest { - /// - [JsonIgnore] - public override string Type => "github_repository"; + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// Short description of the repository. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("description")] - public string? Description { get; set; } +/// Indicates whether the operation succeeded. +[Experimental(Diagnostics.Experimental)] +public sealed class PermissionsModifyRulesResult +{ + /// Whether the operation succeeded. + [JsonPropertyName("success")] + public bool Success { get; set; } +} - /// Git ref this attachment is anchored at (branch, tag, or commit). When absent the default branch is implied. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("ref")] - public string? Ref { get; set; } +/// Scope and add/remove instructions for modifying session- or location-scoped permission rules. +[Experimental(Diagnostics.Experimental)] +internal sealed class PermissionsModifyRulesParams +{ + /// Rules to add to the scope. Applied before `remove`/`removeAll`. + [JsonPropertyName("add")] + public IList? Add { get; set; } - /// Repository pointer. - [JsonPropertyName("repo")] - public required PushGitHubRepoRef Repo { get; set; } + /// Specific rules to remove from the scope. Ignored when `removeAll` is true. + [JsonPropertyName("remove")] + public IList? Remove { get; set; } - /// URL to the repository on GitHub. - [JsonPropertyName("url")] - public required string Url { get; set; } + /// When true, removes every rule currently in the scope (after any `add` is applied). Useful for clearing the location scope wholesale. + [JsonPropertyName("removeAll")] + public bool? RemoveAll { get; set; } + + /// Whether the change applies to ephemeral session-scoped rules (cleared at session end) or to location-scoped rules persisted via the location-permissions config file. + [JsonPropertyName("scope")] + public PermissionsModifyRulesScope Scope { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// One side of a file diff (head or base). +/// Indicates whether the operation succeeded. [Experimental(Diagnostics.Experimental)] -public sealed class PushAttachmentGitHubFileDiffSide +public sealed class PermissionsSetRequiredResult { - /// Repository-relative path to the file. - [JsonPropertyName("path")] - public string Path { get; set; } = string.Empty; + /// Whether the operation succeeded. + [JsonPropertyName("success")] + public bool Success { get; set; } +} - /// Git ref (branch, tag, or commit SHA) the file is read at. - [JsonPropertyName("ref")] - public string Ref { get; set; } = string.Empty; +/// Toggles whether permission prompts should be bridged into session events for this client. +[Experimental(Diagnostics.Experimental)] +internal sealed class PermissionsSetRequiredRequest +{ + /// Whether the client wants `permission.requested` events bridged from the session-owned permission service. CLI clients that render prompt UI set this to `true` for as long as their listener is mounted; headless callers leave it unset (the default is `false`). + [JsonPropertyName("required")] + public bool Required { get; set; } - /// Repository the file lives in. - [JsonPropertyName("repo")] - public PushGitHubRepoRef Repo { get => field ??= new(); set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Pointer to a single-file diff. At least one of `head` and `base` must be present. -/// The github_file_diff variant of . +/// Indicates whether the operation succeeded. [Experimental(Diagnostics.Experimental)] -public partial class PushAttachmentGitHubFileDiff : PushAttachment +public sealed class PermissionsResetSessionApprovalsResult { - /// - [JsonIgnore] - public override string Type => "github_file_diff"; + /// Whether the operation succeeded. + [JsonPropertyName("success")] + public bool Success { get; set; } +} - /// File location on the base side of the diff. Absent for additions. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("base")] - public PushAttachmentGitHubFileDiffSide? Base { get; set; } +/// Clears session-scoped tool permission approvals, and optionally the location-scoped ones. +[Experimental(Diagnostics.Experimental)] +internal sealed class PermissionsResetSessionApprovalsRequest +{ + /// Whether location-scoped approvals are cleared too. Defaults to `true`. + [JsonPropertyName("includeLocation")] + public bool? IncludeLocation { get; set; } - /// File location on the head side of the diff. Absent for deletions. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("head")] - public PushAttachmentGitHubFileDiffSide? Head { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// URL to the diff on GitHub (e.g., a commit, compare, or PR-file URL). - [JsonPropertyName("url")] - public required string Url { get; set; } +/// Indicates whether the operation succeeded. +[Experimental(Diagnostics.Experimental)] +public sealed class PermissionsNotifyPromptShownResult +{ + /// Whether the operation succeeded. + [JsonPropertyName("success")] + public bool Success { get; set; } } -/// One side of a tree comparison (head or base). +/// Notification payload describing the permission prompt that the client just rendered. [Experimental(Diagnostics.Experimental)] -public sealed class PushAttachmentGitHubTreeComparisonSide +internal sealed class PermissionPromptShownNotification { - /// Repository the revision belongs to. - [JsonPropertyName("repo")] - public PushGitHubRepoRef Repo { get => field ??= new(); set; } + /// Human-readable description of the prompt the user is being asked to approve. Used by the runtime to fire the registered `permission_prompt` notification hook (e.g. terminal bell, desktop notification). + [JsonPropertyName("message")] + public string Message { get; set; } = string.Empty; - /// Git revision (branch, tag, or commit SHA). - [JsonPropertyName("revision")] - public string Revision { get; set; } = string.Empty; + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Pointer to a comparison between two git revisions. -/// The github_tree_comparison variant of . +/// Snapshot of the session's allow-listed directories and primary working directory. [Experimental(Diagnostics.Experimental)] -public partial class PushAttachmentGitHubTreeComparison : PushAttachment +public sealed class PermissionPathsList { - /// - [JsonIgnore] - public override string Type => "github_tree_comparison"; + /// All directories currently allowed for tool access on this session. + [JsonPropertyName("directories")] + public IList Directories { get => field ??= []; set; } - /// Base side of the comparison. - [JsonPropertyName("base")] - public required PushAttachmentGitHubTreeComparisonSide Base { get; set; } + /// The primary working directory for this session. + [JsonPropertyName("primary")] + public string Primary { get; set; } = string.Empty; +} - /// Head side of the comparison. - [JsonPropertyName("head")] - public required PushAttachmentGitHubTreeComparisonSide Head { get; set; } +/// No parameters; returns the session's allow-listed directories. +[Experimental(Diagnostics.Experimental)] +internal sealed class PermissionsPathsListRequest +{ + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// URL to the comparison on GitHub. - [JsonPropertyName("url")] - public required string Url { get; set; } +/// Indicates whether the operation succeeded. +[Experimental(Diagnostics.Experimental)] +public sealed class PermissionsPathsAddResult +{ + /// Whether the operation succeeded. + [JsonPropertyName("success")] + public bool Success { get; set; } } -/// Generic GitHub URL reference. -/// The github_url variant of . +/// Directory path to add to the session's allowed directories. [Experimental(Diagnostics.Experimental)] -public partial class PushAttachmentGitHubUrl : PushAttachment +internal sealed class PermissionPathsAddParams { - /// - [JsonIgnore] - public override string Type => "github_url"; + /// Directory to add to the allow-list. The runtime resolves and validates the path before adding. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; - /// URL to the GitHub resource. - [JsonPropertyName("url")] - public required string Url { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Pointer to a file in a GitHub repository at a specific ref. -/// The github_file variant of . +/// Indicates whether the operation succeeded. [Experimental(Diagnostics.Experimental)] -public partial class PushAttachmentGitHubFile : PushAttachment +public sealed class PermissionsPathsUpdatePrimaryResult { - /// - [JsonIgnore] - public override string Type => "github_file"; + /// Whether the operation succeeded. + [JsonPropertyName("success")] + public bool Success { get; set; } +} - /// Repository-relative path to the file. +/// Directory path to set as the session's new primary working directory. +[Experimental(Diagnostics.Experimental)] +internal sealed class PermissionPathsUpdatePrimaryParams +{ + /// Directory to set as the new primary working directory for the session's permission policy. [JsonPropertyName("path")] - public required string Path { get; set; } - - /// Git ref the file is read at (branch, tag, or commit SHA). - [JsonPropertyName("ref")] - public required string Ref { get; set; } - - /// Repository the file lives in. - [JsonPropertyName("repo")] - public required PushGitHubRepoRef Repo { get; set; } + public string Path { get; set; } = string.Empty; - /// URL to the file on GitHub. - [JsonPropertyName("url")] - public required string Url { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Pointer to a line range inside a file in a GitHub repository. -/// The github_snippet variant of . +/// Indicates whether the supplied path is within the session's allowed directories. [Experimental(Diagnostics.Experimental)] -public partial class PushAttachmentGitHubSnippet : PushAttachment +public sealed class PermissionPathsAllowedCheckResult { - /// - [JsonIgnore] - public override string Type => "github_snippet"; - - /// Line range the snippet covers. - [JsonPropertyName("lineRange")] - public required PushAttachmentFileLineRange LineRange { get; set; } + /// Whether the path is within the session's allowed directories. + [JsonPropertyName("allowed")] + public bool Allowed { get; set; } +} - /// Repository-relative path to the file. +/// Path to evaluate against the session's allowed directories. +[Experimental(Diagnostics.Experimental)] +internal sealed class PermissionPathsAllowedCheckParams +{ + /// Path to check against the session's allowed directories. [JsonPropertyName("path")] - public required string Path { get; set; } - - /// Git ref the file is read at (branch, tag, or commit SHA). - [JsonPropertyName("ref")] - public required string Ref { get; set; } + public string Path { get; set; } = string.Empty; - /// Repository the file lives in. - [JsonPropertyName("repo")] - public required PushGitHubRepoRef Repo { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// URL to the snippet on GitHub (with line anchor). - [JsonPropertyName("url")] - public required string Url { get; set; } +/// Indicates whether the supplied path is within the session's workspace directory. +[Experimental(Diagnostics.Experimental)] +public sealed class PermissionPathsWorkspaceCheckResult +{ + /// Whether the path is within the session workspace directory. + [JsonPropertyName("allowed")] + public bool Allowed { get; set; } } -/// Blob attachment with inline base64-encoded data. -/// The blob variant of . +/// Path to evaluate against the session's workspace (primary) directory. [Experimental(Diagnostics.Experimental)] -public partial class PushAttachmentBlob : PushAttachment +internal sealed class PermissionPathsWorkspaceCheckParams { - /// - [JsonIgnore] - public override string Type => "blob"; + /// Path to check against the session workspace directory. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; - /// Base64-encoded content. - [Base64String] - [JsonPropertyName("data")] - public required string Data { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// User-facing display name for the attachment. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("displayName")] - public string? DisplayName { get; set; } +/// Resolved location-permissions key and type. +[Experimental(Diagnostics.Experimental)] +public sealed class PermissionLocationResolveResult +{ + /// Location key used in the location-permissions store. + [JsonPropertyName("locationKey")] + public string LocationKey { get; set; } = string.Empty; - /// MIME type of the inline data. - [JsonPropertyName("mimeType")] - public required string MimeType { get; set; } + /// Whether the location is a git repo or directory. + [JsonPropertyName("locationType")] + public PermissionLocationType LocationType { get; set; } } -/// Slim input shape for extension_context attachments; identity fields are runtime-derived. -/// The extension_context variant of . +/// Working directory to resolve into a location-permissions key. [Experimental(Diagnostics.Experimental)] -public partial class PushAttachmentExtensionContext : PushAttachment +internal sealed class PermissionLocationResolveParams { - /// - [JsonIgnore] - public override string Type => "extension_context"; - - /// Caller-supplied JSON payload (required, may be null but not undefined). - [JsonPropertyName("payload")] - public required JsonElement Payload { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; - /// Human-readable composer pill label. - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] - [MinLength(1)] - [JsonPropertyName("title")] - public required string Title { get; set; } + /// Working directory whose permission location should be resolved. + [JsonPropertyName("workingDirectory")] + public string WorkingDirectory { get; set; } = string.Empty; } -/// Parameters for session.extensions.sendAttachmentsToMessage. +/// Summary of persisted location permissions applied to the session. [Experimental(Diagnostics.Experimental)] -internal sealed class SendAttachmentsToMessageParams +public sealed class PermissionLocationApplyResult { - /// Attachments to push into the next user-message turn. extension_context entries take the slim shape; standard variants take their full AttachmentSchema shape. - [JsonPropertyName("attachments")] - public IList Attachments { get => field ??= []; set; } + /// Number of persisted allowed directories added to the live path manager. + [JsonPropertyName("appliedDirectoryCount")] + public long AppliedDirectoryCount { get; set; } - /// Optional canvas instance binding the push for provenance. When supplied, the runtime resolves the canvas, verifies it is owned by the calling extension, and stamps canvasId/instanceId onto each extension_context entry. When omitted, no resolution runs and those fields stay unset on the attachment. - [JsonPropertyName("instanceId")] - public string? InstanceId { get; set; } + /// Number of location-scoped rules added to the live permission service. + [JsonPropertyName("appliedRuleCount")] + public long AppliedRuleCount { get; set; } + + /// Location-scoped rules applied to the live permission service. + [JsonPropertyName("appliedRules")] + public IList AppliedRules { get => field ??= []; set; } + + /// Whether a different location was applied since the previous apply call. + [JsonPropertyName("changed")] + public bool Changed { get; set; } + + /// Location key used in the location-permissions store. + [JsonPropertyName("locationKey")] + public string LocationKey { get; set; } = string.Empty; + + /// Whether the location is a git repo or directory. + [JsonPropertyName("locationType")] + public PermissionLocationType LocationType { get; set; } +} +/// Working directory to load persisted location permissions for. +[Experimental(Diagnostics.Experimental)] +internal sealed class PermissionLocationApplyParams +{ /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; + + /// Working directory whose persisted location permissions should be applied. + [JsonPropertyName("workingDirectory")] + public string WorkingDirectory { get; set; } = string.Empty; } -/// Indicates whether the external tool call result was handled successfully. +/// Indicates whether the operation succeeded. [Experimental(Diagnostics.Experimental)] -public sealed class HandlePendingToolCallResult +public sealed class PermissionsLocationsAddToolApprovalResult { - /// Whether the tool call result was handled successfully. + /// Whether the operation succeeded. [JsonPropertyName("success")] public bool Success { get; set; } } -/// Pending external tool call request ID, with the tool result or an error describing why it failed. +/// Tool approval to persist and apply. +/// Polymorphic base type discriminated by kind. [Experimental(Diagnostics.Experimental)] -internal sealed class HandlePendingToolCallRequest +[JsonPolymorphic( + TypeDiscriminatorPropertyName = "kind", + UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] +[JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsCommands), "commands")] +[JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsRead), "read")] +[JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsWrite), "write")] +[JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsMcp), "mcp")] +[JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsMcpSampling), "mcp-sampling")] +[JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsMemory), "memory")] +[JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsCustomTool), "custom-tool")] +[JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsExtensionManagement), "extension-management")] +[JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess), "extension-permission-access")] +public partial class PermissionsLocationsAddToolApprovalDetails { - /// Error message if the tool call failed. - [JsonPropertyName("error")] - public string? Error { get; set; } + /// The type discriminator. + [JsonPropertyName("kind")] + public virtual string Kind { get; set; } = string.Empty; +} - /// Request ID of the pending tool call. - [JsonPropertyName("requestId")] - public string RequestId { get; set; } = string.Empty; - /// Tool call result (string or expanded result object). - [JsonPropertyName("result")] - public JsonElement? Result { get; set; } +/// Location-persisted tool approval details for specific command identifiers. +/// The commands variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PermissionsLocationsAddToolApprovalDetailsCommands : PermissionsLocationsAddToolApprovalDetails +{ + /// + [JsonIgnore] + public override string Kind => "commands"; - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Command identifiers covered by this approval. + [JsonPropertyName("commandIdentifiers")] + public required IList CommandIdentifiers { get; set; } } -/// Resolve, build, and validate the runtime tool list for this session. Subagent sessions and consumer flows that need an initialized tool set before `send` invoke this. Default base-class implementation is a no-op for sessions that don't support tool validation. +/// Location-persisted tool approval details for read-only filesystem operations. +/// The read variant of . [Experimental(Diagnostics.Experimental)] -public sealed class ToolsInitializeAndValidateResult +public partial class PermissionsLocationsAddToolApprovalDetailsRead : PermissionsLocationsAddToolApprovalDetails { + /// + [JsonIgnore] + public override string Kind => "read"; } -/// Identifies the target session. +/// Location-persisted tool approval details for filesystem write operations. +/// The write variant of . [Experimental(Diagnostics.Experimental)] -internal sealed class SessionToolsInitializeAndValidateRequest +public partial class PermissionsLocationsAddToolApprovalDetailsWrite : PermissionsLocationsAddToolApprovalDetails { - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// + [JsonIgnore] + public override string Kind => "write"; } -/// Lightweight metadata for a currently initialized session tool. +/// Location-persisted tool approval details for an MCP server tool, or all tools when `toolName` is null. +/// The mcp variant of . [Experimental(Diagnostics.Experimental)] -public sealed class CurrentToolMetadata +public partial class PermissionsLocationsAddToolApprovalDetailsMcp : PermissionsLocationsAddToolApprovalDetails { - /// Whether the tool is loaded on demand via tool search. - [JsonPropertyName("deferLoading")] - public bool? DeferLoading { get; set; } - - /// Tool description. - [JsonPropertyName("description")] - public string Description { get; set; } = string.Empty; - - /// JSON Schema for tool input. - [JsonPropertyName("input_schema")] - public IDictionary? InputSchema { get; set; } - - /// MCP server name for MCP-backed tools. - [JsonPropertyName("mcpServerName")] - public string? McpServerName { get; set; } - - /// Raw MCP tool name for MCP-backed tools. - [JsonPropertyName("mcpToolName")] - public string? McpToolName { get; set; } + /// + [JsonIgnore] + public override string Kind => "mcp"; - /// Model-facing tool name. - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; + /// MCP server name. + [JsonPropertyName("serverName")] + public required string ServerName { get; set; } - /// Optional MCP/config namespaced tool name. - [JsonPropertyName("namespacedName")] - public string? NamespacedName { get; set; } + /// MCP tool name, or null to cover every tool on the server. + [JsonPropertyName("toolName")] + public string? ToolName { get; set; } } -/// Current lightweight tool metadata snapshot for the session. +/// Location-persisted tool approval details for MCP sampling requests from a server. +/// The mcp-sampling variant of . [Experimental(Diagnostics.Experimental)] -public sealed class ToolsGetCurrentMetadataResult +public partial class PermissionsLocationsAddToolApprovalDetailsMcpSampling : PermissionsLocationsAddToolApprovalDetails { - /// Current tool metadata, or null when tools have not been initialized yet. - [JsonPropertyName("tools")] - public IList? Tools { get; set; } + /// + [JsonIgnore] + public override string Kind => "mcp-sampling"; + + /// MCP server name. + [JsonPropertyName("serverName")] + public required string ServerName { get; set; } } -/// Identifies the target session. +/// Location-persisted tool approval details for writes to long-term memory. +/// The memory variant of . [Experimental(Diagnostics.Experimental)] -internal sealed class SessionToolsGetCurrentMetadataRequest +public partial class PermissionsLocationsAddToolApprovalDetailsMemory : PermissionsLocationsAddToolApprovalDetails { - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// + [JsonIgnore] + public override string Kind => "memory"; } -/// Empty result after applying subagent settings. +/// Location-persisted tool approval details for a custom tool, keyed by tool name. +/// The custom-tool variant of . [Experimental(Diagnostics.Experimental)] -public sealed class ToolsUpdateSubagentSettingsResult +public partial class PermissionsLocationsAddToolApprovalDetailsCustomTool : PermissionsLocationsAddToolApprovalDetails { + /// + [JsonIgnore] + public override string Kind => "custom-tool"; + + /// Custom tool name. + [JsonPropertyName("toolName")] + public required string ToolName { get; set; } } -/// Subagent model, reasoning effort, and context tier settings. +/// Location-persisted tool approval details for extension-management operations, optionally narrowed by operation. +/// The extension-management variant of . [Experimental(Diagnostics.Experimental)] -public sealed class SubagentSettingsEntry +public partial class PermissionsLocationsAddToolApprovalDetailsExtensionManagement : PermissionsLocationsAddToolApprovalDetails { - /// Context tier override for matching subagents. - [JsonPropertyName("contextTier")] - public SubagentSettingsEntryContextTier? ContextTier { get; set; } - - /// Reasoning effort override for matching subagents. - [JsonPropertyName("effortLevel")] - public string? EffortLevel { get; set; } + /// + [JsonIgnore] + public override string Kind => "extension-management"; - /// Model override for matching subagents. - [JsonPropertyName("model")] - public string? Model { get; set; } + /// Optional operation identifier; when omitted, the approval covers all extension management operations. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("operation")] + public string? Operation { get; set; } } -/// Configured per-agent subagent overrides. -public sealed class UpdateSubagentSettingsRequestSubagents +/// Location-persisted tool approval details for an extension's permission-gated capability access, keyed by extension name. +/// The extension-permission-access variant of . +[Experimental(Diagnostics.Experimental)] +public partial class PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess : PermissionsLocationsAddToolApprovalDetails { - /// Per-agent settings keyed by subagent agent_type. - [JsonPropertyName("agents")] - public IDictionary? Agents { get; set; } - - /// Names of subagents the user has turned off; they cannot be dispatched. - [JsonPropertyName("disabledSubagents")] - public IList? DisabledSubagents { get; set; } - - /// Maximum number of subagents that can run concurrently; applies to usage-based billing users only. - [JsonPropertyName("maxConcurrency")] - public int? MaxConcurrency { get; set; } + /// + [JsonIgnore] + public override string Kind => "extension-permission-access"; - /// Maximum subagent nesting depth; applies to usage-based billing users only. - [JsonPropertyName("maxDepth")] - public int? MaxDepth { get; set; } + /// Extension name. + [JsonPropertyName("extensionName")] + public required string ExtensionName { get; set; } } -/// Subagent settings to apply to the current session. +/// Location-scoped tool approval to persist. [Experimental(Diagnostics.Experimental)] -internal sealed class UpdateSubagentSettingsRequest +internal sealed class PermissionLocationAddToolApprovalParams { + /// Tool approval to persist and apply. + [JsonPropertyName("approval")] + public PermissionsLocationsAddToolApprovalDetails Approval { get => field ??= new(); set; } + + /// Location key (git root or cwd) to persist the approval to. + [JsonPropertyName("locationKey")] + public string LocationKey { get; set; } = string.Empty; + /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; - - /// Subagent settings to apply, or null to clear the live session override. - [JsonPropertyName("subagents")] - public UpdateSubagentSettingsRequestSubagents? Subagents { get; set; } } -/// Optional filters controlling which command sources to include in the listing. +/// Folder trust check result. [Experimental(Diagnostics.Experimental)] -public sealed class CommandsListRequest +public sealed class FolderTrustCheckResult { - /// Include runtime built-in commands. - [JsonPropertyName("includeBuiltins")] - public bool? IncludeBuiltins { get; set; } - - /// Include commands registered by protocol clients, including SDK clients and extensions. - [JsonPropertyName("includeClientCommands")] - public bool? IncludeClientCommands { get; set; } - - /// Include enabled user-invocable skills and commands. - [JsonPropertyName("includeSkills")] - public bool? IncludeSkills { get; set; } + /// Whether the folder is trusted. + [JsonPropertyName("trusted")] + public bool Trusted { get; set; } } -/// Optional filters controlling which command sources to include in the listing. +/// Folder path to check for trust. [Experimental(Diagnostics.Experimental)] -internal sealed class CommandsListRequestWithSession +internal sealed class FolderTrustCheckParams { - /// Include runtime built-in commands. - [JsonPropertyName("includeBuiltins")] - public bool? IncludeBuiltins { get; set; } - - /// Include commands registered by protocol clients, including SDK clients and extensions. - [JsonPropertyName("includeClientCommands")] - public bool? IncludeClientCommands { get; set; } - - /// Include enabled user-invocable skills and commands. - [JsonPropertyName("includeSkills")] - public bool? IncludeSkills { get; set; } + /// Folder path to check. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Result of invoking the slash command (text output, prompt to send to the agent, completion, or subcommand selection). -/// Polymorphic base type discriminated by kind. +/// Indicates whether the operation succeeded. [Experimental(Diagnostics.Experimental)] -[JsonPolymorphic( - TypeDiscriminatorPropertyName = "kind", - UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] -[JsonDerivedType(typeof(SlashCommandInvocationResultText), "text")] -[JsonDerivedType(typeof(SlashCommandInvocationResultAgentPrompt), "agent-prompt")] -[JsonDerivedType(typeof(SlashCommandInvocationResultCompleted), "completed")] -[JsonDerivedType(typeof(SlashCommandInvocationResultSelectSubcommand), "select-subcommand")] -public partial class SlashCommandInvocationResult +public sealed class PermissionsFolderTrustAddTrustedResult { - /// The type discriminator. - [JsonPropertyName("kind")] - public virtual string Kind { get; set; } = string.Empty; + /// Whether the operation succeeded. + [JsonPropertyName("success")] + public bool Success { get; set; } } - -/// Slash-command invocation result containing text output plus Markdown/ANSI rendering flags. -/// The text variant of . +/// Folder path to add to trusted folders. [Experimental(Diagnostics.Experimental)] -public partial class SlashCommandInvocationResultText : SlashCommandInvocationResult +internal sealed class FolderTrustAddParams { - /// - [JsonIgnore] - public override string Kind => "text"; - - /// Whether text contains Markdown. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("markdown")] - public bool? Markdown { get; set; } - - /// Whether ANSI sequences should be preserved. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("preserveAnsi")] - public bool? PreserveAnsi { get; set; } - - /// True when the invocation mutated user runtime settings; consumers caching settings should refresh. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("runtimeSettingsChanged")] - public bool? RuntimeSettingsChanged { get; set; } + /// Folder path to mark as trusted. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; - /// Text output for the client to render. - [JsonPropertyName("text")] - public required string Text { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Slash-command invocation result that submits an agent prompt, with display prompt, optional mode, optional user-facing notice, and settings-change flag. -/// The agent-prompt variant of . +/// Indicates whether the operation succeeded. [Experimental(Diagnostics.Experimental)] -public partial class SlashCommandInvocationResultAgentPrompt : SlashCommandInvocationResult +public sealed class PermissionsUrlsSetUnrestrictedModeResult { - /// - [JsonIgnore] - public override string Kind => "agent-prompt"; - - /// Prompt text to display to the user. - [JsonPropertyName("displayPrompt")] - public required string DisplayPrompt { get; set; } - - /// Optional target session mode for the agent prompt. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("mode")] - public SessionMode? Mode { get; set; } - - /// Optional user-facing notice to show before the prompt is submitted. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("notice")] - public string? Notice { get; set; } - - /// Prompt to submit to the agent. - [JsonPropertyName("prompt")] - public required string Prompt { get; set; } - - /// True when the invocation mutated user runtime settings; consumers caching settings should refresh. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("runtimeSettingsChanged")] - public bool? RuntimeSettingsChanged { get; set; } + /// Whether the operation succeeded. + [JsonPropertyName("success")] + public bool Success { get; set; } } -/// Slash-command invocation result indicating completion, with optional message and settings-change flag. -/// The completed variant of . +/// Whether the URL-permission policy should run in unrestricted mode. [Experimental(Diagnostics.Experimental)] -public partial class SlashCommandInvocationResultCompleted : SlashCommandInvocationResult +internal sealed class PermissionUrlsSetUnrestrictedModeParams { - /// - [JsonIgnore] - public override string Kind => "completed"; - - /// Optional user-facing message describing the completed command. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("message")] - public string? Message { get; set; } + /// Whether to allow access to all URLs without prompting. Toggles the runtime's URL-permission policy in place. + [JsonPropertyName("enabled")] + public bool Enabled { get; set; } - /// True when the invocation mutated user runtime settings; consumers caching settings should refresh. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("runtimeSettingsChanged")] - public bool? RuntimeSettingsChanged { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Selectable slash-command subcommand option with name, description, and optional group label. +/// The repository the remote session targets. [Experimental(Diagnostics.Experimental)] -public sealed class SlashCommandSelectSubcommandOption +public sealed class MetadataSnapshotRemoteMetadataRepository { - /// Human-readable description of the subcommand. - [JsonPropertyName("description")] - public string Description { get; set; } = string.Empty; - - /// Optional group label for organizing options. - [JsonPropertyName("group")] - public string? Group { get; set; } + /// The branch the remote session is operating on. + [JsonPropertyName("branch")] + public string Branch { get; set; } = string.Empty; - /// Subcommand name to invoke. + /// The GitHub repository name (without owner). [JsonPropertyName("name")] public string Name { get; set; } = string.Empty; + + /// The GitHub owner (user or organization) of the target repository. + [JsonPropertyName("owner")] + public string Owner { get; set; } = string.Empty; } -/// Slash-command invocation result asking the client to present subcommand options for a parent command. -/// The select-subcommand variant of . +/// Remote-session-specific metadata. Populated only when `isRemote` is true. Fields are immutable for the lifetime of the session. [Experimental(Diagnostics.Experimental)] -public partial class SlashCommandInvocationResultSelectSubcommand : SlashCommandInvocationResult +public sealed class MetadataSnapshotRemoteMetadata { - /// - [JsonIgnore] - public override string Kind => "select-subcommand"; - - /// Parent command name that requires subcommand selection. - [JsonPropertyName("command")] - public required string Command { get; set; } + /// The pull request number the remote session is associated with, if any. + [JsonPropertyName("pullRequestNumber")] + public long? PullRequestNumber { get; set; } - /// Available subcommand options for the client to present. - [JsonPropertyName("options")] - public required IList Options { get; set; } + /// The repository the remote session targets. + [JsonPropertyName("repository")] + public MetadataSnapshotRemoteMetadataRepository Repository { get => field ??= new(); set; } - /// True when the invocation mutated user runtime settings; consumers caching settings should refresh. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("runtimeSettingsChanged")] - public bool? RuntimeSettingsChanged { get; set; } + /// The original resource identifier (task ID or PR node ID), preserved across event-replay reconstructions. Falls back to `sessionId` when absent. + [JsonPropertyName("resourceId")] + public string? ResourceId { get; set; } - /// Human-readable title for the selection UI. - [JsonPropertyName("title")] - public required string Title { get; set; } + /// Whether the remote task originated from Copilot Coding Agent (cca) or a CLI `--remote` invocation. + [JsonPropertyName("taskType")] + public MetadataSnapshotRemoteMetadataTaskType? TaskType { get; set; } } -/// Slash command name and optional raw input string to invoke. -[Experimental(Diagnostics.Experimental)] -internal sealed class CommandsInvokeRequest +/// Public-facing projection of workspace metadata for SDK / TUI consumers. +public sealed class SessionMetadataSnapshotWorkspace { - /// Raw input after the command name. - [JsonPropertyName("input")] - public string? Input { get; set; } + /// Branch checked out at session start, if any. + [JsonPropertyName("branch")] + public string? Branch { get; set; } - /// Command name. Leading slashes are stripped and the name is matched case-insensitively. + /// ISO 8601 timestamp when the workspace was created. + [JsonPropertyName("created_at")] + public DateTimeOffset? CreatedAt { get; set; } + + /// Current working directory at session start. + [JsonPropertyName("cwd")] + public string? Cwd { get; set; } + + /// Resolved git root for cwd, if any. + [JsonPropertyName("git_root")] + public string? GitRoot { get; set; } + + /// Repository host type, if known. + [JsonPropertyName("host_type")] + public WorkspaceSummaryHostType? HostType { get; set; } + + /// Workspace identifier (1:1 with sessionId). + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] + [MinLength(1)] + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; + + /// Display name for the session, if set. [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; + public string? Name { get; set; } + + /// Repository identifier in 'owner/repo' or 'org/project/repo' format, if any. + [JsonPropertyName("repository")] + public string? Repository { get; set; } + + /// ISO 8601 timestamp when the workspace was last updated. + [JsonPropertyName("updated_at")] + public DateTimeOffset? UpdatedAt { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Whether the display name was explicitly set by the user. + [JsonPropertyName("user_named")] + public bool? UserNamed { get; set; } } -/// Indicates whether the pending client-handled command was completed successfully. +/// Point-in-time snapshot of slow-changing session identifier and state fields. [Experimental(Diagnostics.Experimental)] -public sealed class CommandsHandlePendingCommandResult +public sealed class SessionMetadataSnapshot { - /// Whether the command was handled successfully. - [JsonPropertyName("success")] - public bool Success { get; set; } -} + /// True when the session was detected to be in use by another process at construction time. Local consumers may surface a confirmation prompt before fully attaching. Always false for new sessions. + [JsonPropertyName("alreadyInUse")] + public bool AlreadyInUse { get; set; } -/// Pending command request ID and an optional error if the client handler failed. -[Experimental(Diagnostics.Experimental)] -internal sealed class CommandsHandlePendingCommandRequest -{ - /// Error message if the command handler failed. - [JsonPropertyName("error")] - public string? Error { get; set; } + /// Runtime client name associated with the session (telemetry identifier). + [JsonPropertyName("clientName")] + public string? ClientName { get; set; } - /// Request ID from the command invocation event. - [JsonPropertyName("requestId")] - public string RequestId { get; set; } = string.Empty; + /// The current agent mode for this session (e.g., 'interactive', 'plan', 'autopilot'). + [JsonPropertyName("currentMode")] + public MetadataSnapshotCurrentMode CurrentMode { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// User-provided name supplied at session construction (via `--name`), if any. Immutable after construction. + [JsonPropertyName("initialName")] + public string? InitialName { get; set; } -/// Error message produced while executing the command, if any. -[Experimental(Diagnostics.Experimental)] -public sealed class ExecuteCommandResult -{ - /// Error message produced while executing the command, if any. Omitted when the handler succeeded. - [JsonPropertyName("error")] - public string? Error { get; set; } -} + /// Whether this is a remote session (i.e., one whose runtime executes elsewhere and is steered through this process). + [JsonPropertyName("isRemote")] + public bool IsRemote { get; set; } -/// Slash command name and argument string to execute synchronously. -[Experimental(Diagnostics.Experimental)] -internal sealed class ExecuteCommandParams -{ - /// Argument string to pass to the command (empty string if none). - [JsonPropertyName("args")] - public string Args { get; set; } = string.Empty; + /// ISO 8601 timestamp of when the session's persisted state was last modified on disk. For new sessions, equals startTime. For resumed sessions, reflects the previous modification time at construction. + [JsonPropertyName("modifiedTime")] + public DateTimeOffset ModifiedTime { get; set; } - /// Name of the slash command to invoke (without the leading '/'). - [JsonPropertyName("commandName")] - public string CommandName { get; set; } = string.Empty; + /// Remote-session-specific metadata. Populated only when `isRemote` is true. Fields are immutable for the lifetime of the session. + [JsonPropertyName("remoteMetadata")] + public MetadataSnapshotRemoteMetadata? RemoteMetadata { get; set; } - /// Target session identifier. + /// Currently selected model identifier, if any. + [JsonPropertyName("selectedModel")] + public string? SelectedModel { get; set; } + + /// The unique identifier of the session. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; -} -/// Indicates whether the command was accepted into the local execution queue. -[Experimental(Diagnostics.Experimental)] -public sealed class EnqueueCommandResult -{ - /// True when the command was accepted into the local execution queue. False when the call targets a session that does not support local command queueing (e.g. remote sessions). - [JsonPropertyName("queued")] - public bool Queued { get; set; } -} + /// Current session limits, or null when no limits are active. + [JsonPropertyName("sessionLimits")] + public SessionLimitsConfig? SessionLimits { get; set; } -/// Slash-prefixed command string to enqueue for FIFO processing. -[Experimental(Diagnostics.Experimental)] -internal sealed class EnqueueCommandParams -{ - /// Slash-prefixed command string to enqueue, e.g. '/compact' or '/model gpt-4'. Queued FIFO with any in-flight items; if the session is idle, processing kicks off immediately. - [JsonPropertyName("command")] - public string Command { get; set; } = string.Empty; + /// ISO 8601 timestamp of when the session started. + [JsonPropertyName("startTime")] + public DateTimeOffset StartTime { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// Short human-readable summary of the session, if known. Omitted when no summary has been generated. + [JsonPropertyName("summary")] + public string? Summary { get; set; } -/// Indicates whether the queued-command response was matched to a pending request. -[Experimental(Diagnostics.Experimental)] -public sealed class CommandsRespondToQueuedCommandResult -{ - /// Whether a pending queued command with the given request ID was found and resolved. False when the request was already resolved, cancelled, or unknown. - [JsonPropertyName("success")] - public bool Success { get; set; } -} + /// Absolute path to the session's current working directory. + [JsonPropertyName("workingDirectory")] + public string WorkingDirectory { get; set; } = string.Empty; -/// Result of the queued command execution. -/// Data type discriminated by handled. -[Experimental(Diagnostics.Experimental)] -public partial class QueuedCommandResult -{ - /// The boolean discriminator. - [JsonPropertyName("handled")] - public bool Handled { get; set; } + /// 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). + [JsonPropertyName("workspace")] + public SessionMetadataSnapshotWorkspace? Workspace { get; set; } - /// When true, the runtime will not process subsequent queued commands until a new request comes in. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("stopProcessingQueue")] - public bool? StopProcessingQueue { get; set; } + /// Absolute path to the session's workspace directory on disk, or null if the session has no associated workspace. + [JsonPropertyName("workspacePath")] + public string? WorkspacePath { get; set; } } -/// Queued-command request ID and the result indicating whether the host executed it (and whether to stop processing further queued commands). +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class CommandsRespondToQueuedCommandRequest +internal sealed class SessionMetadataSnapshotRequest { - /// Request ID from the `command.queued` event the host is responding to. - [JsonPropertyName("requestId")] - public string RequestId { get; set; } = string.Empty; - - /// Result of the queued command execution. - [JsonPropertyName("result")] - public QueuedCommandResult Result { get => field ??= new(); set; } - /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Telemetry engagement ID for the session, when available. +/// Indicates whether the local session is currently processing a turn or background continuation. [Experimental(Diagnostics.Experimental)] -public sealed class SessionTelemetryEngagement +public sealed class MetadataIsProcessingResult { - /// Current telemetry engagement ID, when available. - [JsonPropertyName("engagementId")] - public string? EngagementId { get; set; } + /// Whether the session is currently processing user/agent messages. False for non-local sessions (which don't run a local agentic loop). Reflects an in-flight turn or background continuation. + [JsonPropertyName("processing")] + public bool Processing { get; set; } } /// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionTelemetryGetEngagementIdRequest +internal sealed class SessionMetadataIsProcessingRequest { /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Feature override key/value pairs to attach to subsequent telemetry events from this session. +/// Current activity flags for the session. [Experimental(Diagnostics.Experimental)] -internal sealed class TelemetrySetFeatureOverridesRequest +public sealed class SessionActivity { - /// Override key/value pairs to attach to subsequent telemetry events from this session. Replaces any previously-set overrides. - [JsonPropertyName("features")] - public IDictionary Features { get => field ??= new Dictionary(); set; } - - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// Whether an in-flight operation can currently be aborted. + [JsonPropertyName("abortable")] + public bool Abortable { get; set; } -/// Transient answer generated from current conversation context. -[Experimental(Diagnostics.Experimental)] -public sealed class UIEphemeralQueryResult -{ - /// Full assistant response text. - [JsonPropertyName("answer")] - public string Answer { get; set; } = string.Empty; + /// Whether the session currently has active work, including running turns or tasks. + [JsonPropertyName("hasActiveWork")] + public bool HasActiveWork { get; set; } } -/// Transient question to answer without adding it to conversation history. +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class UIEphemeralQueryRequest +internal sealed class SessionMetadataActivityRequest { - /// In-process `AbortSignal` forwarded to the model client to cancel an in-flight request. Marked internal: excluded from the public SDK surface. Replaced by an explicit cancellation token + cancel RPC in the SDK migration. - [JsonInclude] - [JsonPropertyName("abortSignal")] - internal JsonElement? AbortSignal { get; set; } - - /// In-process streaming callback `(text) => void` invoked with each token as the model emits it. Marked internal: excluded from the public SDK surface. In a process-separated SDK this is replaced by a streaming RPC that yields chunks and a final answer. - [JsonInclude] - [JsonPropertyName("onChunk")] - internal JsonElement? OnChunk { get; set; } - - /// Question to answer from the current conversation context. - [JsonPropertyName("question")] - public string Question { get; set; } = string.Empty; - /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// The elicitation response (accept with form values, decline, or cancel). -[Experimental(Diagnostics.Experimental)] -public sealed class UIElicitationResponse +/// Token-usage breakdown for the session's current context window. +public sealed class MetadataContextInfoResultContextInfo { - /// The user's response: accept (submitted), decline (rejected), or cancel (dismissed). - [JsonPropertyName("action")] - public UIElicitationResponseAction Action { get; set; } + /// Output reserve plus tokens after the buffer-exhaustion blocking threshold (default 95%). + [JsonPropertyName("bufferTokens")] + public long BufferTokens { get; set; } - /// The form values submitted by the user (present when action is 'accept'). - [JsonPropertyName("content")] - public IDictionary? Content { get; set; } -} + /// Token count at which background compaction starts (configurable percentage of promptTokenLimit). + [JsonPropertyName("compactionThreshold")] + public long CompactionThreshold { get; set; } -/// JSON Schema describing the form fields to present to the user. -[Experimental(Diagnostics.Experimental)] -public sealed class UIElicitationSchema -{ - /// Form field definitions, keyed by field name. - [JsonPropertyName("properties")] - public IDictionary Properties { get => field ??= new Dictionary(); set; } + /// Tokens consumed by user/assistant/tool messages. + [JsonPropertyName("conversationTokens")] + public long ConversationTokens { get; set; } - /// List of required field names. - [JsonPropertyName("required")] - public IList? Required { get; set; } + /// Prompt token limit plus the model's full output token limit. + [JsonPropertyName("limit")] + public long Limit { get; set; } - /// Schema type indicator (always 'object'). - [JsonPropertyName("type")] - public string Type { get; set; } = string.Empty; -} + /// Tokens consumed by MCP tool definitions (subset of toolDefinitionsTokens, excludes deferred tools). + [JsonPropertyName("mcpToolsTokens")] + public long McpToolsTokens { get; set; } -/// Prompt message and JSON schema describing the form fields to elicit from the user. -[Experimental(Diagnostics.Experimental)] -internal sealed class UIElicitationRequest -{ - /// Message describing what information is needed from the user. - [JsonPropertyName("message")] - public string Message { get; set; } = string.Empty; + /// The model used for token counting. + [JsonPropertyName("modelName")] + public string ModelName { get; set; } = string.Empty; + + /// Maximum prompt tokens allowed by the model (or DEFAULT_TOKEN_LIMIT if unspecified). + [JsonPropertyName("promptTokenLimit")] + public long PromptTokenLimit { get; set; } + + /// Tokens consumed by the system prompt. + [JsonPropertyName("systemTokens")] + public long SystemTokens { get; set; } - /// JSON Schema describing the form fields to present to the user. - [JsonPropertyName("requestedSchema")] - public UIElicitationSchema RequestedSchema { get => field ??= new(); set; } + /// Tokens consumed by tool definitions sent to the model (excludes deferred tools). + [JsonPropertyName("toolDefinitionsTokens")] + public long ToolDefinitionsTokens { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Sum of system, conversation and tool-definition tokens. + [JsonPropertyName("totalTokens")] + public long TotalTokens { get; set; } } -/// Indicates whether the elicitation response was accepted; false if it was already resolved by another client. +/// Token breakdown for the session's current context window, or null if uninitialized. [Experimental(Diagnostics.Experimental)] -public sealed class UIElicitationResult +public sealed class MetadataContextInfoResult { - /// Whether the response was accepted. False if the request was already resolved by another client. - [JsonPropertyName("success")] - public bool Success { get; set; } + /// Token breakdown for the current context window, or null if the session has not yet been initialized (no system prompt or tool metadata cached). + [JsonPropertyName("contextInfo")] + public MetadataContextInfoResultContextInfo? ContextInfo { get; set; } } -/// Pending elicitation request ID and the user's response (accept/decline/cancel + form values). +/// Model identifier and token limits used to compute the context-info breakdown. [Experimental(Diagnostics.Experimental)] -internal sealed class UIHandlePendingElicitationRequest +internal sealed class MetadataContextInfoRequest { - /// The unique request ID from the elicitation.requested event. - [JsonPropertyName("requestId")] - public string RequestId { get; set; } = string.Empty; + /// Maximum output tokens allowed by the target model. Pass 0 if unknown. + [JsonPropertyName("outputTokenLimit")] + public long OutputTokenLimit { get; set; } - /// The elicitation response (accept with form values, decline, or cancel). - [JsonPropertyName("result")] - public UIElicitationResponse Result { get => field ??= new(); set; } + /// Maximum prompt tokens allowed by the target model. Pass 0 to use the runtime default. + [JsonPropertyName("promptTokenLimit")] + public long PromptTokenLimit { get; set; } + + /// Model identifier used for tokenization. Omit to use the session default. Used both for token counting and to compute display values. + [JsonPropertyName("selectedModel")] + public string? SelectedModel { get; set; } /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Indicates whether the pending UI request was resolved by this call. -[Experimental(Diagnostics.Experimental)] -public sealed class UIHandlePendingResult +/// Successful compaction history for the session. +public sealed class MetadataContextAttributionResultContextAttributionCompactions { - /// True if the request was still pending and was resolved by this call. False if the request ID was unknown, already resolved by another client (e.g. GitHub), expired, or otherwise no longer pending. - [JsonPropertyName("success")] - public bool Success { get; set; } + /// Number of successful compactions in this session. + [JsonPropertyName("count")] + public long Count { get; set; } } -/// User response for a pending user-input request, with answer text and whether it was typed freeform. -[Experimental(Diagnostics.Experimental)] -public sealed class UIUserInputResponse +/// RPC data type for MetadataContextAttributionResultContextAttributionEntry operations. +public sealed class MetadataContextAttributionResultContextAttributionEntry { - /// The user's answer text. - [JsonPropertyName("answer")] - public string Answer { get; set; } = string.Empty; + /// Supplementary per-entry metadata (e.g. `messageCount`, `role`, `evictable`, `pluginSource`). Values are stringified; parse as needed and ignore unrecognized keys. + [JsonPropertyName("attributes")] + public IDictionary? Attributes { get; set; } - /// True if the user typed a freeform response, false if they selected a presented choice. Used by telemetry to differentiate between free text input and choice selection. - [JsonPropertyName("wasFreeform")] - public bool WasFreeform { get; set; } + /// Identifier for this entry, formed by joining its `kind` and source name (e.g. `tool:bash`, `skill:tmux`, `toolDefinition:bash`); unique within the snapshot. Use it to match the same entry across snapshots, to correlate with other APIs (skill/agent/MCP registries), and as the `parentId` target for nesting. Distinct from the human-facing `label`. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; + + /// Source category for this entry. Not a closed set — tolerate unknown values. Known values today: `skill`, `subagent`, `mcpServer`, `tool`, `system`, `toolDefinition`, `plugin`. + [JsonPropertyName("kind")] + public string Kind { get; set; } = string.Empty; + + /// Human-readable display label, e.g. `bash` or `skill: tmux`. Presentation-only; may be localized/reformatted without notice — do not key off it. + [JsonPropertyName("label")] + public string Label { get; set; } = string.Empty; + + /// Optional `id` of the parent entry: e.g. a `plugin` entry parenting its `skill`/`mcpServer` entries, or the `system` entry parenting `toolDefinition` entries. Omitted for top-level entries. + [JsonPropertyName("parentId")] + public string? ParentId { get; set; } + + /// Token count currently in context attributable to this entry. + [JsonPropertyName("tokens")] + public long Tokens { get; set; } } -/// Request ID of a pending `user_input.requested` event and the user's response. -[Experimental(Diagnostics.Experimental)] -internal sealed class UIHandlePendingUserInputRequest +/// Per-source token attribution snapshot for the current context window. The heaviest individual messages are available separately via `metadata.getContextHeaviestMessages`. +public sealed class MetadataContextAttributionResultContextAttribution { - /// The unique request ID from the user_input.requested event. - [JsonPropertyName("requestId")] - public string RequestId { get; set; } = string.Empty; + /// Successful compaction history for the session. + [JsonPropertyName("compactions")] + public MetadataContextAttributionResultContextAttributionCompactions Compactions { get => field ??= new(); set; } - /// User response for a pending user-input request, with answer text and whether it was typed freeform. - [JsonPropertyName("response")] - public UIUserInputResponse Response { get => field ??= new(); set; } + /// Flat list of per-source attribution entries. Group by `kind` and render unrecognized kinds generically. Nesting and rollups are expressed via `parentId`. + [JsonPropertyName("entries")] + public IList Entries { get => field ??= []; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Total token count of the current context window the entries are measured against (system message + conversation messages + tool definitions — the same total reported by /context). Divide an entry's `tokens` by this to derive its share. + [JsonPropertyName("totalTokens")] + public long TotalTokens { get; set; } } -/// Optional sampling result payload. Omit to reject/cancel the sampling request without providing a result. +/// Per-source attribution breakdown for the session's current context window, or null if uninitialized. [Experimental(Diagnostics.Experimental)] -public sealed class UIHandlePendingSamplingResponse +public sealed class MetadataContextAttributionResult { + /// Per-source context-window attribution, or null if the session has not yet been initialized (no system prompt or tool metadata cached). + [JsonPropertyName("contextAttribution")] + public MetadataContextAttributionResultContextAttribution? ContextAttribution { get; set; } } -/// Request ID of a pending `sampling.requested` event and an optional sampling result payload (omit to reject). +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class UIHandlePendingSamplingRequest +internal sealed class SessionMetadataGetContextAttributionRequest { - /// The unique request ID from the sampling.requested event. - [JsonPropertyName("requestId")] - public string RequestId { get; set; } = string.Empty; - - /// Optional sampling result payload. Omit to reject/cancel the sampling request without providing a result. - [JsonPropertyName("response")] - public UIHandlePendingSamplingResponse? Response { get; set; } - /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Request ID of a pending `auto_mode_switch.requested` event and the user's response. +/// A single large message currently in context. [Experimental(Diagnostics.Experimental)] -internal sealed class UIHandlePendingAutoModeSwitchRequest +public sealed class ContextHeaviestMessage { - /// The unique request ID from the auto_mode_switch.requested event. - [JsonPropertyName("requestId")] - public string RequestId { get; set; } = string.Empty; + /// Stable identifier for this message within the snapshot. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; - /// User's choice for auto-mode switching: yes (allow this turn), yes_always (allow + persist as setting), or no (decline). - [JsonPropertyName("response")] - public UIAutoModeSwitchResponse Response { get; set; } + /// Human-readable source label, e.g. `tool: bash` or `skill: tmux`. Presentation-only. + [JsonPropertyName("label")] + public string Label { get; set; } = string.Empty; - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Role of the chat message (`user`, `assistant`, or `tool`). + [JsonPropertyName("role")] + public string Role { get; set; } = string.Empty; + + /// Token count currently in context for this individual message. + [JsonPropertyName("tokens")] + public long Tokens { get; set; } } -/// The user's selected action for an exhausted session limit. +/// The heaviest individual messages in the session's context window, most-expensive first. [Experimental(Diagnostics.Experimental)] -public sealed class UISessionLimitsExhaustedResponse +public sealed class MetadataContextHeaviestMessagesResult { - /// Action selected by the user. - [JsonPropertyName("action")] - public UISessionLimitsExhaustedResponseAction Action { get; set; } - - /// AI Credits to add to the current max when action is 'add'. - [JsonPropertyName("additionalAiCredits")] - public double? AdditionalAiCredits { get; set; } + /// Heaviest messages, most-expensive first. + [JsonPropertyName("messages")] + public IList Messages { get => field ??= []; set; } - /// New absolute max AI Credits when action is 'set'. - [JsonPropertyName("maxAiCredits")] - public double? MaxAiCredits { get; set; } + /// Total token count of the current context window, so callers can compute each message's share without a second call. + [JsonPropertyName("totalTokens")] + public long TotalTokens { get; set; } } -/// Request ID of a pending `session_limits_exhausted.requested` event and the user's selected limit action. +/// Parameters for the heaviest-messages query. [Experimental(Diagnostics.Experimental)] -internal sealed class UIHandlePendingSessionLimitsExhaustedRequest +internal sealed class MetadataContextHeaviestMessagesRequest { - /// The unique request ID from the session_limits_exhausted.requested event. - [JsonPropertyName("requestId")] - public string RequestId { get; set; } = string.Empty; - - /// The selected session-limit action. - [JsonPropertyName("response")] - public UISessionLimitsExhaustedResponse Response { get => field ??= new(); set; } + /// Maximum number of messages to return, most-expensive first. Omit for the server default. + [JsonPropertyName("limit")] + public long? Limit { get; set; } /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// User response for a pending exit-plan-mode request, with approval state, selected action, auto-approve flag, and feedback. +/// Notify the session that its working directory context has changed. Emits a `session.context_changed` event so consumers (telemetry, OTel tracker, ACP, the timeline UI) can react. Use this when the host has detected a cwd/branch/repo change outside the session's normal lifecycle (e.g., after a shell command in interactive mode). For a local session, a report whose `cwd` diverges from the session's current working directory is ignored (the call still succeeds but records nothing and emits no event); move a local session's working directory via `metadata.setWorkingDirectory` instead. [Experimental(Diagnostics.Experimental)] -public sealed class UIExitPlanModeResponse +public sealed class MetadataRecordContextChangeResult { - /// Whether the plan was approved. - [JsonPropertyName("approved")] - public bool Approved { get; set; } - - /// Whether subsequent edits should be auto-approved without confirmation. - [JsonPropertyName("autoApproveEdits")] - public bool? AutoApproveEdits { get; set; } - - /// Feedback from the user when they declined the plan or requested changes. - [JsonPropertyName("feedback")] - public string? Feedback { get; set; } - - /// The action the user selected. Defaults to 'autopilot' when autoApproveEdits is true, otherwise 'interactive'. - [JsonPropertyName("selectedAction")] - public UIExitPlanModeAction? SelectedAction { get; set; } } -/// Request ID of a pending `exit_plan_mode.requested` event and the user's response. +/// Updated working directory and git context. Emitted as the new payload of `session.context_changed`. [Experimental(Diagnostics.Experimental)] -internal sealed class UIHandlePendingExitPlanModeRequest +public sealed class SessionWorkingDirectoryContext { - /// The unique request ID from the exit_plan_mode.requested event. - [JsonPropertyName("requestId")] - public string RequestId { get; set; } = string.Empty; + /// Merge-base commit SHA (fork point from the remote default branch). + [JsonPropertyName("baseCommit")] + public string? BaseCommit { get; set; } - /// User response for a pending exit-plan-mode request, with approval state, selected action, auto-approve flag, and feedback. - [JsonPropertyName("response")] - public UIExitPlanModeResponse Response { get => field ??= new(); set; } + /// Current git branch name. + [JsonPropertyName("branch")] + public string? Branch { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// Current working directory path. + [JsonPropertyName("cwd")] + public string Cwd { get; set; } = string.Empty; -/// Register an in-process handler for `auto_mode_switch.requested` events. The caller still attaches the actual listener via the standard event-subscription mechanism; this registration solely tells the server bridge to skip its own dispatch (so a remote client doesn't race the in-process handler for the same requestId). -[Experimental(Diagnostics.Experimental)] -public sealed class UIRegisterDirectAutoModeSwitchHandlerResult -{ - /// Opaque handle representing the registration. Pass this same handle to `unregisterDirectAutoModeSwitchHandler` when the in-process handler is no longer active. Multiple registrations are reference-counted; the server bridge will only dispatch auto-mode-switch requests when no handles are active. - [JsonPropertyName("handle")] - public string Handle { get; set; } = string.Empty; + /// Root directory of the git repository, resolved via git rev-parse. + [JsonPropertyName("gitRoot")] + public string? GitRoot { get; set; } + + /// Head commit of the current git branch. + [JsonPropertyName("headCommit")] + public string? HeadCommit { get; set; } + + /// Hosting platform type of the repository. + [JsonPropertyName("hostType")] + public SessionWorkingDirectoryContextHostType? HostType { get; set; } + + /// Repository identifier derived from the git remote URL ("owner/name" for GitHub, "org/project/repo" for Azure DevOps). + [JsonPropertyName("repository")] + public string? Repository { get; set; } + + /// Raw host string from the git remote URL (e.g. "github.com", "dev.azure.com"). + [JsonPropertyName("repositoryHost")] + public string? RepositoryHost { get; set; } } -/// Identifies the target session. +/// Updated working-directory/git context to record on the session. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionUiRegisterDirectAutoModeSwitchHandlerRequest +internal sealed class MetadataRecordContextChangeRequest { + /// Updated working directory and git context. Emitted as the new payload of `session.context_changed`. + [JsonPropertyName("context")] + public SessionWorkingDirectoryContext Context { get => field ??= new(); set; } + /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Indicates whether the handle was active and the registration count was decremented. +/// Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for any related side-effects (file index, etc.); it does NOT change the process working directory (a session's cwd is per-session, not process-global). For local sessions the runtime validates the target first (an absolute path that exists on disk) and re-bases the permission primary directory; a rejected validation fails the call before anything is mutated, persisted, or emitted. Location-scoped permission rules are then re-keyed to the new directory (best-effort). Remote sessions only record the path. [Experimental(Diagnostics.Experimental)] -public sealed class UIUnregisterDirectAutoModeSwitchHandlerResult +public sealed class MetadataSetWorkingDirectoryResult { - /// True if the handle was active and decremented the counter; false if the handle was unknown. - [JsonPropertyName("unregistered")] - public bool Unregistered { get; set; } + /// Working directory after the update. + [JsonPropertyName("workingDirectory")] + public string WorkingDirectory { get; set; } = string.Empty; } -/// Opaque handle previously returned by `registerDirectAutoModeSwitchHandler` to release. +/// Absolute path to set as the session's new working directory. For local sessions the path must be absolute and exist on disk: it is validated before any session state changes, and a failing validation rejects the call with nothing mutated, persisted, or emitted. Remote sessions record the path as-is. [Experimental(Diagnostics.Experimental)] -internal sealed class UIUnregisterDirectAutoModeSwitchHandlerRequest +internal sealed class MetadataSetWorkingDirectoryRequest { - /// Handle previously returned by `registerDirectAutoModeSwitchHandler`. - [JsonPropertyName("handle")] - public string Handle { get; set; } = string.Empty; - /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; + + /// Absolute path to set as the session's working directory. The runtime updates the session's recorded cwd so subsequent operations (shell tools, file lookups, telemetry) anchor to it. + [JsonPropertyName("workingDirectory")] + public string WorkingDirectory { get; set; } = string.Empty; } -/// Indicates whether the operation succeeded. +/// Re-tokenize the session's existing messages against `modelId` and return the token totals. Useful for hosts that want an initial estimate of context usage on session resume, before the next agent turn fires `session.context_info_changed` events. Returns zeros for an empty session. [Experimental(Diagnostics.Experimental)] -public sealed class PermissionsConfigureResult +public sealed class MetadataRecomputeContextTokensResult { - /// Whether the operation succeeded. - [JsonPropertyName("success")] - public bool Success { get; set; } + /// Tokens contributed by user/assistant/tool messages (excludes system/developer prompts). + [JsonPropertyName("messagesTokenCount")] + public long MessagesTokenCount { get; set; } + + /// Tokens contributed by system/developer prompt snapshots. + [JsonPropertyName("systemTokenCount")] + public long SystemTokenCount { get; set; } + + /// Sum of tokens across chat-context and system-context messages currently held by the session. + [JsonPropertyName("totalTokens")] + public long TotalTokens { get; set; } } -/// Source descriptor for a `session.permissions.configure` content-exclusion rule, with source name and type. +/// Model identifier to use when re-tokenizing the session's existing messages. [Experimental(Diagnostics.Experimental)] -public sealed class PermissionsConfigureAdditionalContentExclusionPolicyRuleSource +internal sealed class MetadataRecomputeContextTokensRequest { - /// Gets or sets the name value. - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; + /// Model identifier used for tokenization. The runtime token-counts both chat-context and system-context messages against this model. + [JsonPropertyName("modelId")] + public string ModelId { get; set; } = string.Empty; - /// Gets or sets the type value. - [JsonPropertyName("type")] - public string Type { get; set; } = string.Empty; + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Single content-exclusion rule supplied to `session.permissions.configure`, with paths, match conditions, and source. +/// Availability of built-in job tools surfaced to boundary consumers. [Experimental(Diagnostics.Experimental)] -public sealed class PermissionsConfigureAdditionalContentExclusionPolicyRule +public sealed class SessionSettingsBuiltInToolAvailabilitySnapshot { - /// Gets or sets the ifAnyMatch value. - [JsonPropertyName("ifAnyMatch")] - public IList? IfAnyMatch { get; set; } - - /// Gets or sets the ifNoneMatch value. - [JsonPropertyName("ifNoneMatch")] - public IList? IfNoneMatch { get; set; } - - /// Gets or sets the paths value. - [JsonPropertyName("paths")] - public IList Paths { get => field ??= []; set; } + /// Gets or sets the createPullRequest value. + [JsonPropertyName("createPullRequest")] + public bool? CreatePullRequest { get; set; } - /// Source descriptor for a `session.permissions.configure` content-exclusion rule, with source name and type. - [JsonPropertyName("source")] - public PermissionsConfigureAdditionalContentExclusionPolicyRuleSource Source { get => field ??= new(); set; } + /// Gets or sets the reportProgress value. + [JsonPropertyName("reportProgress")] + public bool? ReportProgress { get; set; } } -/// Content-exclusion policy supplied to `session.permissions.configure`, with rules, last-updated data, and scope. +/// Redacted job settings for a session. The job nonce is excluded. [Experimental(Diagnostics.Experimental)] -public sealed class PermissionsConfigureAdditionalContentExclusionPolicy +public sealed class SessionSettingsJobSnapshot { - /// Gets or sets the last_updated_at value. - [JsonPropertyName("last_updated_at")] - public JsonElement LastUpdatedAt { get; set; } + /// Gets or sets the builtInToolAvailability value. + [JsonPropertyName("builtInToolAvailability")] + public SessionSettingsBuiltInToolAvailabilitySnapshot? BuiltInToolAvailability { get; set; } - /// Gets or sets the rules value. - [JsonPropertyName("rules")] - public IList Rules { get => field ??= []; set; } + /// Gets or sets the eventType value. + [JsonPropertyName("eventType")] + public string? EventType { get; set; } - /// Allowed values for the `PermissionsConfigureAdditionalContentExclusionPolicyScope` enumeration. - [JsonPropertyName("scope")] - public PermissionsConfigureAdditionalContentExclusionPolicyScope Scope { get; set; } + /// Gets or sets the isTriggerJob value. + [JsonPropertyName("isTriggerJob")] + public bool? IsTriggerJob { get; set; } } -/// If specified, replaces the session's path-permission policy. The runtime constructs the appropriate PathManager based on these inputs (rooted at the session's working directory). Omit to leave the current path policy unchanged. +/// Redacted model routing settings for a session. [Experimental(Diagnostics.Experimental)] -public sealed class PermissionPathsConfig +public sealed class SessionSettingsModelSnapshot { - /// Additional directories to allow tool access to (in addition to the session's working directory). When `unrestricted` is true, these are still pre-populated on the UnrestrictedPathManager so they remain visible via getDirectories() (e.g. for @-mention completion). - [JsonPropertyName("additionalDirectories")] - public IList? AdditionalDirectories { get; set; } + /// Gets or sets the callbackUrl value. + [JsonPropertyName("callbackUrl")] + public string? CallbackUrl { get; set; } - /// Whether to include the system temp directory in the allowed list (defaults to true). Ignored when `unrestricted` is true. - [JsonPropertyName("includeTempDirectory")] - public bool? IncludeTempDirectory { get; set; } + /// Gets or sets the defaultReasoningEffort value. + [JsonPropertyName("defaultReasoningEffort")] + public string? DefaultReasoningEffort { get; set; } - /// If true, the runtime allows access to all paths without prompting. Equivalent to constructing an UnrestrictedPathManager. - [JsonPropertyName("unrestricted")] - public bool? Unrestricted { get; set; } + /// Gets or sets the instanceId value. + [JsonPropertyName("instanceId")] + public string? InstanceId { get; set; } - /// Workspace root path (special-cased to be allowed even before the directory exists). Ignored when `unrestricted` is true. - [JsonPropertyName("workspacePath")] - public string? WorkspacePath { get; set; } + /// Gets or sets the model value. + [JsonPropertyName("model")] + public string? Model { get; set; } } -/// If specified, replaces the session's approved/denied permission rules. Omit to leave the current rules unchanged. +/// Online-evaluation settings safe to expose across the SDK boundary. [Experimental(Diagnostics.Experimental)] -public sealed class PermissionRulesSet +public sealed class SessionSettingsOnlineEvaluationSnapshot { - /// Rules that auto-approve matching requests. - [JsonPropertyName("approved")] - public IList Approved { get => field ??= []; set; } + /// Gets or sets the disableOnlineEvaluation value. + [JsonPropertyName("disableOnlineEvaluation")] + public bool? DisableOnlineEvaluation { get; set; } - /// Rules that auto-deny matching requests. - [JsonPropertyName("denied")] - public IList Denied { get => field ??= []; set; } + /// Gets or sets the enableOnlineEvaluationOutputFile value. + [JsonPropertyName("enableOnlineEvaluationOutputFile")] + public bool? EnableOnlineEvaluationOutputFile { get; set; } } -/// If specified, replaces the session's URL-permission policy. The runtime constructs a fresh DefaultUrlManager based on these inputs. Omit to leave the current URL policy unchanged. +/// Redacted repository and GitHub host settings for a session. [Experimental(Diagnostics.Experimental)] -public sealed class PermissionUrlsConfig +public sealed class SessionSettingsRepoSnapshot { - /// Initial list of allowed URL/domain patterns. Patterns may include path components. Ignored when `unrestricted` is true. - [JsonPropertyName("initialAllowed")] - public IList? InitialAllowed { get; set; } - - /// If true, the runtime allows access to all URLs without prompting. Initial allow-list is ignored when this is true. - [JsonPropertyName("unrestricted")] - public bool? Unrestricted { get; set; } -} + /// Gets or sets the branch value. + [JsonPropertyName("branch")] + public string? Branch { get; set; } -/// Patch of permission policy fields to apply (omit a field to leave it unchanged). -[Experimental(Diagnostics.Experimental)] -internal sealed class PermissionsConfigureParams -{ - /// If specified, replaces the host-supplied GitHub Content Exclusion policies on the session (combined with natively-discovered policies when evaluating tool/file access). Omit to leave the current policies unchanged. - [JsonPropertyName("additionalContentExclusionPolicies")] - public IList? AdditionalContentExclusionPolicies { get; set; } + /// Gets or sets the commit value. + [JsonPropertyName("commit")] + public string? Commit { get; set; } - /// If specified, sets whether path/URL read permission requests are auto-approved. Omit to leave the current value unchanged. - [JsonPropertyName("approveAllReadPermissionRequests")] - public bool? ApproveAllReadPermissionRequests { get; set; } + /// Gets or sets the host value. + [JsonPropertyName("host")] + public string? Host { get; set; } - /// If specified, sets whether tool permission requests are auto-approved without prompting. Omit to leave the current value unchanged. - [JsonPropertyName("approveAllToolPermissionRequests")] - public bool? ApproveAllToolPermissionRequests { get; set; } + /// Gets or sets the hostProtocol value. + [JsonPropertyName("hostProtocol")] + public string? HostProtocol { get; set; } - /// If specified, replaces the session's path-permission policy. The runtime constructs the appropriate PathManager based on these inputs (rooted at the session's working directory). Omit to leave the current path policy unchanged. - [JsonPropertyName("paths")] - public PermissionPathsConfig? Paths { get; set; } + /// Gets or sets the id value. + [JsonPropertyName("id")] + public double? Id { get; set; } - /// If specified, replaces the session's approved/denied permission rules. Omit to leave the current rules unchanged. - [JsonPropertyName("rules")] - public PermissionRulesSet? Rules { get; set; } + /// Gets or sets the name value. + [JsonPropertyName("name")] + public string? Name { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Gets or sets the ownerId value. + [JsonPropertyName("ownerId")] + public double? OwnerId { get; set; } - /// If specified, replaces the session's URL-permission policy. The runtime constructs a fresh DefaultUrlManager based on these inputs. Omit to leave the current URL policy unchanged. - [JsonPropertyName("urls")] - public PermissionUrlsConfig? Urls { get; set; } -} + /// Gets or sets the ownerName value. + [JsonPropertyName("ownerName")] + public string? OwnerName { get; set; } -/// Indicates whether the permission decision was applied; false when the request was already resolved. -[Experimental(Diagnostics.Experimental)] -public sealed class PermissionRequestResult -{ - /// Whether the permission request was handled successfully. - [JsonPropertyName("success")] - public bool Success { get; set; } -} + /// Gets or sets the prCommitCount value. + [JsonPropertyName("prCommitCount")] + public double? PrCommitCount { get; set; } -/// The client's response to the pending permission prompt. -/// Polymorphic base type discriminated by kind. -[Experimental(Diagnostics.Experimental)] -[JsonPolymorphic( - TypeDiscriminatorPropertyName = "kind", - UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] -[JsonDerivedType(typeof(PermissionDecisionApproveOnce), "approve-once")] -[JsonDerivedType(typeof(PermissionDecisionApproveForSession), "approve-for-session")] -[JsonDerivedType(typeof(PermissionDecisionApproveForLocation), "approve-for-location")] -[JsonDerivedType(typeof(PermissionDecisionApprovePermanently), "approve-permanently")] -[JsonDerivedType(typeof(PermissionDecisionReject), "reject")] -[JsonDerivedType(typeof(PermissionDecisionUserNotAvailable), "user-not-available")] -[JsonDerivedType(typeof(PermissionDecisionApproved), "approved")] -[JsonDerivedType(typeof(PermissionDecisionApprovedForSession), "approved-for-session")] -[JsonDerivedType(typeof(PermissionDecisionApprovedForLocation), "approved-for-location")] -[JsonDerivedType(typeof(PermissionDecisionCancelled), "cancelled")] -[JsonDerivedType(typeof(PermissionDecisionDeniedByRules), "denied-by-rules")] -[JsonDerivedType(typeof(PermissionDecisionDeniedNoApprovalRuleAndCouldNotRequestFromUser), "denied-no-approval-rule-and-could-not-request-from-user")] -[JsonDerivedType(typeof(PermissionDecisionDeniedInteractivelyByUser), "denied-interactively-by-user")] -[JsonDerivedType(typeof(PermissionDecisionDeniedByContentExclusionPolicy), "denied-by-content-exclusion-policy")] -[JsonDerivedType(typeof(PermissionDecisionDeniedByPermissionRequestHook), "denied-by-permission-request-hook")] -public partial class PermissionDecision -{ - /// The type discriminator. - [JsonPropertyName("kind")] - public virtual string Kind { get; set; } = string.Empty; -} + /// Gets or sets the readWrite value. + [JsonPropertyName("readWrite")] + public bool? ReadWrite { get; set; } + /// Gets or sets the secretScanningUrl value. + [JsonPropertyName("secretScanningUrl")] + public string? SecretScanningUrl { get; set; } -/// Permission-decision request variant to approve only the current permission request. -/// The approve-once variant of . -[Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApproveOnce : PermissionDecision -{ - /// - [JsonIgnore] - public override string Kind => "approve-once"; + /// Gets or sets the serverUrl value. + [JsonPropertyName("serverUrl")] + public string? ServerUrl { get; set; } } -/// Session-scoped approval to remember (tool prompts only; omitted for path/url prompts). -/// Polymorphic base type discriminated by kind. +/// Redacted validation and memory-tool settings for a session. [Experimental(Diagnostics.Experimental)] -[JsonPolymorphic( - TypeDiscriminatorPropertyName = "kind", - UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] -[JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalCommands), "commands")] -[JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalRead), "read")] -[JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalWrite), "write")] -[JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalMcp), "mcp")] -[JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalMcpSampling), "mcp-sampling")] -[JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalMemory), "memory")] -[JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalCustomTool), "custom-tool")] -[JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalExtensionManagement), "extension-management")] -[JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess), "extension-permission-access")] -public partial class PermissionDecisionApproveForSessionApproval +public sealed class SessionSettingsValidationSnapshot { - /// The type discriminator. - [JsonPropertyName("kind")] - public virtual string Kind { get; set; } = string.Empty; -} + /// Gets or sets the advisoryEnabled value. + [JsonPropertyName("advisoryEnabled")] + public bool? AdvisoryEnabled { get; set; } + /// Gets or sets the codeqlEnabled value. + [JsonPropertyName("codeqlEnabled")] + public bool? CodeqlEnabled { get; set; } -/// Session-scoped approval details for specific command identifiers. -/// The commands variant of . -[Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApproveForSessionApprovalCommands : PermissionDecisionApproveForSessionApproval -{ - /// - [JsonIgnore] - public override string Kind => "commands"; + /// Gets or sets the codeReviewEnabled value. + [JsonPropertyName("codeReviewEnabled")] + public bool? CodeReviewEnabled { get; set; } - /// Command identifiers covered by this approval. - [JsonPropertyName("commandIdentifiers")] - public required IList CommandIdentifiers { get; set; } -} + /// Gets or sets the codeReviewModel value. + [JsonPropertyName("codeReviewModel")] + public string? CodeReviewModel { get; set; } -/// Session-scoped approval details for read-only filesystem operations. -/// The read variant of . -[Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApproveForSessionApprovalRead : PermissionDecisionApproveForSessionApproval -{ - /// - [JsonIgnore] - public override string Kind => "read"; -} + /// Gets or sets the dependabotTimeout value. + [JsonPropertyName("dependabotTimeout")] + public double? DependabotTimeout { get; set; } -/// Session-scoped approval details for filesystem write operations. -/// The write variant of . -[Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApproveForSessionApprovalWrite : PermissionDecisionApproveForSessionApproval -{ - /// - [JsonIgnore] - public override string Kind => "write"; + /// Gets or sets the memoryStoreEnabled value. + [JsonPropertyName("memoryStoreEnabled")] + public bool? MemoryStoreEnabled { get; set; } + + /// Gets or sets the memoryVoteEnabled value. + [JsonPropertyName("memoryVoteEnabled")] + public bool? MemoryVoteEnabled { get; set; } + + /// Gets or sets the secretScanningEnabled value. + [JsonPropertyName("secretScanningEnabled")] + public bool? SecretScanningEnabled { get; set; } + + /// Gets or sets the timeout value. + [JsonPropertyName("timeout")] + public double? Timeout { get; set; } } -/// Session-scoped approval details for an MCP server tool, or all tools on the server when `toolName` is null. -/// The mcp variant of . +/// Redacted, serializable view of session runtime settings for SDK boundary consumers. Secrets and raw feature flags are intentionally excluded. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApproveForSessionApprovalMcp : PermissionDecisionApproveForSessionApproval +internal sealed class SessionSettingsSnapshot { - /// - [JsonIgnore] - public override string Kind => "mcp"; + /// Gets or sets the clientName value. + [JsonPropertyName("clientName")] + public string? ClientName { get; set; } - /// MCP server name. - [JsonPropertyName("serverName")] - public required string ServerName { get; set; } + /// Gets or sets the job value. + [JsonPropertyName("job")] + public SessionSettingsJobSnapshot Job { get => field ??= new(); set; } - /// MCP tool name, or null to cover every tool on the server. - [JsonPropertyName("toolName")] - public string? ToolName { get; set; } + /// Gets or sets the model value. + [JsonPropertyName("model")] + public SessionSettingsModelSnapshot Model { get => field ??= new(); set; } + + /// Gets or sets the onlineEvaluation value. + [JsonPropertyName("onlineEvaluation")] + public SessionSettingsOnlineEvaluationSnapshot OnlineEvaluation { get => field ??= new(); set; } + + /// Gets or sets the repo value. + [JsonPropertyName("repo")] + public SessionSettingsRepoSnapshot Repo { get => field ??= new(); set; } + + /// Gets or sets the startTimeMs value. + [JsonPropertyName("startTimeMs")] + public double? StartTimeMs { get; set; } + + /// Gets or sets the timeoutMs value. + [JsonPropertyName("timeoutMs")] + public double? TimeoutMs { get; set; } + + /// Gets or sets the validation value. + [JsonPropertyName("validation")] + public SessionSettingsValidationSnapshot Validation { get => field ??= new(); set; } + + /// Gets or sets the version value. + [JsonPropertyName("version")] + public string? Version { get; set; } } -/// Session-scoped approval details for MCP sampling requests from a server. -/// The mcp-sampling variant of . +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApproveForSessionApprovalMcpSampling : PermissionDecisionApproveForSessionApproval +internal sealed class SessionSettingsSnapshotRequest { - /// - [JsonIgnore] - public override string Kind => "mcp-sampling"; - - /// MCP server name. - [JsonPropertyName("serverName")] - public required string ServerName { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Session-scoped approval details for writes to long-term memory. -/// The memory variant of . +/// Result of evaluating a Rust-owned settings predicate. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApproveForSessionApprovalMemory : PermissionDecisionApproveForSessionApproval +internal sealed class SessionSettingsEvaluatePredicateResult { - /// - [JsonIgnore] - public override string Kind => "memory"; + /// Gets or sets the enabled value. + [JsonPropertyName("enabled")] + public bool Enabled { get; set; } } -/// Session-scoped approval details for a custom tool, keyed by tool name. -/// The custom-tool variant of . +/// Named Rust-owned settings predicate to evaluate for this session. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApproveForSessionApprovalCustomTool : PermissionDecisionApproveForSessionApproval +internal sealed class SessionSettingsEvaluatePredicateRequest { - /// - [JsonIgnore] - public override string Kind => "custom-tool"; + /// Predicate name. The runtime owns the raw feature-flag names and composition logic. + [JsonPropertyName("name")] + public SessionSettingsPredicateName Name { get; set; } - /// Custom tool name. + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; + + /// Tool name for tool-scoped predicates such as trivial-change handling. [JsonPropertyName("toolName")] - public required string ToolName { get; set; } + public string? ToolName { get; set; } } -/// Session-scoped approval details for extension-management operations, optionally narrowed by operation. -/// The extension-management variant of . +/// Content-exclusion decision for one requested path. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApproveForSessionApprovalExtensionManagement : PermissionDecisionApproveForSessionApproval +public sealed class ContentExclusionPathCheck { - /// - [JsonIgnore] - public override string Kind => "extension-management"; + /// Whether the session's complete content-exclusion policy excludes the path. + [JsonPropertyName("excluded")] + public bool Excluded { get; set; } - /// Optional operation identifier; when omitted, the approval covers all extension management operations. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("operation")] - public string? Operation { get; set; } + /// The path supplied by the caller. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; } -/// Session-scoped approval details for an extension's permission-gated capability access, keyed by extension name. -/// The extension-permission-access variant of . +/// Batch content-exclusion result. Callers must fail closed when policy evaluation is unavailable. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess : PermissionDecisionApproveForSessionApproval +public sealed class ContentExclusionCheckPathsResult { - /// - [JsonIgnore] - public override string Kind => "extension-permission-access"; + /// Whether the session's policy service was available for the complete batch. When false, checks is empty and callers must treat every requested path as excluded. + [JsonPropertyName("available")] + public bool Available { get; set; } - /// Extension name. - [JsonPropertyName("extensionName")] - public required string ExtensionName { get; set; } + /// Per-path decisions in request order. Empty when available is false. + [JsonPropertyName("checks")] + public IList Checks { get => field ??= []; set; } } -/// Permission-decision request variant to approve for the rest of the session, with optional tool approval or URL domain. -/// The approve-for-session variant of . +/// Local file system absolute paths within the session working directory to check against its content-exclusion policy. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApproveForSession : PermissionDecision +internal sealed class ContentExclusionCheckPathsRequest { - /// - [JsonIgnore] - public override string Kind => "approve-for-session"; - - /// Session-scoped approval to remember (tool prompts only; omitted for path/url prompts). - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("approval")] - public PermissionDecisionApproveForSessionApproval? Approval { get; set; } + /// Local file system absolute paths within the session working directory to check. Results are returned in the same order, including duplicates. + [JsonPropertyName("paths")] + public IList Paths { get => field ??= []; set; } - /// URL domain to approve for the rest of the session (URL prompts only). - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("domain")] - public string? Domain { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Approval to persist for this location. -/// Polymorphic base type discriminated by kind. +/// Identifier of the spawned process, used to correlate streamed output and exit notifications. [Experimental(Diagnostics.Experimental)] -[JsonPolymorphic( - TypeDiscriminatorPropertyName = "kind", - UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] -[JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalCommands), "commands")] -[JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalRead), "read")] -[JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalWrite), "write")] -[JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalMcp), "mcp")] -[JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalMcpSampling), "mcp-sampling")] -[JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalMemory), "memory")] -[JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalCustomTool), "custom-tool")] -[JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalExtensionManagement), "extension-management")] -[JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess), "extension-permission-access")] -public partial class PermissionDecisionApproveForLocationApproval +public sealed class ShellExecResult { - /// The type discriminator. - [JsonPropertyName("kind")] - public virtual string Kind { get; set; } = string.Empty; + /// Unique identifier for tracking streamed output. + [JsonPropertyName("processId")] + public string ProcessId { get; set; } = string.Empty; } - -/// Location-scoped approval details for specific command identifiers. -/// The commands variant of . +/// Shell command to run, with optional working directory and timeout in milliseconds. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApproveForLocationApprovalCommands : PermissionDecisionApproveForLocationApproval +internal sealed class ShellExecRequest { - /// - [JsonIgnore] - public override string Kind => "commands"; + /// Shell command to execute. + [JsonPropertyName("command")] + public string Command { get; set; } = string.Empty; - /// Command identifiers covered by this approval. - [JsonPropertyName("commandIdentifiers")] - public required IList CommandIdentifiers { get; set; } + /// Working directory (defaults to session working directory). + [JsonPropertyName("cwd")] + public string? Cwd { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; + + /// Timeout in milliseconds (default: 30000). + [JsonConverter(typeof(MillisecondsTimeSpanConverter))] + [JsonPropertyName("timeout")] + public TimeSpan? Timeout { get; set; } } -/// Location-scoped approval details for read-only filesystem operations. -/// The read variant of . +/// Indicates whether the signal was delivered; false if the process was unknown or already exited. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApproveForLocationApprovalRead : PermissionDecisionApproveForLocationApproval +public sealed class ShellKillResult { - /// - [JsonIgnore] - public override string Kind => "read"; + /// Whether the signal was sent successfully. + [JsonPropertyName("killed")] + public bool Killed { get; set; } } -/// Location-scoped approval details for filesystem write operations. -/// The write variant of . +/// Identifier of a process previously returned by "shell.exec" and the signal to send. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApproveForLocationApprovalWrite : PermissionDecisionApproveForLocationApproval +internal sealed class ShellKillRequest { - /// - [JsonIgnore] - public override string Kind => "write"; + /// Process identifier returned by shell.exec. + [JsonPropertyName("processId")] + public string ProcessId { get; set; } = string.Empty; + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; + + /// Signal to send (default: SIGTERM). + [JsonPropertyName("signal")] + public ShellKillSignal? Signal { get; set; } } -/// Location-scoped approval details for an MCP server tool, or all tools on the server when `toolName` is null. -/// The mcp variant of . +/// Result of a user-requested shell command. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApproveForLocationApprovalMcp : PermissionDecisionApproveForLocationApproval +public sealed class UserRequestedShellCommandResult { - /// - [JsonIgnore] - public override string Kind => "mcp"; + /// Error output when the execution failed. + [JsonPropertyName("error")] + public string? Error { get; set; } - /// MCP server name. - [JsonPropertyName("serverName")] - public required string ServerName { get; set; } + /// Process exit code, when available. + [JsonPropertyName("exitCode")] + public long? ExitCode { get; set; } - /// MCP tool name, or null to cover every tool on the server. - [JsonPropertyName("toolName")] - public string? ToolName { get; set; } + /// Captured command output. + [JsonPropertyName("output")] + public string Output { get; set; } = string.Empty; + + /// Whether the command completed successfully. + [JsonPropertyName("success")] + public bool Success { get; set; } + + /// Tool call id emitted for the shell execution. + [JsonPropertyName("toolCallId")] + public string ToolCallId { get; set; } = string.Empty; } -/// Location-scoped approval details for MCP sampling requests from a server. -/// The mcp-sampling variant of . +/// User-requested shell command and cancellation handle. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApproveForLocationApprovalMcpSampling : PermissionDecisionApproveForLocationApproval +internal sealed class ShellExecuteUserRequestedRequest { - /// - [JsonIgnore] - public override string Kind => "mcp-sampling"; + /// Shell command to execute. + [JsonPropertyName("command")] + public string Command { get; set; } = string.Empty; - /// MCP server name. - [JsonPropertyName("serverName")] - public required string ServerName { get; set; } + /// Caller-provided cancellation handle for this execution. + [JsonPropertyName("requestId")] + public string RequestId { get; set; } = string.Empty; + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Location-scoped approval details for writes to long-term memory. -/// The memory variant of . +/// Cancellation result for a user-requested shell command. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApproveForLocationApprovalMemory : PermissionDecisionApproveForLocationApproval +public sealed class CancelUserRequestedShellCommandResult { - /// - [JsonIgnore] - public override string Kind => "memory"; + /// Whether an in-flight execution was found and signalled to cancel. + [JsonPropertyName("cancelled")] + public bool Cancelled { get; set; } } -/// Location-scoped approval details for a custom tool, keyed by tool name. -/// The custom-tool variant of . +/// User-requested shell execution cancellation handle. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApproveForLocationApprovalCustomTool : PermissionDecisionApproveForLocationApproval +internal sealed class ShellCancelUserRequestedRequest { - /// - [JsonIgnore] - public override string Kind => "custom-tool"; + /// Request ID previously passed to executeUserRequested. + [JsonPropertyName("requestId")] + public string RequestId { get; set; } = string.Empty; - /// Custom tool name. - [JsonPropertyName("toolName")] - public required string ToolName { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Location-scoped approval details for extension-management operations, optionally narrowed by operation. -/// The extension-management variant of . +/// Post-compaction context window usage breakdown. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApproveForLocationApprovalExtensionManagement : PermissionDecisionApproveForLocationApproval +public sealed class HistoryCompactContextWindow { - /// - [JsonIgnore] - public override string Kind => "extension-management"; + /// Token count from non-system messages (user, assistant, tool). + [JsonPropertyName("conversationTokens")] + public long? ConversationTokens { get; set; } - /// Optional operation identifier; when omitted, the approval covers all extension management operations. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("operation")] - public string? Operation { get; set; } -} + /// Current total tokens in the context window (system + conversation + tool definitions). + [JsonPropertyName("currentTokens")] + public long CurrentTokens { get; set; } -/// Location-scoped approval details for an extension's permission-gated capability access, keyed by extension name. -/// The extension-permission-access variant of . -[Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess : PermissionDecisionApproveForLocationApproval -{ - /// - [JsonIgnore] - public override string Kind => "extension-permission-access"; + /// Current number of messages in the conversation. + [JsonPropertyName("messagesLength")] + public long MessagesLength { get; set; } - /// Extension name. - [JsonPropertyName("extensionName")] - public required string ExtensionName { get; set; } + /// Token count from system message(s). + [JsonPropertyName("systemTokens")] + public long? SystemTokens { get; set; } + + /// Maximum token count for the model's context window. + [JsonPropertyName("tokenLimit")] + public long TokenLimit { get; set; } + + /// Token count from tool definitions. + [JsonPropertyName("toolDefinitionsTokens")] + public long? ToolDefinitionsTokens { get; set; } } -/// Permission-decision request variant to approve and persist a permission for a project location, with approval details and location key. -/// The approve-for-location variant of . +/// Compaction outcome with the number of tokens and messages removed, summary text, and the resulting context window breakdown. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApproveForLocation : PermissionDecision +public sealed class HistoryCompactResult { - /// - [JsonIgnore] - public override string Kind => "approve-for-location"; + /// Post-compaction context window usage breakdown. + [JsonPropertyName("contextWindow")] + public HistoryCompactContextWindow? ContextWindow { get; set; } - /// Approval to persist for this location. - [JsonPropertyName("approval")] - public required PermissionDecisionApproveForLocationApproval Approval { get; set; } + /// Number of messages removed during compaction. + [JsonPropertyName("messagesRemoved")] + public long MessagesRemoved { get; set; } - /// Location key (git root or cwd) to persist the approval to. - [JsonPropertyName("locationKey")] - public required string LocationKey { get; set; } -} + /// Whether compaction completed successfully. + [JsonPropertyName("success")] + public bool Success { get; set; } -/// Permission-decision request variant to permanently approve a URL domain across sessions. -/// The approve-permanently variant of . -[Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApprovePermanently : PermissionDecision -{ - /// - [JsonIgnore] - public override string Kind => "approve-permanently"; + /// Summary text produced by compaction. Omitted when compaction did not produce a summary (e.g. failure path). + [JsonPropertyName("summaryContent")] + public string? SummaryContent { get; set; } - /// URL domain to approve permanently. - [JsonPropertyName("domain")] - public required string Domain { get; set; } + /// Number of tokens freed by compaction. + [JsonPropertyName("tokensRemoved")] + public long TokensRemoved { get; set; } } -/// Permission-decision request variant to reject a pending permission request, with optional feedback. -/// The reject variant of . +/// RPC data type for SessionHistoryCompact operations. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionReject : PermissionDecision +public sealed class SessionHistoryCompactRequest { - /// - [JsonIgnore] - public override string Kind => "reject"; + /// 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 feedback explaining the rejection. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("feedback")] - public string? Feedback { get; set; } + /// Context window token limit this compaction is targeting, recorded as the `tokenLimit` on the persisted `session.compaction_start` / `session.compaction_complete` events. Set it when the compaction targets a window other than the compacting model's own, e.g. switching to a model with a smaller context window: the compaction still runs on the current model, so the limit that motivated it would otherwise be lost. When absent, the events record the compacting model's own resolved limit. Attribution metadata only - it does not change how much the compaction removes. + [JsonPropertyName("tokenLimit")] + public long? TokenLimit { get; set; } + + /// What initiated this compaction request, recorded as the `trigger` on the persisted `session.compaction_start` / `session.compaction_complete` events. When absent, the compaction is persisted without trigger attribution (initiator unknown). + [JsonPropertyName("trigger")] + public SessionHistoryCompactRequestTrigger? Trigger { get; set; } } -/// Permission-decision variant indicating no user was available to confirm the request. -/// The user-not-available variant of . +/// RPC data type for SessionHistoryCompactRequestWithSession operations. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionUserNotAvailable : PermissionDecision +internal sealed class SessionHistoryCompactRequestWithSession { - /// - [JsonIgnore] - public override string Kind => "user-not-available"; + /// 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; + + /// Context window token limit this compaction is targeting, recorded as the `tokenLimit` on the persisted `session.compaction_start` / `session.compaction_complete` events. Set it when the compaction targets a window other than the compacting model's own, e.g. switching to a model with a smaller context window: the compaction still runs on the current model, so the limit that motivated it would otherwise be lost. When absent, the events record the compacting model's own resolved limit. Attribution metadata only - it does not change how much the compaction removes. + [JsonPropertyName("tokenLimit")] + public long? TokenLimit { get; set; } + + /// What initiated this compaction request, recorded as the `trigger` on the persisted `session.compaction_start` / `session.compaction_complete` events. When absent, the compaction is persisted without trigger attribution (initiator unknown). + [JsonPropertyName("trigger")] + public SessionHistoryCompactRequestWithSessionTrigger? Trigger { get; set; } } -/// Permission-decision variant indicating the request was approved. -/// The approved variant of . +/// Number of events that were removed by the truncation. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApproved : PermissionDecision +public sealed class HistoryTruncateResult { - /// - [JsonIgnore] - public override string Kind => "approved"; + /// Failure detail when checkpointCleanupFailed is true. + [JsonPropertyName("checkpointCleanupError")] + public string? CheckpointCleanupError { get; set; } + + /// True when conversation truncation succeeded but post-truncation workspace checkpoint cleanup failed. History is already truncated; callers may still prune snapshots but should report a checkpoint-cleanup rather than a truncation failure. + [JsonPropertyName("checkpointCleanupFailed")] + public bool? CheckpointCleanupFailed { get; set; } + + /// Number of events that were removed. + [JsonPropertyName("eventsRemoved")] + public long EventsRemoved { get; set; } } -/// Permission-decision variant indicating approval was remembered for the session, with approval details. -/// The approved-for-session variant of . +/// Identifier of the event to truncate to; this event and all later events are removed. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApprovedForSession : PermissionDecision +internal sealed class HistoryTruncateRequest { - /// - [JsonIgnore] - public override string Kind => "approved-for-session"; + /// Event ID to truncate to. This event and all events after it are removed from the session. + [JsonPropertyName("eventId")] + public string EventId { get; set; } = string.Empty; - /// The approval to add as a session-scoped rule. - [JsonPropertyName("approval")] - public required UserToolSessionApproval Approval { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Permission-decision variant indicating approval was persisted for a project location, with approval details and location key. -/// The approved-for-location variant of . +/// A root user turn that the session can rewind to. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionApprovedForLocation : PermissionDecision +public sealed class HistoryRewindPoint { - /// - [JsonIgnore] - public override string Kind => "approved-for-location"; + /// Whether at least one file in this turn or a later turn can be restored. + [JsonPropertyName("canRestoreFiles")] + public bool CanRestoreFiles { get; set; } - /// The approval to persist for this location. - [JsonPropertyName("approval")] - public required UserToolSessionApproval Approval { get; set; } + /// ID of the user.message event that begins the discarded suffix. + [JsonPropertyName("eventId")] + public string EventId { get; set; } = string.Empty; - /// The location key (git root or cwd) to persist the approval to. - [JsonPropertyName("locationKey")] - public required string LocationKey { get; set; } + /// Number of unique files in this turn and all later turns that have captured changes. + [JsonPropertyName("fileCount")] + public long FileCount { get; set; } + + /// Whether this turn was an automatically injected autopilot continuation. + [JsonPropertyName("isAutopilotContinuation")] + public bool IsAutopilotContinuation { get; set; } + + /// Lines added by this turn's captured file changes. + [JsonPropertyName("linesAdded")] + public long LinesAdded { get; set; } + + /// Lines removed by this turn's captured file changes. + [JsonPropertyName("linesRemoved")] + public long LinesRemoved { get; set; } + + /// ISO timestamp of the user turn. + [JsonPropertyName("timestamp")] + public string Timestamp { get; set; } = string.Empty; + + /// Whether this turn itself captured any file changes. + [JsonPropertyName("turnChangedFiles")] + public bool TurnChangedFiles { get; set; } + + /// User-visible message text for the turn. + [JsonPropertyName("userMessage")] + public string UserMessage { get; set; } = string.Empty; } -/// Permission-decision variant indicating the request was cancelled before use, with an optional reason. -/// The cancelled variant of . +/// Rewind points and file-change-tracking availability for the session. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionCancelled : PermissionDecision +public sealed class HistoryListRewindPointsResult { - /// - [JsonIgnore] - public override string Kind => "cancelled"; + /// Whether this session captured file changes from its first turn. + [JsonPropertyName("fileChangeTrackingEnabled")] + public bool FileChangeTrackingEnabled { get; set; } - /// Optional explanation of why the request was cancelled. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("reason")] - public string? Reason { get; set; } + /// Root user turns in chronological order. Empty when `unavailableReason` is set. + [JsonPropertyName("points")] + public IList Points { get => field ??= []; set; } + + /// Why the listed points could not be produced, when applicable; the points list is empty whenever it is set. `unsupported-remote-session` is permanent for the session and comes with `fileChangeTrackingEnabled: false`. `session-busy` is transient and only ever reported by a session that *is* tracking (`fileChangeTrackingEnabled: true`), because the file-change captures cannot be read while work that may still mutate them is in flight; the same request succeeds once the session settles, so a client that wants points should retry rather than treat it as a failure. It is never `file-change-tracking-disabled`: an untracked local session still lists conversation-only points and reports that through `fileChangeTrackingEnabled: false`. + [JsonPropertyName("unavailableReason")] + public HistoryRewindUnavailableReason? UnavailableReason { get; set; } } -/// Permission-decision variant indicating explicit denial by permission rules, with the matching rules. -/// The denied-by-rules variant of . +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionDeniedByRules : PermissionDecision +internal sealed class SessionHistoryListRewindPointsRequest { - /// - [JsonIgnore] - public override string Kind => "denied-by-rules"; - - /// Rules that denied the request. - [JsonPropertyName("rules")] - public required IList Rules { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Permission-decision variant indicating no approval rule matched and user confirmation was unavailable. -/// The denied-no-approval-rule-and-could-not-request-from-user variant of . +/// A file that a conversation-and-files rewind would restore. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionDeniedNoApprovalRuleAndCouldNotRequestFromUser : PermissionDecision +public sealed class HistoryRewindFilePreview { - /// - [JsonIgnore] - public override string Kind => "denied-no-approval-rule-and-could-not-request-from-user"; + /// Aggregate change made across the discarded turns. + [JsonPropertyName("changeType")] + public HistoryRewindChangeType ChangeType { get; set; } + + /// Lines added across the discarded turns. + [JsonPropertyName("linesAdded")] + public long LinesAdded { get; set; } + + /// Lines removed across the discarded turns. + [JsonPropertyName("linesRemoved")] + public long LinesRemoved { get; set; } + + /// Absolute path of the captured file. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; } -/// Permission-decision variant indicating the user denied an interactive prompt, with optional feedback and force-reject flag. -/// The denied-interactively-by-user variant of . +/// Files and aggregate changes for a prospective rewind. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionDeniedInteractivelyByUser : PermissionDecision +public sealed class HistoryPreviewRewindResult { - /// - [JsonIgnore] - public override string Kind => "denied-interactively-by-user"; + /// Whether file restore is available for this session. This is authoritative: switch on it and read `reason` only when it is false. + [JsonPropertyName("available")] + public bool Available { get; set; } - /// Optional feedback from the user explaining the denial. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("feedback")] - public string? Feedback { get; set; } + /// Number of unique files in the preview. + [JsonPropertyName("fileCount")] + public long FileCount { get; set; } - /// Whether to force-reject the current agent turn. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("forceReject")] - public bool? ForceReject { get; set; } + /// Files ordered by path. + [JsonPropertyName("files")] + public IList Files { get => field ??= []; set; } + + /// Why file restore is unavailable, when applicable. Populated only when `available` is false and never set when `available` is true. + [JsonPropertyName("reason")] + public HistoryRewindUnavailableReason? Reason { get; set; } } -/// Permission-decision variant indicating denial by content-exclusion policy, with path and message. -/// The denied-by-content-exclusion-policy variant of . +/// Event boundary to preview for conversation-and-files rewind. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionDeniedByContentExclusionPolicy : PermissionDecision +internal sealed class HistoryPreviewRewindRequest { - /// - [JsonIgnore] - public override string Kind => "denied-by-content-exclusion-policy"; + /// ID of the user.message event that begins the discarded suffix. + [JsonPropertyName("eventId")] + public string EventId { get; set; } = string.Empty; - /// Human-readable explanation of why the path was excluded. - [JsonPropertyName("message")] - public required string Message { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// File path that triggered the exclusion. +/// A captured file that rewind intentionally left unchanged. +[Experimental(Diagnostics.Experimental)] +public sealed class HistorySkippedFileRestore +{ + /// Absolute path of the skipped file. [JsonPropertyName("path")] - public required string Path { get; set; } + public string Path { get; set; } = string.Empty; + + /// Reason the file was not restored. + [JsonPropertyName("reason")] + public HistoryFileRestoreSkipReason Reason { get; set; } } -/// Permission-decision variant indicating denial by a permission request hook, with optional message and interrupt flag. -/// The denied-by-permission-request-hook variant of . +/// Structured outcome of a rewind request. [Experimental(Diagnostics.Experimental)] -public partial class PermissionDecisionDeniedByPermissionRequestHook : PermissionDecision +public sealed class HistoryRewindResult { - /// - [JsonIgnore] - public override string Kind => "denied-by-permission-request-hook"; + /// Failure detail. Set only for the failure and partial-failure outcomes (`files-rolled-back`, `rollback-incomplete`, `truncation-failed`, `checkpoint-cleanup-failed`, `snapshot-prune-failed`); omitted for `success` and for the unavailable outcomes (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`). + [JsonPropertyName("error")] + public string? Error { get; set; } - /// Whether to interrupt the current agent turn. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("interrupt")] - public bool? Interrupt { get; set; } + /// Number of persisted events removed by conversation truncation. Present only when truncation succeeded (outcomes `success`, `checkpoint-cleanup-failed`, and `snapshot-prune-failed`); omitted for every unavailable outcome (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`) and for `truncation-failed`, `files-rolled-back`, and `rollback-incomplete`. + [JsonPropertyName("eventsRemoved")] + public long? EventsRemoved { get; set; } - /// Optional message from the hook explaining the denial. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("message")] - public string? Message { get; set; } + /// Overall rewind outcome. This discriminates the result: it governs which of the remaining fields are populated, so consumers must switch on it before reading `eventsRemoved`, `restoredFiles`, `skippedFiles`, or `error`. See each field for the outcomes that populate it. + [JsonPropertyName("outcome")] + public HistoryRewindOutcome Outcome { get; set; } + + /// Absolute paths restored to their captured preimages. Always empty for conversation-only rewinds and for the unavailable outcomes (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`); only conversation-and-files outcomes that reached the file-restore stage populate it. + [JsonPropertyName("restoredFiles")] + public IList RestoredFiles { get => field ??= []; set; } + + /// Captured files intentionally left unchanged. Always empty for conversation-only rewinds and for the unavailable outcomes (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`); only conversation-and-files outcomes that reached the file-restore stage populate it. + [JsonPropertyName("skippedFiles")] + public IList SkippedFiles { get => field ??= []; set; } } -/// Pending permission request ID and the decision to apply (approve/reject and scope). +/// Boundary and mode for rewinding session history. [Experimental(Diagnostics.Experimental)] -internal sealed class PermissionDecisionRequest +internal sealed class HistoryRewindRequest { - /// Request ID of the pending permission request. - [JsonPropertyName("requestId")] - public string RequestId { get; set; } = string.Empty; + /// ID of the user.message event that begins the discarded suffix. + [JsonPropertyName("eventId")] + public string EventId { get; set; } = string.Empty; - /// The client's response to the pending permission prompt. - [JsonPropertyName("result")] - public PermissionDecision Result { get => field ??= new(); set; } + /// Whether to rewind only conversation history or also restore captured files. + [JsonPropertyName("mode")] + public HistoryRewindMode Mode { get; set; } /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Pending permission prompt reconstructed from event history, with request ID and user-facing prompt details. +/// Indicates whether an in-progress background compaction was cancelled. [Experimental(Diagnostics.Experimental)] -public sealed class PendingPermissionRequest +public sealed class HistoryCancelBackgroundCompactionResult { - /// The user-facing permission prompt details (commands, write, read, mcp, url, memory, custom-tool, path, hook). - [JsonPropertyName("request")] - public PermissionPromptRequest Request { get; set; } = null!; + /// Whether an in-progress background compaction was cancelled. False when no compaction was running, when the session is remote, or when the underlying processor was unavailable. + [JsonPropertyName("cancelled")] + public bool Cancelled { get; set; } +} - /// Unique identifier for the pending permission request. - [JsonPropertyName("requestId")] - public string RequestId { get; set; } = string.Empty; +/// Identifies the target session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionHistoryCancelBackgroundCompactionRequest +{ + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// List of pending permission requests reconstructed from event history. +/// Indicates whether an in-progress manual compaction was aborted. [Experimental(Diagnostics.Experimental)] -public sealed class PendingPermissionRequestList +public sealed class HistoryAbortManualCompactionResult { - /// Pending permission prompts reconstructed from the session's event history. Equivalent to the set of `permission.requested` events that have not yet been followed by a matching `permission.completed` event. Used by clients (e.g. the CLI) to hydrate UI for prompts that were emitted before the client attached to the session. - [JsonPropertyName("items")] - public IList Items { get => field ??= []; set; } + /// Whether an in-progress manual compaction was aborted. False when no manual compaction was running, when its abort controller was already aborted, or when the session is remote. + [JsonPropertyName("aborted")] + public bool Aborted { get; set; } } -/// No parameters; returns currently-pending permission requests for the session. +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class PermissionsPendingRequestsRequest +internal sealed class SessionHistoryAbortManualCompactionRequest { /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Indicates whether the operation succeeded. +/// Markdown summary of the conversation context (empty when not available). [Experimental(Diagnostics.Experimental)] -public sealed class PermissionsSetApproveAllResult +public sealed class HistorySummarizeForHandoffResult { - /// Whether the operation succeeded. - [JsonPropertyName("success")] - public bool Success { get; set; } + /// Markdown summary of the conversation context produced by an LLM. Empty string when there are no messages or when the session does not support local summarization. + [JsonPropertyName("summary")] + public string Summary { get; set; } = string.Empty; } -/// Allow-all toggle for tool permission requests, with an optional telemetry source. +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class PermissionsSetApproveAllRequest +internal sealed class SessionHistorySummarizeForHandoffRequest { - /// Whether to auto-approve all tool permission requests. - [JsonPropertyName("enabled")] - public bool Enabled { get; set; } - /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; - - /// Optional source for allow-all telemetry. Defaults to `rpc` when omitted for SDK callers. - [JsonPropertyName("source")] - public PermissionsSetApproveAllSource? Source { get; set; } } -/// Indicates whether the operation succeeded and reports the post-mutation state. +/// User-facing pending queue entry, with kind and display text for a queued message, slash command, or model change. [Experimental(Diagnostics.Experimental)] -public sealed class AllowAllPermissionSetResult +public sealed class QueuePendingItems { - /// Authoritative full allow-all state after the mutation. - [JsonPropertyName("enabled")] - public bool Enabled { get; set; } + /// Agent mode stored on this queued entry, as stamped when it was enqueued. Items without an explicit mode report interactive. This is not necessarily the mode that will constrain the turn: a plan or autopilot session applies its own write gate, continuation loop and permission posture to every drained item regardless of the mode stored here. + [JsonPropertyName("agentMode")] + public SendAgentMode AgentMode { get; set; } - /// Authoritative allow-all mode after the mutation. - [JsonPropertyName("mode")] - public PermissionsAllowAllMode? Mode { get; set; } + /// Human-readable text to display for this queue entry in the UI. + [JsonPropertyName("displayText")] + public string DisplayText { get; set; } = string.Empty; - /// Whether the operation succeeded. - [JsonPropertyName("success")] - public bool Success { get; set; } + /// Stable opaque id for the canonical queued item. Batch rows share one id. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; + + /// Whether this item is a queued user message or a queued slash command / model change. + [JsonPropertyName("kind")] + public QueuePendingItemsKind Kind { get; set; } +} + +/// Snapshot of the session's pending queued items and immediate-steering messages. +[Experimental(Diagnostics.Experimental)] +public sealed class QueuePendingItemsResult +{ + /// Pending queued items in submission order. Includes user messages, queued slash commands, and queued model changes; omits internal system items. + [JsonPropertyName("items")] + public IList Items { get => field ??= []; set; } + + /// Display text for messages currently in the immediate steering queue (interjections sent during a running turn). + [JsonPropertyName("steeringMessages")] + public IList SteeringMessages { get => field ??= []; set; } } -/// Allow-all mode to apply for the session. +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class PermissionsSetAllowAllRequest +internal sealed class SessionQueuePendingItemsRequest { - /// Legacy full allow-all toggle. Prefer `mode`; when `mode` is omitted, `enabled: true` is treated as `mode: "on"` and any other value is treated as `mode: "off"`. - [JsonPropertyName("enabled")] - public bool? Enabled { get; set; } - - /// Allow-all mode to apply. `on` enables full allow-all; `auto` enables advisory LLM auto-approval; `off` disables both. - [JsonPropertyName("mode")] - public PermissionsAllowAllMode? Mode { get; set; } - - /// Optional model id for the `auto` mode auto-approval LLM judging. Only meaningful when `mode` is `auto`; ignored otherwise. When omitted, the session's active model is used. - [JsonPropertyName("model")] - public string? Model { get; set; } - /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; - - /// Optional source for allow-all telemetry. Defaults to `rpc` when omitted for SDK callers. - [JsonPropertyName("source")] - public PermissionsSetAllowAllSource? Source { get; set; } } -/// Current allow-all permission mode. +/// Internal snapshot of native queue state for local session orchestration. [Experimental(Diagnostics.Experimental)] -public sealed class AllowAllPermissionState +internal sealed class QueueSnapshotResult { - /// Whether full allow-all permissions are currently active. - [JsonPropertyName("enabled")] - public bool Enabled { get; set; } + /// Insertion orders for queued items, aligned with `items`. + [JsonPropertyName("itemOrders")] + public IList? ItemOrders { get; set; } - /// Current allow-all mode. - [JsonPropertyName("mode")] - public PermissionsAllowAllMode? Mode { get; set; } + /// User-facing pending items in FIFO order. + [JsonPropertyName("items")] + public IList Items { get => field ??= []; set; } + + /// Insertion orders for immediate steering messages, aligned with `steeringMessages`. + [JsonPropertyName("steeringMessageOrders")] + public IList? SteeringMessageOrders { get; set; } + + /// Immediate steering messages waiting for an active turn. + [JsonPropertyName("steeringMessages")] + public IList SteeringMessages { get => field ??= []; set; } } -/// No parameters. +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class PermissionsGetAllowAllRequest +internal sealed class SessionQueueSnapshotRequest { /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Indicates whether the operation succeeded. +/// Result of moving a queued item. [Experimental(Diagnostics.Experimental)] -public sealed class PermissionsModifyRulesResult +public sealed class QueueMoveItemResult { - /// Whether the operation succeeded. - [JsonPropertyName("success")] - public bool Success { get; set; } + /// True when the item changed position; false when it was already at the requested position. + [JsonPropertyName("changed")] + public bool Changed { get; set; } } -/// Scope and add/remove instructions for modifying session- or location-scoped permission rules. +/// Parameters for moving a queued item by stable id. [Experimental(Diagnostics.Experimental)] -internal sealed class PermissionsModifyRulesParams +internal sealed class QueueMoveItemRequest { - /// Rules to add to the scope. Applied before `remove`/`removeAll`. - [JsonPropertyName("add")] - public IList? Add { get; set; } - - /// Specific rules to remove from the scope. Ignored when `removeAll` is true. - [JsonPropertyName("remove")] - public IList? Remove { get; set; } - - /// When true, removes every rule currently in the scope (after any `add` is applied). Useful for clearing the location scope wholesale. - [JsonPropertyName("removeAll")] - public bool? RemoveAll { get; set; } - - /// Whether the change applies to ephemeral session-scoped rules (cleared at session end) or to location-scoped rules persisted via the location-permissions config file. - [JsonPropertyName("scope")] - public PermissionsModifyRulesScope Scope { get; set; } + /// Stable opaque queued-item id. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; + + /// Zero-based target position in the public visible queue. Values outside the queue clamp to an end. + [JsonPropertyName("toPosition")] + public long ToPosition { get; set; } } -/// Indicates whether the operation succeeded. +/// Result of inserting a queued message. [Experimental(Diagnostics.Experimental)] -public sealed class PermissionsSetRequiredResult +public sealed class QueueInsertAtResult { - /// Whether the operation succeeded. - [JsonPropertyName("success")] - public bool Success { get; set; } + /// Fresh stable opaque id assigned to the inserted item. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; } -/// Toggles whether permission prompts should be bridged into session events for this client. +/// Serializable message fields accepted by queue.insertAt. [Experimental(Diagnostics.Experimental)] -internal sealed class PermissionsSetRequiredRequest +public sealed class QueueInsertMessage { - /// Whether the client wants `permission.requested` events bridged from the session-owned permission service. CLI clients that render prompt UI set this to `true` for as long as their listener is mounted; headless callers leave it unset (the default is `false`). - [JsonPropertyName("required")] - public bool Required { get; set; } + /// Optional explicit agent mode. When omitted, the session's current mode is assigned. + [JsonPropertyName("agentMode")] + public SendAgentMode? AgentMode { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// Optional attachments for the message. + [JsonPropertyName("attachments")] + public IList? Attachments { get; set; } -/// Indicates whether the operation succeeded. -[Experimental(Diagnostics.Experimental)] -public sealed class PermissionsResetSessionApprovalsResult -{ - /// Whether the operation succeeded. - [JsonPropertyName("success")] - public bool Success { get; set; } + /// Whether the message is billable. + [JsonPropertyName("billable")] + public bool? Billable { get; set; } + + /// Accepted for internal SendOptions compatibility but ignored; delivery is derived from current session activity. + [JsonPropertyName("delivery")] + public string? Delivery { get; set; } + + /// Optional user-facing display text. + [JsonPropertyName("displayPrompt")] + public string? DisplayPrompt { get; set; } + + /// Accepted for SendOptions compatibility but ignored; inserted items always use queued delivery semantics. + [JsonPropertyName("mode")] + public SendMode? Mode { get; set; } + + /// Accepted for SendOptions compatibility but ignored; the requested public position controls placement. + [JsonPropertyName("prepend")] + public bool? Prepend { get; set; } + + /// The user message text. + [JsonPropertyName("prompt")] + public string Prompt { get; set; } = string.Empty; + + /// Per-turn request headers. + [JsonPropertyName("requestHeaders")] + public IDictionary? RequestHeaders { get; set; } + + /// Required tool name for the turn, when any. + [JsonPropertyName("requiredTool")] + public string? RequiredTool { get; set; } + + /// Optional provenance source. `system` is rejected: it would hide the inserted row from `pendingItems` and make it unaddressable while still executing, so inserted items must stay visible. + [JsonPropertyName("source")] + public string? Source { get; set; } + + /// Accepted for SendOptions compatibility but ignored; insertion scheduling is controlled by the queue drain state. + [JsonPropertyName("wait")] + public bool? Wait { get; set; } } -/// No parameters; clears all session-scoped tool permission approvals. +/// Parameters for inserting a queued message at a public visible position. [Experimental(Diagnostics.Experimental)] -internal sealed class PermissionsResetSessionApprovalsRequest +internal sealed class QueueInsertAtRequest { + /// Gets or sets the message value. + [JsonPropertyName("message")] + public QueueInsertMessage Message { get => field ??= new(); set; } + + /// Zero-based position in the public visible queue. Values outside the queue clamp to an end. + [JsonPropertyName("position")] + public long Position { get; set; } + /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Indicates whether the operation succeeded. +/// Result of removing a queued item. [Experimental(Diagnostics.Experimental)] -public sealed class PermissionsNotifyPromptShownResult +public sealed class QueueRemoveAtResult { - /// Whether the operation succeeded. - [JsonPropertyName("success")] - public bool Success { get; set; } + /// True when the addressed item was removed. + [JsonPropertyName("removed")] + public bool Removed { get; set; } } -/// Notification payload describing the permission prompt that the client just rendered. +/// Parameters for removing a queued item by stable id. [Experimental(Diagnostics.Experimental)] -internal sealed class PermissionPromptShownNotification +internal sealed class QueueRemoveAtRequest { - /// Human-readable description of the prompt the user is being asked to approve. Used by the runtime to fire the registered `permission_prompt` notification hook (e.g. terminal bell, desktop notification). - [JsonPropertyName("message")] - public string Message { get; set; } = string.Empty; + /// Gets or sets the id value. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Snapshot of the session's allow-listed directories and primary working directory. +/// Result of editing a queued message. [Experimental(Diagnostics.Experimental)] -public sealed class PermissionPathsList +public sealed class QueueUpdateTextResult { - /// All directories currently allowed for tool access on this session. - [JsonPropertyName("directories")] - public IList Directories { get => field ??= []; set; } - - /// The primary working directory for this session. - [JsonPropertyName("primary")] - public string Primary { get; set; } = string.Empty; + /// True when the stored text changed. + [JsonPropertyName("updated")] + public bool Updated { get; set; } } -/// No parameters; returns the session's allow-listed directories. +/// Parameters for editing a single queued message. [Experimental(Diagnostics.Experimental)] -internal sealed class PermissionsPathsListRequest +internal sealed class QueueUpdateTextRequest { + /// Gets or sets the displayPrompt value. + [JsonPropertyName("displayPrompt")] + public string? DisplayPrompt { get; set; } + + /// Gets or sets the id value. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; + + /// Gets or sets the prompt value. + [JsonPropertyName("prompt")] + public string Prompt { get; set; } = string.Empty; + /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Indicates whether the operation succeeded. +/// Result of duplicating a queued item. [Experimental(Diagnostics.Experimental)] -public sealed class PermissionsPathsAddResult +public sealed class QueueDuplicateAtResult { - /// Whether the operation succeeded. - [JsonPropertyName("success")] - public bool Success { get; set; } + /// Fresh stable opaque id assigned to the duplicate. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; } -/// Directory path to add to the session's allowed directories. +/// Parameters for duplicating a queued item. [Experimental(Diagnostics.Experimental)] -internal sealed class PermissionPathsAddParams +internal sealed class QueueDuplicateAtRequest { - /// Directory to add to the allow-list. The runtime resolves and validates the path before adding. - [JsonPropertyName("path")] - public string Path { get; set; } = string.Empty; + /// Gets or sets the id value. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Indicates whether the operation succeeded. -[Experimental(Diagnostics.Experimental)] -public sealed class PermissionsPathsUpdatePrimaryResult -{ - /// Whether the operation succeeded. - [JsonPropertyName("success")] - public bool Success { get; set; } -} - -/// Directory path to set as the session's new primary working directory. +/// Parameters for acquiring or releasing the queued-lane drain pause. Acquisition is exclusive and non-idempotent: `paused: true` against an already-paused session fails with `queue_already_paused`. The pause is never released automatically — it is not tied to the caller's lifetime, so a client that exits without sending `paused: false` leaves the lane frozen. Release is unowned: `paused: false` clears the pause for any caller, including one that never acquired it. [Experimental(Diagnostics.Experimental)] -internal sealed class PermissionPathsUpdatePrimaryParams +internal sealed class QueueSetDrainPausedRequest { - /// Directory to set as the new primary working directory for the session's permission policy. - [JsonPropertyName("path")] - public string Path { get; set; } = string.Empty; + /// Gets or sets the paused value. + [JsonPropertyName("paused")] + public bool Paused { get; set; } /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Indicates whether the supplied path is within the session's allowed directories. +/// Result of trying to steer a queued message into a live turn. [Experimental(Diagnostics.Experimental)] -public sealed class PermissionPathsAllowedCheckResult +public sealed class QueueSendNowResult { - /// Whether the path is within the session's allowed directories. - [JsonPropertyName("allowed")] - public bool Allowed { get; set; } + /// True when the item was accepted into the steering lane; false when no main turn was live. + [JsonPropertyName("steered")] + public bool Steered { get; set; } } -/// Path to evaluate against the session's allowed directories. +/// Parameters for steering a queued message into a live turn. [Experimental(Diagnostics.Experimental)] -internal sealed class PermissionPathsAllowedCheckParams +internal sealed class QueueSendNowRequest { - /// Path to check against the session's allowed directories. - [JsonPropertyName("path")] - public string Path { get; set; } = string.Empty; + /// Gets or sets the id value. + [JsonPropertyName("id")] + public string Id { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Indicates whether the supplied path is within the session's workspace directory. +/// Whether the native queue has pending work. [Experimental(Diagnostics.Experimental)] -public sealed class PermissionPathsWorkspaceCheckResult +internal sealed class QueueHasPendingResult { - /// Whether the path is within the session workspace directory. - [JsonPropertyName("allowed")] - public bool Allowed { get; set; } + /// True when queued or immediate native work is pending. + [JsonPropertyName("hasPending")] + public bool HasPending { get; set; } } -/// Path to evaluate against the session's workspace (primary) directory. +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class PermissionPathsWorkspaceCheckParams +internal sealed class SessionQueueHasPendingRequest { - /// Path to check against the session workspace directory. - [JsonPropertyName("path")] - public string Path { get; set; } = string.Empty; - /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Resolved location-permissions key and type. +/// Whether a deferred-idle drain should run. [Experimental(Diagnostics.Experimental)] -public sealed class PermissionLocationResolveResult +internal sealed class QueueBeginDeferredIdleDrainResult { - /// Location key used in the location-permissions store. - [JsonPropertyName("locationKey")] - public string LocationKey { get; set; } = string.Empty; - - /// Whether the location is a git repo or directory. - [JsonPropertyName("locationType")] - public PermissionLocationType LocationType { get; set; } + /// True when the host should run finishDeferredIdleDrain asynchronously. + [JsonPropertyName("shouldDrain")] + public bool ShouldDrain { get; set; } } -/// Working directory to resolve into a location-permissions key. +/// Inputs for starting a deferred-idle drain. [Experimental(Diagnostics.Experimental)] -internal sealed class PermissionLocationResolveParams +internal sealed class QueueBeginDeferredIdleDrainRequest { + /// Whether the host still has active background work. + [JsonPropertyName("activeBackgroundWork")] + public bool ActiveBackgroundWork { get; set; } + /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; - - /// Working directory whose permission location should be resolved. - [JsonPropertyName("workingDirectory")] - public string WorkingDirectory { get; set; } = string.Empty; } -/// Summary of persisted location permissions applied to the session. +/// Action selected by the native deferred-idle drain. [Experimental(Diagnostics.Experimental)] -public sealed class PermissionLocationApplyResult +internal sealed class QueueFinishDeferredIdleDrainResult { - /// Number of persisted allowed directories added to the live path manager. - [JsonPropertyName("appliedDirectoryCount")] - public long AppliedDirectoryCount { get; set; } - - /// Number of location-scoped rules added to the live permission service. - [JsonPropertyName("appliedRuleCount")] - public long AppliedRuleCount { get; set; } - - /// Location-scoped rules applied to the live permission service. - [JsonPropertyName("appliedRules")] - public IList AppliedRules { get => field ??= []; set; } + /// Whether the deferred idle was caused by an aborted foreground turn. + [JsonPropertyName("aborted")] + public bool Aborted { get; set; } - /// Whether a different location was applied since the previous apply call. - [JsonPropertyName("changed")] - public bool Changed { get; set; } + /// One of none, processQueue, or emitSessionIdle. + [JsonPropertyName("action")] + public string Action { get; set; } = string.Empty; +} - /// Location key used in the location-permissions store. - [JsonPropertyName("locationKey")] - public string LocationKey { get; set; } = string.Empty; +/// Inputs for completing a deferred-idle drain. +[Experimental(Diagnostics.Experimental)] +internal sealed class QueueFinishDeferredIdleDrainRequest +{ + /// Whether the host still has active background work. + [JsonPropertyName("activeBackgroundWork")] + public bool ActiveBackgroundWork { get; set; } - /// Whether the location is a git repo or directory. - [JsonPropertyName("locationType")] - public PermissionLocationType LocationType { get; set; } + /// Whether native queued work remains. + [JsonPropertyName("hasPending")] + public bool HasPending { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Working directory to load persisted location permissions for. +/// Inputs for marking session.idle deferred in native state. [Experimental(Diagnostics.Experimental)] -internal sealed class PermissionLocationApplyParams +internal sealed class QueueDeferSessionIdleRequest { + /// Whether the deferred idle was caused by an aborted foreground turn. + [JsonPropertyName("aborted")] + public bool Aborted { get; set; } + /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; - - /// Working directory whose persisted location permissions should be applied. - [JsonPropertyName("workingDirectory")] - public string WorkingDirectory { get; set; } = string.Empty; } -/// Indicates whether the operation succeeded. +/// Indicates whether a user-facing pending item was removed. [Experimental(Diagnostics.Experimental)] -public sealed class PermissionsLocationsAddToolApprovalResult +public sealed class QueueRemoveMostRecentResult { - /// Whether the operation succeeded. - [JsonPropertyName("success")] - public bool Success { get; set; } + /// True if a user-facing pending item was removed (LIFO across both queues); false when no removable items remained. + [JsonPropertyName("removed")] + public bool Removed { get; set; } } -/// Tool approval to persist and apply. -/// Polymorphic base type discriminated by kind. +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -[JsonPolymorphic( - TypeDiscriminatorPropertyName = "kind", - UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] -[JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsCommands), "commands")] -[JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsRead), "read")] -[JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsWrite), "write")] -[JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsMcp), "mcp")] -[JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsMcpSampling), "mcp-sampling")] -[JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsMemory), "memory")] -[JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsCustomTool), "custom-tool")] -[JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsExtensionManagement), "extension-management")] -[JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess), "extension-permission-access")] -public partial class PermissionsLocationsAddToolApprovalDetails +internal sealed class SessionQueueRemoveMostRecentRequest { - /// The type discriminator. - [JsonPropertyName("kind")] - public virtual string Kind { get; set; } = string.Empty; + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } +/// Identifies the target session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionQueueClearRequest +{ + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} -/// Location-persisted tool approval details for specific command identifiers. -/// The commands variant of . +/// Internal filter for consuming queued system notifications. [Experimental(Diagnostics.Experimental)] -public partial class PermissionsLocationsAddToolApprovalDetailsCommands : PermissionsLocationsAddToolApprovalDetails +internal sealed class QueueConsumeSystemNotificationsRequest { - /// - [JsonIgnore] - public override string Kind => "commands"; + /// Opaque runtime-owned filter object. + [JsonPropertyName("filter")] + public JsonElement Filter { get; set; } - /// Command identifiers covered by this approval. - [JsonPropertyName("commandIdentifiers")] - public required IList CommandIdentifiers { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Location-persisted tool approval details for read-only filesystem operations. -/// The read variant of . +/// Result of enqueueing the resume-pending wake item. [Experimental(Diagnostics.Experimental)] -public partial class PermissionsLocationsAddToolApprovalDetailsRead : PermissionsLocationsAddToolApprovalDetails +internal sealed class QueueEnqueueResumePendingResult { - /// - [JsonIgnore] - public override string Kind => "read"; + /// True when a wake item was newly queued. + [JsonPropertyName("queued")] + public bool Queued { get; set; } } -/// Location-persisted tool approval details for filesystem write operations. -/// The write variant of . +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -public partial class PermissionsLocationsAddToolApprovalDetailsWrite : PermissionsLocationsAddToolApprovalDetails +internal sealed class SessionQueueEnqueueResumePendingRequest { - /// - [JsonIgnore] - public override string Kind => "write"; + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Location-persisted tool approval details for an MCP server tool, or all tools when `toolName` is null. -/// The mcp variant of . +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -public partial class PermissionsLocationsAddToolApprovalDetailsMcp : PermissionsLocationsAddToolApprovalDetails +internal sealed class SessionQueueProcessRequest { - /// - [JsonIgnore] - public override string Kind => "mcp"; + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// MCP server name. - [JsonPropertyName("serverName")] - public required string ServerName { get; set; } +/// Batch of session events returned by a read, with cursor and continuation metadata. +[Experimental(Diagnostics.Experimental)] +public sealed class EventsReadResult +{ + /// Opaque cursor for the next read. Pass back unchanged in the next read.cursor to continue from where this read left off. Always present, even when no events were returned. + [JsonPropertyName("cursor")] + public string Cursor { get; set; } = string.Empty; - /// MCP tool name, or null to cover every tool on the server. - [JsonPropertyName("toolName")] - public string? ToolName { get; set; } + /// Cursor status: 'ok' means the cursor was applied successfully; 'expired' means the cursor referred to an event that no longer exists in history (e.g. truncated or compacted away) and the read started from the beginning of the remaining history. + [JsonPropertyName("cursorStatus")] + public EventsCursorStatus CursorStatus { get; set; } + + /// Session events for this batch, merged into a single stream in creation order: durable (persisted) events and ephemeral events interleave exactly as they were emitted. Set `includeEphemeral: false` to receive only durable events. Ephemeral events are never replayable once pruned from the in-memory ring, so a consumer that needs them should keep reading with a non-zero `waitMs`. + [JsonPropertyName("events")] + public IList Events { get => field ??= []; set; } + + /// True when the read returned `max` events and more events are available immediately. When false, the next read with a non-zero `waitMs` will block until a new event arrives or the wait expires. + [JsonPropertyName("hasMore")] + public bool HasMore { get; set; } } -/// Location-persisted tool approval details for MCP sampling requests from a server. -/// The mcp-sampling variant of . +/// Cursor, batch size, and optional long-poll/filter parameters for reading session events. [Experimental(Diagnostics.Experimental)] -public partial class PermissionsLocationsAddToolApprovalDetailsMcpSampling : PermissionsLocationsAddToolApprovalDetails +internal sealed class EventLogReadRequest { - /// - [JsonIgnore] - public override string Kind => "mcp-sampling"; + /// 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. + [JsonPropertyName("agentScope")] + public EventsAgentScope? AgentScope { get; set; } - /// MCP server name. - [JsonPropertyName("serverName")] - public required string ServerName { get; set; } + /// Opaque cursor returned by a previous read. Omit on the first call to start from the beginning of the session's persisted history. + [JsonPropertyName("cursor")] + public string? Cursor { get; set; } + + /// When false, skip ephemeral events entirely and return only durable (persisted) events. History-backfill callers that discard ephemerals anyway should set this so the read is bounded by the durable log length instead of racing the ephemeral ring on a busy session. Defaults to true (ephemerals are interleaved with durable events in creation order). + [JsonPropertyName("includeEphemeral")] + public bool? IncludeEphemeral { get; set; } + + /// Maximum number of events to return in this batch (1–1000, default 200). + [JsonPropertyName("max")] + public long? Max { get; set; } + + /// Target session identifier. + [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. + [JsonPropertyName("types")] + 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))] + [JsonPropertyName("waitMs")] + public TimeSpan? Wait { get; set; } } -/// Location-persisted tool approval details for writes to long-term memory. -/// The memory variant of . +/// Snapshot of the current tail cursor without returning any events. Use this when a consumer wants to subscribe to live events going forward without first paginating through the entire persisted history (which would happen if `read` were called without a cursor on a long-lived session). [Experimental(Diagnostics.Experimental)] -public partial class PermissionsLocationsAddToolApprovalDetailsMemory : PermissionsLocationsAddToolApprovalDetails +public sealed class EventLogTailResult { - /// - [JsonIgnore] - public override string Kind => "memory"; + /// Opaque cursor pointing at the current tail of the session's persisted-events history. Pass back to `read` to receive only events that arrive AFTER this snapshot. When the session has no events, this returns the same sentinel as an unset cursor (i.e. equivalent to omitting the cursor on a first read). + [JsonPropertyName("cursor")] + public string Cursor { get; set; } = string.Empty; } -/// Location-persisted tool approval details for a custom tool, keyed by tool name. -/// The custom-tool variant of . +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -public partial class PermissionsLocationsAddToolApprovalDetailsCustomTool : PermissionsLocationsAddToolApprovalDetails +internal sealed class SessionEventLogTailRequest { - /// - [JsonIgnore] - public override string Kind => "custom-tool"; - - /// Custom tool name. - [JsonPropertyName("toolName")] - public required string ToolName { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Location-persisted tool approval details for extension-management operations, optionally narrowed by operation. -/// The extension-management variant of . +/// Opaque handle representing an event-type interest registration. [Experimental(Diagnostics.Experimental)] -public partial class PermissionsLocationsAddToolApprovalDetailsExtensionManagement : PermissionsLocationsAddToolApprovalDetails +public sealed class RegisterEventInterestResult { - /// - [JsonIgnore] - public override string Kind => "extension-management"; - - /// Optional operation identifier; when omitted, the approval covers all extension management operations. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("operation")] - public string? Operation { get; set; } + /// Opaque handle for this registration. Pass to releaseInterest to release. Each call to registerInterest produces a fresh handle, even when the same eventType is registered multiple times. + [JsonPropertyName("handle")] + public string Handle { get; set; } = string.Empty; } -/// Location-persisted tool approval details for an extension's permission-gated capability access, keyed by extension name. -/// The extension-permission-access variant of . +/// Event type to register consumer interest for, used by runtime gating logic. [Experimental(Diagnostics.Experimental)] -public partial class PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess : PermissionsLocationsAddToolApprovalDetails +internal sealed class RegisterEventInterestParams { - /// - [JsonIgnore] - public override string Kind => "extension-permission-access"; + /// The event type the consumer wants the runtime to treat as 'observed' for behavior-switching gating. Some runtime code paths inspect whether any consumer is interested in a specific event type and choose a different implementation accordingly (e.g. `mcp.oauth_required`: when interest is registered the runtime delegates interactive OAuth token acquisition to the consumer via `mcp.oauth_required` events; when no interest is registered the runtime still attempts non-interactive reconnect from cached or refreshable tokens, and only marks the server `needs-auth` if usable credentials are unavailable — it does not open a browser or start interactive OAuth without a consumer). SDK clients that long-poll events do NOT automatically appear as listeners to these gating checks — they must explicitly call `registerInterest` for each event type they want the runtime to count as having a consumer. Multiple registrations for the same event type from the same or different consumers are tracked independently and must each be released. See: `mcp.oauth_required`, `sampling.requested`, `auto_mode_switch.requested`, `session_limits_exhausted.requested`, `user_input.requested`, `elicitation.requested`, `command.queued`, `exit_plan_mode.requested`. + [JsonPropertyName("eventType")] + public string EventType { get; set; } = string.Empty; - /// Extension name. - [JsonPropertyName("extensionName")] - public required string ExtensionName { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Location-scoped tool approval to persist. +/// Indicates whether the operation succeeded. [Experimental(Diagnostics.Experimental)] -internal sealed class PermissionLocationAddToolApprovalParams +public sealed class EventLogReleaseInterestResult { - /// Tool approval to persist and apply. - [JsonPropertyName("approval")] - public PermissionsLocationsAddToolApprovalDetails Approval { get => field ??= new(); set; } + /// Whether the operation succeeded. + [JsonPropertyName("success")] + public bool Success { get; set; } +} - /// Location key (git root or cwd) to persist the approval to. - [JsonPropertyName("locationKey")] - public string LocationKey { get; set; } = string.Empty; +/// Opaque handle previously returned by `registerInterest` to release. +[Experimental(Diagnostics.Experimental)] +internal sealed class ReleaseEventInterestParams +{ + /// Handle returned by a previous `registerInterest` call. Idempotent: releasing an unknown or already-released handle is a no-op (returns success). When the last outstanding handle for an event type is released, the runtime reverts to its 'no consumer' code path for that event type. + [JsonPropertyName("handle")] + public string Handle { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Folder trust check result. +/// Aggregated code change metrics. [Experimental(Diagnostics.Experimental)] -public sealed class FolderTrustCheckResult +public sealed class UsageMetricsCodeChanges { - /// Whether the folder is trusted. - [JsonPropertyName("trusted")] - public bool Trusted { get; set; } + /// Distinct file paths modified during the session. + [JsonPropertyName("filesModified")] + public IList FilesModified { get => field ??= []; set; } + + /// Number of distinct files modified. + [JsonPropertyName("filesModifiedCount")] + public long FilesModifiedCount { get; set; } + + /// Total lines of code added. + [JsonPropertyName("linesAdded")] + public long LinesAdded { get; set; } + + /// Total lines of code removed. + [JsonPropertyName("linesRemoved")] + public long LinesRemoved { get; set; } } -/// Folder path to check for trust. +/// Request count and cost metrics for this model. [Experimental(Diagnostics.Experimental)] -internal sealed class FolderTrustCheckParams +public sealed class UsageMetricsModelMetricRequests { - /// Folder path to check. - [JsonPropertyName("path")] - public string Path { get; set; } = string.Empty; + /// User-initiated premium request cost (with multiplier applied). + [JsonPropertyName("cost")] + public double Cost { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Number of API requests made with this model. + [JsonPropertyName("count")] + public long Count { get; set; } } -/// Indicates whether the operation succeeded. +/// Per-model token-detail entry containing the accumulated token count for one token type. [Experimental(Diagnostics.Experimental)] -public sealed class PermissionsFolderTrustAddTrustedResult +public sealed class UsageMetricsModelMetricTokenDetail { - /// Whether the operation succeeded. - [JsonPropertyName("success")] - public bool Success { get; set; } + /// Accumulated token count for this token type. + [JsonPropertyName("tokenCount")] + public long TokenCount { get; set; } } -/// Folder path to add to trusted folders. +/// Token usage metrics for this model. [Experimental(Diagnostics.Experimental)] -internal sealed class FolderTrustAddParams +public sealed class UsageMetricsModelMetricUsage { - /// Folder path to mark as trusted. - [JsonPropertyName("path")] - public string Path { get; set; } = string.Empty; + /// Total tokens read from prompt cache. + [JsonPropertyName("cacheReadTokens")] + public long CacheReadTokens { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// Total tokens written to prompt cache. + [JsonPropertyName("cacheWriteTokens")] + public long CacheWriteTokens { get; set; } -/// Indicates whether the operation succeeded. -[Experimental(Diagnostics.Experimental)] -public sealed class PermissionsUrlsSetUnrestrictedModeResult -{ - /// Whether the operation succeeded. - [JsonPropertyName("success")] - public bool Success { get; set; } -} + /// Total input tokens consumed. + [JsonPropertyName("inputTokens")] + public long InputTokens { get; set; } -/// Whether the URL-permission policy should run in unrestricted mode. -[Experimental(Diagnostics.Experimental)] -internal sealed class PermissionUrlsSetUnrestrictedModeParams -{ - /// Whether to allow access to all URLs without prompting. Toggles the runtime's URL-permission policy in place. - [JsonPropertyName("enabled")] - public bool Enabled { get; set; } + /// Total output tokens produced. + [JsonPropertyName("outputTokens")] + public long OutputTokens { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Total output tokens used for reasoning. + [JsonPropertyName("reasoningTokens")] + public long? ReasoningTokens { get; set; } } -/// The repository the remote session targets. +/// Per-model usage metrics, including request counts/costs, token usage, nano-AI units, and per-token-type details. [Experimental(Diagnostics.Experimental)] -public sealed class MetadataSnapshotRemoteMetadataRepository +public sealed class UsageMetricsModelMetric { - /// The branch the remote session is operating on. - [JsonPropertyName("branch")] - public string Branch { get; set; } = string.Empty; + /// Latest known prompt-cache expiration for this model. A timestamp in the past indicates that the observed cache has expired. + [JsonPropertyName("cacheExpiresAt")] + public DateTimeOffset? CacheExpiresAt { get; set; } - /// The GitHub repository name (without owner). - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; + /// Request count and cost metrics for this model. + [JsonPropertyName("requests")] + public UsageMetricsModelMetricRequests Requests { get => field ??= new(); set; } - /// The GitHub owner (user or organization) of the target repository. - [JsonPropertyName("owner")] - public string Owner { get; set; } = string.Empty; + /// Token count details per type. + [JsonPropertyName("tokenDetails")] + public IDictionary? TokenDetails { get; set; } + + /// Accumulated nano-AI units cost for this model. + [JsonPropertyName("totalNanoAiu")] + public double? TotalNanoAiu { get; set; } + + /// Token usage metrics for this model. + [JsonPropertyName("usage")] + public UsageMetricsModelMetricUsage Usage { get => field ??= new(); set; } } -/// Remote-session-specific metadata. Populated only when `isRemote` is true. Fields are immutable for the lifetime of the session. +/// Session-wide token-detail entry containing the accumulated token count for one token type. [Experimental(Diagnostics.Experimental)] -public sealed class MetadataSnapshotRemoteMetadata +public sealed class UsageMetricsTokenDetail { - /// The pull request number the remote session is associated with, if any. - [JsonPropertyName("pullRequestNumber")] - public long? PullRequestNumber { get; set; } + /// Accumulated token count for this token type. + [JsonPropertyName("tokenCount")] + public long TokenCount { get; set; } +} - /// The repository the remote session targets. - [JsonPropertyName("repository")] - public MetadataSnapshotRemoteMetadataRepository Repository { get => field ??= new(); set; } +/// Accumulated session usage metrics, including premium request cost, token counts, model breakdown, and code-change totals. +[Experimental(Diagnostics.Experimental)] +public sealed class UsageGetMetricsResult +{ + /// Aggregated code change metrics. + [JsonPropertyName("codeChanges")] + public UsageMetricsCodeChanges CodeChanges { get => field ??= new(); set; } - /// The original resource identifier (task ID or PR node ID), preserved across event-replay reconstructions. Falls back to `sessionId` when absent. - [JsonPropertyName("resourceId")] - public string? ResourceId { get; set; } + /// Currently active model identifier. + [JsonPropertyName("currentModel")] + public string? CurrentModel { get; set; } - /// Whether the remote task originated from Copilot Coding Agent (cca) or a CLI `--remote` invocation. - [JsonPropertyName("taskType")] - public MetadataSnapshotRemoteMetadataTaskType? TaskType { get; set; } -} + /// Input tokens from the most recent main-agent API call. + [JsonPropertyName("lastCallInputTokens")] + public long LastCallInputTokens { get; set; } -/// Public-facing projection of workspace metadata for SDK / TUI consumers. -public sealed class SessionMetadataSnapshotWorkspace -{ - /// Branch checked out at session start, if any. - [JsonPropertyName("branch")] - public string? Branch { get; set; } + /// Output tokens from the most recent main-agent API call. + [JsonPropertyName("lastCallOutputTokens")] + public long LastCallOutputTokens { get; set; } - /// ISO 8601 timestamp when the workspace was created. - [JsonPropertyName("created_at")] - public DateTimeOffset? CreatedAt { get; set; } + /// Per-model token and request metrics, keyed by model identifier. + [JsonPropertyName("modelMetrics")] + public IDictionary ModelMetrics { get => field ??= new Dictionary(); set; } - /// Current working directory at session start. - [JsonPropertyName("cwd")] - public string? Cwd { get; set; } + /// ISO 8601 timestamp when the session started. + [JsonPropertyName("sessionStartTime")] + public DateTimeOffset SessionStartTime { get; set; } - /// Resolved git root for cwd, if any. - [JsonPropertyName("git_root")] - public string? GitRoot { get; set; } + /// Session-wide per-token-type accumulated token counts. + [JsonPropertyName("tokenDetails")] + public IDictionary? TokenDetails { get; set; } - /// Repository host type, if known. - [JsonPropertyName("host_type")] - public WorkspaceSummaryHostType? HostType { get; set; } + /// Total time spent in model API calls (milliseconds). + [JsonConverter(typeof(MillisecondsTimeSpanConverter))] + [JsonPropertyName("totalApiDurationMs")] + public TimeSpan TotalApiDuration { get; set; } - /// Workspace identifier (1:1 with sessionId). - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] - [MinLength(1)] - [JsonPropertyName("id")] - public string Id { get; set; } = string.Empty; + /// Session-wide accumulated nano-AI units cost. + [JsonPropertyName("totalNanoAiu")] + public double? TotalNanoAiu { get; set; } - /// Display name for the session, if set. - [JsonPropertyName("name")] - public string? Name { get; set; } + /// Total user-initiated premium request cost across all models (may be fractional due to multipliers). + [JsonPropertyName("totalPremiumRequestCost")] + public double TotalPremiumRequestCost { get; set; } - /// Repository identifier in 'owner/repo' or 'org/project/repo' format, if any. - [JsonPropertyName("repository")] - public string? Repository { get; set; } + /// Raw count of user-initiated API requests. + [JsonPropertyName("totalUserRequests")] + public long TotalUserRequests { get; set; } +} - /// ISO 8601 timestamp when the workspace was last updated. - [JsonPropertyName("updated_at")] - public DateTimeOffset? UpdatedAt { get; set; } +/// Identifies the target session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionUsageGetMetricsRequest +{ + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// Whether the display name was explicitly set by the user. - [JsonPropertyName("user_named")] - public bool? UserNamed { get; set; } +/// Prediction result. Available results include prediction details; unavailable results include an explicit reason. +/// Polymorphic base type discriminated by kind. +[Experimental(Diagnostics.Experimental)] +[JsonPolymorphic( + TypeDiscriminatorPropertyName = "kind", + UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] +[JsonDerivedType(typeof(SessionLimitPredictionResultAvailable), "available")] +[JsonDerivedType(typeof(SessionLimitPredictionResultUnavailable), "unavailable")] +public partial class SessionLimitPredictionResult +{ + /// The type discriminator. + [JsonPropertyName("kind")] + public virtual string Kind { get; set; } = string.Empty; } -/// Point-in-time snapshot of slow-changing session identifier and state fields. + +/// Baseline data provenance for a prediction. [Experimental(Diagnostics.Experimental)] -public sealed class SessionMetadataSnapshot +public sealed class SessionLimitPredictionBaselineData { - /// True when the session was detected to be in use by another process at construction time. Local consumers may surface a confirmation prompt before fully attaching. Always false for new sessions. - [JsonPropertyName("alreadyInUse")] - public bool AlreadyInUse { get; set; } + /// End of the baseline data slice. + [JsonPropertyName("windowEnd")] + public string WindowEnd { get; set; } = string.Empty; - /// Runtime client name associated with the session (telemetry identifier). - [JsonPropertyName("clientName")] - public string? ClientName { get; set; } + /// Start of the baseline data slice. + [JsonPropertyName("windowStart")] + public string WindowStart { get; set; } = string.Empty; +} - /// The current agent mode for this session (e.g., 'interactive', 'plan', 'autopilot'). - [JsonPropertyName("currentMode")] - public MetadataSnapshotCurrentMode CurrentMode { get; set; } +/// Semantic usage tier and its AI-credit cap. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionLimitPredictionTierOption +{ + /// AI-credit cap for this tier. + [JsonPropertyName("cap")] + public double Cap { get; set; } - /// User-provided name supplied at session construction (via `--name`), if any. Immutable after construction. - [JsonPropertyName("initialName")] - public string? InitialName { get; set; } + /// Gets or sets the tier value. + [JsonPropertyName("tier")] + public SessionLimitPredictionTier Tier { get; set; } +} - /// Whether this is a remote session (i.e., one whose runtime executes elsewhere and is steered through this process). - [JsonPropertyName("isRemote")] - public bool IsRemote { get; set; } +/// Explainable AI-credit session-limit prediction. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionLimitPredictionDetails +{ + /// Baseline data provenance. + [JsonPropertyName("baselineData")] + public SessionLimitPredictionBaselineData BaselineData { get => field ??= new(); set; } - /// ISO 8601 timestamp of when the session's persisted state was last modified on disk. For new sessions, equals startTime. For resumed sessions, reflects the previous modification time at construction. - [JsonPropertyName("modifiedTime")] - public DateTimeOffset ModifiedTime { get; set; } + /// Client population used for the prediction. + [JsonPropertyName("clientType")] + public SessionLimitPredictionClientType ClientType { get; set; } - /// Remote-session-specific metadata. Populated only when `isRemote` is true. Fields are immutable for the lifetime of the session. - [JsonPropertyName("remoteMetadata")] - public MetadataSnapshotRemoteMetadata? RemoteMetadata { get; set; } + /// Resolved model family when known. + [JsonPropertyName("family")] + public string? Family { get; set; } - /// Currently selected model identifier, if any. - [JsonPropertyName("selectedModel")] - public string? SelectedModel { get; set; } + /// Model identifier used for lookup. + [JsonPropertyName("modelId")] + public string ModelId { get; set; } = string.Empty; - /// The unique identifier of the session. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Recommended maximum AI credits for this session. + [JsonPropertyName("recommendedCap")] + public double RecommendedCap { get; set; } - /// Current session limits, or null when no limits are active. - [JsonPropertyName("sessionLimits")] - public SessionLimitsConfig? SessionLimits { get; set; } + /// Tier chosen as the recommended cap. + [JsonPropertyName("recommendedTier")] + public SessionLimitPredictionTier RecommendedTier { get; set; } - /// ISO 8601 timestamp of when the session started. - [JsonPropertyName("startTime")] - public DateTimeOffset StartTime { get; set; } + /// Baseline fallback level used to create the prediction. + [JsonPropertyName("source")] + public SessionLimitPredictionSource Source { get; set; } - /// Short human-readable summary of the session, if known. Omitted when no summary has been generated. - [JsonPropertyName("summary")] - public string? Summary { get; set; } + /// Key matched at the source level, such as a model id, family id, or `global`. + [JsonPropertyName("sourceKey")] + public string SourceKey { get; set; } = string.Empty; - /// Absolute path to the session's current working directory. - [JsonPropertyName("workingDirectory")] - public string WorkingDirectory { get; set; } = string.Empty; + /// Ordered usage tiers and their AI-credit caps. + [JsonPropertyName("tiers")] + public IList Tiers { get => field ??= []; set; } +} - /// 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). - [JsonPropertyName("workspace")] - public SessionMetadataSnapshotWorkspace? Workspace { get; set; } +/// The available variant of . +[Experimental(Diagnostics.Experimental)] +public partial class SessionLimitPredictionResultAvailable : SessionLimitPredictionResult +{ + /// + [JsonIgnore] + public override string Kind => "available"; - /// Absolute path to the session's workspace directory on disk, or null if the session has no associated workspace. - [JsonPropertyName("workspacePath")] - public string? WorkspacePath { get; set; } + /// Predicted session limit details. + [JsonPropertyName("prediction")] + public required SessionLimitPredictionDetails Prediction { get; set; } } -/// Identifies the target session. +/// The unavailable variant of . [Experimental(Diagnostics.Experimental)] -internal sealed class SessionMetadataSnapshotRequest +public partial class SessionLimitPredictionResultUnavailable : SessionLimitPredictionResult { - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// + [JsonIgnore] + public override string Kind => "unavailable"; + + /// Reason no prediction is available. + [JsonPropertyName("reason")] + public required SessionLimitPredictionUnavailableReason Reason { get; set; } } -/// Indicates whether the local session is currently processing a turn or background continuation. +/// RPC data type for SessionLimitPredictionPredict operations. [Experimental(Diagnostics.Experimental)] -public sealed class MetadataIsProcessingResult +public sealed class SessionLimitPredictionPredictRequest { - /// Whether the session is currently processing user/agent messages. False for non-local sessions (which don't run a local agentic loop). Reflects an in-flight turn or background continuation. - [JsonPropertyName("processing")] - public bool Processing { get; set; } + /// Client type to size for. Defaults to `cli-interactive`. + [JsonPropertyName("clientType")] + public SessionLimitPredictionClientType? ClientType { get; set; } + + /// Optional model identifier override. If omitted, the session's current model is used. + [JsonPropertyName("modelId")] + public string? ModelId { get; set; } } -/// Identifies the target session. +/// RPC data type for SessionLimitPredictionPredictRequestWithSession operations. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionMetadataIsProcessingRequest +internal sealed class SessionLimitPredictionPredictRequestWithSession { + /// Client type to size for. Defaults to `cli-interactive`. + [JsonPropertyName("clientType")] + public SessionLimitPredictionClientType? ClientType { get; set; } + + /// Optional model identifier override. If omitted, the session's current model is used. + [JsonPropertyName("modelId")] + public string? ModelId { get; set; } + /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Current activity flags for the session. +/// GitHub URL for the session and a flag indicating whether remote steering is enabled. [Experimental(Diagnostics.Experimental)] -public sealed class SessionActivity +public sealed class RemoteEnableResult { - /// Whether an in-flight operation can currently be aborted. - [JsonPropertyName("abortable")] - public bool Abortable { get; set; } + /// Whether remote steering is enabled. + [JsonPropertyName("remoteSteerable")] + public bool RemoteSteerable { get; set; } - /// Whether the session currently has active work, including running turns or tasks. - [JsonPropertyName("hasActiveWork")] - public bool HasActiveWork { get; set; } + /// GitHub frontend URL for this session. + [Url] + [StringSyntax(StringSyntaxAttribute.Uri)] + [JsonPropertyName("url")] + public string? Url { get; set; } } -/// Identifies the target session. +/// Optional remote session mode ("off", "export", or "on"); defaults to enabling both export and remote steering. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionMetadataActivityRequest +internal sealed class RemoteEnableRequest { + /// Per-session remote mode. "off" disables remote, "export" exports session events to GitHub without enabling remote steering, "on" enables both export and remote steering. + [JsonPropertyName("mode")] + public RemoteSessionMode? Mode { get; set; } + /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Token-usage breakdown for the session's current context window. -public sealed class MetadataContextInfoResultContextInfo +/// Identifies the target session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionRemoteDisableRequest { - /// Output reserve plus tokens after the buffer-exhaustion blocking threshold (default 95%). - [JsonPropertyName("bufferTokens")] - public long BufferTokens { get; set; } - - /// Token count at which background compaction starts (configurable percentage of promptTokenLimit). - [JsonPropertyName("compactionThreshold")] - public long CompactionThreshold { get; set; } - - /// Tokens consumed by user/assistant/tool messages. - [JsonPropertyName("conversationTokens")] - public long ConversationTokens { get; set; } - - /// Prompt token limit plus the model's full output token limit. - [JsonPropertyName("limit")] - public long Limit { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// Tokens consumed by MCP tool definitions (subset of toolDefinitionsTokens, excludes deferred tools). - [JsonPropertyName("mcpToolsTokens")] - public long McpToolsTokens { get; set; } +/// Persist a steerability change as a `session.remote_steerable_changed` event. Used by the host (CLI / SDK consumer) when it has just finished enabling or disabling steering on a remote exporter that the runtime does not directly own. +[Experimental(Diagnostics.Experimental)] +public sealed class RemoteNotifySteerableChangedResult +{ +} - /// The model used for token counting. - [JsonPropertyName("modelName")] - public string ModelName { get; set; } = string.Empty; +/// New remote-steerability state to persist as a `session.remote_steerable_changed` event. +[Experimental(Diagnostics.Experimental)] +internal sealed class RemoteNotifySteerableChangedRequest +{ + /// Whether the session now supports remote steering via GitHub. The runtime persists this as a `session.remote_steerable_changed` event so resume/replay sees the up-to-date capability. + [JsonPropertyName("remoteSteerable")] + public bool RemoteSteerable { get; set; } - /// Maximum prompt tokens allowed by the model (or DEFAULT_TOKEN_LIMIT if unspecified). - [JsonPropertyName("promptTokenLimit")] - public long PromptTokenLimit { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// Tokens consumed by the system prompt. - [JsonPropertyName("systemTokens")] - public long SystemTokens { get; set; } +/// Current sharing status and shareable GitHub URL for a session. +[Experimental(Diagnostics.Experimental)] +public sealed class VisibilityGetResult +{ + /// Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. + [Url] + [StringSyntax(StringSyntaxAttribute.Uri)] + [JsonPropertyName("shareUrl")] + public string? ShareUrl { get; set; } - /// Tokens consumed by tool definitions sent to the model (excludes deferred tools). - [JsonPropertyName("toolDefinitionsTokens")] - public long ToolDefinitionsTokens { get; set; } + /// Current sharing status. Absent when the session is not synced or the status could not be retrieved (e.g. the user is not authenticated). + [JsonPropertyName("status")] + public SessionVisibilityStatus? Status { get; set; } - /// Sum of system, conversation and tool-definition tokens. - [JsonPropertyName("totalTokens")] - public long TotalTokens { get; set; } + /// Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the session cannot be shared and `status`/`shareUrl` are absent. + [JsonPropertyName("synced")] + public bool Synced { get; set; } } -/// Token breakdown for the session's current context window, or null if uninitialized. +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -public sealed class MetadataContextInfoResult +internal sealed class SessionVisibilityGetRequest { - /// Token breakdown for the current context window, or null if the session has not yet been initialized (no system prompt or tool metadata cached). - [JsonPropertyName("contextInfo")] - public MetadataContextInfoResultContextInfo? ContextInfo { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Model identifier and token limits used to compute the context-info breakdown. +/// Effective sharing status and shareable GitHub URL after updating session visibility. [Experimental(Diagnostics.Experimental)] -internal sealed class MetadataContextInfoRequest +public sealed class VisibilitySetResult { - /// Maximum output tokens allowed by the target model. Pass 0 if unknown. - [JsonPropertyName("outputTokenLimit")] - public long OutputTokenLimit { get; set; } + /// Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. + [Url] + [StringSyntax(StringSyntaxAttribute.Uri)] + [JsonPropertyName("shareUrl")] + public string? ShareUrl { get; set; } - /// Maximum prompt tokens allowed by the target model. Pass 0 to use the runtime default. - [JsonPropertyName("promptTokenLimit")] - public long PromptTokenLimit { get; set; } + /// Effective sharing status after the update. May differ from the requested status for task types that are already visible to repository readers by default. Absent when the update could not be applied (e.g. the session is not synced or the user is not authenticated). + [JsonPropertyName("status")] + public SessionVisibilityStatus? Status { get; set; } - /// Model identifier used for tokenization. Omit to use the session default. Used both for token counting and to compute display values. - [JsonPropertyName("selectedModel")] - public string? SelectedModel { get; set; } + /// Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the visibility change could not be applied and `status`/`shareUrl` are absent. + [JsonPropertyName("synced")] + public bool Synced { get; set; } +} +/// Desired sharing status for the session. +[Experimental(Diagnostics.Experimental)] +internal sealed class VisibilitySetRequest +{ /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; -} -/// Successful compaction history for the session. -public sealed class MetadataContextAttributionResultContextAttributionCompactions -{ - /// Number of successful compactions in this session. - [JsonPropertyName("count")] - public long Count { get; set; } + /// Sharing status to apply. "repo" makes the session visible to repository readers; "unshared" restricts it to the creator and collaborators. + [JsonPropertyName("status")] + public SessionVisibilityStatus Status { get; set; } } -/// RPC data type for MetadataContextAttributionResultContextAttributionEntry operations. -public sealed class MetadataContextAttributionResultContextAttributionEntry +/// Scheduled prompt entry with ID, timing (`intervalMs`, `cron`, or `at`), prompt text, recurrence, and next run time. +[Experimental(Diagnostics.Experimental)] +public sealed class ScheduleEntry { - /// Supplementary per-entry metadata (e.g. `messageCount`, `role`, `evictable`, `pluginSource`). Values are stringified; parse as needed and ignore unrecognized keys. - [JsonPropertyName("attributes")] - public IDictionary? Attributes { get; set; } + /// Absolute fire time (epoch milliseconds) for a one-shot calendar schedule. + [JsonPropertyName("at")] + public long? At { get; set; } - /// Identifier for this entry, formed by joining its `kind` and source name (e.g. `tool:bash`, `skill:tmux`, `toolDefinition:bash`); unique within the snapshot. Use it to match the same entry across snapshots, to correlate with other APIs (skill/agent/MCP registries), and as the `parentId` target for nesting. Distinct from the human-facing `label`. - [JsonPropertyName("id")] - public string Id { get; set; } = string.Empty; + /// 5-field cron expression for a recurring calendar schedule, evaluated in `tz`. + [JsonPropertyName("cron")] + public string? Cron { get; set; } - /// Source category for this entry. Not a closed set — tolerate unknown values. Known values today: `skill`, `subagent`, `mcpServer`, `tool`, `system`, `toolDefinition`, `plugin`. - [JsonPropertyName("kind")] - public string Kind { get; set; } = string.Empty; + /// Display-only label for the prompt as shown in the UI (e.g. `/skill-name` for a skill-invocation schedule). The actual enqueued prompt is `prompt`. + [JsonPropertyName("displayPrompt")] + public string? DisplayPrompt { get; set; } - /// Human-readable display label, e.g. `bash` or `skill: tmux`. Presentation-only; may be localized/reformatted without notice — do not key off it. - [JsonPropertyName("label")] - public string Label { get; set; } = string.Empty; + /// Sequential id assigned by the runtime within the session. Stable across resumes (rebuilt from the event log). + [JsonPropertyName("id")] + public long Id { get; set; } - /// Optional `id` of the parent entry: e.g. a `plugin` entry parenting its `skill`/`mcpServer` entries, or the `system` entry parenting `toolDefinition` entries. Omitted for top-level entries. - [JsonPropertyName("parentId")] - public string? ParentId { get; set; } + /// Interval between scheduled ticks, in milliseconds (relative-interval schedules). + [JsonConverter(typeof(MillisecondsTimeSpanConverter))] + [JsonPropertyName("intervalMs")] + public TimeSpan? Interval { get; set; } - /// Token count currently in context attributable to this entry. - [JsonPropertyName("tokens")] - public long Tokens { get; set; } -} + /// ISO 8601 timestamp when the next tick is scheduled to fire. + [JsonPropertyName("nextRunAt")] + public DateTimeOffset NextRunAt { get; set; } -/// Per-source token attribution snapshot for the current context window. The heaviest individual messages are available separately via `metadata.getContextHeaviestMessages`. -public sealed class MetadataContextAttributionResultContextAttribution -{ - /// Successful compaction history for the session. - [JsonPropertyName("compactions")] - public MetadataContextAttributionResultContextAttributionCompactions Compactions { get => field ??= new(); set; } + /// Prompt text that gets enqueued on every tick. + [JsonPropertyName("prompt")] + public string Prompt { get; set; } = string.Empty; - /// Flat list of per-source attribution entries. Group by `kind` and render unrecognized kinds generically. Nesting and rollups are expressed via `parentId`. - [JsonPropertyName("entries")] - public IList Entries { get => field ??= []; set; } + /// Whether the schedule re-arms after each tick (`/every`) or fires once (`/after`). + [JsonPropertyName("recurring")] + public bool Recurring { get; set; } - /// Total token count of the current context window the entries are measured against (system message + conversation messages + tool definitions — the same total reported by /context). Divide an entry's `tokens` by this to derive its share. - [JsonPropertyName("totalTokens")] - public long TotalTokens { get; set; } + /// True for a self-paced (`dynamic`) schedule: no fixed cadence; the model arms each next run via the `manage_schedule` `wakeup` action. `nextRunAt` is model-controlled. + [JsonPropertyName("selfPaced")] + public bool? SelfPaced { get; set; } + + /// IANA timezone the `cron` expression is evaluated in. + [JsonPropertyName("tz")] + public string? Tz { get; set; } } -/// Per-source attribution breakdown for the session's current context window, or null if uninitialized. +/// Snapshot of the currently active recurring prompts for this session. [Experimental(Diagnostics.Experimental)] -public sealed class MetadataContextAttributionResult +public sealed class ScheduleList { - /// Per-source context-window attribution, or null if the session has not yet been initialized (no system prompt or tool metadata cached). - [JsonPropertyName("contextAttribution")] - public MetadataContextAttributionResultContextAttribution? ContextAttribution { get; set; } + /// Active scheduled prompts, ordered by id. + [JsonPropertyName("entries")] + public IList Entries { get => field ??= []; set; } } /// Identifies the target session. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionMetadataGetContextAttributionRequest +internal sealed class SessionScheduleListRequest { /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// A single large message currently in context. +/// Identifies the target session. [Experimental(Diagnostics.Experimental)] -public sealed class ContextHeaviestMessage +internal sealed class SessionScheduleHydrateRequest { - /// Stable identifier for this message within the snapshot. - [JsonPropertyName("id")] - public string Id { get; set; } = string.Empty; - - /// Human-readable source label, e.g. `tool: bash` or `skill: tmux`. Presentation-only. - [JsonPropertyName("label")] - public string Label { get; set; } = string.Empty; + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// Role of the chat message (`user`, `assistant`, or `tool`). - [JsonPropertyName("role")] - public string Role { get; set; } = string.Empty; +/// Whether the session currently has an active self-paced schedule. +[Experimental(Diagnostics.Experimental)] +internal sealed class ScheduleHasSelfPacedResult +{ + /// True when at least one active schedule is self-paced. + [JsonPropertyName("hasSelfPaced")] + public bool HasSelfPaced { get; set; } +} - /// Token count currently in context for this individual message. - [JsonPropertyName("tokens")] - public long Tokens { get; set; } +/// Identifies the target session. +[Experimental(Diagnostics.Experimental)] +internal sealed class SessionScheduleHasSelfPacedRequest +{ + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// The heaviest individual messages in the session's context window, most-expensive first. +/// Result of registering or re-arming a scheduled prompt. [Experimental(Diagnostics.Experimental)] -public sealed class MetadataContextHeaviestMessagesResult +internal sealed class ScheduleAddResult { - /// Heaviest messages, most-expensive first. - [JsonPropertyName("messages")] - public IList Messages { get => field ??= []; set; } + /// The registered or updated schedule entry. + [JsonPropertyName("entry")] + public ScheduleEntry? Entry { get; set; } - /// Total token count of the current context window, so callers can compute each message's share without a second call. - [JsonPropertyName("totalTokens")] - public long TotalTokens { get; set; } + /// User-facing validation error, when registration failed. + [JsonPropertyName("error")] + public string? Error { get; set; } } -/// Parameters for the heaviest-messages query. +/// Register a relative-interval scheduled prompt. [Experimental(Diagnostics.Experimental)] -internal sealed class MetadataContextHeaviestMessagesRequest +internal sealed class ScheduleAddRequest { - /// Maximum number of messages to return, most-expensive first. Omit for the server default. - [JsonPropertyName("limit")] - public long? Limit { get; set; } + /// Optional display-only prompt label. + [JsonPropertyName("displayPrompt")] + public string? DisplayPrompt { get; set; } + + /// Human-readable interval such as `30s`, `5m`, or `2h`. + [JsonPropertyName("interval")] + public string Interval { get; set; } = string.Empty; + + /// Prompt text to enqueue when the schedule fires. + [JsonPropertyName("prompt")] + public string Prompt { get; set; } = string.Empty; + + /// Whether the schedule should re-arm after each tick. Defaults to true. + [JsonPropertyName("recurring")] + public bool? Recurring { get; set; } /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Notify the session that its working directory context has changed. Emits a `session.context_changed` event so consumers (telemetry, OTel tracker, ACP, the timeline UI) can react. Use this when the host has detected a cwd/branch/repo change outside the session's normal lifecycle (e.g., after a shell command in interactive mode). For a local session, a report whose `cwd` diverges from the session's current working directory is ignored (the call still succeeds but records nothing and emits no event); move a local session's working directory via `metadata.setWorkingDirectory` instead. +/// Register a cron scheduled prompt. [Experimental(Diagnostics.Experimental)] -public sealed class MetadataRecordContextChangeResult +internal sealed class ScheduleAddCronRequest { + /// 5-field cron expression. + [JsonPropertyName("cron")] + public string Cron { get; set; } = string.Empty; + + /// Optional display-only prompt label. + [JsonPropertyName("displayPrompt")] + public string? DisplayPrompt { get; set; } + + /// Prompt text to enqueue when the schedule fires. + [JsonPropertyName("prompt")] + public string Prompt { get; set; } = string.Empty; + + /// Whether the schedule should re-arm after each tick. Defaults to true. + [JsonPropertyName("recurring")] + public bool? Recurring { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; + + /// IANA timezone for evaluating the cron expression. + [JsonPropertyName("tz")] + public string? Tz { get; set; } } -/// Updated working directory and git context. Emitted as the new payload of `session.context_changed`. +/// Register an absolute-time scheduled prompt. [Experimental(Diagnostics.Experimental)] -public sealed class SessionWorkingDirectoryContext +internal sealed class ScheduleAddAtRequest { - /// Merge-base commit SHA (fork point from the remote default branch). - [JsonPropertyName("baseCommit")] - public string? BaseCommit { get; set; } + /// Epoch milliseconds when the prompt should fire. + [JsonPropertyName("at")] + public long At { get; set; } - /// Current git branch name. - [JsonPropertyName("branch")] - public string? Branch { get; set; } + /// Optional display-only prompt label. + [JsonPropertyName("displayPrompt")] + public string? DisplayPrompt { get; set; } - /// Current working directory path. - [JsonPropertyName("cwd")] - public string Cwd { get; set; } = string.Empty; + /// Prompt text to enqueue when the schedule fires. + [JsonPropertyName("prompt")] + public string Prompt { get; set; } = string.Empty; - /// Root directory of the git repository, resolved via git rev-parse. - [JsonPropertyName("gitRoot")] - public string? GitRoot { get; set; } + /// Whether the schedule should re-arm after each tick. Defaults to false. + [JsonPropertyName("recurring")] + public bool? Recurring { get; set; } - /// Head commit of the current git branch. - [JsonPropertyName("headCommit")] - public string? HeadCommit { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// Hosting platform type of the repository. - [JsonPropertyName("hostType")] - public SessionWorkingDirectoryContextHostType? HostType { get; set; } +/// Register a self-paced scheduled prompt. +[Experimental(Diagnostics.Experimental)] +internal sealed class ScheduleAddSelfPacedRequest +{ + /// Optional display-only prompt label. + [JsonPropertyName("displayPrompt")] + public string? DisplayPrompt { get; set; } - /// Repository identifier derived from the git remote URL ("owner/name" for GitHub, "org/project/repo" for Azure DevOps). - [JsonPropertyName("repository")] - public string? Repository { get; set; } + /// Prompt text to enqueue when the schedule fires. + [JsonPropertyName("prompt")] + public string Prompt { get; set; } = string.Empty; - /// Raw host string from the git remote URL (e.g. "github.com", "dev.azure.com"). - [JsonPropertyName("repositoryHost")] - public string? RepositoryHost { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Updated working-directory/git context to record on the session. +/// Re-arm a self-paced scheduled prompt. [Experimental(Diagnostics.Experimental)] -internal sealed class MetadataRecordContextChangeRequest +internal sealed class ScheduleRearmSelfPacedRequest { - /// Updated working directory and git context. Emitted as the new payload of `session.context_changed`. - [JsonPropertyName("context")] - public SessionWorkingDirectoryContext Context { get => field ??= new(); set; } + /// Epoch milliseconds when the prompt should next fire. + [JsonPropertyName("at")] + public long At { get; set; } + + /// Id of the self-paced scheduled prompt. + [JsonPropertyName("id")] + public long Id { get; set; } /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for any related side-effects (file index, etc.); it does NOT change the process working directory (a session's cwd is per-session, not process-global). For local sessions the runtime validates the target first (an absolute path that exists on disk) and re-bases the permission primary directory; a rejected validation fails the call before anything is mutated, persisted, or emitted. Location-scoped permission rules are then re-keyed to the new directory (best-effort). Remote sessions only record the path. +/// Remove a scheduled prompt by id. The result entry is omitted if the id was unknown. [Experimental(Diagnostics.Experimental)] -public sealed class MetadataSetWorkingDirectoryResult +public sealed class ScheduleStopResult { - /// Working directory after the update. - [JsonPropertyName("workingDirectory")] - public string WorkingDirectory { get; set; } = string.Empty; + /// The removed entry, or omitted if no entry matched. + [JsonPropertyName("entry")] + public ScheduleEntry? Entry { get; set; } } -/// Absolute path to set as the session's new working directory. For local sessions the path must be absolute and exist on disk: it is validated before any session state changes, and a failing validation rejects the call with nothing mutated, persisted, or emitted. Remote sessions record the path as-is. +/// Identifier of the scheduled prompt to remove. [Experimental(Diagnostics.Experimental)] -internal sealed class MetadataSetWorkingDirectoryRequest +internal sealed class ScheduleStopRequest { + /// Id of the scheduled prompt to remove. + [JsonPropertyName("id")] + public long Id { get; set; } + /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; - - /// Absolute path to set as the session's working directory. The runtime updates the session's recorded cwd so subsequent operations (shell tools, file lookups, telemetry) anchor to it. - [JsonPropertyName("workingDirectory")] - public string WorkingDirectory { get; set; } = string.Empty; } -/// Re-tokenize the session's existing messages against `modelId` and return the token totals. Useful for hosts that want an initial estimate of context usage on session resume, before the next agent turn fires `session.context_info_changed` events. Returns zeros for an empty session. +/// A bearer token supplied by the SDK client for a BYOK provider. The runtime sets it as `Authorization: Bearer <token>` on the outbound request and does no caching; the SDK consumer owns token caching and refresh. [Experimental(Diagnostics.Experimental)] -public sealed class MetadataRecomputeContextTokensResult +public sealed class ProviderTokenAcquireResult { - /// Tokens contributed by user/assistant/tool messages (excludes system/developer prompts). - [JsonPropertyName("messagesTokenCount")] - public long MessagesTokenCount { get; set; } - - /// Tokens contributed by system/developer prompt snapshots. - [JsonPropertyName("systemTokenCount")] - public long SystemTokenCount { get; set; } - - /// Sum of tokens across chat-context and system-context messages currently held by the session. - [JsonPropertyName("totalTokens")] - public long TotalTokens { get; set; } + /// The bearer token value (without the `Bearer ` prefix). + [JsonPropertyName("token")] + public string Token { get; set; } = string.Empty; } -/// Model identifier to use when re-tokenizing the session's existing messages. +/// Asks the SDK client to acquire a bearer token for a BYOK provider whose config set `hasBearerTokenProvider: true`. Issued by the runtime before each outbound model request; the runtime does no caching, so this is sent once per request. [Experimental(Diagnostics.Experimental)] -internal sealed class MetadataRecomputeContextTokensRequest +public sealed class ProviderTokenAcquireRequest { - /// Model identifier used for tokenization. The runtime token-counts both chat-context and system-context messages against this model. - [JsonPropertyName("modelId")] - public string ModelId { get; set; } = string.Empty; + /// Name of the BYOK provider needing a token. For the legacy whole-session `provider` this is the implicit provider name; for named providers it is `NamedProviderConfig.name`. + [JsonPropertyName("providerName")] + public string ProviderName { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Availability of built-in job tools surfaced to boundary consumers. +/// Result returned by an extension factory closure. [Experimental(Diagnostics.Experimental)] -public sealed class SessionSettingsBuiltInToolAvailabilitySnapshot +public sealed class FactoryExecuteResult { - /// Gets or sets the createPullRequest value. - [JsonPropertyName("createPullRequest")] - public bool? CreatePullRequest { get; set; } - - /// Gets or sets the reportProgress value. - [JsonPropertyName("reportProgress")] - public bool? ReportProgress { get; set; } + /// Factory result value. + [JsonPropertyName("result")] + public JsonElement? Result { get; set; } } -/// Redacted job settings for a session. The job nonce is excluded. +/// Parameters sent to the owning extension to execute a factory closure. [Experimental(Diagnostics.Experimental)] -public sealed class SessionSettingsJobSnapshot +public sealed class FactoryExecuteRequest { - /// Gets or sets the builtInToolAvailability value. - [JsonPropertyName("builtInToolAvailability")] - public SessionSettingsBuiltInToolAvailabilitySnapshot? BuiltInToolAvailability { get; set; } + /// Factory input value. + [JsonPropertyName("args")] + public JsonElement Args { get; set; } - /// Gets or sets the eventType value. - [JsonPropertyName("eventType")] - public string? EventType { get; set; } + /// Opaque token identifying this factory execution attempt. + [JsonPropertyName("executionToken")] + public string ExecutionToken { get; set; } = string.Empty; - /// Gets or sets the isTriggerJob value. - [JsonPropertyName("isTriggerJob")] - public bool? IsTriggerJob { get; set; } + /// Registered factory name. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; + + /// Factory run identifier. + [JsonPropertyName("runId")] + public string RunId { get; set; } = string.Empty; + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Redacted model routing settings for a session. +/// Parameters for cooperatively aborting a factory body. [Experimental(Diagnostics.Experimental)] -public sealed class SessionSettingsModelSnapshot +public sealed class FactoryAbortRequest { - /// Gets or sets the callbackUrl value. - [JsonPropertyName("callbackUrl")] - public string? CallbackUrl { get; set; } + /// Factory run identifier. + [JsonPropertyName("runId")] + public string RunId { get; set; } = string.Empty; - /// Gets or sets the defaultReasoningEffort value. - [JsonPropertyName("defaultReasoningEffort")] - public string? DefaultReasoningEffort { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// Gets or sets the instanceId value. - [JsonPropertyName("instanceId")] - public string? InstanceId { get; set; } +/// Describes a filesystem error. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionFsError +{ + /// Error classification. + [JsonPropertyName("code")] + public SessionFsErrorCode Code { get; set; } - /// Gets or sets the model value. - [JsonPropertyName("model")] - public string? Model { get; set; } + /// Free-form detail about the error, for logging/diagnostics. + [JsonPropertyName("message")] + public string? Message { get; set; } } -/// Online-evaluation settings safe to expose across the SDK boundary. +/// File content as a UTF-8 string, or a filesystem error if the read failed. [Experimental(Diagnostics.Experimental)] -public sealed class SessionSettingsOnlineEvaluationSnapshot +public sealed class SessionFsReadFileResult { - /// Gets or sets the disableOnlineEvaluation value. - [JsonPropertyName("disableOnlineEvaluation")] - public bool? DisableOnlineEvaluation { get; set; } + /// File content as UTF-8 string. + [JsonPropertyName("content")] + public string Content { get; set; } = string.Empty; - /// Gets or sets the enableOnlineEvaluationOutputFile value. - [JsonPropertyName("enableOnlineEvaluationOutputFile")] - public bool? EnableOnlineEvaluationOutputFile { get; set; } + /// Describes a filesystem error. + [JsonPropertyName("error")] + public SessionFsError? Error { get; set; } } -/// Redacted repository and GitHub host settings for a session. +/// Path of the file to read from the client-provided session filesystem. [Experimental(Diagnostics.Experimental)] -public sealed class SessionSettingsRepoSnapshot +public sealed class SessionFsReadFileRequest { - /// Gets or sets the branch value. - [JsonPropertyName("branch")] - public string? Branch { get; set; } - - /// Gets or sets the commit value. - [JsonPropertyName("commit")] - public string? Commit { get; set; } - - /// Gets or sets the host value. - [JsonPropertyName("host")] - public string? Host { get; set; } + /// Path using SessionFs conventions. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; - /// Gets or sets the hostProtocol value. - [JsonPropertyName("hostProtocol")] - public string? HostProtocol { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// Gets or sets the id value. - [JsonPropertyName("id")] - public double? Id { get; set; } +/// File path, content to write, and optional mode for the client-provided session filesystem. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionFsWriteFileRequest +{ + /// Content to write. + [JsonPropertyName("content")] + public string Content { get; set; } = string.Empty; - /// Gets or sets the name value. - [JsonPropertyName("name")] - public string? Name { get; set; } + /// Optional POSIX-style mode for newly created files. + [JsonPropertyName("mode")] + public long? Mode { get; set; } - /// Gets or sets the ownerId value. - [JsonPropertyName("ownerId")] - public double? OwnerId { get; set; } + /// Path using SessionFs conventions. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; - /// Gets or sets the ownerName value. - [JsonPropertyName("ownerName")] - public string? OwnerName { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// Gets or sets the prCommitCount value. - [JsonPropertyName("prCommitCount")] - public double? PrCommitCount { get; set; } +/// File path, content to append, and optional mode for the client-provided session filesystem. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionFsAppendFileRequest +{ + /// Content to append. + [JsonPropertyName("content")] + public string Content { get; set; } = string.Empty; - /// Gets or sets the readWrite value. - [JsonPropertyName("readWrite")] - public bool? ReadWrite { get; set; } + /// Optional POSIX-style mode for newly created files. + [JsonPropertyName("mode")] + public long? Mode { get; set; } - /// Gets or sets the secretScanningUrl value. - [JsonPropertyName("secretScanningUrl")] - public string? SecretScanningUrl { get; set; } + /// Path using SessionFs conventions. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; - /// Gets or sets the serverUrl value. - [JsonPropertyName("serverUrl")] - public string? ServerUrl { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Redacted validation and memory-tool settings for a session. +/// Indicates whether the requested path exists in the client-provided session filesystem. [Experimental(Diagnostics.Experimental)] -public sealed class SessionSettingsValidationSnapshot +public sealed class SessionFsExistsResult { - /// Gets or sets the advisoryEnabled value. - [JsonPropertyName("advisoryEnabled")] - public bool? AdvisoryEnabled { get; set; } + /// Whether the path exists. + [JsonPropertyName("exists")] + public bool Exists { get; set; } +} - /// Gets or sets the codeqlEnabled value. - [JsonPropertyName("codeqlEnabled")] - public bool? CodeqlEnabled { get; set; } +/// Path to test for existence in the client-provided session filesystem. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionFsExistsRequest +{ + /// Path using SessionFs conventions. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; - /// Gets or sets the codeReviewEnabled value. - [JsonPropertyName("codeReviewEnabled")] - public bool? CodeReviewEnabled { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// Gets or sets the codeReviewModel value. - [JsonPropertyName("codeReviewModel")] - public string? CodeReviewModel { get; set; } +/// Filesystem metadata for the requested path, or a filesystem error if the stat failed. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionFsStatResult +{ + /// ISO 8601 timestamp of creation. + [JsonPropertyName("birthtime")] + public DateTimeOffset Birthtime { get; set; } - /// Gets or sets the dependabotTimeout value. - [JsonPropertyName("dependabotTimeout")] - public double? DependabotTimeout { get; set; } + /// Describes a filesystem error. + [JsonPropertyName("error")] + public SessionFsError? Error { get; set; } - /// Gets or sets the memoryStoreEnabled value. - [JsonPropertyName("memoryStoreEnabled")] - public bool? MemoryStoreEnabled { get; set; } + /// Whether the path is a directory. + [JsonPropertyName("isDirectory")] + public bool IsDirectory { get; set; } - /// Gets or sets the memoryVoteEnabled value. - [JsonPropertyName("memoryVoteEnabled")] - public bool? MemoryVoteEnabled { get; set; } + /// Whether the path is a file. + [JsonPropertyName("isFile")] + public bool IsFile { get; set; } - /// Gets or sets the secretScanningEnabled value. - [JsonPropertyName("secretScanningEnabled")] - public bool? SecretScanningEnabled { get; set; } + /// ISO 8601 timestamp of last modification. + [JsonPropertyName("mtime")] + public DateTimeOffset Mtime { get; set; } - /// Gets or sets the timeout value. - [JsonPropertyName("timeout")] - public double? Timeout { get; set; } + /// File size in bytes. + [JsonPropertyName("size")] + public long Size { get; set; } } -/// Redacted, serializable view of session runtime settings for SDK boundary consumers. Secrets and raw feature flags are intentionally excluded. +/// Path whose metadata should be returned from the client-provided session filesystem. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionSettingsSnapshot +public sealed class SessionFsStatRequest { - /// Gets or sets the clientName value. - [JsonPropertyName("clientName")] - public string? ClientName { get; set; } - - /// Gets or sets the job value. - [JsonPropertyName("job")] - public SessionSettingsJobSnapshot Job { get => field ??= new(); set; } + /// Path using SessionFs conventions. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; - /// Gets or sets the model value. - [JsonPropertyName("model")] - public SessionSettingsModelSnapshot Model { get => field ??= new(); set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// Gets or sets the onlineEvaluation value. - [JsonPropertyName("onlineEvaluation")] - public SessionSettingsOnlineEvaluationSnapshot OnlineEvaluation { get => field ??= new(); set; } +/// Directory path to create in the client-provided session filesystem, with options for recursive creation and POSIX mode. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionFsMkdirRequest +{ + /// Optional POSIX-style mode for newly created directories. + [JsonPropertyName("mode")] + public long? Mode { get; set; } - /// Gets or sets the repo value. - [JsonPropertyName("repo")] - public SessionSettingsRepoSnapshot Repo { get => field ??= new(); set; } + /// Path using SessionFs conventions. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; - /// Gets or sets the startTimeMs value. - [JsonPropertyName("startTimeMs")] - public double? StartTimeMs { get; set; } + /// Create parent directories as needed. + [JsonPropertyName("recursive")] + public bool? Recursive { get; set; } - /// Gets or sets the timeoutMs value. - [JsonPropertyName("timeoutMs")] - public double? TimeoutMs { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// Gets or sets the validation value. - [JsonPropertyName("validation")] - public SessionSettingsValidationSnapshot Validation { get => field ??= new(); set; } +/// Names of entries in the requested directory, or a filesystem error if the read failed. +[Experimental(Diagnostics.Experimental)] +public sealed class SessionFsReaddirResult +{ + /// Entry names in the directory. + [JsonPropertyName("entries")] + public IList Entries { get => field ??= []; set; } - /// Gets or sets the version value. - [JsonPropertyName("version")] - public string? Version { get; set; } + /// Describes a filesystem error. + [JsonPropertyName("error")] + public SessionFsError? Error { get; set; } } -/// Identifies the target session. +/// Directory path whose entries should be listed from the client-provided session filesystem. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionSettingsSnapshotRequest +public sealed class SessionFsReaddirRequest { + /// Path using SessionFs conventions. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; + /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Result of evaluating a Rust-owned settings predicate. -[Experimental(Diagnostics.Experimental)] -internal sealed class SessionSettingsEvaluatePredicateResult -{ - /// Gets or sets the enabled value. - [JsonPropertyName("enabled")] - public bool Enabled { get; set; } -} - -/// Named Rust-owned settings predicate to evaluate for this session. +/// Directory entry returned by session filesystem `readdirWithTypes`, with name and entry type. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionSettingsEvaluatePredicateRequest +public sealed class SessionFsReaddirWithTypesEntry { - /// Predicate name. The runtime owns the raw feature-flag names and composition logic. + /// Entry name. [JsonPropertyName("name")] - public SessionSettingsPredicateName Name { get; set; } - - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + public string Name { get; set; } = string.Empty; - /// Tool name for tool-scoped predicates such as trivial-change handling. - [JsonPropertyName("toolName")] - public string? ToolName { get; set; } + /// Entry type. + [JsonPropertyName("type")] + public SessionFsReaddirWithTypesEntryType Type { get; set; } } -/// Identifier of the spawned process, used to correlate streamed output and exit notifications. +/// Entries in the requested directory paired with file/directory type information, or a filesystem error if the read failed. [Experimental(Diagnostics.Experimental)] -public sealed class ShellExecResult +public sealed class SessionFsReaddirWithTypesResult { - /// Unique identifier for tracking streamed output. - [JsonPropertyName("processId")] - public string ProcessId { get; set; } = string.Empty; + /// Directory entries with type information. + [JsonPropertyName("entries")] + public IList Entries { get => field ??= []; set; } + + /// Describes a filesystem error. + [JsonPropertyName("error")] + public SessionFsError? Error { get; set; } } -/// Shell command to run, with optional working directory and timeout in milliseconds. +/// Directory path whose entries (with type information) should be listed from the client-provided session filesystem. [Experimental(Diagnostics.Experimental)] -internal sealed class ShellExecRequest +public sealed class SessionFsReaddirWithTypesRequest { - /// Shell command to execute. - [JsonPropertyName("command")] - public string Command { get; set; } = string.Empty; - - /// Working directory (defaults to session working directory). - [JsonPropertyName("cwd")] - public string? Cwd { get; set; } + /// Path using SessionFs conventions. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; - - /// Timeout in milliseconds (default: 30000). - [JsonConverter(typeof(MillisecondsTimeSpanConverter))] - [JsonPropertyName("timeout")] - public TimeSpan? Timeout { get; set; } } -/// Indicates whether the signal was delivered; false if the process was unknown or already exited. +/// Path to remove from the client-provided session filesystem, with options for recursive removal and force. [Experimental(Diagnostics.Experimental)] -public sealed class ShellKillResult +public sealed class SessionFsRmRequest { - /// Whether the signal was sent successfully. - [JsonPropertyName("killed")] - public bool Killed { get; set; } + /// Ignore errors if the path does not exist. + [JsonPropertyName("force")] + public bool? Force { get; set; } + + /// Path using SessionFs conventions. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; + + /// Remove directories and their contents recursively. + [JsonPropertyName("recursive")] + public bool? Recursive { get; set; } + + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Identifier of a process previously returned by "shell.exec" and the signal to send. +/// Source and destination paths for renaming or moving an entry in the client-provided session filesystem. [Experimental(Diagnostics.Experimental)] -internal sealed class ShellKillRequest +public sealed class SessionFsRenameRequest { - /// Process identifier returned by shell.exec. - [JsonPropertyName("processId")] - public string ProcessId { get; set; } = string.Empty; + /// Destination path using SessionFs conventions. + [JsonPropertyName("dest")] + public string Dest { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; - /// Signal to send (default: SIGTERM). - [JsonPropertyName("signal")] - public ShellKillSignal? Signal { get; set; } + /// Source path using SessionFs conventions. + [JsonPropertyName("src")] + public string Src { get; set; } = string.Empty; } -/// Result of a user-requested shell command. +/// Query results including rows, columns, and rows affected, or a filesystem error if execution failed. [Experimental(Diagnostics.Experimental)] -public sealed class UserRequestedShellCommandResult +public sealed class SessionFsSqliteQueryResult { - /// Error output when the execution failed. - [JsonPropertyName("error")] - public string? Error { get; set; } + /// Column names from the result set. + [JsonPropertyName("columns")] + public IList Columns { get => field ??= []; set; } - /// Process exit code, when available. - [JsonPropertyName("exitCode")] - public long? ExitCode { get; set; } + /// Describes a filesystem error. + [JsonPropertyName("error")] + public SessionFsError? Error { get; set; } - /// Captured command output. - [JsonPropertyName("output")] - public string Output { get; set; } = string.Empty; + /// SQLite last_insert_rowid() value for INSERT. + [JsonPropertyName("lastInsertRowid")] + public long? LastInsertRowid { get; set; } - /// Whether the command completed successfully. - [JsonPropertyName("success")] - public bool Success { get; set; } + /// For SELECT: array of row objects. For others: empty array. + [JsonPropertyName("rows")] + public IList> Rows { get => field ??= []; set; } - /// Tool call id emitted for the shell execution. - [JsonPropertyName("toolCallId")] - public string ToolCallId { get; set; } = string.Empty; + /// Number of rows affected (for INSERT/UPDATE/DELETE). + [JsonPropertyName("rowsAffected")] + public long RowsAffected { get; set; } } -/// User-requested shell command and cancellation handle. +/// SQL query, query type, and optional bind parameters for executing a SQLite query against the per-session database. The provider applies its SQLite busy timeout for every call. [Experimental(Diagnostics.Experimental)] -internal sealed class ShellExecuteUserRequestedRequest +public sealed class SessionFsSqliteQueryRequest { - /// Shell command to execute. - [JsonPropertyName("command")] - public string Command { get; set; } = string.Empty; + /// Optional named bind parameters. + [JsonPropertyName("params")] + public IDictionary? Params { get; set; } - /// Caller-provided cancellation handle for this execution. - [JsonPropertyName("requestId")] - public string RequestId { get; set; } = string.Empty; + /// SQL query to execute. + [JsonPropertyName("query")] + public string Query { get; set; } = string.Empty; + + /// How to execute the query: 'exec' for DDL/multi-statement (no results), 'query' for SELECT (returns rows), 'run' for INSERT/UPDATE/DELETE (returns rowsAffected). + [JsonPropertyName("queryType")] + public SessionFsSqliteQueryType QueryType { get; set; } /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Cancellation result for a user-requested shell command. +/// Classified SQLite transaction failure. busyOrLocked guarantees rollback; postCommitAmbiguous must never be retried. [Experimental(Diagnostics.Experimental)] -public sealed class CancelUserRequestedShellCommandResult +public sealed class SessionFsSqliteTransactionError { - /// Whether an in-flight execution was found and signalled to cancel. - [JsonPropertyName("cancelled")] - public bool Cancelled { get; set; } + /// Gets or sets the errorClass value. + [JsonPropertyName("errorClass")] + public SessionFsSqliteTransactionErrorClass ErrorClass { get; set; } + + /// Gets or sets the message value. + [JsonPropertyName("message")] + public string Message { get; set; } = string.Empty; } -/// User-requested shell execution cancellation handle. +/// Per-statement results, or a classified transaction error. [Experimental(Diagnostics.Experimental)] -internal sealed class ShellCancelUserRequestedRequest +public sealed class SessionFsSqliteTransactionResult { - /// Request ID previously passed to executeUserRequested. - [JsonPropertyName("requestId")] - public string RequestId { get; set; } = string.Empty; + /// Gets or sets the error value. + [JsonPropertyName("error")] + public SessionFsSqliteTransactionError? Error { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Gets or sets the results value. + [JsonPropertyName("results")] + public IList Results { get => field ??= []; set; } } -/// Post-compaction context window usage breakdown. +/// One statement in an atomic SQLite transaction. [Experimental(Diagnostics.Experimental)] -public sealed class HistoryCompactContextWindow +public sealed class SessionFsSqliteTransactionStatement { - /// Token count from non-system messages (user, assistant, tool). - [JsonPropertyName("conversationTokens")] - public long? ConversationTokens { get; set; } - - /// Current total tokens in the context window (system + conversation + tool definitions). - [JsonPropertyName("currentTokens")] - public long CurrentTokens { get; set; } - - /// Current number of messages in the conversation. - [JsonPropertyName("messagesLength")] - public long MessagesLength { get; set; } - - /// Token count from system message(s). - [JsonPropertyName("systemTokens")] - public long? SystemTokens { get; set; } + /// Optional named bind parameters. + [JsonPropertyName("params")] + public IDictionary? Params { get; set; } - /// Maximum token count for the model's context window. - [JsonPropertyName("tokenLimit")] - public long TokenLimit { get; set; } + /// SQL statement to execute. + [JsonPropertyName("query")] + public string Query { get; set; } = string.Empty; - /// Token count from tool definitions. - [JsonPropertyName("toolDefinitionsTokens")] - public long? ToolDefinitionsTokens { get; set; } + /// How to execute the statement. + [JsonPropertyName("queryType")] + public SessionFsSqliteQueryType QueryType { get; set; } } -/// Compaction outcome with the number of tokens and messages removed, summary text, and the resulting context window breakdown. +/// Statements to execute atomically. Providers apply busy handling for every call. [Experimental(Diagnostics.Experimental)] -public sealed class HistoryCompactResult +public sealed class SessionFsSqliteTransactionRequest { - /// Post-compaction context window usage breakdown. - [JsonPropertyName("contextWindow")] - public HistoryCompactContextWindow? ContextWindow { get; set; } - - /// Number of messages removed during compaction. - [JsonPropertyName("messagesRemoved")] - public long MessagesRemoved { get; set; } - - /// Whether compaction completed successfully. - [JsonPropertyName("success")] - public bool Success { get; set; } - - /// Summary text produced by compaction. Omitted when compaction did not produce a summary (e.g. failure path). - [JsonPropertyName("summaryContent")] - public string? SummaryContent { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; - /// Number of tokens freed by compaction. - [JsonPropertyName("tokensRemoved")] - public long TokensRemoved { get; set; } + /// Gets or sets the statements value. + [JsonPropertyName("statements")] + public IList Statements { get => field ??= []; set; } } -/// Optional compaction parameters. +/// Indicates whether the per-session SQLite database already exists. [Experimental(Diagnostics.Experimental)] -public sealed class HistoryCompactRequest +public sealed class SessionFsSqliteExistsResult { - /// 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; } + /// Whether the session database already exists. + [JsonPropertyName("exists")] + public bool Exists { get; set; } } -/// Optional compaction parameters. -[Experimental(Diagnostics.Experimental)] -internal sealed class HistoryCompactRequestWithSession +/// Identifies the target session. +public sealed class SessionFsSqliteExistsRequest { - /// 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; } -/// Number of events that were removed by the truncation. +/// Canvas open result returned by the provider. [Experimental(Diagnostics.Experimental)] -public sealed class HistoryTruncateResult +public sealed class CanvasProviderOpenResult { - /// Number of events that were removed. - [JsonPropertyName("eventsRemoved")] - public long EventsRemoved { get; set; } -} + /// Provider-supplied status text. + [JsonPropertyName("status")] + public string? Status { get; set; } -/// Identifier of the event to truncate to; this event and all later events are removed. -[Experimental(Diagnostics.Experimental)] -internal sealed class HistoryTruncateRequest -{ - /// Event ID to truncate to. This event and all events after it are removed from the session. - [JsonPropertyName("eventId")] - public string EventId { get; set; } = string.Empty; + /// Provider-supplied title. + [JsonPropertyName("title")] + public string? Title { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// URL for web-rendered canvases. + [JsonPropertyName("url")] + public string? Url { get; set; } } -/// Indicates whether an in-progress background compaction was cancelled. +/// Host capabilities. [Experimental(Diagnostics.Experimental)] -public sealed class HistoryCancelBackgroundCompactionResult +public sealed class CanvasHostContextCapabilities { - /// Whether an in-progress background compaction was cancelled. False when no compaction was running, when the session is remote, or when the underlying processor was unavailable. - [JsonPropertyName("cancelled")] - public bool Cancelled { get; set; } + /// Whether canvas rendering is supported. + [JsonPropertyName("canvases")] + public bool? Canvases { get; set; } } -/// Identifies the target session. +/// Host context supplied by the runtime. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionHistoryCancelBackgroundCompactionRequest +public sealed class CanvasHostContext { - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Host capabilities. + [JsonPropertyName("capabilities")] + public CanvasHostContextCapabilities? Capabilities { get; set; } } -/// Indicates whether an in-progress manual compaction was aborted. +/// Session context supplied by the runtime. [Experimental(Diagnostics.Experimental)] -public sealed class HistoryAbortManualCompactionResult +public sealed class CanvasSessionContext { - /// Whether an in-progress manual compaction was aborted. False when no manual compaction was running, when its abort controller was already aborted, or when the session is remote. - [JsonPropertyName("aborted")] - public bool Aborted { get; set; } + /// Active session working directory, when known. + [JsonPropertyName("workingDirectory")] + public string? WorkingDirectory { get; set; } } -/// Identifies the target session. +/// Canvas open parameters sent to the provider. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionHistoryAbortManualCompactionRequest +public sealed class CanvasProviderOpenRequest { + /// Provider-local canvas identifier. + [JsonPropertyName("canvasId")] + public string CanvasId { get; set; } = string.Empty; + + /// Owning provider identifier. + [JsonPropertyName("extensionId")] + public string ExtensionId { get; set; } = string.Empty; + + /// Host context supplied by the runtime. + [JsonPropertyName("host")] + public CanvasHostContext? Host { get; set; } + + /// Canvas open input. + [JsonPropertyName("input")] + public JsonElement? Input { get; set; } + + /// Stable caller-supplied canvas instance identifier. + [JsonPropertyName("instanceId")] + public string InstanceId { get; set; } = string.Empty; + + /// Session context supplied by the runtime. + [JsonPropertyName("session")] + public CanvasSessionContext? Session { get; set; } + /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Markdown summary of the conversation context (empty when not available). +/// Canvas close parameters sent to the provider. [Experimental(Diagnostics.Experimental)] -public sealed class HistorySummarizeForHandoffResult +public sealed class CanvasProviderCloseRequest { - /// Markdown summary of the conversation context produced by an LLM. Empty string when there are no messages or when the session does not support local summarization. - [JsonPropertyName("summary")] - public string Summary { get; set; } = string.Empty; -} + /// Provider-local canvas identifier. + [JsonPropertyName("canvasId")] + public string CanvasId { get; set; } = string.Empty; + + /// Owning provider identifier. + [JsonPropertyName("extensionId")] + public string ExtensionId { get; set; } = string.Empty; + + /// Host context supplied by the runtime. + [JsonPropertyName("host")] + public CanvasHostContext? Host { get; set; } + + /// Canvas instance identifier. + [JsonPropertyName("instanceId")] + public string InstanceId { get; set; } = string.Empty; + + /// Session context supplied by the runtime. + [JsonPropertyName("session")] + public CanvasSessionContext? Session { get; set; } -/// Identifies the target session. -[Experimental(Diagnostics.Experimental)] -internal sealed class SessionHistorySummarizeForHandoffRequest -{ /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// User-facing pending queue entry, with kind and display text for a queued message, slash command, or model change. +/// Canvas action invocation parameters sent to the provider. [Experimental(Diagnostics.Experimental)] -public sealed class QueuePendingItems +public sealed class CanvasProviderInvokeActionRequest { - /// Human-readable text to display for this queue entry in the UI. - [JsonPropertyName("displayText")] - public string DisplayText { get; set; } = string.Empty; + /// Action name to invoke. + [JsonPropertyName("actionName")] + public string ActionName { get; set; } = string.Empty; - /// Whether this item is a queued user message or a queued slash command / model change. - [JsonPropertyName("kind")] - public QueuePendingItemsKind Kind { get; set; } -} + /// Provider-local canvas identifier. + [JsonPropertyName("canvasId")] + public string CanvasId { get; set; } = string.Empty; -/// Snapshot of the session's pending queued items and immediate-steering messages. -[Experimental(Diagnostics.Experimental)] -public sealed class QueuePendingItemsResult -{ - /// Pending queued items in submission order. Includes user messages, queued slash commands, and queued model changes; omits internal system items. - [JsonPropertyName("items")] - public IList Items { get => field ??= []; set; } + /// Owning provider identifier. + [JsonPropertyName("extensionId")] + public string ExtensionId { get; set; } = string.Empty; - /// Display text for messages currently in the immediate steering queue (interjections sent during a running turn). - [JsonPropertyName("steeringMessages")] - public IList SteeringMessages { get => field ??= []; set; } -} + /// Host context supplied by the runtime. + [JsonPropertyName("host")] + public CanvasHostContext? Host { get; set; } + + /// Action input. + [JsonPropertyName("input")] + public JsonElement? Input { get; set; } + + /// Canvas instance identifier. + [JsonPropertyName("instanceId")] + public string InstanceId { get; set; } = string.Empty; + + /// Session context supplied by the runtime. + [JsonPropertyName("session")] + public CanvasSessionContext? Session { get; set; } -/// Identifies the target session. -[Experimental(Diagnostics.Experimental)] -internal sealed class SessionQueuePendingItemsRequest -{ /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Indicates whether a user-facing pending item was removed. +/// Acknowledgement. Returning successfully simply means the SDK accepted the start frame; it does not imply the request will succeed. [Experimental(Diagnostics.Experimental)] -public sealed class QueueRemoveMostRecentResult +public sealed class LlmInferenceHttpRequestStartResult { - /// True if a user-facing pending item was removed (LIFO across both queues); false when no removable items remained. - [JsonPropertyName("removed")] - public bool Removed { get; set; } } -/// Identifies the target session. +/// The head of an outbound model-layer HTTP request. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionQueueRemoveMostRecentRequest +public sealed class LlmInferenceHttpRequestStartRequest { - /// Target session identifier. + /// Stable identity of the agent trajectory that issued this request. Present when the request originates from an agent turn; absent for requests outside any agent context. This is the same identity used by lifecycle and bridged session events and remains constant across turns and retries. + [JsonPropertyName("agentId")] + public string? AgentId { get; set; } + + /// Identity of the agent invocation (one agentic loop) that issued this request. It remains fixed across physical retries within the invocation and is distinct from the stable trajectory `agentId`. A caller-supplied invocation id always takes precedence (this covers auxiliary calls that have no model call id). Otherwise, first-party CAPI requests fall back to the runtime's agent task id — the same value the runtime emits as the `X-Agent-Task-Id` header — while custom-provider requests fall back to the model call id. + [JsonPropertyName("agentInvocationId")] + public string? AgentInvocationId { get; set; } + + /// Gets or sets the headers value. + [JsonPropertyName("headers")] + public IDictionary> Headers { get => field ??= new Dictionary>(); set; } + + /// Coarse classification of the interaction that produced this request. Open string for forward-compatibility; known values include `conversation-agent`, `conversation-subagent`, `conversation-sampling`, `conversation-background`, `conversation-compaction`, and `conversation-user`. Absent when the runtime did not classify the request. Comes from the runtime's per-request agent context independently of transport; on the CAPI transport the runtime derives the upstream `X-Interaction-Type` header from this same context. + [JsonPropertyName("interactionType")] + public string? InteractionType { get; set; } + + /// HTTP method, e.g. GET, POST. + [JsonPropertyName("method")] + public string Method { get; set; } = string.Empty; + + /// Stable identity of the immediate parent trajectory. Present for child trajectories such as subagents and conversation-sampling requests; absent for root-agent and non-agent requests. + [JsonPropertyName("parentAgentId")] + public string? ParentAgentId { get; set; } + + /// Opaque runtime-minted id, unique per in-flight request. The SDK uses this to correlate httpRequestChunk frames and to address its httpResponseStart / httpResponseChunk replies back to the runtime. + [JsonPropertyName("requestId")] + public string RequestId { get; set; } = string.Empty; + + /// Id of the runtime session that triggered this request, when one is in scope. Absent for requests issued outside any session (e.g. startup model-catalog or capability resolution). This is a payload field — not a dispatch key — because the client-global API is registered process-wide rather than per session. [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + public string? SessionId { get; set; } + + /// Transport the runtime would otherwise use for this request. `http` (the default when absent) covers plain HTTP and SSE responses; `websocket` indicates a full-duplex message channel where each body chunk maps to one WebSocket message and the `binary` flag distinguishes text from binary frames. The SDK consumer uses this to decide whether to service the request with an HTTP client or a WebSocket client. It is the one piece of request metadata the consumer cannot reliably infer from the URL or headers alone. + [JsonPropertyName("transport")] + public LlmInferenceHttpRequestStartTransport? Transport { get; set; } + + /// Absolute request URL. + [JsonPropertyName("url")] + public string Url { get; set; } = string.Empty; } -/// Identifies the target session. +/// Acknowledgement. The SDK is free to ignore the ack and treat chunk delivery as fire-and-forget. [Experimental(Diagnostics.Experimental)] -internal sealed class SessionQueueClearRequest +public sealed class LlmInferenceHttpRequestChunkResult { - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; } -/// Batch of session events returned by a read, with cursor and continuation metadata. +/// A request body chunk or cancellation signal. [Experimental(Diagnostics.Experimental)] -public sealed class EventsReadResult +public sealed class LlmInferenceHttpRequestChunkRequest { - /// Opaque cursor for the next read. Pass back unchanged in the next read.cursor to continue from where this read left off. Always present, even when no events were returned. - [JsonPropertyName("cursor")] - public string Cursor { get; set; } = string.Empty; + /// Identity of the agent invocation (one agentic loop) this body chunk belongs to, matching the `agentInvocationId` semantics on httpRequestStart. Carried per chunk so a persistent transport can attribute successive turns correctly: when a WebSocket connection is reused across turns, the httpRequestStart identity reflects only the turn that opened the connection, so each later turn stamps its own invocation id here. Absent when the runtime has no invocation context for the request, or on the plain-HTTP transport where every request has its own httpRequestStart. + [JsonPropertyName("agentInvocationId")] + public string? AgentInvocationId { get; set; } - /// Cursor status: 'ok' means the cursor was applied successfully; 'expired' means the cursor referred to an event that no longer exists in history (e.g. truncated or compacted away) and the read started from the beginning of the remaining history. - [JsonPropertyName("cursorStatus")] - public EventsCursorStatus CursorStatus { get; set; } + /// When true, `data` is base64-encoded bytes. When absent or false, `data` is UTF-8 text. + [JsonPropertyName("binary")] + public bool? Binary { get; set; } - /// Events are delivered in two batches per read: persisted events first (in append order), then ephemeral events (in seq order). When `waitMs > 0` and the catch-up batches were empty, post-wait events follow the same two-batch ordering. Persisted and ephemeral events do not interleave within a single read. - [JsonPropertyName("events")] - public IList Events { get => field ??= []; set; } + /// When true, the runtime is cancelling the in-flight request (e.g. upstream consumer aborted). `data` is ignored. Implies end-of-request. + [JsonPropertyName("cancel")] + public bool? Cancel { get; set; } - /// True when the read returned `max` events and more events are available immediately. When false, the next read with a non-zero `waitMs` will block until a new event arrives or the wait expires. - [JsonPropertyName("hasMore")] - public bool HasMore { get; set; } + /// Optional human-readable reason for the cancellation, propagated for logging. + [JsonPropertyName("cancelReason")] + public string? CancelReason { get; set; } + + /// Body byte range. UTF-8 text when `binary` is absent or false; base64-encoded bytes when `binary` is true. May be empty. + [JsonPropertyName("data")] + public string Data { get; set; } = string.Empty; + + /// When true, this is the final body chunk for the request. The SDK may rely on having received an end-marked chunk before treating the request body as complete. + [JsonPropertyName("end")] + public bool? End { get; set; } + + /// Matches the requestId from the originating httpRequestStart frame. + [JsonPropertyName("requestId")] + public string RequestId { get; set; } = string.Empty; } -/// Cursor, batch size, and optional long-poll/filter parameters for reading session events. +/// Client environment metadata describing the process that produced a telemetry event. [Experimental(Diagnostics.Experimental)] -internal sealed class EventLogReadRequest +public sealed class GitHubTelemetryClientInfo { - /// 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. - [JsonPropertyName("agentScope")] - public EventsAgentScope? AgentScope { get; set; } + /// Copilot CLI version string. + [JsonPropertyName("cli_version")] + public string CliVersion { get; set; } = string.Empty; + + /// Name of the client application. + [JsonPropertyName("client_name")] + public string? ClientName { get; set; } + + /// Type of client. + [JsonPropertyName("client_type")] + public string? ClientType { get; set; } - /// Opaque cursor returned by a previous read. Omit on the first call to start from the beginning of the session's persisted history. - [JsonPropertyName("cursor")] - public string? Cursor { get; set; } + /// Copilot subscription plan, when known. + [JsonPropertyName("copilot_plan")] + public string? CopilotPlan { get; set; } - /// Maximum number of events to return in this batch (1–1000, default 200). - [JsonPropertyName("max")] - public long? Max { get; set; } + /// Stable machine identifier for the device. + [JsonPropertyName("dev_device_id")] + public string? DevDeviceId { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Whether the user is a GitHub/Microsoft staff member. + [JsonPropertyName("is_staff")] + public bool? IsStaff { get; set; } - /// Either '*' to receive all event types, or a non-empty list of event types to receive. - [JsonPropertyName("types")] - public JsonElement? Types { get; set; } + /// Node.js runtime version string. + [JsonPropertyName("node_version")] + public string NodeVersion { get; set; } = string.Empty; - /// 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))] - [JsonPropertyName("waitMs")] - public TimeSpan? Wait { get; set; } -} + /// Operating system architecture (e.g. arm64, x64). + [JsonPropertyName("os_arch")] + public string OsArch { get; set; } = string.Empty; -/// Snapshot of the current tail cursor without returning any events. Use this when a consumer wants to subscribe to live events going forward without first paginating through the entire persisted history (which would happen if `read` were called without a cursor on a long-lived session). -[Experimental(Diagnostics.Experimental)] -public sealed class EventLogTailResult -{ - /// Opaque cursor pointing at the current tail of the session's persisted-events history. Pass back to `read` to receive only events that arrive AFTER this snapshot. When the session has no events, this returns the same sentinel as an unset cursor (i.e. equivalent to omitting the cursor on a first read). - [JsonPropertyName("cursor")] - public string Cursor { get; set; } = string.Empty; -} + /// Operating system platform (e.g. darwin, linux, win32). + [JsonPropertyName("os_platform")] + public string OsPlatform { get; set; } = string.Empty; -/// Identifies the target session. -[Experimental(Diagnostics.Experimental)] -internal sealed class SessionEventLogTailRequest -{ - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Operating system version string. + [JsonPropertyName("os_version")] + public string OsVersion { get; set; } = string.Empty; } -/// Opaque handle representing an event-type interest registration. +/// A single telemetry event in the runtime's native GitHub-shaped telemetry format, forwarded verbatim to opted-in hosts. The `restricted` flag on the enclosing GitHubTelemetryNotification distinguishes standard from restricted events; the payload shape is identical for both. [Experimental(Diagnostics.Experimental)] -public sealed class RegisterEventInterestResult +public sealed class GitHubTelemetryEvent { - /// Opaque handle for this registration. Pass to releaseInterest to release. Each call to registerInterest produces a fresh handle, even when the same eventType is registered multiple times. - [JsonPropertyName("handle")] - public string Handle { get; set; } = string.Empty; -} + /// Client environment metadata. + [JsonPropertyName("client")] + public GitHubTelemetryClientInfo? Client { get; set; } -/// Event type to register consumer interest for, used by runtime gating logic. -[Experimental(Diagnostics.Experimental)] -internal sealed class RegisterEventInterestParams -{ - /// The event type the consumer wants the runtime to treat as 'observed' for behavior-switching gating. Some runtime code paths inspect whether any consumer is interested in a specific event type and choose a different implementation accordingly (e.g. `mcp.oauth_required`: when interest is registered the runtime delegates interactive OAuth token acquisition to the consumer via `mcp.oauth_required` events; when no interest is registered the runtime still attempts non-interactive reconnect from cached or refreshable tokens, and only marks the server `needs-auth` if usable credentials are unavailable — it does not open a browser or start interactive OAuth without a consumer). SDK clients that long-poll events do NOT automatically appear as listeners to these gating checks — they must explicitly call `registerInterest` for each event type they want the runtime to count as having a consumer. Multiple registrations for the same event type from the same or different consumers are tracked independently and must each be released. See: `mcp.oauth_required`, `sampling.requested`, `auto_mode_switch.requested`, `session_limits_exhausted.requested`, `user_input.requested`, `elicitation.requested`, `command.queued`, `exit_plan_mode.requested`. - [JsonPropertyName("eventType")] - public string EventType { get; set; } = string.Empty; + /// Copilot tracking ID for user-level attribution. + [JsonPropertyName("copilot_tracking_id")] + public string? CopilotTrackingId { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// Timestamp when the event was created (ISO 8601 format). + [JsonPropertyName("created_at")] + public string? CreatedAt { get; set; } -/// Indicates whether the operation succeeded. -[Experimental(Diagnostics.Experimental)] -public sealed class EventLogReleaseInterestResult -{ - /// Whether the operation succeeded. - [JsonPropertyName("success")] - public bool Success { get; set; } -} + /// Experiment assignment context. + [JsonPropertyName("exp_assignment_context")] + public string? ExpAssignmentContext { get; set; } -/// Opaque handle previously returned by `registerInterest` to release. -[Experimental(Diagnostics.Experimental)] -internal sealed class ReleaseEventInterestParams -{ - /// Handle returned by a previous `registerInterest` call. Idempotent: releasing an unknown or already-released handle is a no-op (returns success). When the last outstanding handle for an event type is released, the runtime reverts to its 'no consumer' code path for that event type. - [JsonPropertyName("handle")] - public string Handle { get; set; } = string.Empty; + /// Feature flags enabled for this session, as a map from flag to value. + [JsonPropertyName("features")] + public IDictionary? Features { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// Event type/kind (e.g. get_completion_with_tools_turn, tool_call_executed). + [JsonPropertyName("kind")] + public string Kind { get; set; } = string.Empty; -/// Aggregated code change metrics. -[Experimental(Diagnostics.Experimental)] -public sealed class UsageMetricsCodeChanges -{ - /// Distinct file paths modified during the session. - [JsonPropertyName("filesModified")] - public IList FilesModified { get => field ??= []; set; } + /// Numeric metrics as a map from key to value. + [JsonPropertyName("metrics")] + public IDictionary Metrics { get => field ??= new Dictionary(); set; } - /// Number of distinct files modified. - [JsonPropertyName("filesModifiedCount")] - public long FilesModifiedCount { get; set; } + /// Reference to the model call that produced this event. + [JsonPropertyName("model_call_id")] + public string? ModelCallId { get; set; } - /// Total lines of code added. - [JsonPropertyName("linesAdded")] - public long LinesAdded { get; set; } + /// String-valued properties as a map from key to value. + [JsonPropertyName("properties")] + public IDictionary Properties { get => field ??= new Dictionary(); set; } - /// Total lines of code removed. - [JsonPropertyName("linesRemoved")] - public long LinesRemoved { get; set; } + /// Session identifier the event belongs to. + [JsonPropertyName("session_id")] + public string? SessionId { get; set; } } -/// Request count and cost metrics for this model. +/// Payload for a `gitHubTelemetry.event` notification: a single GitHub telemetry event the runtime forwards to a host connection that opted into telemetry forwarding during the `server.connect` handshake. [Experimental(Diagnostics.Experimental)] -public sealed class UsageMetricsModelMetricRequests +public sealed class GitHubTelemetryNotification { - /// User-initiated premium request cost (with multiplier applied). - [JsonPropertyName("cost")] - public double Cost { get; set; } + /// The telemetry event, in the runtime's native GitHub-shaped telemetry format. + [JsonPropertyName("event")] + public GitHubTelemetryEvent Event { get => field ??= new(); set; } - /// Number of API requests made with this model. - [JsonPropertyName("count")] - public long Count { get; set; } -} + /// Whether this is a restricted telemetry event (cli.restricted_telemetry). Hosts must route restricted events to first-party Microsoft stores only. + [JsonPropertyName("restricted")] + public bool Restricted { get; set; } -/// Per-model token-detail entry containing the accumulated token count for one token type. -[Experimental(Diagnostics.Experimental)] -public sealed class UsageMetricsModelMetricTokenDetail -{ - /// Accumulated token count for this token type. - [JsonPropertyName("tokenCount")] - public long TokenCount { get; set; } + /// Session the telemetry event belongs to, when it is session-scoped. Omitted for sessionless events (for example, `server.sendTelemetry` calls with no session id), which are still forwarded to opted-in connections. + [JsonPropertyName("sessionId")] + public string? SessionId { get; set; } } -/// Token usage metrics for this model. +/// Resolved Anthropic adaptive-thinking capability for a model. [Experimental(Diagnostics.Experimental)] -public sealed class UsageMetricsModelMetricUsage +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct AdaptiveThinkingSupport : IEquatable { - /// Total tokens read from prompt cache. - [JsonPropertyName("cacheReadTokens")] - public long CacheReadTokens { get; set; } + private readonly string? _value; - /// Total tokens written to prompt cache. - [JsonPropertyName("cacheWriteTokens")] - public long CacheWriteTokens { get; set; } + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public AdaptiveThinkingSupport(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } - /// Total input tokens consumed. - [JsonPropertyName("inputTokens")] - public long InputTokens { get; set; } + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; - /// Total output tokens produced. - [JsonPropertyName("outputTokens")] - public long OutputTokens { get; set; } + /// The model does not accept thinking.type='adaptive'. + public static AdaptiveThinkingSupport Unsupported { get; } = new("unsupported"); - /// Total output tokens used for reasoning. - [JsonPropertyName("reasoningTokens")] - public long? ReasoningTokens { get; set; } -} + /// The model accepts adaptive thinking but also accepts thinking.type='enabled'. + public static AdaptiveThinkingSupport Optional { get; } = new("optional"); -/// Per-model usage metrics, including request counts/costs, token usage, nano-AI units, and per-token-type details. -[Experimental(Diagnostics.Experimental)] -public sealed class UsageMetricsModelMetric -{ - /// Latest known prompt-cache expiration for this model. A timestamp in the past indicates that the observed cache has expired. - [JsonPropertyName("cacheExpiresAt")] - public DateTimeOffset? CacheExpiresAt { get; set; } + /// The model only accepts adaptive thinking and rejects thinking.type='enabled' with HTTP 400 (e.g. opus-4.7/4.8). + public static AdaptiveThinkingSupport Required { get; } = new("required"); - /// Request count and cost metrics for this model. - [JsonPropertyName("requests")] - public UsageMetricsModelMetricRequests Requests { get => field ??= new(); set; } + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(AdaptiveThinkingSupport left, AdaptiveThinkingSupport right) => left.Equals(right); - /// Token count details per type. - [JsonPropertyName("tokenDetails")] - public IDictionary? TokenDetails { get; set; } + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(AdaptiveThinkingSupport left, AdaptiveThinkingSupport right) => !(left == right); - /// Accumulated nano-AI units cost for this model. - [JsonPropertyName("totalNanoAiu")] - public double? TotalNanoAiu { get; set; } + /// + public override bool Equals(object? obj) => obj is AdaptiveThinkingSupport other && Equals(other); - /// Token usage metrics for this model. - [JsonPropertyName("usage")] - public UsageMetricsModelMetricUsage Usage { get => field ??= new(); set; } -} + /// + public bool Equals(AdaptiveThinkingSupport other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); -/// Session-wide token-detail entry containing the accumulated token count for one token type. -[Experimental(Diagnostics.Experimental)] -public sealed class UsageMetricsTokenDetail -{ - /// Accumulated token count for this token type. - [JsonPropertyName("tokenCount")] - public long TokenCount { get; set; } + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override AdaptiveThinkingSupport Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, AdaptiveThinkingSupport value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AdaptiveThinkingSupport)); + } + } } -/// Accumulated session usage metrics, including premium request cost, token counts, model breakdown, and code-change totals. + +/// Model capability category for grouping in the model picker. [Experimental(Diagnostics.Experimental)] -public sealed class UsageGetMetricsResult +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct ModelPickerCategory : IEquatable { - /// Aggregated code change metrics. - [JsonPropertyName("codeChanges")] - public UsageMetricsCodeChanges CodeChanges { get => field ??= new(); set; } + private readonly string? _value; - /// Currently active model identifier. - [JsonPropertyName("currentModel")] - public string? CurrentModel { get; set; } + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public ModelPickerCategory(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } - /// Input tokens from the most recent main-agent API call. - [JsonPropertyName("lastCallInputTokens")] - public long LastCallInputTokens { get; set; } + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; - /// Output tokens from the most recent main-agent API call. - [JsonPropertyName("lastCallOutputTokens")] - public long LastCallOutputTokens { get; set; } + /// Lightweight model category optimized for faster, lower-cost interactions. + public static ModelPickerCategory Lightweight { get; } = new("lightweight"); - /// Per-model token and request metrics, keyed by model identifier. - [JsonPropertyName("modelMetrics")] - public IDictionary ModelMetrics { get => field ??= new Dictionary(); set; } + /// Versatile model category suitable for a broad range of tasks. + public static ModelPickerCategory Versatile { get; } = new("versatile"); - /// ISO 8601 timestamp when the session started. - [JsonPropertyName("sessionStartTime")] - public DateTimeOffset SessionStartTime { get; set; } + /// Powerful model category optimized for complex tasks. + public static ModelPickerCategory Powerful { get; } = new("powerful"); - /// Session-wide per-token-type accumulated token counts. - [JsonPropertyName("tokenDetails")] - public IDictionary? TokenDetails { get; set; } + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(ModelPickerCategory left, ModelPickerCategory right) => left.Equals(right); - /// Total time spent in model API calls (milliseconds). - [JsonConverter(typeof(MillisecondsTimeSpanConverter))] - [JsonPropertyName("totalApiDurationMs")] - public TimeSpan TotalApiDuration { get; set; } + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(ModelPickerCategory left, ModelPickerCategory right) => !(left == right); - /// Session-wide accumulated nano-AI units cost. - [JsonPropertyName("totalNanoAiu")] - public double? TotalNanoAiu { get; set; } + /// + public override bool Equals(object? obj) => obj is ModelPickerCategory other && Equals(other); - /// Total user-initiated premium request cost across all models (may be fractional due to multipliers). - [JsonPropertyName("totalPremiumRequestCost")] - public double TotalPremiumRequestCost { get; set; } + /// + public bool Equals(ModelPickerCategory other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); - /// Raw count of user-initiated API requests. - [JsonPropertyName("totalUserRequests")] - public long TotalUserRequests { get; set; } -} + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); -/// Identifies the target session. -[Experimental(Diagnostics.Experimental)] -internal sealed class SessionUsageGetMetricsRequest -{ - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// + public override string ToString() => Value; -/// GitHub URL for the session and a flag indicating whether remote steering is enabled. -[Experimental(Diagnostics.Experimental)] -public sealed class RemoteEnableResult -{ - /// Whether remote steering is enabled. - [JsonPropertyName("remoteSteerable")] - public bool RemoteSteerable { get; set; } + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override ModelPickerCategory Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } - /// GitHub frontend URL for this session. - [Url] - [StringSyntax(StringSyntaxAttribute.Uri)] - [JsonPropertyName("url")] - public string? Url { get; set; } + /// + public override void Write(Utf8JsonWriter writer, ModelPickerCategory value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ModelPickerCategory)); + } + } } -/// Optional remote session mode ("off", "export", or "on"); defaults to enabling both export and remote steering. + +/// Relative cost tier for token-based billing users. [Experimental(Diagnostics.Experimental)] -internal sealed class RemoteEnableRequest +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct ModelPickerPriceCategory : IEquatable { - /// Per-session remote mode. "off" disables remote, "export" exports session events to GitHub without enabling remote steering, "on" enables both export and remote steering. - [JsonPropertyName("mode")] - public RemoteSessionMode? Mode { get; set; } + private readonly string? _value; - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public ModelPickerPriceCategory(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } -/// Identifies the target session. -[Experimental(Diagnostics.Experimental)] -internal sealed class SessionRemoteDisableRequest -{ - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; -/// Persist a steerability change as a `session.remote_steerable_changed` event. Used by the host (CLI / SDK consumer) when it has just finished enabling or disabling steering on a remote exporter that the runtime does not directly own. -[Experimental(Diagnostics.Experimental)] -public sealed class RemoteNotifySteerableChangedResult -{ -} + /// Lowest relative token cost tier. + public static ModelPickerPriceCategory Low { get; } = new("low"); -/// New remote-steerability state to persist as a `session.remote_steerable_changed` event. -[Experimental(Diagnostics.Experimental)] -internal sealed class RemoteNotifySteerableChangedRequest -{ - /// Whether the session now supports remote steering via GitHub. The runtime persists this as a `session.remote_steerable_changed` event so resume/replay sees the up-to-date capability. - [JsonPropertyName("remoteSteerable")] - public bool RemoteSteerable { get; set; } + /// Medium relative token cost tier. + public static ModelPickerPriceCategory Medium { get; } = new("medium"); - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// High relative token cost tier. + public static ModelPickerPriceCategory High { get; } = new("high"); -/// Current sharing status and shareable GitHub URL for a session. -[Experimental(Diagnostics.Experimental)] -public sealed class VisibilityGetResult -{ - /// Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. - [Url] - [StringSyntax(StringSyntaxAttribute.Uri)] - [JsonPropertyName("shareUrl")] - public string? ShareUrl { get; set; } + /// Highest relative token cost tier. + public static ModelPickerPriceCategory VeryHigh { get; } = new("very_high"); - /// Current sharing status. Absent when the session is not synced or the status could not be retrieved (e.g. the user is not authenticated). - [JsonPropertyName("status")] - public SessionVisibilityStatus? Status { get; set; } + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(ModelPickerPriceCategory left, ModelPickerPriceCategory right) => left.Equals(right); - /// Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the session cannot be shared and `status`/`shareUrl` are absent. - [JsonPropertyName("synced")] - public bool Synced { get; set; } -} + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(ModelPickerPriceCategory left, ModelPickerPriceCategory right) => !(left == right); -/// Identifies the target session. -[Experimental(Diagnostics.Experimental)] -internal sealed class SessionVisibilityGetRequest -{ - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// + public override bool Equals(object? obj) => obj is ModelPickerPriceCategory other && Equals(other); -/// Effective sharing status and shareable GitHub URL after updating session visibility. -[Experimental(Diagnostics.Experimental)] -public sealed class VisibilitySetResult -{ - /// Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. - [Url] - [StringSyntax(StringSyntaxAttribute.Uri)] - [JsonPropertyName("shareUrl")] - public string? ShareUrl { get; set; } + /// + public bool Equals(ModelPickerPriceCategory other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); - /// Effective sharing status after the update. May differ from the requested status for task types that are already visible to repository readers by default. Absent when the update could not be applied (e.g. the session is not synced or the user is not authenticated). - [JsonPropertyName("status")] - public SessionVisibilityStatus? Status { get; set; } + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); - /// Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the visibility change could not be applied and `status`/`shareUrl` are absent. - [JsonPropertyName("synced")] - public bool Synced { get; set; } + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override ModelPickerPriceCategory Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, ModelPickerPriceCategory value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ModelPickerPriceCategory)); + } + } } -/// Desired sharing status for the session. + +/// Current policy state for this model. [Experimental(Diagnostics.Experimental)] -internal sealed class VisibilitySetRequest +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct ModelPolicyState : IEquatable { - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public ModelPolicyState(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } - /// Sharing status to apply. "repo" makes the session visible to repository readers; "unshared" restricts it to the creator and collaborators. - [JsonPropertyName("status")] - public SessionVisibilityStatus Status { get; set; } -} + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; -/// Scheduled prompt entry with ID, timing (`intervalMs`, `cron`, or `at`), prompt text, recurrence, and next run time. -[Experimental(Diagnostics.Experimental)] -public sealed class ScheduleEntry -{ - /// Absolute fire time (epoch milliseconds) for a one-shot calendar schedule. - [JsonPropertyName("at")] - public long? At { get; set; } + /// The model is enabled by policy. + public static ModelPolicyState Enabled { get; } = new("enabled"); - /// 5-field cron expression for a recurring calendar schedule, evaluated in `tz`. - [JsonPropertyName("cron")] - public string? Cron { get; set; } + /// The model is disabled by policy. + public static ModelPolicyState Disabled { get; } = new("disabled"); - /// Display-only label for the prompt as shown in the UI (e.g. `/skill-name` for a skill-invocation schedule). The actual enqueued prompt is `prompt`. - [JsonPropertyName("displayPrompt")] - public string? DisplayPrompt { get; set; } + /// No explicit policy is configured for the model. + public static ModelPolicyState Unconfigured { get; } = new("unconfigured"); - /// Sequential id assigned by the runtime within the session. Stable across resumes (rebuilt from the event log). - [JsonPropertyName("id")] - public long Id { get; set; } + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(ModelPolicyState left, ModelPolicyState right) => left.Equals(right); - /// Interval between scheduled ticks, in milliseconds (relative-interval schedules). - [JsonConverter(typeof(MillisecondsTimeSpanConverter))] - [JsonPropertyName("intervalMs")] - public TimeSpan? Interval { get; set; } + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(ModelPolicyState left, ModelPolicyState right) => !(left == right); - /// ISO 8601 timestamp when the next tick is scheduled to fire. - [JsonPropertyName("nextRunAt")] - public DateTimeOffset NextRunAt { get; set; } + /// + public override bool Equals(object? obj) => obj is ModelPolicyState other && Equals(other); - /// Prompt text that gets enqueued on every tick. - [JsonPropertyName("prompt")] - public string Prompt { get; set; } = string.Empty; + /// + public bool Equals(ModelPolicyState other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); - /// Whether the schedule re-arms after each tick (`/every`) or fires once (`/after`). - [JsonPropertyName("recurring")] - public bool Recurring { get; set; } + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); - /// True for a self-paced (`dynamic`) schedule: no fixed cadence; the model arms each next run via the `manage_schedule` `wakeup` action. `nextRunAt` is model-controlled. - [JsonPropertyName("selfPaced")] - public bool? SelfPaced { get; set; } + /// + public override string ToString() => Value; - /// IANA timezone the `cron` expression is evaluated in. - [JsonPropertyName("tz")] - public string? Tz { get; set; } -} + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override ModelPolicyState Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } -/// Snapshot of the currently active recurring prompts for this session. -[Experimental(Diagnostics.Experimental)] -public sealed class ScheduleList -{ - /// Active scheduled prompts, ordered by id. - [JsonPropertyName("entries")] - public IList Entries { get => field ??= []; set; } + /// + public override void Write(Utf8JsonWriter writer, ModelPolicyState value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ModelPolicyState)); + } + } } -/// Identifies the target session. -[Experimental(Diagnostics.Experimental)] -internal sealed class SessionScheduleListRequest -{ - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} -/// Remove a scheduled prompt by id. The result entry is omitted if the id was unknown. +/// Server transport type: stdio, http, sse (deprecated), or memory. [Experimental(Diagnostics.Experimental)] -public sealed class ScheduleStopResult +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct DiscoveredMcpServerType : IEquatable { - /// The removed entry, or omitted if no entry matched. - [JsonPropertyName("entry")] - public ScheduleEntry? Entry { get; set; } -} + private readonly string? _value; -/// Identifier of the scheduled prompt to remove. -[Experimental(Diagnostics.Experimental)] -internal sealed class ScheduleStopRequest -{ - /// Id of the scheduled prompt to remove. - [JsonPropertyName("id")] - public long Id { get; set; } + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public DiscoveredMcpServerType(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; -/// A bearer token supplied by the SDK client for a BYOK provider. The runtime sets it as `Authorization: Bearer <token>` on the outbound request and does no caching; the SDK consumer owns token caching and refresh. -[Experimental(Diagnostics.Experimental)] -public sealed class ProviderTokenAcquireResult -{ - /// The bearer token value (without the `Bearer ` prefix). - [JsonPropertyName("token")] - public string Token { get; set; } = string.Empty; -} + /// Server communicates over stdio with a local child process. + public static DiscoveredMcpServerType Stdio { get; } = new("stdio"); -/// Asks the SDK client to acquire a bearer token for a BYOK provider whose config set `hasBearerTokenProvider: true`. Issued by the runtime before each outbound model request; the runtime does no caching, so this is sent once per request. -[Experimental(Diagnostics.Experimental)] -public sealed class ProviderTokenAcquireRequest -{ - /// Name of the BYOK provider needing a token. For the legacy whole-session `provider` this is the implicit provider name; for named providers it is `NamedProviderConfig.name`. - [JsonPropertyName("providerName")] - public string ProviderName { get; set; } = string.Empty; + /// Server communicates over streamable HTTP. + public static DiscoveredMcpServerType Http { get; } = new("http"); - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// Server communicates over Server-Sent Events (deprecated). + public static DiscoveredMcpServerType Sse { get; } = new("sse"); -/// Result returned by an extension factory closure. -[Experimental(Diagnostics.Experimental)] -public sealed class FactoryExecuteResult -{ - /// Factory result value. - [JsonPropertyName("result")] - public JsonElement Result { get; set; } -} + /// Server is backed by an in-memory runtime implementation. + public static DiscoveredMcpServerType Memory { get; } = new("memory"); -/// Parameters sent to the owning extension to execute a factory closure. -[Experimental(Diagnostics.Experimental)] -public sealed class FactoryExecuteRequest -{ - /// Factory input value. - [JsonPropertyName("args")] - public JsonElement Args { get; set; } + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(DiscoveredMcpServerType left, DiscoveredMcpServerType right) => left.Equals(right); - /// Registered factory name. - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(DiscoveredMcpServerType left, DiscoveredMcpServerType right) => !(left == right); - /// Factory run identifier. - [JsonPropertyName("runId")] - public string RunId { get; set; } = string.Empty; + /// + public override bool Equals(object? obj) => obj is DiscoveredMcpServerType other && Equals(other); - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// + public bool Equals(DiscoveredMcpServerType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); -/// Parameters for cooperatively aborting a factory body. -[Experimental(Diagnostics.Experimental)] -public sealed class FactoryAbortRequest -{ - /// Factory run identifier. - [JsonPropertyName("runId")] - public string RunId { get; set; } = string.Empty; + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// + public override string ToString() => Value; -/// Describes a filesystem error. -[Experimental(Diagnostics.Experimental)] -public sealed class SessionFsError -{ - /// Error classification. - [JsonPropertyName("code")] - public SessionFsErrorCode Code { get; set; } + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override DiscoveredMcpServerType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } - /// Free-form detail about the error, for logging/diagnostics. - [JsonPropertyName("message")] - public string? Message { get; set; } + /// + public override void Write(Utf8JsonWriter writer, DiscoveredMcpServerType value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DiscoveredMcpServerType)); + } + } } -/// File content as a UTF-8 string, or a filesystem error if the read failed. + +/// Which tier this directory belongs to. [Experimental(Diagnostics.Experimental)] -public sealed class SessionFsReadFileResult +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct SkillDiscoveryScope : IEquatable { - /// File content as UTF-8 string. - [JsonPropertyName("content")] - public string Content { get; set; } = string.Empty; + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public SkillDiscoveryScope(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// A project's repository skill directory. + public static SkillDiscoveryScope Project { get; } = new("project"); + + /// The user's personal Copilot skill directory. + public static SkillDiscoveryScope PersonalCopilot { get; } = new("personal-copilot"); + + /// The user's personal agents skill directory. + public static SkillDiscoveryScope PersonalAgents { get; } = new("personal-agents"); + + /// A configured custom skill directory. + public static SkillDiscoveryScope Custom { get; } = new("custom"); - /// Describes a filesystem error. - [JsonPropertyName("error")] - public SessionFsError? Error { get; set; } -} + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SkillDiscoveryScope left, SkillDiscoveryScope right) => left.Equals(right); -/// Path of the file to read from the client-provided session filesystem. -[Experimental(Diagnostics.Experimental)] -public sealed class SessionFsReadFileRequest -{ - /// Path using SessionFs conventions. - [JsonPropertyName("path")] - public string Path { get; set; } = string.Empty; + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SkillDiscoveryScope left, SkillDiscoveryScope right) => !(left == right); - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// + public override bool Equals(object? obj) => obj is SkillDiscoveryScope other && Equals(other); -/// File path, content to write, and optional mode for the client-provided session filesystem. -[Experimental(Diagnostics.Experimental)] -public sealed class SessionFsWriteFileRequest -{ - /// Content to write. - [JsonPropertyName("content")] - public string Content { get; set; } = string.Empty; + /// + public bool Equals(SkillDiscoveryScope other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); - /// Optional POSIX-style mode for newly created files. - [JsonPropertyName("mode")] - public long? Mode { get; set; } + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); - /// Path using SessionFs conventions. - [JsonPropertyName("path")] - public string Path { get; set; } = string.Empty; + /// + public override string ToString() => Value; - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override SkillDiscoveryScope Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, SkillDiscoveryScope value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SkillDiscoveryScope)); + } + } } -/// File path, content to append, and optional mode for the client-provided session filesystem. + +/// Where the agent definition was loaded from. [Experimental(Diagnostics.Experimental)] -public sealed class SessionFsAppendFileRequest +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct AgentInfoSource : IEquatable { - /// Content to append. - [JsonPropertyName("content")] - public string Content { get; set; } = string.Empty; + private readonly string? _value; - /// Optional POSIX-style mode for newly created files. - [JsonPropertyName("mode")] - public long? Mode { get; set; } + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public AgentInfoSource(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } - /// Path using SessionFs conventions. - [JsonPropertyName("path")] - public string Path { get; set; } = string.Empty; + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// Agent loaded from the user's personal agent configuration. + public static AgentInfoSource User { get; } = new("user"); -/// Indicates whether the requested path exists in the client-provided session filesystem. -[Experimental(Diagnostics.Experimental)] -public sealed class SessionFsExistsResult -{ - /// Whether the path exists. - [JsonPropertyName("exists")] - public bool Exists { get; set; } -} + /// Agent loaded from the current project's repository configuration. + public static AgentInfoSource Project { get; } = new("project"); -/// Path to test for existence in the client-provided session filesystem. -[Experimental(Diagnostics.Experimental)] -public sealed class SessionFsExistsRequest -{ - /// Path using SessionFs conventions. - [JsonPropertyName("path")] - public string Path { get; set; } = string.Empty; + /// Agent inherited from a parent project or workspace. + public static AgentInfoSource Inherited { get; } = new("inherited"); - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// Agent provided by a remote runtime or service. + public static AgentInfoSource Remote { get; } = new("remote"); -/// Filesystem metadata for the requested path, or a filesystem error if the stat failed. -[Experimental(Diagnostics.Experimental)] -public sealed class SessionFsStatResult -{ - /// ISO 8601 timestamp of creation. - [JsonPropertyName("birthtime")] - public DateTimeOffset Birthtime { get; set; } + /// Agent contributed by an installed plugin. + public static AgentInfoSource Plugin { get; } = new("plugin"); - /// Describes a filesystem error. - [JsonPropertyName("error")] - public SessionFsError? Error { get; set; } + /// Agent built into the Copilot runtime. + public static AgentInfoSource Builtin { get; } = new("builtin"); - /// Whether the path is a directory. - [JsonPropertyName("isDirectory")] - public bool IsDirectory { get; set; } + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(AgentInfoSource left, AgentInfoSource right) => left.Equals(right); - /// Whether the path is a file. - [JsonPropertyName("isFile")] - public bool IsFile { get; set; } + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(AgentInfoSource left, AgentInfoSource right) => !(left == right); - /// ISO 8601 timestamp of last modification. - [JsonPropertyName("mtime")] - public DateTimeOffset Mtime { get; set; } + /// + public override bool Equals(object? obj) => obj is AgentInfoSource other && Equals(other); - /// File size in bytes. - [JsonPropertyName("size")] - public long Size { get; set; } -} + /// + public bool Equals(AgentInfoSource other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); -/// Path whose metadata should be returned from the client-provided session filesystem. -[Experimental(Diagnostics.Experimental)] -public sealed class SessionFsStatRequest -{ - /// Path using SessionFs conventions. - [JsonPropertyName("path")] - public string Path { get; set; } = string.Empty; + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override AgentInfoSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, AgentInfoSource value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentInfoSource)); + } + } } -/// Directory path to create in the client-provided session filesystem, with options for recursive creation and POSIX mode. + +/// Which tier this directory belongs to. [Experimental(Diagnostics.Experimental)] -public sealed class SessionFsMkdirRequest +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct AgentDiscoveryPathScope : IEquatable { - /// Optional POSIX-style mode for newly created directories. - [JsonPropertyName("mode")] - public long? Mode { get; set; } + private readonly string? _value; - /// Path using SessionFs conventions. - [JsonPropertyName("path")] - public string Path { get; set; } = string.Empty; + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public AgentDiscoveryPathScope(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } - /// Create parent directories as needed. - [JsonPropertyName("recursive")] - public bool? Recursive { get; set; } + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// The user's personal agent configuration directory. + public static AgentDiscoveryPathScope User { get; } = new("user"); -/// Names of entries in the requested directory, or a filesystem error if the read failed. -[Experimental(Diagnostics.Experimental)] -public sealed class SessionFsReaddirResult -{ - /// Entry names in the directory. - [JsonPropertyName("entries")] - public IList Entries { get => field ??= []; set; } + /// A project's repository agent directory. + public static AgentDiscoveryPathScope Project { get; } = new("project"); - /// Describes a filesystem error. - [JsonPropertyName("error")] - public SessionFsError? Error { get; set; } -} + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(AgentDiscoveryPathScope left, AgentDiscoveryPathScope right) => left.Equals(right); -/// Directory path whose entries should be listed from the client-provided session filesystem. -[Experimental(Diagnostics.Experimental)] -public sealed class SessionFsReaddirRequest -{ - /// Path using SessionFs conventions. - [JsonPropertyName("path")] - public string Path { get; set; } = string.Empty; + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(AgentDiscoveryPathScope left, AgentDiscoveryPathScope right) => !(left == right); - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// + public override bool Equals(object? obj) => obj is AgentDiscoveryPathScope other && Equals(other); -/// Directory entry returned by session filesystem `readdirWithTypes`, with name and entry type. -[Experimental(Diagnostics.Experimental)] -public sealed class SessionFsReaddirWithTypesEntry -{ - /// Entry name. - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; + /// + public bool Equals(AgentDiscoveryPathScope other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); - /// Entry type. - [JsonPropertyName("type")] - public SessionFsReaddirWithTypesEntryType Type { get; set; } -} + /// + public override string ToString() => Value; -/// Entries in the requested directory paired with file/directory type information, or a filesystem error if the read failed. -[Experimental(Diagnostics.Experimental)] -public sealed class SessionFsReaddirWithTypesResult -{ - /// Directory entries with type information. - [JsonPropertyName("entries")] - public IList Entries { get => field ??= []; set; } + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override AgentDiscoveryPathScope Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } - /// Describes a filesystem error. - [JsonPropertyName("error")] - public SessionFsError? Error { get; set; } + /// + public override void Write(Utf8JsonWriter writer, AgentDiscoveryPathScope value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentDiscoveryPathScope)); + } + } } -/// Directory path whose entries (with type information) should be listed from the client-provided session filesystem. + +/// Where this source lives — used for UI grouping. [Experimental(Diagnostics.Experimental)] -public sealed class SessionFsReaddirWithTypesRequest +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct InstructionSourceLocation : IEquatable { - /// Path using SessionFs conventions. - [JsonPropertyName("path")] - public string Path { get; set; } = string.Empty; + private readonly string? _value; - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public InstructionSourceLocation(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } -/// Path to remove from the client-provided session filesystem, with options for recursive removal and force. -[Experimental(Diagnostics.Experimental)] -public sealed class SessionFsRmRequest -{ - /// Ignore errors if the path does not exist. - [JsonPropertyName("force")] - public bool? Force { get; set; } + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; - /// Path using SessionFs conventions. - [JsonPropertyName("path")] - public string Path { get; set; } = string.Empty; + /// Instructions live in user-level configuration. + public static InstructionSourceLocation User { get; } = new("user"); - /// Remove directories and their contents recursively. - [JsonPropertyName("recursive")] - public bool? Recursive { get; set; } + /// Instructions live in repository-level configuration. + public static InstructionSourceLocation Repository { get; } = new("repository"); - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// Instructions live under the current working directory. + public static InstructionSourceLocation WorkingDirectory { get; } = new("working-directory"); -/// Source and destination paths for renaming or moving an entry in the client-provided session filesystem. -[Experimental(Diagnostics.Experimental)] -public sealed class SessionFsRenameRequest -{ - /// Destination path using SessionFs conventions. - [JsonPropertyName("dest")] - public string Dest { get; set; } = string.Empty; + /// Instructions live in plugin-provided configuration. + public static InstructionSourceLocation Plugin { get; } = new("plugin"); - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(InstructionSourceLocation left, InstructionSourceLocation right) => left.Equals(right); - /// Source path using SessionFs conventions. - [JsonPropertyName("src")] - public string Src { get; set; } = string.Empty; -} + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(InstructionSourceLocation left, InstructionSourceLocation right) => !(left == right); -/// Query results including rows, columns, and rows affected, or a filesystem error if execution failed. -[Experimental(Diagnostics.Experimental)] -public sealed class SessionFsSqliteQueryResult -{ - /// Column names from the result set. - [JsonPropertyName("columns")] - public IList Columns { get => field ??= []; set; } + /// + public override bool Equals(object? obj) => obj is InstructionSourceLocation other && Equals(other); - /// Describes a filesystem error. - [JsonPropertyName("error")] - public SessionFsError? Error { get; set; } + /// + public bool Equals(InstructionSourceLocation other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); - /// SQLite last_insert_rowid() value for INSERT. - [JsonPropertyName("lastInsertRowid")] - public long? LastInsertRowid { get; set; } + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); - /// For SELECT: array of row objects. For others: empty array. - [JsonPropertyName("rows")] - public IList> Rows { get => field ??= []; set; } + /// + public override string ToString() => Value; - /// Number of rows affected (for INSERT/UPDATE/DELETE). - [JsonPropertyName("rowsAffected")] - public long RowsAffected { get; set; } + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override InstructionSourceLocation Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, InstructionSourceLocation value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(InstructionSourceLocation)); + } + } } -/// SQL query, query type, and optional bind parameters for executing a SQLite query against the per-session database. + +/// Category of instruction source — used for merge logic. [Experimental(Diagnostics.Experimental)] -public sealed class SessionFsSqliteQueryRequest +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct InstructionSourceType : IEquatable { - /// Optional named bind parameters. - [JsonPropertyName("params")] - public IDictionary? Params { get; set; } - - /// SQL query to execute. - [JsonPropertyName("query")] - public string Query { get; set; } = string.Empty; + private readonly string? _value; - /// How to execute the query: 'exec' for DDL/multi-statement (no results), 'query' for SELECT (returns rows), 'run' for INSERT/UPDATE/DELETE (returns rowsAffected). - [JsonPropertyName("queryType")] - public SessionFsSqliteQueryType QueryType { get; set; } + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public InstructionSourceType(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; -/// Indicates whether the per-session SQLite database already exists. -[Experimental(Diagnostics.Experimental)] -public sealed class SessionFsSqliteExistsResult -{ - /// Whether the session database already exists. - [JsonPropertyName("exists")] - public bool Exists { get; set; } -} + /// Instructions loaded from the user's home configuration. + public static InstructionSourceType Home { get; } = new("home"); -/// Identifies the target session. -public sealed class SessionFsSqliteExistsRequest -{ - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// Instructions loaded from repository-scoped files. + public static InstructionSourceType Repo { get; } = new("repo"); -/// Canvas open result returned by the provider. -[Experimental(Diagnostics.Experimental)] -public sealed class CanvasProviderOpenResult -{ - /// Provider-supplied status text. - [JsonPropertyName("status")] - public string? Status { get; set; } + /// Instructions loaded from model-specific files. + public static InstructionSourceType Model { get; } = new("model"); - /// Provider-supplied title. - [JsonPropertyName("title")] - public string? Title { get; set; } + /// Instructions loaded from VS Code instruction files. + public static InstructionSourceType Vscode { get; } = new("vscode"); - /// URL for web-rendered canvases. - [JsonPropertyName("url")] - public string? Url { get; set; } -} + /// Instructions discovered from nested agent files. + public static InstructionSourceType NestedAgents { get; } = new("nested-agents"); -/// Host capabilities. -[Experimental(Diagnostics.Experimental)] -public sealed class CanvasHostContextCapabilities -{ - /// Whether canvas rendering is supported. - [JsonPropertyName("canvases")] - public bool? Canvases { get; set; } -} + /// Instructions inherited from child instruction files. + public static InstructionSourceType ChildInstructions { get; } = new("child-instructions"); -/// Host context supplied by the runtime. -[Experimental(Diagnostics.Experimental)] -public sealed class CanvasHostContext -{ - /// Host capabilities. - [JsonPropertyName("capabilities")] - public CanvasHostContextCapabilities? Capabilities { get; set; } -} + /// Instructions supplied by an installed plugin. + public static InstructionSourceType Plugin { get; } = new("plugin"); -/// Session context supplied by the runtime. -[Experimental(Diagnostics.Experimental)] -public sealed class CanvasSessionContext -{ - /// Active session working directory, when known. - [JsonPropertyName("workingDirectory")] - public string? WorkingDirectory { get; set; } -} + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(InstructionSourceType left, InstructionSourceType right) => left.Equals(right); -/// Canvas open parameters sent to the provider. -[Experimental(Diagnostics.Experimental)] -public sealed class CanvasProviderOpenRequest -{ - /// Provider-local canvas identifier. - [JsonPropertyName("canvasId")] - public string CanvasId { get; set; } = string.Empty; + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(InstructionSourceType left, InstructionSourceType right) => !(left == right); - /// Owning provider identifier. - [JsonPropertyName("extensionId")] - public string ExtensionId { get; set; } = string.Empty; + /// + public override bool Equals(object? obj) => obj is InstructionSourceType other && Equals(other); - /// Host context supplied by the runtime. - [JsonPropertyName("host")] - public CanvasHostContext? Host { get; set; } + /// + public bool Equals(InstructionSourceType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); - /// Canvas open input. - [JsonPropertyName("input")] - public JsonElement? Input { get; set; } + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); - /// Stable caller-supplied canvas instance identifier. - [JsonPropertyName("instanceId")] - public string InstanceId { get; set; } = string.Empty; + /// + public override string ToString() => Value; - /// Session context supplied by the runtime. - [JsonPropertyName("session")] - public CanvasSessionContext? Session { get; set; } + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override InstructionSourceType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// + public override void Write(Utf8JsonWriter writer, InstructionSourceType value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(InstructionSourceType)); + } + } } -/// Canvas close parameters sent to the provider. + +/// Whether the target is a single file or a directory of instruction files. [Experimental(Diagnostics.Experimental)] -public sealed class CanvasProviderCloseRequest +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct InstructionDiscoveryPathKind : IEquatable { - /// Provider-local canvas identifier. - [JsonPropertyName("canvasId")] - public string CanvasId { get; set; } = string.Empty; - - /// Owning provider identifier. - [JsonPropertyName("extensionId")] - public string ExtensionId { get; set; } = string.Empty; + private readonly string? _value; - /// Host context supplied by the runtime. - [JsonPropertyName("host")] - public CanvasHostContext? Host { get; set; } + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public InstructionDiscoveryPathKind(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } - /// Canvas instance identifier. - [JsonPropertyName("instanceId")] - public string InstanceId { get; set; } = string.Empty; + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; - /// Session context supplied by the runtime. - [JsonPropertyName("session")] - public CanvasSessionContext? Session { get; set; } + /// The target is a single instruction file. + public static InstructionDiscoveryPathKind File { get; } = new("file"); - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} + /// The target is a directory that holds instruction files. + public static InstructionDiscoveryPathKind Directory { get; } = new("directory"); -/// Canvas action invocation parameters sent to the provider. -[Experimental(Diagnostics.Experimental)] -public sealed class CanvasProviderInvokeActionRequest -{ - /// Action name to invoke. - [JsonPropertyName("actionName")] - public string ActionName { get; set; } = string.Empty; + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(InstructionDiscoveryPathKind left, InstructionDiscoveryPathKind right) => left.Equals(right); - /// Provider-local canvas identifier. - [JsonPropertyName("canvasId")] - public string CanvasId { get; set; } = string.Empty; + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(InstructionDiscoveryPathKind left, InstructionDiscoveryPathKind right) => !(left == right); - /// Owning provider identifier. - [JsonPropertyName("extensionId")] - public string ExtensionId { get; set; } = string.Empty; + /// + public override bool Equals(object? obj) => obj is InstructionDiscoveryPathKind other && Equals(other); - /// Host context supplied by the runtime. - [JsonPropertyName("host")] - public CanvasHostContext? Host { get; set; } + /// + public bool Equals(InstructionDiscoveryPathKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); - /// Action input. - [JsonPropertyName("input")] - public JsonElement? Input { get; set; } + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); - /// Canvas instance identifier. - [JsonPropertyName("instanceId")] - public string InstanceId { get; set; } = string.Empty; + /// + public override string ToString() => Value; - /// Session context supplied by the runtime. - [JsonPropertyName("session")] - public CanvasSessionContext? Session { get; set; } + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override InstructionDiscoveryPathKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// + public override void Write(Utf8JsonWriter writer, InstructionDiscoveryPathKind value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(InstructionDiscoveryPathKind)); + } + } } -/// Acknowledgement. Returning successfully simply means the SDK accepted the start frame; it does not imply the request will succeed. -[Experimental(Diagnostics.Experimental)] -public sealed class LlmInferenceHttpRequestStartResult -{ -} -/// The head of an outbound model-layer HTTP request. +/// Which tier this target belongs to. [Experimental(Diagnostics.Experimental)] -public sealed class LlmInferenceHttpRequestStartRequest +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct InstructionDiscoveryPathLocation : IEquatable { - /// Stable identity of the agent trajectory that issued this request. Present when the request originates from an agent turn; absent for requests outside any agent context. This is the same identity used by lifecycle and bridged session events and remains constant across turns and retries. - [JsonPropertyName("agentId")] - public string? AgentId { get; set; } + private readonly string? _value; - /// Identity of the agent invocation (one agentic loop) that issued this request. It remains fixed across physical retries within the invocation and is distinct from the stable trajectory `agentId`. A caller-supplied invocation id always takes precedence (this covers auxiliary calls that have no model call id). Otherwise, first-party CAPI requests fall back to the runtime's agent task id — the same value the runtime emits as the `X-Agent-Task-Id` header — while custom-provider requests fall back to the model call id. - [JsonPropertyName("agentInvocationId")] - public string? AgentInvocationId { get; set; } + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public InstructionDiscoveryPathLocation(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } - /// Gets or sets the headers value. - [JsonPropertyName("headers")] - public IDictionary> Headers { get => field ??= new Dictionary>(); set; } + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; - /// Coarse classification of the interaction that produced this request. Open string for forward-compatibility; known values include `conversation-agent`, `conversation-subagent`, `conversation-sampling`, `conversation-background`, `conversation-compaction`, and `conversation-user`. Absent when the runtime did not classify the request. Comes from the runtime's per-request agent context independently of transport; on the CAPI transport the runtime derives the upstream `X-Interaction-Type` header from this same context. - [JsonPropertyName("interactionType")] - public string? InteractionType { get; set; } + /// Instructions live in user-level configuration. + public static InstructionDiscoveryPathLocation User { get; } = new("user"); - /// HTTP method, e.g. GET, POST. - [JsonPropertyName("method")] - public string Method { get; set; } = string.Empty; + /// Instructions live in repository-level configuration. + public static InstructionDiscoveryPathLocation Repository { get; } = new("repository"); - /// Stable identity of the immediate parent trajectory. Present for child trajectories such as subagents and conversation-sampling requests; absent for root-agent and non-agent requests. - [JsonPropertyName("parentAgentId")] - public string? ParentAgentId { get; set; } + /// Instructions live under the current working directory. + public static InstructionDiscoveryPathLocation WorkingDirectory { get; } = new("working-directory"); - /// Opaque runtime-minted id, unique per in-flight request. The SDK uses this to correlate httpRequestChunk frames and to address its httpResponseStart / httpResponseChunk replies back to the runtime. - [JsonPropertyName("requestId")] - public string RequestId { get; set; } = string.Empty; + /// Instructions live in plugin-provided configuration. + public static InstructionDiscoveryPathLocation Plugin { get; } = new("plugin"); - /// Id of the runtime session that triggered this request, when one is in scope. Absent for requests issued outside any session (e.g. startup model-catalog or capability resolution). This is a payload field — not a dispatch key — because the client-global API is registered process-wide rather than per session. - [JsonPropertyName("sessionId")] - public string? SessionId { get; set; } + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(InstructionDiscoveryPathLocation left, InstructionDiscoveryPathLocation right) => left.Equals(right); - /// Transport the runtime would otherwise use for this request. `http` (the default when absent) covers plain HTTP and SSE responses; `websocket` indicates a full-duplex message channel where each body chunk maps to one WebSocket message and the `binary` flag distinguishes text from binary frames. The SDK consumer uses this to decide whether to service the request with an HTTP client or a WebSocket client. It is the one piece of request metadata the consumer cannot reliably infer from the URL or headers alone. - [JsonPropertyName("transport")] - public LlmInferenceHttpRequestStartTransport? Transport { get; set; } + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(InstructionDiscoveryPathLocation left, InstructionDiscoveryPathLocation right) => !(left == right); - /// Absolute request URL. - [JsonPropertyName("url")] - public string Url { get; set; } = string.Empty; -} + /// + public override bool Equals(object? obj) => obj is InstructionDiscoveryPathLocation other && Equals(other); -/// Acknowledgement. The SDK is free to ignore the ack and treat chunk delivery as fire-and-forget. -[Experimental(Diagnostics.Experimental)] -public sealed class LlmInferenceHttpRequestChunkResult -{ + /// + public bool Equals(InstructionDiscoveryPathLocation other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override InstructionDiscoveryPathLocation Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, InstructionDiscoveryPathLocation value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(InstructionDiscoveryPathLocation)); + } + } } -/// A request body chunk or cancellation signal. + +/// Optional completion hint for the input (e.g. 'directory' for filesystem path completion). [Experimental(Diagnostics.Experimental)] -public sealed class LlmInferenceHttpRequestChunkRequest +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct SlashCommandInputCompletion : IEquatable { - /// Identity of the agent invocation (one agentic loop) this body chunk belongs to, matching the `agentInvocationId` semantics on httpRequestStart. Carried per chunk so a persistent transport can attribute successive turns correctly: when a WebSocket connection is reused across turns, the httpRequestStart identity reflects only the turn that opened the connection, so each later turn stamps its own invocation id here. Absent when the runtime has no invocation context for the request, or on the plain-HTTP transport where every request has its own httpRequestStart. - [JsonPropertyName("agentInvocationId")] - public string? AgentInvocationId { get; set; } + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public SlashCommandInputCompletion(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// Input should complete filesystem directories. + public static SlashCommandInputCompletion Directory { get; } = new("directory"); - /// When true, `data` is base64-encoded bytes. When absent or false, `data` is UTF-8 text. - [JsonPropertyName("binary")] - public bool? Binary { get; set; } + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SlashCommandInputCompletion left, SlashCommandInputCompletion right) => left.Equals(right); - /// When true, the runtime is cancelling the in-flight request (e.g. upstream consumer aborted). `data` is ignored. Implies end-of-request. - [JsonPropertyName("cancel")] - public bool? Cancel { get; set; } + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SlashCommandInputCompletion left, SlashCommandInputCompletion right) => !(left == right); - /// Optional human-readable reason for the cancellation, propagated for logging. - [JsonPropertyName("cancelReason")] - public string? CancelReason { get; set; } + /// + public override bool Equals(object? obj) => obj is SlashCommandInputCompletion other && Equals(other); - /// Body byte range. UTF-8 text when `binary` is absent or false; base64-encoded bytes when `binary` is true. May be empty. - [JsonPropertyName("data")] - public string Data { get; set; } = string.Empty; + /// + public bool Equals(SlashCommandInputCompletion other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); - /// When true, this is the final body chunk for the request. The SDK may rely on having received an end-marked chunk before treating the request body as complete. - [JsonPropertyName("end")] - public bool? End { get; set; } + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); - /// Matches the requestId from the originating httpRequestStart frame. - [JsonPropertyName("requestId")] - public string RequestId { get; set; } = string.Empty; + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override SlashCommandInputCompletion Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, SlashCommandInputCompletion value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SlashCommandInputCompletion)); + } + } } -/// Client environment metadata describing the process that produced a telemetry event. + +/// Coarse command category for grouping and behavior: runtime built-in, skill-backed command, or SDK/client-owned command. [Experimental(Diagnostics.Experimental)] -public sealed class GitHubTelemetryClientInfo +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct SlashCommandKind : IEquatable { - /// Copilot CLI version string. - [JsonPropertyName("cli_version")] - public string CliVersion { get; set; } = string.Empty; + private readonly string? _value; - /// Name of the client application. - [JsonPropertyName("client_name")] - public string? ClientName { get; set; } + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public SlashCommandKind(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } - /// Type of client. - [JsonPropertyName("client_type")] - public string? ClientType { get; set; } + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; - /// Copilot subscription plan, when known. - [JsonPropertyName("copilot_plan")] - public string? CopilotPlan { get; set; } + /// Command implemented by the runtime. + public static SlashCommandKind Builtin { get; } = new("builtin"); - /// Stable machine identifier for the device. - [JsonPropertyName("dev_device_id")] - public string? DevDeviceId { get; set; } + /// Command backed by a skill. + public static SlashCommandKind Skill { get; } = new("skill"); - /// Whether the user is a GitHub/Microsoft staff member. - [JsonPropertyName("is_staff")] - public bool? IsStaff { get; set; } + /// Command registered by an SDK client or extension. + public static SlashCommandKind Client { get; } = new("client"); - /// Node.js runtime version string. - [JsonPropertyName("node_version")] - public string NodeVersion { get; set; } = string.Empty; + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SlashCommandKind left, SlashCommandKind right) => left.Equals(right); - /// Operating system architecture (e.g. arm64, x64). - [JsonPropertyName("os_arch")] - public string OsArch { get; set; } = string.Empty; + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SlashCommandKind left, SlashCommandKind right) => !(left == right); - /// Operating system platform (e.g. darwin, linux, win32). - [JsonPropertyName("os_platform")] - public string OsPlatform { get; set; } = string.Empty; + /// + public override bool Equals(object? obj) => obj is SlashCommandKind other && Equals(other); - /// Operating system version string. - [JsonPropertyName("os_version")] - public string OsVersion { get; set; } = string.Empty; + /// + public bool Equals(SlashCommandKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override SlashCommandKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, SlashCommandKind value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SlashCommandKind)); + } + } } -/// A single telemetry event in the runtime's native GitHub-shaped telemetry format, forwarded verbatim to opted-in hosts. The `restricted` flag on the enclosing GitHubTelemetryNotification distinguishes standard from restricted events; the payload shape is identical for both. + +/// Path conventions used by this filesystem. [Experimental(Diagnostics.Experimental)] -public sealed class GitHubTelemetryEvent +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct SessionFsSetProviderConventions : IEquatable { - /// Client environment metadata. - [JsonPropertyName("client")] - public GitHubTelemetryClientInfo? Client { get; set; } + private readonly string? _value; - /// Copilot tracking ID for user-level attribution. - [JsonPropertyName("copilot_tracking_id")] - public string? CopilotTrackingId { get; set; } + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public SessionFsSetProviderConventions(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } - /// Timestamp when the event was created (ISO 8601 format). - [JsonPropertyName("created_at")] - public string? CreatedAt { get; set; } + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; - /// Experiment assignment context. - [JsonPropertyName("exp_assignment_context")] - public string? ExpAssignmentContext { get; set; } + /// Paths use Windows path conventions. + public static SessionFsSetProviderConventions Windows { get; } = new("windows"); - /// Feature flags enabled for this session, as a map from flag to value. - [JsonPropertyName("features")] - public IDictionary? Features { get; set; } + /// Paths use POSIX path conventions. + public static SessionFsSetProviderConventions Posix { get; } = new("posix"); - /// Event type/kind (e.g. get_completion_with_tools_turn, tool_call_executed). - [JsonPropertyName("kind")] - public string Kind { get; set; } = string.Empty; + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SessionFsSetProviderConventions left, SessionFsSetProviderConventions right) => left.Equals(right); - /// Numeric metrics as a map from key to value. - [JsonPropertyName("metrics")] - public IDictionary Metrics { get => field ??= new Dictionary(); set; } + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SessionFsSetProviderConventions left, SessionFsSetProviderConventions right) => !(left == right); - /// Reference to the model call that produced this event. - [JsonPropertyName("model_call_id")] - public string? ModelCallId { get; set; } + /// + public override bool Equals(object? obj) => obj is SessionFsSetProviderConventions other && Equals(other); - /// String-valued properties as a map from key to value. - [JsonPropertyName("properties")] - public IDictionary Properties { get => field ??= new Dictionary(); set; } + /// + public bool Equals(SessionFsSetProviderConventions other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); - /// Session identifier the event belongs to. - [JsonPropertyName("session_id")] - public string? SessionId { get; set; } -} + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); -/// Payload for a `gitHubTelemetry.event` notification: a single GitHub telemetry event the runtime forwards to a host connection that opted into telemetry forwarding during the `server.connect` handshake. -[Experimental(Diagnostics.Experimental)] -public sealed class GitHubTelemetryNotification -{ - /// The telemetry event, in the runtime's native GitHub-shaped telemetry format. - [JsonPropertyName("event")] - public GitHubTelemetryEvent Event { get => field ??= new(); set; } + /// + public override string ToString() => Value; - /// Whether this is a restricted telemetry event (cli.restricted_telemetry). Hosts must route restricted events to first-party Microsoft stores only. - [JsonPropertyName("restricted")] - public bool Restricted { get; set; } + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override SessionFsSetProviderConventions Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } - /// Session the telemetry event belongs to, when it is session-scoped. Omitted for sessionless events (for example, `server.sendTelemetry` calls with no session id), which are still forwarded to opted-in connections. - [JsonPropertyName("sessionId")] - public string? SessionId { get; set; } + /// + public override void Write(Utf8JsonWriter writer, SessionFsSetProviderConventions value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionFsSetProviderConventions)); + } + } } -/// Resolved Anthropic adaptive-thinking capability for a model. + +/// Repository host type. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct AdaptiveThinkingSupport : IEquatable +public readonly struct SessionContextHostType : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public AdaptiveThinkingSupport(string value) + public SessionContextHostType(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The model does not accept thinking.type='adaptive'. - public static AdaptiveThinkingSupport Unsupported { get; } = new("unsupported"); - - /// The model accepts adaptive thinking but also accepts thinking.type='enabled'. - public static AdaptiveThinkingSupport Optional { get; } = new("optional"); + /// Session repository is hosted on GitHub. + public static SessionContextHostType GitHub { get; } = new("github"); - /// The model only accepts adaptive thinking and rejects thinking.type='enabled' with HTTP 400 (e.g. opus-4.7/4.8). - public static AdaptiveThinkingSupport Required { get; } = new("required"); + /// Session repository is hosted on Azure DevOps. + public static SessionContextHostType Ado { get; } = new("ado"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(AdaptiveThinkingSupport left, AdaptiveThinkingSupport right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SessionContextHostType left, SessionContextHostType right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(AdaptiveThinkingSupport left, AdaptiveThinkingSupport right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SessionContextHostType left, SessionContextHostType right) => !(left == right); /// - public override bool Equals(object? obj) => obj is AdaptiveThinkingSupport other && Equals(other); + public override bool Equals(object? obj) => obj is SessionContextHostType other && Equals(other); /// - public bool Equals(AdaptiveThinkingSupport other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(SessionContextHostType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -13049,65 +15996,62 @@ public AdaptiveThinkingSupport(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override AdaptiveThinkingSupport Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override SessionContextHostType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, AdaptiveThinkingSupport value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, SessionContextHostType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AdaptiveThinkingSupport)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionContextHostType)); } } } -/// Model capability category for grouping in the model picker. +/// Whether the remote task originated from CCA or CLI `--remote`. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct ModelPickerCategory : IEquatable +public readonly struct RemoteSessionMetadataTaskType : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public ModelPickerCategory(string value) + public RemoteSessionMetadataTaskType(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Lightweight model category optimized for faster, lower-cost interactions. - public static ModelPickerCategory Lightweight { get; } = new("lightweight"); - - /// Versatile model category suitable for a broad range of tasks. - public static ModelPickerCategory Versatile { get; } = new("versatile"); + /// GitHub Copilot coding agent task. + public static RemoteSessionMetadataTaskType Cca { get; } = new("cca"); - /// Powerful model category optimized for complex tasks. - public static ModelPickerCategory Powerful { get; } = new("powerful"); + /// CLI remote task. + public static RemoteSessionMetadataTaskType Cli { get; } = new("cli"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(ModelPickerCategory left, ModelPickerCategory right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(RemoteSessionMetadataTaskType left, RemoteSessionMetadataTaskType right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(ModelPickerCategory left, ModelPickerCategory right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(RemoteSessionMetadataTaskType left, RemoteSessionMetadataTaskType right) => !(left == right); /// - public override bool Equals(object? obj) => obj is ModelPickerCategory other && Equals(other); + public override bool Equals(object? obj) => obj is RemoteSessionMetadataTaskType other && Equals(other); /// - public bool Equals(ModelPickerCategory other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(RemoteSessionMetadataTaskType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -13115,68 +16059,62 @@ public ModelPickerCategory(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override ModelPickerCategory Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override RemoteSessionMetadataTaskType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, ModelPickerCategory value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, RemoteSessionMetadataTaskType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ModelPickerCategory)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(RemoteSessionMetadataTaskType)); } } } -/// Relative cost tier for token-based billing users. +/// Step status. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct ModelPickerPriceCategory : IEquatable +public readonly struct SessionsOpenProgressStatus : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public ModelPickerPriceCategory(string value) + public SessionsOpenProgressStatus(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Lowest relative token cost tier. - public static ModelPickerPriceCategory Low { get; } = new("low"); - - /// Medium relative token cost tier. - public static ModelPickerPriceCategory Medium { get; } = new("medium"); - - /// High relative token cost tier. - public static ModelPickerPriceCategory High { get; } = new("high"); + /// The step has started and has not yet finished. + public static SessionsOpenProgressStatus InProgress { get; } = new("in-progress"); - /// Highest relative token cost tier. - public static ModelPickerPriceCategory VeryHigh { get; } = new("very_high"); + /// The step has completed successfully. + public static SessionsOpenProgressStatus Complete { get; } = new("complete"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(ModelPickerPriceCategory left, ModelPickerPriceCategory right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SessionsOpenProgressStatus left, SessionsOpenProgressStatus right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(ModelPickerPriceCategory left, ModelPickerPriceCategory right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SessionsOpenProgressStatus left, SessionsOpenProgressStatus right) => !(left == right); /// - public override bool Equals(object? obj) => obj is ModelPickerPriceCategory other && Equals(other); + public override bool Equals(object? obj) => obj is SessionsOpenProgressStatus other && Equals(other); /// - public bool Equals(ModelPickerPriceCategory other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(SessionsOpenProgressStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -13184,65 +16122,74 @@ public ModelPickerPriceCategory(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override ModelPickerPriceCategory Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override SessionsOpenProgressStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, ModelPickerPriceCategory value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, SessionsOpenProgressStatus value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ModelPickerPriceCategory)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionsOpenProgressStatus)); } } } -/// Current policy state for this model. +/// Handoff step. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct ModelPolicyState : IEquatable +public readonly struct SessionsOpenProgressStep : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public ModelPolicyState(string value) + public SessionsOpenProgressStep(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The model is enabled by policy. - public static ModelPolicyState Enabled { get; } = new("enabled"); + /// Loading the source session's events from the remote service. + public static SessionsOpenProgressStep LoadSession { get; } = new("load-session"); - /// The model is disabled by policy. - public static ModelPolicyState Disabled { get; } = new("disabled"); + /// Validating that the local repository matches the remote session's repository. + public static SessionsOpenProgressStep ValidateRepo { get; } = new("validate-repo"); - /// No explicit policy is configured for the model. - public static ModelPolicyState Unconfigured { get; } = new("unconfigured"); + /// Checking the local working tree for uncommitted changes that would block the handoff. + public static SessionsOpenProgressStep CheckChanges { get; } = new("check-changes"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(ModelPolicyState left, ModelPolicyState right) => left.Equals(right); + /// Checking out the branch associated with the remote session in the local working tree. + public static SessionsOpenProgressStep CheckoutBranch { get; } = new("checkout-branch"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(ModelPolicyState left, ModelPolicyState right) => !(left == right); + /// Creating the new local session and seeding it with the source session's events. + public static SessionsOpenProgressStep CreateSession { get; } = new("create-session"); + + /// Persisting the newly-created local session to disk. + public static SessionsOpenProgressStep SaveSession { get; } = new("save-session"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SessionsOpenProgressStep left, SessionsOpenProgressStep right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SessionsOpenProgressStep left, SessionsOpenProgressStep right) => !(left == right); /// - public override bool Equals(object? obj) => obj is ModelPolicyState other && Equals(other); + public override bool Equals(object? obj) => obj is SessionsOpenProgressStep other && Equals(other); /// - public bool Equals(ModelPolicyState other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(SessionsOpenProgressStep other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -13250,68 +16197,71 @@ public ModelPolicyState(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override ModelPolicyState Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override SessionsOpenProgressStep Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, ModelPolicyState value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, SessionsOpenProgressStep value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ModelPolicyState)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionsOpenProgressStep)); } } } -/// Server transport type: stdio, http, sse (deprecated), or memory. +/// Outcome of the open request. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct DiscoveredMcpServerType : IEquatable +public readonly struct SessionsOpenStatus : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public DiscoveredMcpServerType(string value) + public SessionsOpenStatus(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Server communicates over stdio with a local child process. - public static DiscoveredMcpServerType Stdio { get; } = new("stdio"); + /// A new session was created. + public static SessionsOpenStatus Created { get; } = new("created"); - /// Server communicates over streamable HTTP. - public static DiscoveredMcpServerType Http { get; } = new("http"); + /// An existing session was loaded or reattached. + public static SessionsOpenStatus Resumed { get; } = new("resumed"); - /// Server communicates over Server-Sent Events (deprecated). - public static DiscoveredMcpServerType Sse { get; } = new("sse"); + /// No matching persisted session was found. + public static SessionsOpenStatus NotFound { get; } = new("not_found"); - /// Server is backed by an in-memory runtime implementation. - public static DiscoveredMcpServerType Memory { get; } = new("memory"); + /// Connected to an existing remote session. + public static SessionsOpenStatus Connected { get; } = new("connected"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(DiscoveredMcpServerType left, DiscoveredMcpServerType right) => left.Equals(right); + /// Remote session was handed off to a new local session. + public static SessionsOpenStatus HandedOff { get; } = new("handed_off"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(DiscoveredMcpServerType left, DiscoveredMcpServerType right) => !(left == right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SessionsOpenStatus left, SessionsOpenStatus right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SessionsOpenStatus left, SessionsOpenStatus right) => !(left == right); /// - public override bool Equals(object? obj) => obj is DiscoveredMcpServerType other && Equals(other); + public override bool Equals(object? obj) => obj is SessionsOpenStatus other && Equals(other); /// - public bool Equals(DiscoveredMcpServerType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(SessionsOpenStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -13319,68 +16269,62 @@ public DiscoveredMcpServerType(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override DiscoveredMcpServerType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override SessionsOpenStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, DiscoveredMcpServerType value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, SessionsOpenStatus value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DiscoveredMcpServerType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionsOpenStatus)); } } } -/// Which tier this directory belongs to. +/// Neutral SDK discriminator for the connected remote session kind. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct SkillDiscoveryScope : IEquatable +public readonly struct ConnectedRemoteSessionMetadataKind : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public SkillDiscoveryScope(string value) + public ConnectedRemoteSessionMetadataKind(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// A project's repository skill directory. - public static SkillDiscoveryScope Project { get; } = new("project"); - - /// The user's personal Copilot skill directory. - public static SkillDiscoveryScope PersonalCopilot { get; } = new("personal-copilot"); - - /// The user's personal agents skill directory. - public static SkillDiscoveryScope PersonalAgents { get; } = new("personal-agents"); + /// Remote CLI session. + public static ConnectedRemoteSessionMetadataKind RemoteSession { get; } = new("remote-session"); - /// A configured custom skill directory. - public static SkillDiscoveryScope Custom { get; } = new("custom"); + /// GitHub Copilot coding agent session. + public static ConnectedRemoteSessionMetadataKind CodingAgent { get; } = new("coding-agent"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(SkillDiscoveryScope left, SkillDiscoveryScope right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(ConnectedRemoteSessionMetadataKind left, ConnectedRemoteSessionMetadataKind right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(SkillDiscoveryScope left, SkillDiscoveryScope right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(ConnectedRemoteSessionMetadataKind left, ConnectedRemoteSessionMetadataKind right) => !(left == right); /// - public override bool Equals(object? obj) => obj is SkillDiscoveryScope other && Equals(other); + public override bool Equals(object? obj) => obj is ConnectedRemoteSessionMetadataKind other && Equals(other); /// - public bool Equals(SkillDiscoveryScope other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(ConnectedRemoteSessionMetadataKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -13388,74 +16332,65 @@ public SkillDiscoveryScope(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override SkillDiscoveryScope Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override ConnectedRemoteSessionMetadataKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, SkillDiscoveryScope value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, ConnectedRemoteSessionMetadataKind value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SkillDiscoveryScope)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ConnectedRemoteSessionMetadataKind)); } } } -/// Where the agent definition was loaded from. +/// Which session sources to include. Defaults to `local` for backward compatibility. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct AgentInfoSource : IEquatable +public readonly struct SessionSource : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public AgentInfoSource(string value) + public SessionSource(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Agent loaded from the user's personal agent configuration. - public static AgentInfoSource User { get; } = new("user"); - - /// Agent loaded from the current project's repository configuration. - public static AgentInfoSource Project { get; } = new("project"); - - /// Agent inherited from a parent project or workspace. - public static AgentInfoSource Inherited { get; } = new("inherited"); - - /// Agent provided by a remote runtime or service. - public static AgentInfoSource Remote { get; } = new("remote"); + /// Return only local sessions. + public static SessionSource Local { get; } = new("local"); - /// Agent contributed by an installed plugin. - public static AgentInfoSource Plugin { get; } = new("plugin"); + /// Return only remote sessions. + public static SessionSource Remote { get; } = new("remote"); - /// Agent built into the Copilot runtime. - public static AgentInfoSource Builtin { get; } = new("builtin"); + /// Return both local and remote sessions. + public static SessionSource All { get; } = new("all"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(AgentInfoSource left, AgentInfoSource right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SessionSource left, SessionSource right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(AgentInfoSource left, AgentInfoSource right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SessionSource left, SessionSource right) => !(left == right); /// - public override bool Equals(object? obj) => obj is AgentInfoSource other && Equals(other); + public override bool Equals(object? obj) => obj is SessionSource other && Equals(other); /// - public bool Equals(AgentInfoSource other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(SessionSource other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -13463,62 +16398,71 @@ public AgentInfoSource(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override AgentInfoSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override SessionSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, AgentInfoSource value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, SessionSource value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentInfoSource)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionSource)); } } } -/// Which tier this directory belongs to. +/// Kind of attention required when status === "attention". Meaningful only when status === "attention". [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct AgentDiscoveryPathScope : IEquatable +public readonly struct AgentRegistryLiveTargetEntryAttentionKind : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public AgentDiscoveryPathScope(string value) + public AgentRegistryLiveTargetEntryAttentionKind(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The user's personal agent configuration directory. - public static AgentDiscoveryPathScope User { get; } = new("user"); + /// Session is blocked on an unrecoverable error. + public static AgentRegistryLiveTargetEntryAttentionKind Error { get; } = new("error"); - /// A project's repository agent directory. - public static AgentDiscoveryPathScope Project { get; } = new("project"); + /// Session is waiting for a tool-permission decision. + public static AgentRegistryLiveTargetEntryAttentionKind Permission { get; } = new("permission"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(AgentDiscoveryPathScope left, AgentDiscoveryPathScope right) => left.Equals(right); + /// Session is waiting for the user to approve or reject a plan. + public static AgentRegistryLiveTargetEntryAttentionKind ExitPlan { get; } = new("exit_plan"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(AgentDiscoveryPathScope left, AgentDiscoveryPathScope right) => !(left == right); + /// Session is waiting on an elicitation prompt. + public static AgentRegistryLiveTargetEntryAttentionKind Elicitation { get; } = new("elicitation"); + + /// Session is waiting for free-form user input. + public static AgentRegistryLiveTargetEntryAttentionKind UserInput { get; } = new("user_input"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(AgentRegistryLiveTargetEntryAttentionKind left, AgentRegistryLiveTargetEntryAttentionKind right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(AgentRegistryLiveTargetEntryAttentionKind left, AgentRegistryLiveTargetEntryAttentionKind right) => !(left == right); /// - public override bool Equals(object? obj) => obj is AgentDiscoveryPathScope other && Equals(other); + public override bool Equals(object? obj) => obj is AgentRegistryLiveTargetEntryAttentionKind other && Equals(other); /// - public bool Equals(AgentDiscoveryPathScope other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(AgentRegistryLiveTargetEntryAttentionKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -13526,68 +16470,62 @@ public AgentDiscoveryPathScope(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override AgentDiscoveryPathScope Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override AgentRegistryLiveTargetEntryAttentionKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, AgentDiscoveryPathScope value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, AgentRegistryLiveTargetEntryAttentionKind value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentDiscoveryPathScope)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentRegistryLiveTargetEntryAttentionKind)); } } } -/// Where this source lives — used for UI grouping. +/// Process kind tag for the registry entry. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct InstructionSourceLocation : IEquatable +public readonly struct AgentRegistryLiveTargetEntryKind : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public InstructionSourceLocation(string value) + public AgentRegistryLiveTargetEntryKind(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Instructions live in user-level configuration. - public static InstructionSourceLocation User { get; } = new("user"); - - /// Instructions live in repository-level configuration. - public static InstructionSourceLocation Repository { get; } = new("repository"); - - /// Instructions live under the current working directory. - public static InstructionSourceLocation WorkingDirectory { get; } = new("working-directory"); + /// Interactive Copilot CLI exposing a UI server (legacy/normal CLI process). + public static AgentRegistryLiveTargetEntryKind UiServer { get; } = new("ui-server"); - /// Instructions live in plugin-provided configuration. - public static InstructionSourceLocation Plugin { get; } = new("plugin"); + /// Headless `--server --managed-server` child spawned by a controller. + public static AgentRegistryLiveTargetEntryKind ManagedServer { get; } = new("managed-server"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(InstructionSourceLocation left, InstructionSourceLocation right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(AgentRegistryLiveTargetEntryKind left, AgentRegistryLiveTargetEntryKind right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(InstructionSourceLocation left, InstructionSourceLocation right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(AgentRegistryLiveTargetEntryKind left, AgentRegistryLiveTargetEntryKind right) => !(left == right); /// - public override bool Equals(object? obj) => obj is InstructionSourceLocation other && Equals(other); + public override bool Equals(object? obj) => obj is AgentRegistryLiveTargetEntryKind other && Equals(other); /// - public bool Equals(InstructionSourceLocation other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(AgentRegistryLiveTargetEntryKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -13595,77 +16533,62 @@ public InstructionSourceLocation(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override InstructionSourceLocation Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override AgentRegistryLiveTargetEntryKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, InstructionSourceLocation value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, AgentRegistryLiveTargetEntryKind value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(InstructionSourceLocation)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentRegistryLiveTargetEntryKind)); } } } -/// Category of instruction source — used for merge logic. +/// How the most recent turn ended (clean vs aborted). Lets the renderer distinguish done from done_cancelled. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct InstructionSourceType : IEquatable +public readonly struct AgentRegistryLiveTargetEntryLastTerminalEvent : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public InstructionSourceType(string value) + public AgentRegistryLiveTargetEntryLastTerminalEvent(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Instructions loaded from the user's home configuration. - public static InstructionSourceType Home { get; } = new("home"); - - /// Instructions loaded from repository-scoped files. - public static InstructionSourceType Repo { get; } = new("repo"); - - /// Instructions loaded from model-specific files. - public static InstructionSourceType Model { get; } = new("model"); - - /// Instructions loaded from VS Code instruction files. - public static InstructionSourceType Vscode { get; } = new("vscode"); - - /// Instructions discovered from nested agent files. - public static InstructionSourceType NestedAgents { get; } = new("nested-agents"); - - /// Instructions inherited from child instruction files. - public static InstructionSourceType ChildInstructions { get; } = new("child-instructions"); + /// Last turn ended cleanly (model returned a final assistant message). + public static AgentRegistryLiveTargetEntryLastTerminalEvent TurnEnd { get; } = new("turn_end"); - /// Instructions supplied by an installed plugin. - public static InstructionSourceType Plugin { get; } = new("plugin"); + /// Last turn was aborted (e.g. user interrupted). + public static AgentRegistryLiveTargetEntryLastTerminalEvent Abort { get; } = new("abort"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(InstructionSourceType left, InstructionSourceType right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(AgentRegistryLiveTargetEntryLastTerminalEvent left, AgentRegistryLiveTargetEntryLastTerminalEvent right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(InstructionSourceType left, InstructionSourceType right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(AgentRegistryLiveTargetEntryLastTerminalEvent left, AgentRegistryLiveTargetEntryLastTerminalEvent right) => !(left == right); /// - public override bool Equals(object? obj) => obj is InstructionSourceType other && Equals(other); + public override bool Equals(object? obj) => obj is AgentRegistryLiveTargetEntryLastTerminalEvent other && Equals(other); /// - public bool Equals(InstructionSourceType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(AgentRegistryLiveTargetEntryLastTerminalEvent other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -13673,62 +16596,68 @@ public InstructionSourceType(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override InstructionSourceType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override AgentRegistryLiveTargetEntryLastTerminalEvent Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, InstructionSourceType value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, AgentRegistryLiveTargetEntryLastTerminalEvent value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(InstructionSourceType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentRegistryLiveTargetEntryLastTerminalEvent)); } } } -/// Whether the target is a single file or a directory of instruction files. +/// Coarse lifecycle status of the foreground session. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct InstructionDiscoveryPathKind : IEquatable +public readonly struct AgentRegistryLiveTargetEntryStatus : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public InstructionDiscoveryPathKind(string value) + public AgentRegistryLiveTargetEntryStatus(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The target is a single instruction file. - public static InstructionDiscoveryPathKind File { get; } = new("file"); + /// Session is actively processing a turn. + public static AgentRegistryLiveTargetEntryStatus Working { get; } = new("working"); - /// The target is a directory that holds instruction files. - public static InstructionDiscoveryPathKind Directory { get; } = new("directory"); + /// Session is idle, waiting for input. + public static AgentRegistryLiveTargetEntryStatus Waiting { get; } = new("waiting"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(InstructionDiscoveryPathKind left, InstructionDiscoveryPathKind right) => left.Equals(right); + /// Last turn completed successfully. + public static AgentRegistryLiveTargetEntryStatus Done { get; } = new("done"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(InstructionDiscoveryPathKind left, InstructionDiscoveryPathKind right) => !(left == right); + /// Session needs user attention (see attentionKind for the specific reason). + public static AgentRegistryLiveTargetEntryStatus Attention { get; } = new("attention"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(AgentRegistryLiveTargetEntryStatus left, AgentRegistryLiveTargetEntryStatus right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(AgentRegistryLiveTargetEntryStatus left, AgentRegistryLiveTargetEntryStatus right) => !(left == right); /// - public override bool Equals(object? obj) => obj is InstructionDiscoveryPathKind other && Equals(other); + public override bool Equals(object? obj) => obj is AgentRegistryLiveTargetEntryStatus other && Equals(other); /// - public bool Equals(InstructionDiscoveryPathKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(AgentRegistryLiveTargetEntryStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -13736,68 +16665,65 @@ public InstructionDiscoveryPathKind(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override InstructionDiscoveryPathKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override AgentRegistryLiveTargetEntryStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, InstructionDiscoveryPathKind value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, AgentRegistryLiveTargetEntryStatus value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(InstructionDiscoveryPathKind)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentRegistryLiveTargetEntryStatus)); } } } -/// Which tier this target belongs to. +/// Categorized reason for log-open failure. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct InstructionDiscoveryPathLocation : IEquatable +public readonly struct AgentRegistryLogCaptureOpenErrorReason : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public InstructionDiscoveryPathLocation(string value) + public AgentRegistryLogCaptureOpenErrorReason(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Instructions live in user-level configuration. - public static InstructionDiscoveryPathLocation User { get; } = new("user"); - - /// Instructions live in repository-level configuration. - public static InstructionDiscoveryPathLocation Repository { get; } = new("repository"); + /// Filesystem permission denied opening the log file. + public static AgentRegistryLogCaptureOpenErrorReason Permission { get; } = new("permission"); - /// Instructions live under the current working directory. - public static InstructionDiscoveryPathLocation WorkingDirectory { get; } = new("working-directory"); + /// No space left on device. + public static AgentRegistryLogCaptureOpenErrorReason DiskFull { get; } = new("disk_full"); - /// Instructions live in plugin-provided configuration. - public static InstructionDiscoveryPathLocation Plugin { get; } = new("plugin"); + /// Other / uncategorized open failure. + public static AgentRegistryLogCaptureOpenErrorReason Other { get; } = new("other"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(InstructionDiscoveryPathLocation left, InstructionDiscoveryPathLocation right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(AgentRegistryLogCaptureOpenErrorReason left, AgentRegistryLogCaptureOpenErrorReason right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(InstructionDiscoveryPathLocation left, InstructionDiscoveryPathLocation right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(AgentRegistryLogCaptureOpenErrorReason left, AgentRegistryLogCaptureOpenErrorReason right) => !(left == right); /// - public override bool Equals(object? obj) => obj is InstructionDiscoveryPathLocation other && Equals(other); + public override bool Equals(object? obj) => obj is AgentRegistryLogCaptureOpenErrorReason other && Equals(other); /// - public bool Equals(InstructionDiscoveryPathLocation other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(AgentRegistryLogCaptureOpenErrorReason other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -13805,59 +16731,71 @@ public InstructionDiscoveryPathLocation(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override InstructionDiscoveryPathLocation Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override AgentRegistryLogCaptureOpenErrorReason Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, InstructionDiscoveryPathLocation value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, AgentRegistryLogCaptureOpenErrorReason value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(InstructionDiscoveryPathLocation)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentRegistryLogCaptureOpenErrorReason)); } } } -/// Optional completion hint for the input (e.g. 'directory' for filesystem path completion). +/// Which parameter field was invalid. Omitted when the rejection is not field-specific. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct SlashCommandInputCompletion : IEquatable +public readonly struct AgentRegistrySpawnValidationErrorField : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public SlashCommandInputCompletion(string value) + public AgentRegistrySpawnValidationErrorField(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Input should complete filesystem directories. - public static SlashCommandInputCompletion Directory { get; } = new("directory"); + /// The cwd parameter. + public static AgentRegistrySpawnValidationErrorField Cwd { get; } = new("cwd"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(SlashCommandInputCompletion left, SlashCommandInputCompletion right) => left.Equals(right); + /// The session name parameter. + public static AgentRegistrySpawnValidationErrorField Name { get; } = new("name"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(SlashCommandInputCompletion left, SlashCommandInputCompletion right) => !(left == right); + /// The agentName parameter. + public static AgentRegistrySpawnValidationErrorField AgentName { get; } = new("agentName"); + + /// The model parameter. + public static AgentRegistrySpawnValidationErrorField Model { get; } = new("model"); + + /// The permissionMode parameter. + public static AgentRegistrySpawnValidationErrorField PermissionMode { get; } = new("permissionMode"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(AgentRegistrySpawnValidationErrorField left, AgentRegistrySpawnValidationErrorField right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(AgentRegistrySpawnValidationErrorField left, AgentRegistrySpawnValidationErrorField right) => !(left == right); /// - public override bool Equals(object? obj) => obj is SlashCommandInputCompletion other && Equals(other); + public override bool Equals(object? obj) => obj is AgentRegistrySpawnValidationErrorField other && Equals(other); /// - public bool Equals(SlashCommandInputCompletion other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(AgentRegistrySpawnValidationErrorField other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -13865,65 +16803,74 @@ public SlashCommandInputCompletion(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override SlashCommandInputCompletion Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override AgentRegistrySpawnValidationErrorField Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, SlashCommandInputCompletion value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, AgentRegistrySpawnValidationErrorField value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SlashCommandInputCompletion)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentRegistrySpawnValidationErrorField)); } } } -/// Coarse command category for grouping and behavior: runtime built-in, skill-backed command, or SDK/client-owned command. +/// Categorized reason for the rejection. Low-cardinality enum so telemetry can aggregate by reason without leaking raw paths or agent/model names. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct SlashCommandKind : IEquatable +public readonly struct AgentRegistrySpawnValidationErrorReason : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public SlashCommandKind(string value) + public AgentRegistrySpawnValidationErrorReason(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Command implemented by the runtime. - public static SlashCommandKind Builtin { get; } = new("builtin"); + /// Provided cwd does not exist on disk. + public static AgentRegistrySpawnValidationErrorReason CwdNotFound { get; } = new("cwd-not-found"); - /// Command backed by a skill. - public static SlashCommandKind Skill { get; } = new("skill"); + /// Provided cwd exists but is not a directory. + public static AgentRegistrySpawnValidationErrorReason CwdNotDirectory { get; } = new("cwd-not-directory"); - /// Command registered by an SDK client or extension. - public static SlashCommandKind Client { get; } = new("client"); + /// Session name failed validateSessionName. + public static AgentRegistrySpawnValidationErrorReason InvalidName { get; } = new("invalid-name"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(SlashCommandKind left, SlashCommandKind right) => left.Equals(right); + /// Requested agent name was not found in builtin or custom agents. + public static AgentRegistrySpawnValidationErrorReason UnknownAgent { get; } = new("unknown-agent"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(SlashCommandKind left, SlashCommandKind right) => !(left == right); + /// Requested model is not available to this session. + public static AgentRegistrySpawnValidationErrorReason UnknownModel { get; } = new("unknown-model"); + + /// Caller asked for permissionMode='yolo' but the controller is not currently in allow-all mode. + public static AgentRegistrySpawnValidationErrorReason YoloNotAllowed { get; } = new("yolo-not-allowed"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(AgentRegistrySpawnValidationErrorReason left, AgentRegistrySpawnValidationErrorReason right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(AgentRegistrySpawnValidationErrorReason left, AgentRegistrySpawnValidationErrorReason right) => !(left == right); /// - public override bool Equals(object? obj) => obj is SlashCommandKind other && Equals(other); + public override bool Equals(object? obj) => obj is AgentRegistrySpawnValidationErrorReason other && Equals(other); /// - public bool Equals(SlashCommandKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(AgentRegistrySpawnValidationErrorReason other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -13931,62 +16878,62 @@ public SlashCommandKind(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override SlashCommandKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override AgentRegistrySpawnValidationErrorReason Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, SlashCommandKind value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, AgentRegistrySpawnValidationErrorReason value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SlashCommandKind)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentRegistrySpawnValidationErrorReason)); } } } -/// Path conventions used by this filesystem. +/// Permission posture for the new session. 'yolo' requires the controller-local session to currently be in allow-all mode. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct SessionFsSetProviderConventions : IEquatable +public readonly struct AgentRegistrySpawnPermissionMode : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public SessionFsSetProviderConventions(string value) + public AgentRegistrySpawnPermissionMode(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Paths use Windows path conventions. - public static SessionFsSetProviderConventions Windows { get; } = new("windows"); + /// Standard permission posture (prompts for each request). + public static AgentRegistrySpawnPermissionMode Default { get; } = new("default"); - /// Paths use POSIX path conventions. - public static SessionFsSetProviderConventions Posix { get; } = new("posix"); + /// Full allow-all (requires the controller-local session to currently be in allow-all mode). + public static AgentRegistrySpawnPermissionMode Yolo { get; } = new("yolo"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(SessionFsSetProviderConventions left, SessionFsSetProviderConventions right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(AgentRegistrySpawnPermissionMode left, AgentRegistrySpawnPermissionMode right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(SessionFsSetProviderConventions left, SessionFsSetProviderConventions right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(AgentRegistrySpawnPermissionMode left, AgentRegistrySpawnPermissionMode right) => !(left == right); /// - public override bool Equals(object? obj) => obj is SessionFsSetProviderConventions other && Equals(other); + public override bool Equals(object? obj) => obj is AgentRegistrySpawnPermissionMode other && Equals(other); /// - public bool Equals(SessionFsSetProviderConventions other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(AgentRegistrySpawnPermissionMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -13994,62 +16941,68 @@ public SessionFsSetProviderConventions(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override SessionFsSetProviderConventions Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override AgentRegistrySpawnPermissionMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, SessionFsSetProviderConventions value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, AgentRegistrySpawnPermissionMode value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionFsSetProviderConventions)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentRegistrySpawnPermissionMode)); } } } -/// Repository host type. +/// The UI mode the agent was in when this message was sent. Defaults to the session's current mode. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct SessionContextHostType : IEquatable +public readonly struct SendAgentMode : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public SessionContextHostType(string value) + public SendAgentMode(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Session repository is hosted on GitHub. - public static SessionContextHostType GitHub { get; } = new("github"); + /// The agent is responding interactively to the user. + public static SendAgentMode Interactive { get; } = new("interactive"); - /// Session repository is hosted on Azure DevOps. - public static SessionContextHostType Ado { get; } = new("ado"); + /// The agent is preparing a plan before making changes. + public static SendAgentMode Plan { get; } = new("plan"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(SessionContextHostType left, SessionContextHostType right) => left.Equals(right); + /// The agent is working autonomously toward task completion. + public static SendAgentMode Autopilot { get; } = new("autopilot"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(SessionContextHostType left, SessionContextHostType right) => !(left == right); + /// The agent is in shell-focused UI mode. + public static SendAgentMode Shell { get; } = new("shell"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SendAgentMode left, SendAgentMode right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SendAgentMode left, SendAgentMode right) => !(left == right); /// - public override bool Equals(object? obj) => obj is SessionContextHostType other && Equals(other); + public override bool Equals(object? obj) => obj is SendAgentMode other && Equals(other); /// - public bool Equals(SessionContextHostType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(SendAgentMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -14057,62 +17010,62 @@ public SessionContextHostType(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override SessionContextHostType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override SendAgentMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, SessionContextHostType value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, SendAgentMode value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionContextHostType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SendAgentMode)); } } } -/// Whether the remote task originated from CCA or CLI `--remote`. +/// How to deliver the message. `enqueue` (default) appends to the message queue. `immediate` interjects during an in-progress turn. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct RemoteSessionMetadataTaskType : IEquatable +public readonly struct SendMode : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public RemoteSessionMetadataTaskType(string value) + public SendMode(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// GitHub Copilot coding agent task. - public static RemoteSessionMetadataTaskType Cca { get; } = new("cca"); + /// Append the message to the normal session queue. + public static SendMode Enqueue { get; } = new("enqueue"); - /// CLI remote task. - public static RemoteSessionMetadataTaskType Cli { get; } = new("cli"); + /// Interject the message during the in-progress turn. + public static SendMode Immediate { get; } = new("immediate"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(RemoteSessionMetadataTaskType left, RemoteSessionMetadataTaskType right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SendMode left, SendMode right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(RemoteSessionMetadataTaskType left, RemoteSessionMetadataTaskType right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SendMode left, SendMode right) => !(left == right); /// - public override bool Equals(object? obj) => obj is RemoteSessionMetadataTaskType other && Equals(other); + public override bool Equals(object? obj) => obj is SendMode other && Equals(other); /// - public bool Equals(RemoteSessionMetadataTaskType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(SendMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -14120,62 +17073,65 @@ public RemoteSessionMetadataTaskType(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override RemoteSessionMetadataTaskType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override SendMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, RemoteSessionMetadataTaskType value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, SendMode value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(RemoteSessionMetadataTaskType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SendMode)); } } } -/// Step status. +/// Log severity level. Determines how the message is displayed in the timeline. Defaults to "info". [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct SessionsOpenProgressStatus : IEquatable +public readonly struct SessionLogLevel : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public SessionsOpenProgressStatus(string value) + public SessionLogLevel(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The step has started and has not yet finished. - public static SessionsOpenProgressStatus InProgress { get; } = new("in-progress"); + /// Informational message. + public static SessionLogLevel Info { get; } = new("info"); - /// The step has completed successfully. - public static SessionsOpenProgressStatus Complete { get; } = new("complete"); + /// Warning message that may require attention. + public static SessionLogLevel Warning { get; } = new("warning"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(SessionsOpenProgressStatus left, SessionsOpenProgressStatus right) => left.Equals(right); + /// Error message describing a failure. + public static SessionLogLevel Error { get; } = new("error"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(SessionsOpenProgressStatus left, SessionsOpenProgressStatus right) => !(left == right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SessionLogLevel left, SessionLogLevel right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SessionLogLevel left, SessionLogLevel right) => !(left == right); /// - public override bool Equals(object? obj) => obj is SessionsOpenProgressStatus other && Equals(other); + public override bool Equals(object? obj) => obj is SessionLogLevel other && Equals(other); /// - public bool Equals(SessionsOpenProgressStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(SessionLogLevel other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -14183,74 +17139,77 @@ public SessionsOpenProgressStatus(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override SessionsOpenProgressStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override SessionLogLevel Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, SessionsOpenProgressStatus value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, SessionLogLevel value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionsOpenProgressStatus)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionLogLevel)); } } } -/// Handoff step. +/// Authentication type. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct SessionsOpenProgressStep : IEquatable +public readonly struct AuthInfoType : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public SessionsOpenProgressStep(string value) + public AuthInfoType(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Loading the source session's events from the remote service. - public static SessionsOpenProgressStep LoadSession { get; } = new("load-session"); + /// Authentication provided by a GitHub App HMAC credential. + public static AuthInfoType Hmac { get; } = new("hmac"); - /// Validating that the local repository matches the remote session's repository. - public static SessionsOpenProgressStep ValidateRepo { get; } = new("validate-repo"); + /// Authentication resolved from environment-provided credentials. + public static AuthInfoType Env { get; } = new("env"); - /// Checking the local working tree for uncommitted changes that would block the handoff. - public static SessionsOpenProgressStep CheckChanges { get; } = new("check-changes"); + /// Authentication from an interactive user sign-in. + public static AuthInfoType User { get; } = new("user"); - /// Checking out the branch associated with the remote session in the local working tree. - public static SessionsOpenProgressStep CheckoutBranch { get; } = new("checkout-branch"); + /// Authentication delegated to the GitHub CLI. + public static AuthInfoType GhCli { get; } = new("gh-cli"); - /// Creating the new local session and seeding it with the source session's events. - public static SessionsOpenProgressStep CreateSession { get; } = new("create-session"); + /// Authentication from an API key credential. + public static AuthInfoType ApiKey { get; } = new("api-key"); - /// Persisting the newly-created local session to disk. - public static SessionsOpenProgressStep SaveSession { get; } = new("save-session"); + /// Authentication from a GitHub token. + public static AuthInfoType Token { get; } = new("token"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(SessionsOpenProgressStep left, SessionsOpenProgressStep right) => left.Equals(right); + /// Authentication from a Copilot API token. + public static AuthInfoType CopilotApiToken { get; } = new("copilot-api-token"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(SessionsOpenProgressStep left, SessionsOpenProgressStep right) => !(left == right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(AuthInfoType left, AuthInfoType right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(AuthInfoType left, AuthInfoType right) => !(left == right); /// - public override bool Equals(object? obj) => obj is SessionsOpenProgressStep other && Equals(other); + public override bool Equals(object? obj) => obj is AuthInfoType other && Equals(other); /// - public bool Equals(SessionsOpenProgressStep other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(AuthInfoType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -14258,71 +17217,68 @@ public SessionsOpenProgressStep(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override SessionsOpenProgressStep Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override AuthInfoType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, SessionsOpenProgressStep value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, AuthInfoType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionsOpenProgressStep)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AuthInfoType)); } } } -/// Outcome of the open request. +/// Source category for a collected debug bundle entry. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct SessionsOpenStatus : IEquatable +public readonly struct DebugCollectLogsSource : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public SessionsOpenStatus(string value) + public DebugCollectLogsSource(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// A new session was created. - public static SessionsOpenStatus Created { get; } = new("created"); - - /// An existing session was loaded or reattached. - public static SessionsOpenStatus Resumed { get; } = new("resumed"); + /// Session event log. + public static DebugCollectLogsSource Events { get; } = new("events"); - /// No matching persisted session was found. - public static SessionsOpenStatus NotFound { get; } = new("not_found"); + /// Process log for the session. + public static DebugCollectLogsSource ProcessLog { get; } = new("process-log"); - /// Connected to an existing remote session. - public static SessionsOpenStatus Connected { get; } = new("connected"); + /// Interactive shell log for the session. + public static DebugCollectLogsSource ShellLog { get; } = new("shell-log"); - /// Remote session was handed off to a new local session. - public static SessionsOpenStatus HandedOff { get; } = new("handed_off"); + /// Caller-provided diagnostic entry. + public static DebugCollectLogsSource Additional { get; } = new("additional"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(SessionsOpenStatus left, SessionsOpenStatus right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(DebugCollectLogsSource left, DebugCollectLogsSource right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(SessionsOpenStatus left, SessionsOpenStatus right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(DebugCollectLogsSource left, DebugCollectLogsSource right) => !(left == right); /// - public override bool Equals(object? obj) => obj is SessionsOpenStatus other && Equals(other); + public override bool Equals(object? obj) => obj is DebugCollectLogsSource other && Equals(other); /// - public bool Equals(SessionsOpenStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(DebugCollectLogsSource other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -14330,62 +17286,62 @@ public SessionsOpenStatus(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override SessionsOpenStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override DebugCollectLogsSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, SessionsOpenStatus value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, DebugCollectLogsSource value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionsOpenStatus)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DebugCollectLogsSource)); } } } -/// Neutral SDK discriminator for the connected remote session kind. +/// Destination kind that was written. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct ConnectedRemoteSessionMetadataKind : IEquatable +public readonly struct DebugCollectLogsResultKind : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public ConnectedRemoteSessionMetadataKind(string value) + public DebugCollectLogsResultKind(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Remote CLI session. - public static ConnectedRemoteSessionMetadataKind RemoteSession { get; } = new("remote-session"); + /// A .tgz archive was written. + public static DebugCollectLogsResultKind Archive { get; } = new("archive"); - /// GitHub Copilot coding agent session. - public static ConnectedRemoteSessionMetadataKind CodingAgent { get; } = new("coding-agent"); + /// A directory containing redacted files was written. + public static DebugCollectLogsResultKind Directory { get; } = new("directory"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(ConnectedRemoteSessionMetadataKind left, ConnectedRemoteSessionMetadataKind right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(DebugCollectLogsResultKind left, DebugCollectLogsResultKind right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(ConnectedRemoteSessionMetadataKind left, ConnectedRemoteSessionMetadataKind right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(DebugCollectLogsResultKind left, DebugCollectLogsResultKind right) => !(left == right); /// - public override bool Equals(object? obj) => obj is ConnectedRemoteSessionMetadataKind other && Equals(other); + public override bool Equals(object? obj) => obj is DebugCollectLogsResultKind other && Equals(other); /// - public bool Equals(ConnectedRemoteSessionMetadataKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(DebugCollectLogsResultKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -14393,65 +17349,62 @@ public ConnectedRemoteSessionMetadataKind(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override ConnectedRemoteSessionMetadataKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override DebugCollectLogsResultKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, ConnectedRemoteSessionMetadataKind value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, DebugCollectLogsResultKind value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ConnectedRemoteSessionMetadataKind)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DebugCollectLogsResultKind)); } } } -/// Which session sources to include. Defaults to `local` for backward compatibility. +/// Kind of caller-provided debug log entry. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct SessionSource : IEquatable +public readonly struct DebugCollectLogsEntryKind : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public SessionSource(string value) + public DebugCollectLogsEntryKind(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . - public string Value => _value ?? string.Empty; - - /// Return only local sessions. - public static SessionSource Local { get; } = new("local"); + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; - /// Return only remote sessions. - public static SessionSource Remote { get; } = new("remote"); + /// Include a single server-local file. + public static DebugCollectLogsEntryKind File { get; } = new("file"); - /// Return both local and remote sessions. - public static SessionSource All { get; } = new("all"); + /// Include files from a server-local directory recursively. + public static DebugCollectLogsEntryKind Directory { get; } = new("directory"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(SessionSource left, SessionSource right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(DebugCollectLogsEntryKind left, DebugCollectLogsEntryKind right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(SessionSource left, SessionSource right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(DebugCollectLogsEntryKind left, DebugCollectLogsEntryKind right) => !(left == right); /// - public override bool Equals(object? obj) => obj is SessionSource other && Equals(other); + public override bool Equals(object? obj) => obj is DebugCollectLogsEntryKind other && Equals(other); /// - public bool Equals(SessionSource other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(DebugCollectLogsEntryKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -14459,71 +17412,62 @@ public SessionSource(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override SessionSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override DebugCollectLogsEntryKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, SessionSource value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, DebugCollectLogsEntryKind value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionSource)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DebugCollectLogsEntryKind)); } } } -/// Kind of attention required when status === "attention". Meaningful only when status === "attention". +/// How a collected debug entry should be redacted before being staged. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct AgentRegistryLiveTargetEntryAttentionKind : IEquatable +public readonly struct DebugCollectLogsRedaction : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public AgentRegistryLiveTargetEntryAttentionKind(string value) + public DebugCollectLogsRedaction(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Session is blocked on an unrecoverable error. - public static AgentRegistryLiveTargetEntryAttentionKind Error { get; } = new("error"); - - /// Session is waiting for a tool-permission decision. - public static AgentRegistryLiveTargetEntryAttentionKind Permission { get; } = new("permission"); - - /// Session is waiting for the user to approve or reject a plan. - public static AgentRegistryLiveTargetEntryAttentionKind ExitPlan { get; } = new("exit_plan"); - - /// Session is waiting on an elicitation prompt. - public static AgentRegistryLiveTargetEntryAttentionKind Elicitation { get; } = new("elicitation"); + /// Redact the file as plain UTF-8 log text. + public static DebugCollectLogsRedaction PlainText { get; } = new("plain-text"); - /// Session is waiting for free-form user input. - public static AgentRegistryLiveTargetEntryAttentionKind UserInput { get; } = new("user_input"); + /// Redact each non-empty line as a session event JSON object, falling back to plain-text redaction for malformed lines. + public static DebugCollectLogsRedaction EventsJsonl { get; } = new("events-jsonl"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(AgentRegistryLiveTargetEntryAttentionKind left, AgentRegistryLiveTargetEntryAttentionKind right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(DebugCollectLogsRedaction left, DebugCollectLogsRedaction right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(AgentRegistryLiveTargetEntryAttentionKind left, AgentRegistryLiveTargetEntryAttentionKind right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(DebugCollectLogsRedaction left, DebugCollectLogsRedaction right) => !(left == right); /// - public override bool Equals(object? obj) => obj is AgentRegistryLiveTargetEntryAttentionKind other && Equals(other); + public override bool Equals(object? obj) => obj is DebugCollectLogsRedaction other && Equals(other); /// - public bool Equals(AgentRegistryLiveTargetEntryAttentionKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(DebugCollectLogsRedaction other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -14531,62 +17475,65 @@ public AgentRegistryLiveTargetEntryAttentionKind(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override AgentRegistryLiveTargetEntryAttentionKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override DebugCollectLogsRedaction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, AgentRegistryLiveTargetEntryAttentionKind value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, DebugCollectLogsRedaction value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentRegistryLiveTargetEntryAttentionKind)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DebugCollectLogsRedaction)); } } } -/// Process kind tag for the registry entry. +/// Cumulative resource ceiling that stopped a factory run. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct AgentRegistryLiveTargetEntryKind : IEquatable +public readonly struct FactoryRunFailureKind : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public AgentRegistryLiveTargetEntryKind(string value) + public FactoryRunFailureKind(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Interactive Copilot CLI exposing a UI server (legacy/normal CLI process). - public static AgentRegistryLiveTargetEntryKind UiServer { get; } = new("ui-server"); + /// The run admitted the approved maximum total number of subagents. + public static FactoryRunFailureKind MaxTotalSubagents { get; } = new("maxTotalSubagents"); - /// Headless `--server --managed-server` child spawned by a controller. - public static AgentRegistryLiveTargetEntryKind ManagedServer { get; } = new("managed-server"); + /// The run reached the approved accumulated active-execution time in seconds. + public static FactoryRunFailureKind TimeoutSeconds { get; } = new("timeoutSeconds"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(AgentRegistryLiveTargetEntryKind left, AgentRegistryLiveTargetEntryKind right) => left.Equals(right); + /// The run's settled subagent model usage exceeded the approved AI-credit ceiling, or no headroom remained for another subagent. + public static FactoryRunFailureKind MaxAiCredits { get; } = new("maxAiCredits"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(AgentRegistryLiveTargetEntryKind left, AgentRegistryLiveTargetEntryKind right) => !(left == right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(FactoryRunFailureKind left, FactoryRunFailureKind right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(FactoryRunFailureKind left, FactoryRunFailureKind right) => !(left == right); /// - public override bool Equals(object? obj) => obj is AgentRegistryLiveTargetEntryKind other && Equals(other); + public override bool Equals(object? obj) => obj is FactoryRunFailureKind other && Equals(other); /// - public bool Equals(AgentRegistryLiveTargetEntryKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(FactoryRunFailureKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -14594,62 +17541,86 @@ public AgentRegistryLiveTargetEntryKind(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override AgentRegistryLiveTargetEntryKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override FactoryRunFailureKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, AgentRegistryLiveTargetEntryKind value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, FactoryRunFailureKind value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentRegistryLiveTargetEntryKind)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(FactoryRunFailureKind)); } } } -/// How the most recent turn ended (clean vs aborted). Lets the renderer distinguish done from done_cancelled. +/// Execution-critical factory storage operation. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct AgentRegistryLiveTargetEntryLastTerminalEvent : IEquatable +public readonly struct FactoryDurableOperation : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public AgentRegistryLiveTargetEntryLastTerminalEvent(string value) + public FactoryDurableOperation(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Last turn ended cleanly (model returned a final assistant message). - public static AgentRegistryLiveTargetEntryLastTerminalEvent TurnEnd { get; } = new("turn_end"); + /// Creating the durable run and declared phases. + public static FactoryDurableOperation CreateRun { get; } = new("createRun"); - /// Last turn was aborted (e.g. user interrupted). - public static AgentRegistryLiveTargetEntryLastTerminalEvent Abort { get; } = new("abort"); + /// Persisting the transition to running. + public static FactoryDurableOperation MarkRunStarted { get; } = new("markRunStarted"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(AgentRegistryLiveTargetEntryLastTerminalEvent left, AgentRegistryLiveTargetEntryLastTerminalEvent right) => left.Equals(right); + /// Persisting the terminal run envelope. + public static FactoryDurableOperation FinishRun { get; } = new("finishRun"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(AgentRegistryLiveTargetEntryLastTerminalEvent left, AgentRegistryLiveTargetEntryLastTerminalEvent right) => !(left == right); + /// Persisting subagent admission accounting. + public static FactoryDurableOperation ReserveAgent { get; } = new("reserveAgent"); + + /// Rolling back an uncommitted subagent admission. + public static FactoryDurableOperation ReleaseAgent { get; } = new("releaseAgent"); + + /// Persisting an idempotent model-usage charge. + public static FactoryDurableOperation ChargeCredit { get; } = new("chargeCredit"); + + /// Persisting active execution time. + public static FactoryDurableOperation AddElapsed { get; } = new("addElapsed"); + + /// Reading the authoritative AI-credit total. + public static FactoryDurableOperation ReconcileCreditTotal { get; } = new("reconcileCreditTotal"); + + /// Reading a journal entry without treating storage failure as a cache miss. + public static FactoryDurableOperation JournalGet { get; } = new("journalGet"); + + /// Persisting a journal entry before reporting success. + public static FactoryDurableOperation JournalPut { get; } = new("journalPut"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(FactoryDurableOperation left, FactoryDurableOperation right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(FactoryDurableOperation left, FactoryDurableOperation right) => !(left == right); /// - public override bool Equals(object? obj) => obj is AgentRegistryLiveTargetEntryLastTerminalEvent other && Equals(other); + public override bool Equals(object? obj) => obj is FactoryDurableOperation other && Equals(other); /// - public bool Equals(AgentRegistryLiveTargetEntryLastTerminalEvent other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(FactoryDurableOperation other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -14657,68 +17628,74 @@ public AgentRegistryLiveTargetEntryLastTerminalEvent(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override AgentRegistryLiveTargetEntryLastTerminalEvent Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override FactoryDurableOperation Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, AgentRegistryLiveTargetEntryLastTerminalEvent value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, FactoryDurableOperation value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentRegistryLiveTargetEntryLastTerminalEvent)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(FactoryDurableOperation)); } } } -/// Coarse lifecycle status of the foreground session. +/// Current or terminal state of a factory run. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct AgentRegistryLiveTargetEntryStatus : IEquatable +public readonly struct FactoryRunStatus : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public AgentRegistryLiveTargetEntryStatus(string value) + public FactoryRunStatus(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Session is actively processing a turn. - public static AgentRegistryLiveTargetEntryStatus Working { get; } = new("working"); + /// The run was minted and is awaiting approval. + public static FactoryRunStatus Pending { get; } = new("pending"); - /// Session is idle, waiting for input. - public static AgentRegistryLiveTargetEntryStatus Waiting { get; } = new("waiting"); + /// The run is executing. + public static FactoryRunStatus Running { get; } = new("running"); - /// Last turn completed successfully. - public static AgentRegistryLiveTargetEntryStatus Done { get; } = new("done"); + /// The run completed successfully. + public static FactoryRunStatus Completed { get; } = new("completed"); - /// Session needs user attention (see attentionKind for the specific reason). - public static AgentRegistryLiveTargetEntryStatus Attention { get; } = new("attention"); + /// The run was interrupted while resource budget remained. + public static FactoryRunStatus Halted { get; } = new("halted"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(AgentRegistryLiveTargetEntryStatus left, AgentRegistryLiveTargetEntryStatus right) => left.Equals(right); + /// The run was cancelled before completion. + public static FactoryRunStatus Cancelled { get; } = new("cancelled"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(AgentRegistryLiveTargetEntryStatus left, AgentRegistryLiveTargetEntryStatus right) => !(left == right); + /// The factory body failed or reached a cumulative resource ceiling. + public static FactoryRunStatus Error { get; } = new("error"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(FactoryRunStatus left, FactoryRunStatus right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(FactoryRunStatus left, FactoryRunStatus right) => !(left == right); /// - public override bool Equals(object? obj) => obj is AgentRegistryLiveTargetEntryStatus other && Equals(other); + public override bool Equals(object? obj) => obj is FactoryRunStatus other && Equals(other); /// - public bool Equals(AgentRegistryLiveTargetEntryStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(FactoryRunStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -14726,65 +17703,68 @@ public AgentRegistryLiveTargetEntryStatus(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override AgentRegistryLiveTargetEntryStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override FactoryRunStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, AgentRegistryLiveTargetEntryStatus value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, FactoryRunStatus value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentRegistryLiveTargetEntryStatus)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(FactoryRunStatus)); } } } -/// Categorized reason for log-open failure. +/// Derived lifecycle state of a factory phase. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct AgentRegistryLogCaptureOpenErrorReason : IEquatable +public readonly struct FactoryPhaseStatus : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public AgentRegistryLogCaptureOpenErrorReason(string value) + public FactoryPhaseStatus(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Filesystem permission denied opening the log file. - public static AgentRegistryLogCaptureOpenErrorReason Permission { get; } = new("permission"); + /// The phase has not been entered yet. + public static FactoryPhaseStatus Pending { get; } = new("pending"); - /// No space left on device. - public static AgentRegistryLogCaptureOpenErrorReason DiskFull { get; } = new("disk_full"); + /// The phase is currently entered and accumulating active time. + public static FactoryPhaseStatus Active { get; } = new("active"); - /// Other / uncategorized open failure. - public static AgentRegistryLogCaptureOpenErrorReason Other { get; } = new("other"); + /// The phase was entered and has since been closed. + public static FactoryPhaseStatus Completed { get; } = new("completed"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(AgentRegistryLogCaptureOpenErrorReason left, AgentRegistryLogCaptureOpenErrorReason right) => left.Equals(right); + /// The phase was never entered because a later phase was entered or the run reached a terminal state. + public static FactoryPhaseStatus Skipped { get; } = new("skipped"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(AgentRegistryLogCaptureOpenErrorReason left, AgentRegistryLogCaptureOpenErrorReason right) => !(left == right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(FactoryPhaseStatus left, FactoryPhaseStatus right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(FactoryPhaseStatus left, FactoryPhaseStatus right) => !(left == right); /// - public override bool Equals(object? obj) => obj is AgentRegistryLogCaptureOpenErrorReason other && Equals(other); + public override bool Equals(object? obj) => obj is FactoryPhaseStatus other && Equals(other); /// - public bool Equals(AgentRegistryLogCaptureOpenErrorReason other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(FactoryPhaseStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -14792,71 +17772,62 @@ public AgentRegistryLogCaptureOpenErrorReason(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override AgentRegistryLogCaptureOpenErrorReason Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override FactoryPhaseStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, AgentRegistryLogCaptureOpenErrorReason value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, FactoryPhaseStatus value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentRegistryLogCaptureOpenErrorReason)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(FactoryPhaseStatus)); } } } -/// Which parameter field was invalid. Omitted when the rejection is not field-specific. +/// Kind of factory progress line. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct AgentRegistrySpawnValidationErrorField : IEquatable +public readonly struct FactoryLogLineKind : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public AgentRegistrySpawnValidationErrorField(string value) + public FactoryLogLineKind(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . - public string Value => _value ?? string.Empty; - - /// The cwd parameter. - public static AgentRegistrySpawnValidationErrorField Cwd { get; } = new("cwd"); - - /// The session name parameter. - public static AgentRegistrySpawnValidationErrorField Name { get; } = new("name"); - - /// The agentName parameter. - public static AgentRegistrySpawnValidationErrorField AgentName { get; } = new("agentName"); + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; - /// The model parameter. - public static AgentRegistrySpawnValidationErrorField Model { get; } = new("model"); + /// A narrator log line. + public static FactoryLogLineKind Log { get; } = new("log"); - /// The permissionMode parameter. - public static AgentRegistrySpawnValidationErrorField PermissionMode { get; } = new("permissionMode"); + /// A named factory phase marker. + public static FactoryLogLineKind Phase { get; } = new("phase"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(AgentRegistrySpawnValidationErrorField left, AgentRegistrySpawnValidationErrorField right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(FactoryLogLineKind left, FactoryLogLineKind right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(AgentRegistrySpawnValidationErrorField left, AgentRegistrySpawnValidationErrorField right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(FactoryLogLineKind left, FactoryLogLineKind right) => !(left == right); /// - public override bool Equals(object? obj) => obj is AgentRegistrySpawnValidationErrorField other && Equals(other); + public override bool Equals(object? obj) => obj is FactoryLogLineKind other && Equals(other); /// - public bool Equals(AgentRegistrySpawnValidationErrorField other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(FactoryLogLineKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -14864,74 +17835,62 @@ public AgentRegistrySpawnValidationErrorField(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override AgentRegistrySpawnValidationErrorField Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override FactoryLogLineKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, AgentRegistrySpawnValidationErrorField value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, FactoryLogLineKind value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentRegistrySpawnValidationErrorField)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(FactoryLogLineKind)); } } } -/// Categorized reason for the rejection. Low-cardinality enum so telemetry can aggregate by reason without leaking raw paths or agent/model names. +/// Allowed values for the `WorkspacesWorkspaceDetailsHostType` enumeration. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct AgentRegistrySpawnValidationErrorReason : IEquatable +public readonly struct WorkspacesWorkspaceDetailsHostType : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public AgentRegistrySpawnValidationErrorReason(string value) + public WorkspacesWorkspaceDetailsHostType(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Provided cwd does not exist on disk. - public static AgentRegistrySpawnValidationErrorReason CwdNotFound { get; } = new("cwd-not-found"); - - /// Provided cwd exists but is not a directory. - public static AgentRegistrySpawnValidationErrorReason CwdNotDirectory { get; } = new("cwd-not-directory"); - - /// Session name failed validateSessionName. - public static AgentRegistrySpawnValidationErrorReason InvalidName { get; } = new("invalid-name"); - - /// Requested agent name was not found in builtin or custom agents. - public static AgentRegistrySpawnValidationErrorReason UnknownAgent { get; } = new("unknown-agent"); - - /// Requested model is not available to this session. - public static AgentRegistrySpawnValidationErrorReason UnknownModel { get; } = new("unknown-model"); + /// Workspace repository is hosted on GitHub. + public static WorkspacesWorkspaceDetailsHostType GitHub { get; } = new("github"); - /// Caller asked for permissionMode='yolo' but the controller is not currently in allow-all mode. - public static AgentRegistrySpawnValidationErrorReason YoloNotAllowed { get; } = new("yolo-not-allowed"); + /// Workspace repository is hosted on Azure DevOps. + public static WorkspacesWorkspaceDetailsHostType Ado { get; } = new("ado"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(AgentRegistrySpawnValidationErrorReason left, AgentRegistrySpawnValidationErrorReason right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(WorkspacesWorkspaceDetailsHostType left, WorkspacesWorkspaceDetailsHostType right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(AgentRegistrySpawnValidationErrorReason left, AgentRegistrySpawnValidationErrorReason right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(WorkspacesWorkspaceDetailsHostType left, WorkspacesWorkspaceDetailsHostType right) => !(left == right); /// - public override bool Equals(object? obj) => obj is AgentRegistrySpawnValidationErrorReason other && Equals(other); + public override bool Equals(object? obj) => obj is WorkspacesWorkspaceDetailsHostType other && Equals(other); /// - public bool Equals(AgentRegistrySpawnValidationErrorReason other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(WorkspacesWorkspaceDetailsHostType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -14939,62 +17898,68 @@ public AgentRegistrySpawnValidationErrorReason(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override AgentRegistrySpawnValidationErrorReason Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override WorkspacesWorkspaceDetailsHostType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, AgentRegistrySpawnValidationErrorReason value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, WorkspacesWorkspaceDetailsHostType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentRegistrySpawnValidationErrorReason)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(WorkspacesWorkspaceDetailsHostType)); } } } -/// Permission posture for the new session. 'yolo' requires the controller-local session to currently be in allow-all mode. +/// Type of change represented by this file diff. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct AgentRegistrySpawnPermissionMode : IEquatable +public readonly struct WorkspaceDiffFileChangeType : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public AgentRegistrySpawnPermissionMode(string value) + public WorkspaceDiffFileChangeType(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Standard permission posture (prompts for each request). - public static AgentRegistrySpawnPermissionMode Default { get; } = new("default"); + /// The file was added. + public static WorkspaceDiffFileChangeType Added { get; } = new("added"); - /// Full allow-all (requires the controller-local session to currently be in allow-all mode). - public static AgentRegistrySpawnPermissionMode Yolo { get; } = new("yolo"); + /// The file was modified. + public static WorkspaceDiffFileChangeType Modified { get; } = new("modified"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(AgentRegistrySpawnPermissionMode left, AgentRegistrySpawnPermissionMode right) => left.Equals(right); + /// The file was deleted. + public static WorkspaceDiffFileChangeType Deleted { get; } = new("deleted"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(AgentRegistrySpawnPermissionMode left, AgentRegistrySpawnPermissionMode right) => !(left == right); + /// The file was renamed. + public static WorkspaceDiffFileChangeType Renamed { get; } = new("renamed"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(WorkspaceDiffFileChangeType left, WorkspaceDiffFileChangeType right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(WorkspaceDiffFileChangeType left, WorkspaceDiffFileChangeType right) => !(left == right); /// - public override bool Equals(object? obj) => obj is AgentRegistrySpawnPermissionMode other && Equals(other); + public override bool Equals(object? obj) => obj is WorkspaceDiffFileChangeType other && Equals(other); /// - public bool Equals(AgentRegistrySpawnPermissionMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(WorkspaceDiffFileChangeType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -15002,68 +17967,65 @@ public AgentRegistrySpawnPermissionMode(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override AgentRegistrySpawnPermissionMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override WorkspaceDiffFileChangeType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, AgentRegistrySpawnPermissionMode value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, WorkspaceDiffFileChangeType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AgentRegistrySpawnPermissionMode)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(WorkspaceDiffFileChangeType)); } } } -/// The UI mode the agent was in when this message was sent. Defaults to the session's current mode. +/// Diff mode requested by the client. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct SendAgentMode : IEquatable +public readonly struct WorkspaceDiffMode : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public SendAgentMode(string value) + public WorkspaceDiffMode(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The agent is responding interactively to the user. - public static SendAgentMode Interactive { get; } = new("interactive"); - - /// The agent is preparing a plan before making changes. - public static SendAgentMode Plan { get; } = new("plan"); + /// Return staged, unstaged, and untracked working tree changes. + public static WorkspaceDiffMode Unstaged { get; } = new("unstaged"); - /// The agent is working autonomously toward task completion. - public static SendAgentMode Autopilot { get; } = new("autopilot"); + /// Return changes compared with the default branch. + public static WorkspaceDiffMode Branch { get; } = new("branch"); - /// The agent is in shell-focused UI mode. - public static SendAgentMode Shell { get; } = new("shell"); + /// Return the cumulative diff of files Copilot changed this session (used in non-git workspaces). + public static WorkspaceDiffMode Session { get; } = new("session"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(SendAgentMode left, SendAgentMode right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(WorkspaceDiffMode left, WorkspaceDiffMode right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(SendAgentMode left, SendAgentMode right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(WorkspaceDiffMode left, WorkspaceDiffMode right) => !(left == right); /// - public override bool Equals(object? obj) => obj is SendAgentMode other && Equals(other); + public override bool Equals(object? obj) => obj is WorkspaceDiffMode other && Equals(other); /// - public bool Equals(SendAgentMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(WorkspaceDiffMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -15071,62 +18033,65 @@ public SendAgentMode(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override SendAgentMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override WorkspaceDiffMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, SendAgentMode value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, WorkspaceDiffMode value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SendAgentMode)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(WorkspaceDiffMode)); } } } -/// How to deliver the message. `enqueue` (default) appends to the message queue. `immediate` interjects during an in-progress turn. +/// Reason a rewind read (rewind points, file-restore preview, or session diff) could not be answered from the session's file-change captures. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct SendMode : IEquatable +public readonly struct HistoryRewindUnavailableReason : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public SendMode(string value) + public HistoryRewindUnavailableReason(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Append the message to the normal session queue. - public static SendMode Enqueue { get; } = new("enqueue"); + /// The session did not opt into file-change tracking before its first turn. + public static HistoryRewindUnavailableReason FileChangeTrackingDisabled { get; } = new("file-change-tracking-disabled"); - /// Interject the message during the in-progress turn. - public static SendMode Immediate { get; } = new("immediate"); + /// The session still has work that may mutate files or history. Transient: the same request succeeds once the session settles, so callers should retry rather than treat it as a failure. + public static HistoryRewindUnavailableReason SessionBusy { get; } = new("session-busy"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(SendMode left, SendMode right) => left.Equals(right); + /// Remote-backed rewind routing is not supported. + public static HistoryRewindUnavailableReason UnsupportedRemoteSession { get; } = new("unsupported-remote-session"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(SendMode left, SendMode right) => !(left == right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(HistoryRewindUnavailableReason left, HistoryRewindUnavailableReason right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(HistoryRewindUnavailableReason left, HistoryRewindUnavailableReason right) => !(left == right); /// - public override bool Equals(object? obj) => obj is SendMode other && Equals(other); + public override bool Equals(object? obj) => obj is HistoryRewindUnavailableReason other && Equals(other); /// - public bool Equals(SendMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(HistoryRewindUnavailableReason other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -15134,65 +18099,62 @@ public SendMode(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override SendMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override HistoryRewindUnavailableReason Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, SendMode value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, HistoryRewindUnavailableReason value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SendMode)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(HistoryRewindUnavailableReason)); } } } -/// Log severity level. Determines how the message is displayed in the timeline. Defaults to "info". +/// Whether task execution is synchronously awaited or managed in the background. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct SessionLogLevel : IEquatable +public readonly struct TaskExecutionMode : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public SessionLogLevel(string value) + public TaskExecutionMode(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Informational message. - public static SessionLogLevel Info { get; } = new("info"); - - /// Warning message that may require attention. - public static SessionLogLevel Warning { get; } = new("warning"); + /// The task was started with synchronous waiting. + public static TaskExecutionMode Sync { get; } = new("sync"); - /// Error message describing a failure. - public static SessionLogLevel Error { get; } = new("error"); + /// The task is managed in the background. + public static TaskExecutionMode Background { get; } = new("background"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(SessionLogLevel left, SessionLogLevel right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(TaskExecutionMode left, TaskExecutionMode right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(SessionLogLevel left, SessionLogLevel right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(TaskExecutionMode left, TaskExecutionMode right) => !(left == right); /// - public override bool Equals(object? obj) => obj is SessionLogLevel other && Equals(other); + public override bool Equals(object? obj) => obj is TaskExecutionMode other && Equals(other); /// - public bool Equals(SessionLogLevel other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(TaskExecutionMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -15200,77 +18162,71 @@ public SessionLogLevel(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override SessionLogLevel Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override TaskExecutionMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, SessionLogLevel value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, TaskExecutionMode value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionLogLevel)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(TaskExecutionMode)); } } } -/// Authentication type. +/// Current lifecycle status of the task. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct AuthInfoType : IEquatable +public readonly struct TaskStatus : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public AuthInfoType(string value) + public TaskStatus(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Authentication provided by a GitHub App HMAC credential. - public static AuthInfoType Hmac { get; } = new("hmac"); - - /// Authentication resolved from environment-provided credentials. - public static AuthInfoType Env { get; } = new("env"); - - /// Authentication from an interactive user sign-in. - public static AuthInfoType User { get; } = new("user"); + /// The task is actively executing. + public static TaskStatus Running { get; } = new("running"); - /// Authentication delegated to the GitHub CLI. - public static AuthInfoType GhCli { get; } = new("gh-cli"); + /// The task is waiting for additional input. + public static TaskStatus Idle { get; } = new("idle"); - /// Authentication from an API key credential. - public static AuthInfoType ApiKey { get; } = new("api-key"); + /// The task finished successfully. + public static TaskStatus Completed { get; } = new("completed"); - /// Authentication from a GitHub token. - public static AuthInfoType Token { get; } = new("token"); + /// The task finished with an error. + public static TaskStatus Failed { get; } = new("failed"); - /// Authentication from a Copilot API token. - public static AuthInfoType CopilotApiToken { get; } = new("copilot-api-token"); + /// The task was cancelled before completion. + public static TaskStatus Cancelled { get; } = new("cancelled"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(AuthInfoType left, AuthInfoType right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(TaskStatus left, TaskStatus right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(AuthInfoType left, AuthInfoType right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(TaskStatus left, TaskStatus right) => !(left == right); /// - public override bool Equals(object? obj) => obj is AuthInfoType other && Equals(other); + public override bool Equals(object? obj) => obj is TaskStatus other && Equals(other); /// - public bool Equals(AuthInfoType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(TaskStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -15278,68 +18234,62 @@ public AuthInfoType(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override AuthInfoType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override TaskStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, AuthInfoType value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, TaskStatus value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AuthInfoType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(TaskStatus)); } } } -/// Source category for a collected debug bundle entry. +/// Whether the shell runs inside a managed PTY session or as an independent background process. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct DebugCollectLogsSource : IEquatable +public readonly struct TaskShellInfoAttachmentMode : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public DebugCollectLogsSource(string value) + public TaskShellInfoAttachmentMode(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Session event log. - public static DebugCollectLogsSource Events { get; } = new("events"); - - /// Process log for the session. - public static DebugCollectLogsSource ProcessLog { get; } = new("process-log"); - - /// Interactive shell log for the session. - public static DebugCollectLogsSource ShellLog { get; } = new("shell-log"); + /// The shell runs in a managed PTY session. + public static TaskShellInfoAttachmentMode Attached { get; } = new("attached"); - /// Caller-provided diagnostic entry. - public static DebugCollectLogsSource Additional { get; } = new("additional"); + /// The shell runs as an independent background process. + public static TaskShellInfoAttachmentMode Detached { get; } = new("detached"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(DebugCollectLogsSource left, DebugCollectLogsSource right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(TaskShellInfoAttachmentMode left, TaskShellInfoAttachmentMode right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(DebugCollectLogsSource left, DebugCollectLogsSource right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(TaskShellInfoAttachmentMode left, TaskShellInfoAttachmentMode right) => !(left == right); /// - public override bool Equals(object? obj) => obj is DebugCollectLogsSource other && Equals(other); + public override bool Equals(object? obj) => obj is TaskShellInfoAttachmentMode other && Equals(other); /// - public bool Equals(DebugCollectLogsSource other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(TaskShellInfoAttachmentMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -15347,62 +18297,62 @@ public DebugCollectLogsSource(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override DebugCollectLogsSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override TaskShellInfoAttachmentMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, DebugCollectLogsSource value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, TaskShellInfoAttachmentMode value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DebugCollectLogsSource)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(TaskShellInfoAttachmentMode)); } } } -/// Destination kind that was written. +/// Consumer allowed to call an MCP tool. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct DebugCollectLogsResultKind : IEquatable +public readonly struct McpToolUiVisibility : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public DebugCollectLogsResultKind(string value) + public McpToolUiVisibility(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// A .tgz archive was written. - public static DebugCollectLogsResultKind Archive { get; } = new("archive"); + /// The model may call the tool. + public static McpToolUiVisibility Model { get; } = new("model"); - /// A directory containing redacted files was written. - public static DebugCollectLogsResultKind Directory { get; } = new("directory"); + /// An MCP App view may call the tool. + public static McpToolUiVisibility App { get; } = new("app"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(DebugCollectLogsResultKind left, DebugCollectLogsResultKind right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(McpToolUiVisibility left, McpToolUiVisibility right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(DebugCollectLogsResultKind left, DebugCollectLogsResultKind right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(McpToolUiVisibility left, McpToolUiVisibility right) => !(left == right); /// - public override bool Equals(object? obj) => obj is DebugCollectLogsResultKind other && Equals(other); + public override bool Equals(object? obj) => obj is McpToolUiVisibility other && Equals(other); /// - public bool Equals(DebugCollectLogsResultKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(McpToolUiVisibility other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -15410,62 +18360,65 @@ public DebugCollectLogsResultKind(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override DebugCollectLogsResultKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override McpToolUiVisibility Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, DebugCollectLogsResultKind value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, McpToolUiVisibility value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DebugCollectLogsResultKind)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpToolUiVisibility)); } } } -/// Kind of caller-provided debug log entry. +/// 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. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct DebugCollectLogsEntryKind : IEquatable +public readonly struct McpSamplingExecutionAction : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public DebugCollectLogsEntryKind(string value) + public McpSamplingExecutionAction(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Include a single server-local file. - public static DebugCollectLogsEntryKind File { get; } = new("file"); + /// The sampling inference completed and produced a result. + public static McpSamplingExecutionAction Success { get; } = new("success"); - /// Include files from a server-local directory recursively. - public static DebugCollectLogsEntryKind Directory { get; } = new("directory"); + /// The sampling inference failed or was rejected. + public static McpSamplingExecutionAction Failure { get; } = new("failure"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(DebugCollectLogsEntryKind left, DebugCollectLogsEntryKind right) => left.Equals(right); + /// The sampling inference was cancelled before completion. + public static McpSamplingExecutionAction Cancelled { get; } = new("cancelled"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(DebugCollectLogsEntryKind left, DebugCollectLogsEntryKind right) => !(left == right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(McpSamplingExecutionAction left, McpSamplingExecutionAction right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(McpSamplingExecutionAction left, McpSamplingExecutionAction right) => !(left == right); /// - public override bool Equals(object? obj) => obj is DebugCollectLogsEntryKind other && Equals(other); + public override bool Equals(object? obj) => obj is McpSamplingExecutionAction other && Equals(other); /// - public bool Equals(DebugCollectLogsEntryKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(McpSamplingExecutionAction other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -15473,62 +18426,62 @@ public DebugCollectLogsEntryKind(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override DebugCollectLogsEntryKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override McpSamplingExecutionAction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, DebugCollectLogsEntryKind value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, McpSamplingExecutionAction value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DebugCollectLogsEntryKind)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpSamplingExecutionAction)); } } } -/// How a collected debug entry should be redacted before being staged. +/// 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". [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct DebugCollectLogsRedaction : IEquatable +public readonly struct McpSetEnvValueModeDetails : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public DebugCollectLogsRedaction(string value) + public McpSetEnvValueModeDetails(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Redact the file as plain UTF-8 log text. - public static DebugCollectLogsRedaction PlainText { get; } = new("plain-text"); + /// Treat MCP server environment values as literal strings. + public static McpSetEnvValueModeDetails Direct { get; } = new("direct"); - /// Redact each non-empty line as a session event JSON object, falling back to plain-text redaction for malformed lines. - public static DebugCollectLogsRedaction EventsJsonl { get; } = new("events-jsonl"); + /// Treat MCP server environment values as host-side references to resolve before launch. + public static McpSetEnvValueModeDetails Indirect { get; } = new("indirect"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(DebugCollectLogsRedaction left, DebugCollectLogsRedaction right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(McpSetEnvValueModeDetails left, McpSetEnvValueModeDetails right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(DebugCollectLogsRedaction left, DebugCollectLogsRedaction right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(McpSetEnvValueModeDetails left, McpSetEnvValueModeDetails right) => !(left == right); /// - public override bool Equals(object? obj) => obj is DebugCollectLogsRedaction other && Equals(other); + public override bool Equals(object? obj) => obj is McpSetEnvValueModeDetails other && Equals(other); /// - public bool Equals(DebugCollectLogsRedaction other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(McpSetEnvValueModeDetails other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -15536,62 +18489,62 @@ public DebugCollectLogsRedaction(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override DebugCollectLogsRedaction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override McpSetEnvValueModeDetails Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, DebugCollectLogsRedaction value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, McpSetEnvValueModeDetails value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DebugCollectLogsRedaction)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpSetEnvValueModeDetails)); } } } -/// Cumulative resource ceiling that stopped a factory run. +/// OAuth grant type override for this login. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct FactoryRunFailureKind : IEquatable +public readonly struct McpOauthLoginGrantType : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public FactoryRunFailureKind(string value) + public McpOauthLoginGrantType(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The run admitted the approved maximum total number of subagents. - public static FactoryRunFailureKind MaxTotalSubagents { get; } = new("maxTotalSubagents"); - - /// The run reached the approved timeout deadline. - public static FactoryRunFailureKind Timeout { get; } = new("timeout"); + /// Interactive browser-based OAuth flow using an authorization code, typically with PKCE. + public static McpOauthLoginGrantType AuthorizationCode { get; } = new("authorization_code"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(FactoryRunFailureKind left, FactoryRunFailureKind right) => left.Equals(right); + /// Headless OAuth flow where a confidential client authenticates directly with a client secret. + public static McpOauthLoginGrantType ClientCredentials { get; } = new("client_credentials"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(FactoryRunFailureKind left, FactoryRunFailureKind right) => !(left == right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(McpOauthLoginGrantType left, McpOauthLoginGrantType right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(McpOauthLoginGrantType left, McpOauthLoginGrantType right) => !(left == right); /// - public override bool Equals(object? obj) => obj is FactoryRunFailureKind other && Equals(other); + public override bool Equals(object? obj) => obj is McpOauthLoginGrantType other && Equals(other); /// - public bool Equals(FactoryRunFailureKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(McpOauthLoginGrantType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -15599,74 +18552,65 @@ public FactoryRunFailureKind(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override FactoryRunFailureKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override McpOauthLoginGrantType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, FactoryRunFailureKind value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, McpOauthLoginGrantType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(FactoryRunFailureKind)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpOauthLoginGrantType)); } } } -/// Current or terminal state of a factory run. +/// Allowed values for the `McpAppsSetHostContextDetailsAvailableDisplayMode` enumeration. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct FactoryRunStatus : IEquatable +public readonly struct McpAppsSetHostContextDetailsAvailableDisplayMode : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public FactoryRunStatus(string value) + public McpAppsSetHostContextDetailsAvailableDisplayMode(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The run was minted and is awaiting approval. - public static FactoryRunStatus Pending { get; } = new("pending"); - - /// The run is executing. - public static FactoryRunStatus Running { get; } = new("running"); - - /// The run completed successfully. - public static FactoryRunStatus Completed { get; } = new("completed"); - - /// The run was interrupted while resource budget remained. - public static FactoryRunStatus Halted { get; } = new("halted"); + /// Rendered inline within the host conversation surface. + public static McpAppsSetHostContextDetailsAvailableDisplayMode Inline { get; } = new("inline"); - /// The run was cancelled before completion. - public static FactoryRunStatus Cancelled { get; } = new("cancelled"); + /// Rendered as a fullscreen overlay. + public static McpAppsSetHostContextDetailsAvailableDisplayMode Fullscreen { get; } = new("fullscreen"); - /// The factory body failed or reached a cumulative resource ceiling. - public static FactoryRunStatus Error { get; } = new("error"); + /// Rendered as a picture-in-picture floating panel. + public static McpAppsSetHostContextDetailsAvailableDisplayMode Pip { get; } = new("pip"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(FactoryRunStatus left, FactoryRunStatus right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(McpAppsSetHostContextDetailsAvailableDisplayMode left, McpAppsSetHostContextDetailsAvailableDisplayMode right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(FactoryRunStatus left, FactoryRunStatus right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(McpAppsSetHostContextDetailsAvailableDisplayMode left, McpAppsSetHostContextDetailsAvailableDisplayMode right) => !(left == right); /// - public override bool Equals(object? obj) => obj is FactoryRunStatus other && Equals(other); + public override bool Equals(object? obj) => obj is McpAppsSetHostContextDetailsAvailableDisplayMode other && Equals(other); /// - public bool Equals(FactoryRunStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(McpAppsSetHostContextDetailsAvailableDisplayMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -15674,62 +18618,65 @@ public FactoryRunStatus(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override FactoryRunStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override McpAppsSetHostContextDetailsAvailableDisplayMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, FactoryRunStatus value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, McpAppsSetHostContextDetailsAvailableDisplayMode value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(FactoryRunStatus)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpAppsSetHostContextDetailsAvailableDisplayMode)); } } } -/// Kind of factory progress line. +/// Current display mode (SEP-1865). [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct FactoryLogLineKind : IEquatable +public readonly struct McpAppsSetHostContextDetailsDisplayMode : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public FactoryLogLineKind(string value) + public McpAppsSetHostContextDetailsDisplayMode(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// A narrator log line. - public static FactoryLogLineKind Log { get; } = new("log"); + /// Rendered inline within the host conversation surface. + public static McpAppsSetHostContextDetailsDisplayMode Inline { get; } = new("inline"); - /// A named factory phase marker. - public static FactoryLogLineKind Phase { get; } = new("phase"); + /// Rendered as a fullscreen overlay. + public static McpAppsSetHostContextDetailsDisplayMode Fullscreen { get; } = new("fullscreen"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(FactoryLogLineKind left, FactoryLogLineKind right) => left.Equals(right); + /// Rendered as a picture-in-picture floating panel. + public static McpAppsSetHostContextDetailsDisplayMode Pip { get; } = new("pip"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(FactoryLogLineKind left, FactoryLogLineKind right) => !(left == right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(McpAppsSetHostContextDetailsDisplayMode left, McpAppsSetHostContextDetailsDisplayMode right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(McpAppsSetHostContextDetailsDisplayMode left, McpAppsSetHostContextDetailsDisplayMode right) => !(left == right); /// - public override bool Equals(object? obj) => obj is FactoryLogLineKind other && Equals(other); + public override bool Equals(object? obj) => obj is McpAppsSetHostContextDetailsDisplayMode other && Equals(other); /// - public bool Equals(FactoryLogLineKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(McpAppsSetHostContextDetailsDisplayMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -15737,62 +18684,65 @@ public FactoryLogLineKind(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override FactoryLogLineKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override McpAppsSetHostContextDetailsDisplayMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, FactoryLogLineKind value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, McpAppsSetHostContextDetailsDisplayMode value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(FactoryLogLineKind)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpAppsSetHostContextDetailsDisplayMode)); } } } -/// Allowed values for the `WorkspacesWorkspaceDetailsHostType` enumeration. +/// Platform type for responsive design. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct WorkspacesWorkspaceDetailsHostType : IEquatable +public readonly struct McpAppsSetHostContextDetailsPlatform : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public WorkspacesWorkspaceDetailsHostType(string value) + public McpAppsSetHostContextDetailsPlatform(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Workspace repository is hosted on GitHub. - public static WorkspacesWorkspaceDetailsHostType GitHub { get; } = new("github"); + /// Host runs in a web browser. + public static McpAppsSetHostContextDetailsPlatform Web { get; } = new("web"); - /// Workspace repository is hosted on Azure DevOps. - public static WorkspacesWorkspaceDetailsHostType Ado { get; } = new("ado"); + /// Host runs as a desktop application. + public static McpAppsSetHostContextDetailsPlatform Desktop { get; } = new("desktop"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(WorkspacesWorkspaceDetailsHostType left, WorkspacesWorkspaceDetailsHostType right) => left.Equals(right); + /// Host runs on a mobile device. + public static McpAppsSetHostContextDetailsPlatform Mobile { get; } = new("mobile"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(WorkspacesWorkspaceDetailsHostType left, WorkspacesWorkspaceDetailsHostType right) => !(left == right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(McpAppsSetHostContextDetailsPlatform left, McpAppsSetHostContextDetailsPlatform right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(McpAppsSetHostContextDetailsPlatform left, McpAppsSetHostContextDetailsPlatform right) => !(left == right); /// - public override bool Equals(object? obj) => obj is WorkspacesWorkspaceDetailsHostType other && Equals(other); + public override bool Equals(object? obj) => obj is McpAppsSetHostContextDetailsPlatform other && Equals(other); /// - public bool Equals(WorkspacesWorkspaceDetailsHostType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(McpAppsSetHostContextDetailsPlatform other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -15800,68 +18750,62 @@ public WorkspacesWorkspaceDetailsHostType(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override WorkspacesWorkspaceDetailsHostType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override McpAppsSetHostContextDetailsPlatform Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, WorkspacesWorkspaceDetailsHostType value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, McpAppsSetHostContextDetailsPlatform value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(WorkspacesWorkspaceDetailsHostType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpAppsSetHostContextDetailsPlatform)); } } } -/// Type of change represented by this file diff. +/// UI theme preference per SEP-1865. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct WorkspaceDiffFileChangeType : IEquatable +public readonly struct McpAppsSetHostContextDetailsTheme : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public WorkspaceDiffFileChangeType(string value) + public McpAppsSetHostContextDetailsTheme(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The file was added. - public static WorkspaceDiffFileChangeType Added { get; } = new("added"); - - /// The file was modified. - public static WorkspaceDiffFileChangeType Modified { get; } = new("modified"); - - /// The file was deleted. - public static WorkspaceDiffFileChangeType Deleted { get; } = new("deleted"); + /// Light UI theme. + public static McpAppsSetHostContextDetailsTheme Light { get; } = new("light"); - /// The file was renamed. - public static WorkspaceDiffFileChangeType Renamed { get; } = new("renamed"); + /// Dark UI theme. + public static McpAppsSetHostContextDetailsTheme Dark { get; } = new("dark"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(WorkspaceDiffFileChangeType left, WorkspaceDiffFileChangeType right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(McpAppsSetHostContextDetailsTheme left, McpAppsSetHostContextDetailsTheme right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(WorkspaceDiffFileChangeType left, WorkspaceDiffFileChangeType right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(McpAppsSetHostContextDetailsTheme left, McpAppsSetHostContextDetailsTheme right) => !(left == right); /// - public override bool Equals(object? obj) => obj is WorkspaceDiffFileChangeType other && Equals(other); + public override bool Equals(object? obj) => obj is McpAppsSetHostContextDetailsTheme other && Equals(other); /// - public bool Equals(WorkspaceDiffFileChangeType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(McpAppsSetHostContextDetailsTheme other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -15869,65 +18813,65 @@ public WorkspaceDiffFileChangeType(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override WorkspaceDiffFileChangeType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override McpAppsSetHostContextDetailsTheme Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, WorkspaceDiffFileChangeType value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, McpAppsSetHostContextDetailsTheme value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(WorkspaceDiffFileChangeType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpAppsSetHostContextDetailsTheme)); } } } -/// Diff mode requested by the client. +/// Allowed values for the `McpAppsHostContextDetailsAvailableDisplayMode` enumeration. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct WorkspaceDiffMode : IEquatable +public readonly struct McpAppsHostContextDetailsAvailableDisplayMode : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public WorkspaceDiffMode(string value) + public McpAppsHostContextDetailsAvailableDisplayMode(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Return staged, unstaged, and untracked working tree changes. - public static WorkspaceDiffMode Unstaged { get; } = new("unstaged"); + /// Rendered inline within the host conversation surface. + public static McpAppsHostContextDetailsAvailableDisplayMode Inline { get; } = new("inline"); - /// Return changes compared with the default branch. - public static WorkspaceDiffMode Branch { get; } = new("branch"); + /// Rendered as a fullscreen overlay. + public static McpAppsHostContextDetailsAvailableDisplayMode Fullscreen { get; } = new("fullscreen"); - /// Return the cumulative diff of files Copilot changed this session (used in non-git workspaces). - public static WorkspaceDiffMode Session { get; } = new("session"); + /// Rendered as a picture-in-picture floating panel. + public static McpAppsHostContextDetailsAvailableDisplayMode Pip { get; } = new("pip"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(WorkspaceDiffMode left, WorkspaceDiffMode right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(McpAppsHostContextDetailsAvailableDisplayMode left, McpAppsHostContextDetailsAvailableDisplayMode right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(WorkspaceDiffMode left, WorkspaceDiffMode right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(McpAppsHostContextDetailsAvailableDisplayMode left, McpAppsHostContextDetailsAvailableDisplayMode right) => !(left == right); /// - public override bool Equals(object? obj) => obj is WorkspaceDiffMode other && Equals(other); + public override bool Equals(object? obj) => obj is McpAppsHostContextDetailsAvailableDisplayMode other && Equals(other); /// - public bool Equals(WorkspaceDiffMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(McpAppsHostContextDetailsAvailableDisplayMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -15935,62 +18879,65 @@ public WorkspaceDiffMode(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override WorkspaceDiffMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override McpAppsHostContextDetailsAvailableDisplayMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, WorkspaceDiffMode value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, McpAppsHostContextDetailsAvailableDisplayMode value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(WorkspaceDiffMode)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpAppsHostContextDetailsAvailableDisplayMode)); } } } -/// Whether task execution is synchronously awaited or managed in the background. +/// Current display mode (SEP-1865). [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct TaskExecutionMode : IEquatable +public readonly struct McpAppsHostContextDetailsDisplayMode : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public TaskExecutionMode(string value) + public McpAppsHostContextDetailsDisplayMode(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The task was started with synchronous waiting. - public static TaskExecutionMode Sync { get; } = new("sync"); + /// Rendered inline within the host conversation surface. + public static McpAppsHostContextDetailsDisplayMode Inline { get; } = new("inline"); - /// The task is managed in the background. - public static TaskExecutionMode Background { get; } = new("background"); + /// Rendered as a fullscreen overlay. + public static McpAppsHostContextDetailsDisplayMode Fullscreen { get; } = new("fullscreen"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(TaskExecutionMode left, TaskExecutionMode right) => left.Equals(right); + /// Rendered as a picture-in-picture floating panel. + public static McpAppsHostContextDetailsDisplayMode Pip { get; } = new("pip"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(TaskExecutionMode left, TaskExecutionMode right) => !(left == right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(McpAppsHostContextDetailsDisplayMode left, McpAppsHostContextDetailsDisplayMode right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(McpAppsHostContextDetailsDisplayMode left, McpAppsHostContextDetailsDisplayMode right) => !(left == right); /// - public override bool Equals(object? obj) => obj is TaskExecutionMode other && Equals(other); + public override bool Equals(object? obj) => obj is McpAppsHostContextDetailsDisplayMode other && Equals(other); /// - public bool Equals(TaskExecutionMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(McpAppsHostContextDetailsDisplayMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -15998,71 +18945,65 @@ public TaskExecutionMode(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override TaskExecutionMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override McpAppsHostContextDetailsDisplayMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, TaskExecutionMode value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, McpAppsHostContextDetailsDisplayMode value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(TaskExecutionMode)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpAppsHostContextDetailsDisplayMode)); } } } -/// Current lifecycle status of the task. +/// Platform type for responsive design. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct TaskStatus : IEquatable +public readonly struct McpAppsHostContextDetailsPlatform : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public TaskStatus(string value) + public McpAppsHostContextDetailsPlatform(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The task is actively executing. - public static TaskStatus Running { get; } = new("running"); - - /// The task is waiting for additional input. - public static TaskStatus Idle { get; } = new("idle"); - - /// The task finished successfully. - public static TaskStatus Completed { get; } = new("completed"); + /// Host runs in a web browser. + public static McpAppsHostContextDetailsPlatform Web { get; } = new("web"); - /// The task finished with an error. - public static TaskStatus Failed { get; } = new("failed"); + /// Host runs as a desktop application. + public static McpAppsHostContextDetailsPlatform Desktop { get; } = new("desktop"); - /// The task was cancelled before completion. - public static TaskStatus Cancelled { get; } = new("cancelled"); + /// Host runs on a mobile device. + public static McpAppsHostContextDetailsPlatform Mobile { get; } = new("mobile"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(TaskStatus left, TaskStatus right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(McpAppsHostContextDetailsPlatform left, McpAppsHostContextDetailsPlatform right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(TaskStatus left, TaskStatus right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(McpAppsHostContextDetailsPlatform left, McpAppsHostContextDetailsPlatform right) => !(left == right); /// - public override bool Equals(object? obj) => obj is TaskStatus other && Equals(other); + public override bool Equals(object? obj) => obj is McpAppsHostContextDetailsPlatform other && Equals(other); /// - public bool Equals(TaskStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(McpAppsHostContextDetailsPlatform other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -16070,62 +19011,62 @@ public TaskStatus(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override TaskStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override McpAppsHostContextDetailsPlatform Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, TaskStatus value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, McpAppsHostContextDetailsPlatform value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(TaskStatus)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpAppsHostContextDetailsPlatform)); } } } -/// Whether the shell runs inside a managed PTY session or as an independent background process. +/// UI theme preference per SEP-1865. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct TaskShellInfoAttachmentMode : IEquatable +public readonly struct McpAppsHostContextDetailsTheme : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public TaskShellInfoAttachmentMode(string value) + public McpAppsHostContextDetailsTheme(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The shell runs in a managed PTY session. - public static TaskShellInfoAttachmentMode Attached { get; } = new("attached"); + /// Light UI theme. + public static McpAppsHostContextDetailsTheme Light { get; } = new("light"); - /// The shell runs as an independent background process. - public static TaskShellInfoAttachmentMode Detached { get; } = new("detached"); + /// Dark UI theme. + public static McpAppsHostContextDetailsTheme Dark { get; } = new("dark"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(TaskShellInfoAttachmentMode left, TaskShellInfoAttachmentMode right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(McpAppsHostContextDetailsTheme left, McpAppsHostContextDetailsTheme right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(TaskShellInfoAttachmentMode left, TaskShellInfoAttachmentMode right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(McpAppsHostContextDetailsTheme left, McpAppsHostContextDetailsTheme right) => !(left == right); /// - public override bool Equals(object? obj) => obj is TaskShellInfoAttachmentMode other && Equals(other); + public override bool Equals(object? obj) => obj is McpAppsHostContextDetailsTheme other && Equals(other); /// - public bool Equals(TaskShellInfoAttachmentMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(McpAppsHostContextDetailsTheme other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -16133,62 +19074,62 @@ public TaskShellInfoAttachmentMode(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override TaskShellInfoAttachmentMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override McpAppsHostContextDetailsTheme Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, TaskShellInfoAttachmentMode value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, McpAppsHostContextDetailsTheme value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(TaskShellInfoAttachmentMode)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpAppsHostContextDetailsTheme)); } } } -/// Consumer allowed to call an MCP tool. +/// Transport to be used for provider requests. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct McpToolUiVisibility : IEquatable +public readonly struct ProviderEndpointTransport : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public McpToolUiVisibility(string value) + public ProviderEndpointTransport(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The model may call the tool. - public static McpToolUiVisibility Model { get; } = new("model"); + /// HTTP request/streaming transport. + public static ProviderEndpointTransport Http { get; } = new("http"); - /// An MCP App view may call the tool. - public static McpToolUiVisibility App { get; } = new("app"); + /// WebSocket transport. + public static ProviderEndpointTransport Websockets { get; } = new("websockets"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(McpToolUiVisibility left, McpToolUiVisibility right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(ProviderEndpointTransport left, ProviderEndpointTransport right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(McpToolUiVisibility left, McpToolUiVisibility right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(ProviderEndpointTransport left, ProviderEndpointTransport right) => !(left == right); /// - public override bool Equals(object? obj) => obj is McpToolUiVisibility other && Equals(other); + public override bool Equals(object? obj) => obj is ProviderEndpointTransport other && Equals(other); /// - public bool Equals(McpToolUiVisibility other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(ProviderEndpointTransport other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -16196,65 +19137,65 @@ public McpToolUiVisibility(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override McpToolUiVisibility Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override ProviderEndpointTransport Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, McpToolUiVisibility value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, ProviderEndpointTransport value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpToolUiVisibility)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ProviderEndpointTransport)); } } } -/// 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. +/// Provider family. Matches the `type` field of a BYOK provider config. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct McpSamplingExecutionAction : IEquatable +public readonly struct ProviderEndpointType : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public McpSamplingExecutionAction(string value) + public ProviderEndpointType(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The sampling inference completed and produced a result. - public static McpSamplingExecutionAction Success { get; } = new("success"); + /// OpenAI-compatible endpoint (use the OpenAI client library). + public static ProviderEndpointType Openai { get; } = new("openai"); - /// The sampling inference failed or was rejected. - public static McpSamplingExecutionAction Failure { get; } = new("failure"); + /// Azure OpenAI endpoint (use the OpenAI client library with the Azure base URL). + public static ProviderEndpointType Azure { get; } = new("azure"); - /// The sampling inference was cancelled before completion. - public static McpSamplingExecutionAction Cancelled { get; } = new("cancelled"); + /// Anthropic endpoint (use the Anthropic client library). + public static ProviderEndpointType Anthropic { get; } = new("anthropic"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(McpSamplingExecutionAction left, McpSamplingExecutionAction right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(ProviderEndpointType left, ProviderEndpointType right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(McpSamplingExecutionAction left, McpSamplingExecutionAction right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(ProviderEndpointType left, ProviderEndpointType right) => !(left == right); /// - public override bool Equals(object? obj) => obj is McpSamplingExecutionAction other && Equals(other); + public override bool Equals(object? obj) => obj is ProviderEndpointType other && Equals(other); /// - public bool Equals(McpSamplingExecutionAction other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(ProviderEndpointType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -16262,62 +19203,62 @@ public McpSamplingExecutionAction(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override McpSamplingExecutionAction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override ProviderEndpointType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, McpSamplingExecutionAction value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, ProviderEndpointType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpSamplingExecutionAction)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ProviderEndpointType)); } } } -/// 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". +/// Wire API to be used, when required for the provider type. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct McpSetEnvValueModeDetails : IEquatable +public readonly struct ProviderEndpointWireApi : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public McpSetEnvValueModeDetails(string value) + public ProviderEndpointWireApi(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Treat MCP server environment values as literal strings. - public static McpSetEnvValueModeDetails Direct { get; } = new("direct"); + /// Classic chat-completions request shape. + public static ProviderEndpointWireApi Completions { get; } = new("completions"); - /// Treat MCP server environment values as host-side references to resolve before launch. - public static McpSetEnvValueModeDetails Indirect { get; } = new("indirect"); + /// Newer responses request shape. + public static ProviderEndpointWireApi Responses { get; } = new("responses"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(McpSetEnvValueModeDetails left, McpSetEnvValueModeDetails right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(ProviderEndpointWireApi left, ProviderEndpointWireApi right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(McpSetEnvValueModeDetails left, McpSetEnvValueModeDetails right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(ProviderEndpointWireApi left, ProviderEndpointWireApi right) => !(left == right); /// - public override bool Equals(object? obj) => obj is McpSetEnvValueModeDetails other && Equals(other); + public override bool Equals(object? obj) => obj is ProviderEndpointWireApi other && Equals(other); /// - public bool Equals(McpSetEnvValueModeDetails other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(ProviderEndpointWireApi other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -16325,62 +19266,62 @@ public McpSetEnvValueModeDetails(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override McpSetEnvValueModeDetails Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override ProviderEndpointWireApi Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, McpSetEnvValueModeDetails value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, ProviderEndpointWireApi value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpSetEnvValueModeDetails)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ProviderEndpointWireApi)); } } } -/// OAuth grant type override for this login. +/// Provider transport. Defaults to "http". [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct McpOauthLoginGrantType : IEquatable +public readonly struct ProviderConfigTransport : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public McpOauthLoginGrantType(string value) + public ProviderConfigTransport(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Interactive browser-based OAuth flow using an authorization code, typically with PKCE. - public static McpOauthLoginGrantType AuthorizationCode { get; } = new("authorization_code"); + /// HTTP request/streaming transport. + public static ProviderConfigTransport Http { get; } = new("http"); - /// Headless OAuth flow where a confidential client authenticates directly with a client secret. - public static McpOauthLoginGrantType ClientCredentials { get; } = new("client_credentials"); + /// WebSocket transport. + public static ProviderConfigTransport Websockets { get; } = new("websockets"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(McpOauthLoginGrantType left, McpOauthLoginGrantType right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(ProviderConfigTransport left, ProviderConfigTransport right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(McpOauthLoginGrantType left, McpOauthLoginGrantType right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(ProviderConfigTransport left, ProviderConfigTransport right) => !(left == right); /// - public override bool Equals(object? obj) => obj is McpOauthLoginGrantType other && Equals(other); + public override bool Equals(object? obj) => obj is ProviderConfigTransport other && Equals(other); /// - public bool Equals(McpOauthLoginGrantType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(ProviderConfigTransport other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -16388,65 +19329,65 @@ public McpOauthLoginGrantType(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override McpOauthLoginGrantType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override ProviderConfigTransport Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, McpOauthLoginGrantType value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, ProviderConfigTransport value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpOauthLoginGrantType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ProviderConfigTransport)); } } } -/// Allowed values for the `McpAppsSetHostContextDetailsAvailableDisplayMode` enumeration. +/// Provider type. Defaults to "openai" for generic OpenAI-compatible APIs. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct McpAppsSetHostContextDetailsAvailableDisplayMode : IEquatable +public readonly struct ProviderConfigType : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public McpAppsSetHostContextDetailsAvailableDisplayMode(string value) + public ProviderConfigType(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Rendered inline within the host conversation surface. - public static McpAppsSetHostContextDetailsAvailableDisplayMode Inline { get; } = new("inline"); + /// Generic OpenAI-compatible API. + public static ProviderConfigType Openai { get; } = new("openai"); - /// Rendered as a fullscreen overlay. - public static McpAppsSetHostContextDetailsAvailableDisplayMode Fullscreen { get; } = new("fullscreen"); + /// Azure OpenAI Service endpoint. + public static ProviderConfigType Azure { get; } = new("azure"); - /// Rendered as a picture-in-picture floating panel. - public static McpAppsSetHostContextDetailsAvailableDisplayMode Pip { get; } = new("pip"); + /// Anthropic API endpoint. + public static ProviderConfigType Anthropic { get; } = new("anthropic"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(McpAppsSetHostContextDetailsAvailableDisplayMode left, McpAppsSetHostContextDetailsAvailableDisplayMode right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(ProviderConfigType left, ProviderConfigType right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(McpAppsSetHostContextDetailsAvailableDisplayMode left, McpAppsSetHostContextDetailsAvailableDisplayMode right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(ProviderConfigType left, ProviderConfigType right) => !(left == right); /// - public override bool Equals(object? obj) => obj is McpAppsSetHostContextDetailsAvailableDisplayMode other && Equals(other); + public override bool Equals(object? obj) => obj is ProviderConfigType other && Equals(other); /// - public bool Equals(McpAppsSetHostContextDetailsAvailableDisplayMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(ProviderConfigType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -16454,65 +19395,62 @@ public McpAppsSetHostContextDetailsAvailableDisplayMode(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override McpAppsSetHostContextDetailsAvailableDisplayMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override ProviderConfigType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, McpAppsSetHostContextDetailsAvailableDisplayMode value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, ProviderConfigType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpAppsSetHostContextDetailsAvailableDisplayMode)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ProviderConfigType)); } } } -/// Current display mode (SEP-1865). +/// Wire API format (openai/azure only). Defaults to "completions". [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct McpAppsSetHostContextDetailsDisplayMode : IEquatable +public readonly struct ProviderConfigWireApi : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public McpAppsSetHostContextDetailsDisplayMode(string value) + public ProviderConfigWireApi(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Rendered inline within the host conversation surface. - public static McpAppsSetHostContextDetailsDisplayMode Inline { get; } = new("inline"); - - /// Rendered as a fullscreen overlay. - public static McpAppsSetHostContextDetailsDisplayMode Fullscreen { get; } = new("fullscreen"); + /// OpenAI Chat Completions wire format. + public static ProviderConfigWireApi Completions { get; } = new("completions"); - /// Rendered as a picture-in-picture floating panel. - public static McpAppsSetHostContextDetailsDisplayMode Pip { get; } = new("pip"); + /// OpenAI Responses API wire format. + public static ProviderConfigWireApi Responses { get; } = new("responses"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(McpAppsSetHostContextDetailsDisplayMode left, McpAppsSetHostContextDetailsDisplayMode right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(ProviderConfigWireApi left, ProviderConfigWireApi right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(McpAppsSetHostContextDetailsDisplayMode left, McpAppsSetHostContextDetailsDisplayMode right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(ProviderConfigWireApi left, ProviderConfigWireApi right) => !(left == right); /// - public override bool Equals(object? obj) => obj is McpAppsSetHostContextDetailsDisplayMode other && Equals(other); + public override bool Equals(object? obj) => obj is ProviderConfigWireApi other && Equals(other); /// - public bool Equals(McpAppsSetHostContextDetailsDisplayMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(ProviderConfigWireApi other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -16520,65 +19458,62 @@ public McpAppsSetHostContextDetailsDisplayMode(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override McpAppsSetHostContextDetailsDisplayMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override ProviderConfigWireApi Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, McpAppsSetHostContextDetailsDisplayMode value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, ProviderConfigWireApi value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpAppsSetHostContextDetailsDisplayMode)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ProviderConfigWireApi)); } } } -/// Platform type for responsive design. +/// Allowed values for the `OptionsUpdateAdditionalContentExclusionPolicyScope` enumeration. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct McpAppsSetHostContextDetailsPlatform : IEquatable +public readonly struct OptionsUpdateAdditionalContentExclusionPolicyScope : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public McpAppsSetHostContextDetailsPlatform(string value) + public OptionsUpdateAdditionalContentExclusionPolicyScope(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Host runs in a web browser. - public static McpAppsSetHostContextDetailsPlatform Web { get; } = new("web"); - - /// Host runs as a desktop application. - public static McpAppsSetHostContextDetailsPlatform Desktop { get; } = new("desktop"); + /// The content exclusion policy applies to the current repository. + public static OptionsUpdateAdditionalContentExclusionPolicyScope Repo { get; } = new("repo"); - /// Host runs on a mobile device. - public static McpAppsSetHostContextDetailsPlatform Mobile { get; } = new("mobile"); + /// The content exclusion policy applies across all repositories. + public static OptionsUpdateAdditionalContentExclusionPolicyScope All { get; } = new("all"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(McpAppsSetHostContextDetailsPlatform left, McpAppsSetHostContextDetailsPlatform right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(OptionsUpdateAdditionalContentExclusionPolicyScope left, OptionsUpdateAdditionalContentExclusionPolicyScope right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(McpAppsSetHostContextDetailsPlatform left, McpAppsSetHostContextDetailsPlatform right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(OptionsUpdateAdditionalContentExclusionPolicyScope left, OptionsUpdateAdditionalContentExclusionPolicyScope right) => !(left == right); /// - public override bool Equals(object? obj) => obj is McpAppsSetHostContextDetailsPlatform other && Equals(other); + public override bool Equals(object? obj) => obj is OptionsUpdateAdditionalContentExclusionPolicyScope other && Equals(other); /// - public bool Equals(McpAppsSetHostContextDetailsPlatform other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(OptionsUpdateAdditionalContentExclusionPolicyScope other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -16586,62 +19521,62 @@ public McpAppsSetHostContextDetailsPlatform(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override McpAppsSetHostContextDetailsPlatform Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override OptionsUpdateAdditionalContentExclusionPolicyScope Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, McpAppsSetHostContextDetailsPlatform value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, OptionsUpdateAdditionalContentExclusionPolicyScope value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpAppsSetHostContextDetailsPlatform)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(OptionsUpdateAdditionalContentExclusionPolicyScope)); } } } -/// UI theme preference per SEP-1865. +/// Context tier for models with tiered pricing. The session uses this to derive effective `modelCapabilitiesOverrides` so compaction, truncation, token display, and request limits honor the selected tier. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct McpAppsSetHostContextDetailsTheme : IEquatable +public readonly struct OptionsUpdateContextTier : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public McpAppsSetHostContextDetailsTheme(string value) + public OptionsUpdateContextTier(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Light UI theme. - public static McpAppsSetHostContextDetailsTheme Light { get; } = new("light"); + /// Use the model's default context tier and its standard token limits / pricing. + public static OptionsUpdateContextTier Default { get; } = new("default"); - /// Dark UI theme. - public static McpAppsSetHostContextDetailsTheme Dark { get; } = new("dark"); + /// Use the model's long-context tier (when available) so larger inputs are accepted and tier-specific pricing applies. + public static OptionsUpdateContextTier LongContext { get; } = new("long_context"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(McpAppsSetHostContextDetailsTheme left, McpAppsSetHostContextDetailsTheme right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(OptionsUpdateContextTier left, OptionsUpdateContextTier right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(McpAppsSetHostContextDetailsTheme left, McpAppsSetHostContextDetailsTheme right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(OptionsUpdateContextTier left, OptionsUpdateContextTier right) => !(left == right); /// - public override bool Equals(object? obj) => obj is McpAppsSetHostContextDetailsTheme other && Equals(other); + public override bool Equals(object? obj) => obj is OptionsUpdateContextTier other && Equals(other); /// - public bool Equals(McpAppsSetHostContextDetailsTheme other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(OptionsUpdateContextTier other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -16649,65 +19584,62 @@ public McpAppsSetHostContextDetailsTheme(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override McpAppsSetHostContextDetailsTheme Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override OptionsUpdateContextTier Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, McpAppsSetHostContextDetailsTheme value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, OptionsUpdateContextTier value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpAppsSetHostContextDetailsTheme)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(OptionsUpdateContextTier)); } } } -/// Allowed values for the `McpAppsHostContextDetailsAvailableDisplayMode` enumeration. +/// How env values are passed to MCP servers (`direct` inlines literal values; `indirect` resolves at launch). [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct McpAppsHostContextDetailsAvailableDisplayMode : IEquatable +public readonly struct OptionsUpdateEnvValueMode : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public McpAppsHostContextDetailsAvailableDisplayMode(string value) + public OptionsUpdateEnvValueMode(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Rendered inline within the host conversation surface. - public static McpAppsHostContextDetailsAvailableDisplayMode Inline { get; } = new("inline"); - - /// Rendered as a fullscreen overlay. - public static McpAppsHostContextDetailsAvailableDisplayMode Fullscreen { get; } = new("fullscreen"); + /// Pass MCP server environment values as literal strings. + public static OptionsUpdateEnvValueMode Direct { get; } = new("direct"); - /// Rendered as a picture-in-picture floating panel. - public static McpAppsHostContextDetailsAvailableDisplayMode Pip { get; } = new("pip"); + /// Resolve MCP server environment values from host-side references. + public static OptionsUpdateEnvValueMode Indirect { get; } = new("indirect"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(McpAppsHostContextDetailsAvailableDisplayMode left, McpAppsHostContextDetailsAvailableDisplayMode right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(OptionsUpdateEnvValueMode left, OptionsUpdateEnvValueMode right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(McpAppsHostContextDetailsAvailableDisplayMode left, McpAppsHostContextDetailsAvailableDisplayMode right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(OptionsUpdateEnvValueMode left, OptionsUpdateEnvValueMode right) => !(left == right); /// - public override bool Equals(object? obj) => obj is McpAppsHostContextDetailsAvailableDisplayMode other && Equals(other); + public override bool Equals(object? obj) => obj is OptionsUpdateEnvValueMode other && Equals(other); /// - public bool Equals(McpAppsHostContextDetailsAvailableDisplayMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(OptionsUpdateEnvValueMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -16715,65 +19647,65 @@ public McpAppsHostContextDetailsAvailableDisplayMode(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override McpAppsHostContextDetailsAvailableDisplayMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override OptionsUpdateEnvValueMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, McpAppsHostContextDetailsAvailableDisplayMode value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, OptionsUpdateEnvValueMode value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpAppsHostContextDetailsAvailableDisplayMode)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(OptionsUpdateEnvValueMode)); } } } -/// Current display mode (SEP-1865). +/// Reasoning summary mode for supported model clients. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct McpAppsHostContextDetailsDisplayMode : IEquatable +public readonly struct OptionsUpdateReasoningSummary : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public McpAppsHostContextDetailsDisplayMode(string value) + public OptionsUpdateReasoningSummary(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Rendered inline within the host conversation surface. - public static McpAppsHostContextDetailsDisplayMode Inline { get; } = new("inline"); + /// Do not request reasoning summaries from the model. + public static OptionsUpdateReasoningSummary None { get; } = new("none"); - /// Rendered as a fullscreen overlay. - public static McpAppsHostContextDetailsDisplayMode Fullscreen { get; } = new("fullscreen"); + /// Request a concise summary of model reasoning. + public static OptionsUpdateReasoningSummary Concise { get; } = new("concise"); - /// Rendered as a picture-in-picture floating panel. - public static McpAppsHostContextDetailsDisplayMode Pip { get; } = new("pip"); + /// Request a detailed summary of model reasoning. + public static OptionsUpdateReasoningSummary Detailed { get; } = new("detailed"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(McpAppsHostContextDetailsDisplayMode left, McpAppsHostContextDetailsDisplayMode right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(OptionsUpdateReasoningSummary left, OptionsUpdateReasoningSummary right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(McpAppsHostContextDetailsDisplayMode left, McpAppsHostContextDetailsDisplayMode right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(OptionsUpdateReasoningSummary left, OptionsUpdateReasoningSummary right) => !(left == right); /// - public override bool Equals(object? obj) => obj is McpAppsHostContextDetailsDisplayMode other && Equals(other); + public override bool Equals(object? obj) => obj is OptionsUpdateReasoningSummary other && Equals(other); /// - public bool Equals(McpAppsHostContextDetailsDisplayMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(OptionsUpdateReasoningSummary other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -16781,65 +19713,89 @@ public McpAppsHostContextDetailsDisplayMode(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override McpAppsHostContextDetailsDisplayMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override OptionsUpdateReasoningSummary Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, McpAppsHostContextDetailsDisplayMode value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, OptionsUpdateReasoningSummary value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpAppsHostContextDetailsDisplayMode)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(OptionsUpdateReasoningSummary)); } } } -/// Platform type for responsive design. +/// Session capability enabled for this session. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct McpAppsHostContextDetailsPlatform : IEquatable +public readonly struct SessionCapability : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public McpAppsHostContextDetailsPlatform(string value) + public SessionCapability(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Host runs in a web browser. - public static McpAppsHostContextDetailsPlatform Web { get; } = new("web"); + /// TUI-specific prompt hints such as keyboard shortcuts. + public static SessionCapability TuiHints { get; } = new("tui-hints"); - /// Host runs as a desktop application. - public static McpAppsHostContextDetailsPlatform Desktop { get; } = new("desktop"); + /// Plan-mode handling and instructions. + public static SessionCapability PlanMode { get; } = new("plan-mode"); - /// Host runs on a mobile device. - public static McpAppsHostContextDetailsPlatform Mobile { get; } = new("mobile"); + /// Memory tool and memories prompt section. + public static SessionCapability Memory { get; } = new("memory"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(McpAppsHostContextDetailsPlatform left, McpAppsHostContextDetailsPlatform right) => left.Equals(right); + /// Copilot CLI documentation tool and prompt section. + public static SessionCapability CliDocumentation { get; } = new("cli-documentation"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(McpAppsHostContextDetailsPlatform left, McpAppsHostContextDetailsPlatform right) => !(left == right); + /// Interactive ask_user tool support. + public static SessionCapability AskUser { get; } = new("ask-user"); + + /// Interactive CLI identity and behavior. + public static SessionCapability InteractiveMode { get; } = new("interactive-mode"); + + /// Automatic hidden system notifications. + public static SessionCapability SystemNotifications { get; } = new("system-notifications"); + + /// SDK elicitation support. + public static SessionCapability Elicitation { get; } = new("elicitation"); + + /// Cross-session history tools and session-store SQL prompt/tool metadata. + public static SessionCapability SessionStore { get; } = new("session-store"); + + /// MCP Apps UI passthrough. + public static SessionCapability McpApps { get; } = new("mcp-apps"); + + /// Host-provided canvas rendering support. + public static SessionCapability CanvasRenderer { get; } = new("canvas-renderer"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SessionCapability left, SessionCapability right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SessionCapability left, SessionCapability right) => !(left == right); /// - public override bool Equals(object? obj) => obj is McpAppsHostContextDetailsPlatform other && Equals(other); + public override bool Equals(object? obj) => obj is SessionCapability other && Equals(other); /// - public bool Equals(McpAppsHostContextDetailsPlatform other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(SessionCapability other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -16847,62 +19803,62 @@ public McpAppsHostContextDetailsPlatform(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override McpAppsHostContextDetailsPlatform Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override SessionCapability Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, McpAppsHostContextDetailsPlatform value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, SessionCapability value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpAppsHostContextDetailsPlatform)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionCapability)); } } } -/// UI theme preference per SEP-1865. +/// Controls automatic non-interactive profile loading where supported. Explicit initScripts are unaffected. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct McpAppsHostContextDetailsTheme : IEquatable +public readonly struct ShellInitProfile : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public McpAppsHostContextDetailsTheme(string value) + public ShellInitProfile(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Light UI theme. - public static McpAppsHostContextDetailsTheme Light { get; } = new("light"); + /// Disable automatic non-interactive profile loading. Explicit initScripts still run. + public static ShellInitProfile None { get; } = new("none"); - /// Dark UI theme. - public static McpAppsHostContextDetailsTheme Dark { get; } = new("dark"); + /// Allow automatic non-interactive profile loading when supported. Explicit initScripts still run. + public static ShellInitProfile NonInteractive { get; } = new("non-interactive"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(McpAppsHostContextDetailsTheme left, McpAppsHostContextDetailsTheme right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(ShellInitProfile left, ShellInitProfile right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(McpAppsHostContextDetailsTheme left, McpAppsHostContextDetailsTheme right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(ShellInitProfile left, ShellInitProfile right) => !(left == right); /// - public override bool Equals(object? obj) => obj is McpAppsHostContextDetailsTheme other && Equals(other); + public override bool Equals(object? obj) => obj is ShellInitProfile other && Equals(other); /// - public bool Equals(McpAppsHostContextDetailsTheme other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(ShellInitProfile other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -16910,62 +19866,62 @@ public McpAppsHostContextDetailsTheme(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override McpAppsHostContextDetailsTheme Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override ShellInitProfile Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, McpAppsHostContextDetailsTheme value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, ShellInitProfile value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(McpAppsHostContextDetailsTheme)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ShellInitProfile)); } } } -/// Transport to be used for provider requests. +/// Supported built-in shells for initialization scripts. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct ProviderEndpointTransport : IEquatable +public readonly struct ShellInitScriptShell : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public ProviderEndpointTransport(string value) + public ShellInitScriptShell(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// HTTP request/streaming transport. - public static ProviderEndpointTransport Http { get; } = new("http"); + /// Source the script in the built-in Bash shell on macOS and Linux. + public static ShellInitScriptShell Bash { get; } = new("bash"); - /// WebSocket transport. - public static ProviderEndpointTransport Websockets { get; } = new("websockets"); + /// Source the script in the built-in PowerShell shell on Windows. + public static ShellInitScriptShell Powershell { get; } = new("powershell"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(ProviderEndpointTransport left, ProviderEndpointTransport right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(ShellInitScriptShell left, ShellInitScriptShell right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(ProviderEndpointTransport left, ProviderEndpointTransport right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(ShellInitScriptShell left, ShellInitScriptShell right) => !(left == right); /// - public override bool Equals(object? obj) => obj is ProviderEndpointTransport other && Equals(other); + public override bool Equals(object? obj) => obj is ShellInitScriptShell other && Equals(other); /// - public bool Equals(ProviderEndpointTransport other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(ShellInitScriptShell other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -16973,65 +19929,62 @@ public ProviderEndpointTransport(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override ProviderEndpointTransport Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override ShellInitScriptShell Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, ProviderEndpointTransport value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, ShellInitScriptShell value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ProviderEndpointTransport)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ShellInitScriptShell)); } } } -/// Provider family. Matches the `type` field of a BYOK provider config. +/// Controls how availableTools (allowlist) and excludedTools (denylist) combine when both are set. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct ProviderEndpointType : IEquatable +public readonly struct OptionsUpdateToolFilterPrecedence : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public ProviderEndpointType(string value) + public OptionsUpdateToolFilterPrecedence(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// OpenAI-compatible endpoint (use the OpenAI client library). - public static ProviderEndpointType Openai { get; } = new("openai"); - - /// Azure OpenAI endpoint (use the OpenAI client library with the Azure base URL). - public static ProviderEndpointType Azure { get; } = new("azure"); + /// If availableTools is set, it is the only constraint that applies (excludedTools is ignored). Preserves CLI / pre-existing client behavior. Default. + public static OptionsUpdateToolFilterPrecedence Available { get; } = new("available"); - /// Anthropic endpoint (use the Anthropic client library). - public static ProviderEndpointType Anthropic { get; } = new("anthropic"); + /// A tool is enabled if and only if it matches the allowlist (or the allowlist is unset) AND it does not match the denylist. Makes 'all except X' expressible by combining the two lists. + public static OptionsUpdateToolFilterPrecedence Excluded { get; } = new("excluded"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(ProviderEndpointType left, ProviderEndpointType right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(OptionsUpdateToolFilterPrecedence left, OptionsUpdateToolFilterPrecedence right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(ProviderEndpointType left, ProviderEndpointType right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(OptionsUpdateToolFilterPrecedence left, OptionsUpdateToolFilterPrecedence right) => !(left == right); /// - public override bool Equals(object? obj) => obj is ProviderEndpointType other && Equals(other); + public override bool Equals(object? obj) => obj is OptionsUpdateToolFilterPrecedence other && Equals(other); /// - public bool Equals(ProviderEndpointType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(OptionsUpdateToolFilterPrecedence other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -17039,62 +19992,68 @@ public ProviderEndpointType(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override ProviderEndpointType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override OptionsUpdateToolFilterPrecedence Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, ProviderEndpointType value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, OptionsUpdateToolFilterPrecedence value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ProviderEndpointType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(OptionsUpdateToolFilterPrecedence)); } } } -/// Wire API to be used, when required for the provider type. +/// Discovery source: project (.github/extensions/), user (~/.copilot/extensions/), plugin (installed plugin), or session (session-state/<id>/extensions/). [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct ProviderEndpointWireApi : IEquatable +public readonly struct ExtensionSource : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public ProviderEndpointWireApi(string value) + public ExtensionSource(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Classic chat-completions request shape. - public static ProviderEndpointWireApi Completions { get; } = new("completions"); + /// Extension discovered from the current project's .github/extensions directory. + public static ExtensionSource Project { get; } = new("project"); - /// Newer responses request shape. - public static ProviderEndpointWireApi Responses { get; } = new("responses"); + /// Extension discovered from the user's ~/.copilot/extensions directory. + public static ExtensionSource User { get; } = new("user"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(ProviderEndpointWireApi left, ProviderEndpointWireApi right) => left.Equals(right); + /// Extension contributed by an installed plugin. + public static ExtensionSource Plugin { get; } = new("plugin"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(ProviderEndpointWireApi left, ProviderEndpointWireApi right) => !(left == right); + /// Extension discovered from the current session's state directory (loaded only for this session). + public static ExtensionSource Session { get; } = new("session"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(ExtensionSource left, ExtensionSource right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(ExtensionSource left, ExtensionSource right) => !(left == right); /// - public override bool Equals(object? obj) => obj is ProviderEndpointWireApi other && Equals(other); + public override bool Equals(object? obj) => obj is ExtensionSource other && Equals(other); /// - public bool Equals(ProviderEndpointWireApi other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(ExtensionSource other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -17102,62 +20061,68 @@ public ProviderEndpointWireApi(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override ProviderEndpointWireApi Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override ExtensionSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, ProviderEndpointWireApi value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, ExtensionSource value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ProviderEndpointWireApi)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ExtensionSource)); } } } -/// Provider transport. Defaults to "http". +/// Current status: running, disabled, failed, or starting. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct ProviderConfigTransport : IEquatable +public readonly struct ExtensionStatus : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public ProviderConfigTransport(string value) + public ExtensionStatus(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// HTTP request/streaming transport. - public static ProviderConfigTransport Http { get; } = new("http"); + /// The extension process is running. + public static ExtensionStatus Running { get; } = new("running"); - /// WebSocket transport. - public static ProviderConfigTransport Websockets { get; } = new("websockets"); + /// The extension is installed but disabled. + public static ExtensionStatus Disabled { get; } = new("disabled"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(ProviderConfigTransport left, ProviderConfigTransport right) => left.Equals(right); + /// The extension failed to start or crashed. + public static ExtensionStatus Failed { get; } = new("failed"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(ProviderConfigTransport left, ProviderConfigTransport right) => !(left == right); + /// The extension process is starting. + public static ExtensionStatus Starting { get; } = new("starting"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(ExtensionStatus left, ExtensionStatus right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(ExtensionStatus left, ExtensionStatus right) => !(left == right); /// - public override bool Equals(object? obj) => obj is ProviderConfigTransport other && Equals(other); + public override bool Equals(object? obj) => obj is ExtensionStatus other && Equals(other); /// - public bool Equals(ProviderConfigTransport other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(ExtensionStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -17165,65 +20130,65 @@ public ProviderConfigTransport(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override ProviderConfigTransport Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override ExtensionStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, ProviderConfigTransport value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, ExtensionStatus value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ProviderConfigTransport)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ExtensionStatus)); } } } -/// Provider type. Defaults to "openai" for generic OpenAI-compatible APIs. +/// Type of GitHub reference. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct ProviderConfigType : IEquatable +public readonly struct PushAttachmentGitHubReferenceType : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public ProviderConfigType(string value) + public PushAttachmentGitHubReferenceType(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Generic OpenAI-compatible API. - public static ProviderConfigType Openai { get; } = new("openai"); + /// GitHub issue reference. + public static PushAttachmentGitHubReferenceType Issue { get; } = new("issue"); - /// Azure OpenAI Service endpoint. - public static ProviderConfigType Azure { get; } = new("azure"); + /// GitHub pull request reference. + public static PushAttachmentGitHubReferenceType Pr { get; } = new("pr"); - /// Anthropic API endpoint. - public static ProviderConfigType Anthropic { get; } = new("anthropic"); + /// GitHub discussion reference. + public static PushAttachmentGitHubReferenceType Discussion { get; } = new("discussion"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(ProviderConfigType left, ProviderConfigType right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(PushAttachmentGitHubReferenceType left, PushAttachmentGitHubReferenceType right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(ProviderConfigType left, ProviderConfigType right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(PushAttachmentGitHubReferenceType left, PushAttachmentGitHubReferenceType right) => !(left == right); /// - public override bool Equals(object? obj) => obj is ProviderConfigType other && Equals(other); + public override bool Equals(object? obj) => obj is PushAttachmentGitHubReferenceType other && Equals(other); /// - public bool Equals(ProviderConfigType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(PushAttachmentGitHubReferenceType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -17231,62 +20196,65 @@ public ProviderConfigType(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override ProviderConfigType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override PushAttachmentGitHubReferenceType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, ProviderConfigType value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, PushAttachmentGitHubReferenceType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ProviderConfigType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PushAttachmentGitHubReferenceType)); } } } -/// Wire API format (openai/azure only). Defaults to "completions". +/// Context tier override for matching subagents. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct ProviderConfigWireApi : IEquatable +public readonly struct SubagentSettingsEntryContextTier : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public ProviderConfigWireApi(string value) + public SubagentSettingsEntryContextTier(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// OpenAI Chat Completions wire format. - public static ProviderConfigWireApi Completions { get; } = new("completions"); + /// Inherit the parent session's effective context tier at dispatch time. + public static SubagentSettingsEntryContextTier Inherit { get; } = new("inherit"); - /// OpenAI Responses API wire format. - public static ProviderConfigWireApi Responses { get; } = new("responses"); + /// Use the model's default context window. + public static SubagentSettingsEntryContextTier Default { get; } = new("default"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(ProviderConfigWireApi left, ProviderConfigWireApi right) => left.Equals(right); + /// Pin the subagent to the long-context tier when supported. + public static SubagentSettingsEntryContextTier LongContext { get; } = new("long_context"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(ProviderConfigWireApi left, ProviderConfigWireApi right) => !(left == right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SubagentSettingsEntryContextTier left, SubagentSettingsEntryContextTier right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SubagentSettingsEntryContextTier left, SubagentSettingsEntryContextTier right) => !(left == right); /// - public override bool Equals(object? obj) => obj is ProviderConfigWireApi other && Equals(other); + public override bool Equals(object? obj) => obj is SubagentSettingsEntryContextTier other && Equals(other); /// - public bool Equals(ProviderConfigWireApi other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(SubagentSettingsEntryContextTier other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -17294,62 +20262,65 @@ public ProviderConfigWireApi(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override ProviderConfigWireApi Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override SubagentSettingsEntryContextTier Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, ProviderConfigWireApi value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, SubagentSettingsEntryContextTier value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ProviderConfigWireApi)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SubagentSettingsEntryContextTier)); } } } -/// Allowed values for the `OptionsUpdateAdditionalContentExclusionPolicyScope` enumeration. +/// The user's response: accept (submitted), decline (rejected), or cancel (dismissed). [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct OptionsUpdateAdditionalContentExclusionPolicyScope : IEquatable +public readonly struct UIElicitationResponseAction : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public OptionsUpdateAdditionalContentExclusionPolicyScope(string value) + public UIElicitationResponseAction(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The content exclusion policy applies to the current repository. - public static OptionsUpdateAdditionalContentExclusionPolicyScope Repo { get; } = new("repo"); + /// The user submitted the requested form values. + public static UIElicitationResponseAction Accept { get; } = new("accept"); - /// The content exclusion policy applies across all repositories. - public static OptionsUpdateAdditionalContentExclusionPolicyScope All { get; } = new("all"); + /// The user explicitly declined to provide the requested input. + public static UIElicitationResponseAction Decline { get; } = new("decline"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(OptionsUpdateAdditionalContentExclusionPolicyScope left, OptionsUpdateAdditionalContentExclusionPolicyScope right) => left.Equals(right); + /// The user dismissed the elicitation request. + public static UIElicitationResponseAction Cancel { get; } = new("cancel"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(OptionsUpdateAdditionalContentExclusionPolicyScope left, OptionsUpdateAdditionalContentExclusionPolicyScope right) => !(left == right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(UIElicitationResponseAction left, UIElicitationResponseAction right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(UIElicitationResponseAction left, UIElicitationResponseAction right) => !(left == right); /// - public override bool Equals(object? obj) => obj is OptionsUpdateAdditionalContentExclusionPolicyScope other && Equals(other); + public override bool Equals(object? obj) => obj is UIElicitationResponseAction other && Equals(other); /// - public bool Equals(OptionsUpdateAdditionalContentExclusionPolicyScope other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(UIElicitationResponseAction other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -17357,62 +20328,65 @@ public OptionsUpdateAdditionalContentExclusionPolicyScope(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override OptionsUpdateAdditionalContentExclusionPolicyScope Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override UIElicitationResponseAction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, OptionsUpdateAdditionalContentExclusionPolicyScope value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, UIElicitationResponseAction value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(OptionsUpdateAdditionalContentExclusionPolicyScope)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UIElicitationResponseAction)); } } } -/// Context tier for models with tiered pricing. The session uses this to derive effective `modelCapabilitiesOverrides` so compaction, truncation, token display, and request limits honor the selected tier. +/// User's choice for auto-mode switching: yes (allow this turn), yes_always (allow + persist as setting), or no (decline). [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct OptionsUpdateContextTier : IEquatable +public readonly struct UIAutoModeSwitchResponse : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public OptionsUpdateContextTier(string value) + public UIAutoModeSwitchResponse(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Use the model's default context tier and its standard token limits / pricing. - public static OptionsUpdateContextTier Default { get; } = new("default"); + /// Allow the automatic mode switch for this turn. + public static UIAutoModeSwitchResponse Yes { get; } = new("yes"); - /// Use the model's long-context tier (when available) so larger inputs are accepted and tier-specific pricing applies. - public static OptionsUpdateContextTier LongContext { get; } = new("long_context"); + /// Allow this mode switch and persist the preference. + public static UIAutoModeSwitchResponse YesAlways { get; } = new("yes_always"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(OptionsUpdateContextTier left, OptionsUpdateContextTier right) => left.Equals(right); + /// Decline the automatic mode switch. + public static UIAutoModeSwitchResponse No { get; } = new("no"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(OptionsUpdateContextTier left, OptionsUpdateContextTier right) => !(left == right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(UIAutoModeSwitchResponse left, UIAutoModeSwitchResponse right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(UIAutoModeSwitchResponse left, UIAutoModeSwitchResponse right) => !(left == right); /// - public override bool Equals(object? obj) => obj is OptionsUpdateContextTier other && Equals(other); + public override bool Equals(object? obj) => obj is UIAutoModeSwitchResponse other && Equals(other); /// - public bool Equals(OptionsUpdateContextTier other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(UIAutoModeSwitchResponse other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -17420,62 +20394,68 @@ public OptionsUpdateContextTier(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override OptionsUpdateContextTier Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override UIAutoModeSwitchResponse Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, OptionsUpdateContextTier value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, UIAutoModeSwitchResponse value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(OptionsUpdateContextTier)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UIAutoModeSwitchResponse)); } } } -/// How env values are passed to MCP servers (`direct` inlines literal values; `indirect` resolves at launch). +/// User action selected for an exhausted session limit. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct OptionsUpdateEnvValueMode : IEquatable +public readonly struct UISessionLimitsExhaustedResponseAction : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public OptionsUpdateEnvValueMode(string value) + public UISessionLimitsExhaustedResponseAction(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Pass MCP server environment values as literal strings. - public static OptionsUpdateEnvValueMode Direct { get; } = new("direct"); + /// Increase the current max by an exact AI Credits amount. + public static UISessionLimitsExhaustedResponseAction Add { get; } = new("add"); - /// Resolve MCP server environment values from host-side references. - public static OptionsUpdateEnvValueMode Indirect { get; } = new("indirect"); + /// Set a new absolute max AI Credits value. + public static UISessionLimitsExhaustedResponseAction Set { get; } = new("set"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(OptionsUpdateEnvValueMode left, OptionsUpdateEnvValueMode right) => left.Equals(right); + /// Remove the current session limit. + public static UISessionLimitsExhaustedResponseAction Unset { get; } = new("unset"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(OptionsUpdateEnvValueMode left, OptionsUpdateEnvValueMode right) => !(left == right); + /// Leave the limit unchanged and cancel the blocked model request. + public static UISessionLimitsExhaustedResponseAction Cancel { get; } = new("cancel"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(UISessionLimitsExhaustedResponseAction left, UISessionLimitsExhaustedResponseAction right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(UISessionLimitsExhaustedResponseAction left, UISessionLimitsExhaustedResponseAction right) => !(left == right); /// - public override bool Equals(object? obj) => obj is OptionsUpdateEnvValueMode other && Equals(other); + public override bool Equals(object? obj) => obj is UISessionLimitsExhaustedResponseAction other && Equals(other); /// - public bool Equals(OptionsUpdateEnvValueMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(UISessionLimitsExhaustedResponseAction other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -17483,65 +20463,68 @@ public OptionsUpdateEnvValueMode(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override OptionsUpdateEnvValueMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override UISessionLimitsExhaustedResponseAction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, OptionsUpdateEnvValueMode value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, UISessionLimitsExhaustedResponseAction value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(OptionsUpdateEnvValueMode)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UISessionLimitsExhaustedResponseAction)); } } } -/// Reasoning summary mode for supported model clients. +/// The action the user selected. Defaults to 'autopilot' when autoApproveEdits is true, otherwise 'interactive'. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct OptionsUpdateReasoningSummary : IEquatable +public readonly struct UIExitPlanModeAction : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public OptionsUpdateReasoningSummary(string value) + public UIExitPlanModeAction(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Do not request reasoning summaries from the model. - public static OptionsUpdateReasoningSummary None { get; } = new("none"); + /// Exit plan mode without starting implementation. + public static UIExitPlanModeAction ExitOnly { get; } = new("exit_only"); - /// Request a concise summary of model reasoning. - public static OptionsUpdateReasoningSummary Concise { get; } = new("concise"); + /// Exit plan mode and continue interactively. + public static UIExitPlanModeAction Interactive { get; } = new("interactive"); - /// Request a detailed summary of model reasoning. - public static OptionsUpdateReasoningSummary Detailed { get; } = new("detailed"); + /// Exit plan mode and continue in autopilot mode. + public static UIExitPlanModeAction Autopilot { get; } = new("autopilot"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(OptionsUpdateReasoningSummary left, OptionsUpdateReasoningSummary right) => left.Equals(right); + /// Exit plan mode and continue in autopilot mode with parallel subagent execution. + public static UIExitPlanModeAction AutopilotFleet { get; } = new("autopilot_fleet"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(OptionsUpdateReasoningSummary left, OptionsUpdateReasoningSummary right) => !(left == right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(UIExitPlanModeAction left, UIExitPlanModeAction right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(UIExitPlanModeAction left, UIExitPlanModeAction right) => !(left == right); /// - public override bool Equals(object? obj) => obj is OptionsUpdateReasoningSummary other && Equals(other); + public override bool Equals(object? obj) => obj is UIExitPlanModeAction other && Equals(other); /// - public bool Equals(OptionsUpdateReasoningSummary other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(UIExitPlanModeAction other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -17549,89 +20532,62 @@ public OptionsUpdateReasoningSummary(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override OptionsUpdateReasoningSummary Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override UIExitPlanModeAction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, OptionsUpdateReasoningSummary value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, UIExitPlanModeAction value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(OptionsUpdateReasoningSummary)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UIExitPlanModeAction)); } } } -/// Session capability enabled for this session. +/// Allowed values for the `PermissionsConfigureAdditionalContentExclusionPolicyScope` enumeration. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct SessionCapability : IEquatable +public readonly struct PermissionsConfigureAdditionalContentExclusionPolicyScope : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public SessionCapability(string value) + public PermissionsConfigureAdditionalContentExclusionPolicyScope(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// TUI-specific prompt hints such as keyboard shortcuts. - public static SessionCapability TuiHints { get; } = new("tui-hints"); - - /// Plan-mode handling and instructions. - public static SessionCapability PlanMode { get; } = new("plan-mode"); - - /// Memory tool and memories prompt section. - public static SessionCapability Memory { get; } = new("memory"); - - /// Copilot CLI documentation tool and prompt section. - public static SessionCapability CliDocumentation { get; } = new("cli-documentation"); - - /// Interactive ask_user tool support. - public static SessionCapability AskUser { get; } = new("ask-user"); - - /// Interactive CLI identity and behavior. - public static SessionCapability InteractiveMode { get; } = new("interactive-mode"); - - /// Automatic hidden system notifications. - public static SessionCapability SystemNotifications { get; } = new("system-notifications"); - - /// SDK elicitation support. - public static SessionCapability Elicitation { get; } = new("elicitation"); - - /// Cross-session history tools and session-store SQL prompt/tool metadata. - public static SessionCapability SessionStore { get; } = new("session-store"); - - /// MCP Apps UI passthrough. - public static SessionCapability McpApps { get; } = new("mcp-apps"); + /// The content exclusion policy applies to the current repository. + public static PermissionsConfigureAdditionalContentExclusionPolicyScope Repo { get; } = new("repo"); - /// Host-provided canvas rendering support. - public static SessionCapability CanvasRenderer { get; } = new("canvas-renderer"); + /// The content exclusion policy applies across all repositories. + public static PermissionsConfigureAdditionalContentExclusionPolicyScope All { get; } = new("all"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(SessionCapability left, SessionCapability right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(PermissionsConfigureAdditionalContentExclusionPolicyScope left, PermissionsConfigureAdditionalContentExclusionPolicyScope right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(SessionCapability left, SessionCapability right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(PermissionsConfigureAdditionalContentExclusionPolicyScope left, PermissionsConfigureAdditionalContentExclusionPolicyScope right) => !(left == right); /// - public override bool Equals(object? obj) => obj is SessionCapability other && Equals(other); + public override bool Equals(object? obj) => obj is PermissionsConfigureAdditionalContentExclusionPolicyScope other && Equals(other); /// - public bool Equals(SessionCapability other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(PermissionsConfigureAdditionalContentExclusionPolicyScope other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -17639,62 +20595,68 @@ public SessionCapability(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override SessionCapability Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override PermissionsConfigureAdditionalContentExclusionPolicyScope Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, SessionCapability value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, PermissionsConfigureAdditionalContentExclusionPolicyScope value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionCapability)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsConfigureAdditionalContentExclusionPolicyScope)); } } } -/// Controls how availableTools (allowlist) and excludedTools (denylist) combine when both are set. +/// Optional source for allow-all telemetry. Defaults to `rpc` when omitted for SDK callers. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct OptionsUpdateToolFilterPrecedence : IEquatable +public readonly struct PermissionsSetApproveAllSource : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public OptionsUpdateToolFilterPrecedence(string value) + public PermissionsSetApproveAllSource(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// If availableTools is set, it is the only constraint that applies (excludedTools is ignored). Preserves CLI / pre-existing client behavior. Default. - public static OptionsUpdateToolFilterPrecedence Available { get; } = new("available"); + /// Allow-all was enabled from a CLI command-line flag. + public static PermissionsSetApproveAllSource CliFlag { get; } = new("cli_flag"); - /// A tool is enabled if and only if it matches the allowlist (or the allowlist is unset) AND it does not match the denylist. Makes 'all except X' expressible by combining the two lists. - public static OptionsUpdateToolFilterPrecedence Excluded { get; } = new("excluded"); + /// Allow-all was enabled by a slash command. + public static PermissionsSetApproveAllSource SlashCommand { get; } = new("slash_command"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(OptionsUpdateToolFilterPrecedence left, OptionsUpdateToolFilterPrecedence right) => left.Equals(right); + /// Allow-all was enabled by confirming autopilot behavior. + public static PermissionsSetApproveAllSource AutopilotConfirmation { get; } = new("autopilot_confirmation"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(OptionsUpdateToolFilterPrecedence left, OptionsUpdateToolFilterPrecedence right) => !(left == right); + /// Allow-all was enabled through an RPC caller. + public static PermissionsSetApproveAllSource Rpc { get; } = new("rpc"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(PermissionsSetApproveAllSource left, PermissionsSetApproveAllSource right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(PermissionsSetApproveAllSource left, PermissionsSetApproveAllSource right) => !(left == right); /// - public override bool Equals(object? obj) => obj is OptionsUpdateToolFilterPrecedence other && Equals(other); + public override bool Equals(object? obj) => obj is PermissionsSetApproveAllSource other && Equals(other); /// - public bool Equals(OptionsUpdateToolFilterPrecedence other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(PermissionsSetApproveAllSource other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -17702,68 +20664,65 @@ public OptionsUpdateToolFilterPrecedence(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override OptionsUpdateToolFilterPrecedence Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override PermissionsSetApproveAllSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, OptionsUpdateToolFilterPrecedence value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, PermissionsSetApproveAllSource value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(OptionsUpdateToolFilterPrecedence)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsSetApproveAllSource)); } } } -/// Discovery source: project (.github/extensions/), user (~/.copilot/extensions/), plugin (installed plugin), or session (session-state/<id>/extensions/). +/// Current or requested allow-all mode. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct ExtensionSource : IEquatable +public readonly struct PermissionsAllowAllMode : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public ExtensionSource(string value) + public PermissionsAllowAllMode(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Extension discovered from the current project's .github/extensions directory. - public static ExtensionSource Project { get; } = new("project"); - - /// Extension discovered from the user's ~/.copilot/extensions directory. - public static ExtensionSource User { get; } = new("user"); + /// Permission requests follow the normal approval flow. + public static PermissionsAllowAllMode Off { get; } = new("off"); - /// Extension contributed by an installed plugin. - public static ExtensionSource Plugin { get; } = new("plugin"); + /// Tool, path, and URL permission requests are automatically approved. + public static PermissionsAllowAllMode On { get; } = new("on"); - /// Extension discovered from the current session's state directory (loaded only for this session). - public static ExtensionSource Session { get; } = new("session"); + /// Permission requests follow the normal approval flow with an LLM advisory recommendation attached; clients may choose to auto-approve requests the judge evaluated as acceptable. + public static PermissionsAllowAllMode Auto { get; } = new("auto"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(ExtensionSource left, ExtensionSource right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(PermissionsAllowAllMode left, PermissionsAllowAllMode right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(ExtensionSource left, ExtensionSource right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(PermissionsAllowAllMode left, PermissionsAllowAllMode right) => !(left == right); /// - public override bool Equals(object? obj) => obj is ExtensionSource other && Equals(other); + public override bool Equals(object? obj) => obj is PermissionsAllowAllMode other && Equals(other); /// - public bool Equals(ExtensionSource other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(PermissionsAllowAllMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -17771,68 +20730,68 @@ public ExtensionSource(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override ExtensionSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override PermissionsAllowAllMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, ExtensionSource value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, PermissionsAllowAllMode value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ExtensionSource)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsAllowAllMode)); } } } -/// Current status: running, disabled, failed, or starting. +/// Optional source for allow-all telemetry. Defaults to `rpc` when omitted for SDK callers. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct ExtensionStatus : IEquatable +public readonly struct PermissionsSetAllowAllSource : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public ExtensionStatus(string value) + public PermissionsSetAllowAllSource(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The extension process is running. - public static ExtensionStatus Running { get; } = new("running"); + /// Allow-all was enabled from a CLI command-line flag. + public static PermissionsSetAllowAllSource CliFlag { get; } = new("cli_flag"); - /// The extension is installed but disabled. - public static ExtensionStatus Disabled { get; } = new("disabled"); + /// Allow-all was enabled by a slash command. + public static PermissionsSetAllowAllSource SlashCommand { get; } = new("slash_command"); - /// The extension failed to start or crashed. - public static ExtensionStatus Failed { get; } = new("failed"); + /// Allow-all was enabled by confirming autopilot behavior. + public static PermissionsSetAllowAllSource AutopilotConfirmation { get; } = new("autopilot_confirmation"); - /// The extension process is starting. - public static ExtensionStatus Starting { get; } = new("starting"); + /// Allow-all was enabled through an RPC caller. + public static PermissionsSetAllowAllSource Rpc { get; } = new("rpc"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(ExtensionStatus left, ExtensionStatus right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(PermissionsSetAllowAllSource left, PermissionsSetAllowAllSource right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(ExtensionStatus left, ExtensionStatus right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(PermissionsSetAllowAllSource left, PermissionsSetAllowAllSource right) => !(left == right); /// - public override bool Equals(object? obj) => obj is ExtensionStatus other && Equals(other); + public override bool Equals(object? obj) => obj is PermissionsSetAllowAllSource other && Equals(other); /// - public bool Equals(ExtensionStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(PermissionsSetAllowAllSource other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -17840,65 +20799,62 @@ public ExtensionStatus(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override ExtensionStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override PermissionsSetAllowAllSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, ExtensionStatus value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, PermissionsSetAllowAllSource value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ExtensionStatus)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsSetAllowAllSource)); } } } -/// Type of GitHub reference. +/// Whether the change applies to ephemeral session-scoped rules (cleared at session end) or to location-scoped rules persisted via the location-permissions config file. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct PushAttachmentGitHubReferenceType : IEquatable +public readonly struct PermissionsModifyRulesScope : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public PushAttachmentGitHubReferenceType(string value) + public PermissionsModifyRulesScope(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// GitHub issue reference. - public static PushAttachmentGitHubReferenceType Issue { get; } = new("issue"); - - /// GitHub pull request reference. - public static PushAttachmentGitHubReferenceType Pr { get; } = new("pr"); + /// Apply the rule change only to this session. + public static PermissionsModifyRulesScope Session { get; } = new("session"); - /// GitHub discussion reference. - public static PushAttachmentGitHubReferenceType Discussion { get; } = new("discussion"); + /// Persist the rule change for this project location. + public static PermissionsModifyRulesScope Location { get; } = new("location"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(PushAttachmentGitHubReferenceType left, PushAttachmentGitHubReferenceType right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(PermissionsModifyRulesScope left, PermissionsModifyRulesScope right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(PushAttachmentGitHubReferenceType left, PushAttachmentGitHubReferenceType right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(PermissionsModifyRulesScope left, PermissionsModifyRulesScope right) => !(left == right); /// - public override bool Equals(object? obj) => obj is PushAttachmentGitHubReferenceType other && Equals(other); + public override bool Equals(object? obj) => obj is PermissionsModifyRulesScope other && Equals(other); /// - public bool Equals(PushAttachmentGitHubReferenceType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(PermissionsModifyRulesScope other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -17906,65 +20862,62 @@ public PushAttachmentGitHubReferenceType(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override PushAttachmentGitHubReferenceType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override PermissionsModifyRulesScope Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, PushAttachmentGitHubReferenceType value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, PermissionsModifyRulesScope value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PushAttachmentGitHubReferenceType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsModifyRulesScope)); } } } -/// Context tier override for matching subagents. +/// Whether the location is a git repo or directory. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct SubagentSettingsEntryContextTier : IEquatable +public readonly struct PermissionLocationType : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public SubagentSettingsEntryContextTier(string value) + public PermissionLocationType(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Inherit the parent session's effective context tier at dispatch time. - public static SubagentSettingsEntryContextTier Inherit { get; } = new("inherit"); - - /// Use the model's default context window. - public static SubagentSettingsEntryContextTier Default { get; } = new("default"); + /// The permission location is persisted at the git repository root. + public static PermissionLocationType Repo { get; } = new("repo"); - /// Pin the subagent to the long-context tier when supported. - public static SubagentSettingsEntryContextTier LongContext { get; } = new("long_context"); + /// The permission location is persisted at the working directory. + public static PermissionLocationType Dir { get; } = new("dir"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(SubagentSettingsEntryContextTier left, SubagentSettingsEntryContextTier right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(PermissionLocationType left, PermissionLocationType right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(SubagentSettingsEntryContextTier left, SubagentSettingsEntryContextTier right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(PermissionLocationType left, PermissionLocationType right) => !(left == right); /// - public override bool Equals(object? obj) => obj is SubagentSettingsEntryContextTier other && Equals(other); + public override bool Equals(object? obj) => obj is PermissionLocationType other && Equals(other); /// - public bool Equals(SubagentSettingsEntryContextTier other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(PermissionLocationType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -17972,65 +20925,65 @@ public SubagentSettingsEntryContextTier(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override SubagentSettingsEntryContextTier Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override PermissionLocationType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, SubagentSettingsEntryContextTier value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, PermissionLocationType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SubagentSettingsEntryContextTier)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionLocationType)); } } } -/// The user's response: accept (submitted), decline (rejected), or cancel (dismissed). +/// The current agent mode for this session (e.g., 'interactive', 'plan', 'autopilot'). [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct UIElicitationResponseAction : IEquatable +public readonly struct MetadataSnapshotCurrentMode : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public UIElicitationResponseAction(string value) + public MetadataSnapshotCurrentMode(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The user submitted the requested form values. - public static UIElicitationResponseAction Accept { get; } = new("accept"); + /// The agent is responding interactively to the user. + public static MetadataSnapshotCurrentMode Interactive { get; } = new("interactive"); - /// The user explicitly declined to provide the requested input. - public static UIElicitationResponseAction Decline { get; } = new("decline"); + /// The agent is preparing a plan before making changes. + public static MetadataSnapshotCurrentMode Plan { get; } = new("plan"); - /// The user dismissed the elicitation request. - public static UIElicitationResponseAction Cancel { get; } = new("cancel"); + /// The agent is working autonomously toward task completion. + public static MetadataSnapshotCurrentMode Autopilot { get; } = new("autopilot"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(UIElicitationResponseAction left, UIElicitationResponseAction right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(MetadataSnapshotCurrentMode left, MetadataSnapshotCurrentMode right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(UIElicitationResponseAction left, UIElicitationResponseAction right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(MetadataSnapshotCurrentMode left, MetadataSnapshotCurrentMode right) => !(left == right); /// - public override bool Equals(object? obj) => obj is UIElicitationResponseAction other && Equals(other); + public override bool Equals(object? obj) => obj is MetadataSnapshotCurrentMode other && Equals(other); /// - public bool Equals(UIElicitationResponseAction other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(MetadataSnapshotCurrentMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -18038,65 +20991,62 @@ public UIElicitationResponseAction(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override UIElicitationResponseAction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override MetadataSnapshotCurrentMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, UIElicitationResponseAction value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, MetadataSnapshotCurrentMode value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UIElicitationResponseAction)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(MetadataSnapshotCurrentMode)); } } } -/// User's choice for auto-mode switching: yes (allow this turn), yes_always (allow + persist as setting), or no (decline). +/// Whether the remote task originated from Copilot Coding Agent (cca) or a CLI `--remote` invocation. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct UIAutoModeSwitchResponse : IEquatable +public readonly struct MetadataSnapshotRemoteMetadataTaskType : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public UIAutoModeSwitchResponse(string value) + public MetadataSnapshotRemoteMetadataTaskType(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Allow the automatic mode switch for this turn. - public static UIAutoModeSwitchResponse Yes { get; } = new("yes"); - - /// Allow this mode switch and persist the preference. - public static UIAutoModeSwitchResponse YesAlways { get; } = new("yes_always"); + /// Remote task originated from Copilot Coding Agent. + public static MetadataSnapshotRemoteMetadataTaskType Cca { get; } = new("cca"); - /// Decline the automatic mode switch. - public static UIAutoModeSwitchResponse No { get; } = new("no"); + /// Remote task originated from a CLI remote-session invocation. + public static MetadataSnapshotRemoteMetadataTaskType Cli { get; } = new("cli"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(UIAutoModeSwitchResponse left, UIAutoModeSwitchResponse right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(MetadataSnapshotRemoteMetadataTaskType left, MetadataSnapshotRemoteMetadataTaskType right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(UIAutoModeSwitchResponse left, UIAutoModeSwitchResponse right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(MetadataSnapshotRemoteMetadataTaskType left, MetadataSnapshotRemoteMetadataTaskType right) => !(left == right); /// - public override bool Equals(object? obj) => obj is UIAutoModeSwitchResponse other && Equals(other); + public override bool Equals(object? obj) => obj is MetadataSnapshotRemoteMetadataTaskType other && Equals(other); /// - public bool Equals(UIAutoModeSwitchResponse other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(MetadataSnapshotRemoteMetadataTaskType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -18104,68 +21054,62 @@ public UIAutoModeSwitchResponse(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override UIAutoModeSwitchResponse Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override MetadataSnapshotRemoteMetadataTaskType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, UIAutoModeSwitchResponse value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, MetadataSnapshotRemoteMetadataTaskType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UIAutoModeSwitchResponse)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(MetadataSnapshotRemoteMetadataTaskType)); } } } -/// User action selected for an exhausted session limit. +/// Repository host type, if known. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct UISessionLimitsExhaustedResponseAction : IEquatable +public readonly struct WorkspaceSummaryHostType : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public UISessionLimitsExhaustedResponseAction(string value) + public WorkspaceSummaryHostType(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Increase the current max by an exact AI Credits amount. - public static UISessionLimitsExhaustedResponseAction Add { get; } = new("add"); - - /// Set a new absolute max AI Credits value. - public static UISessionLimitsExhaustedResponseAction Set { get; } = new("set"); - - /// Remove the current session limit. - public static UISessionLimitsExhaustedResponseAction Unset { get; } = new("unset"); + /// Workspace summary repository is hosted on GitHub. + public static WorkspaceSummaryHostType GitHub { get; } = new("github"); - /// Leave the limit unchanged and cancel the blocked model request. - public static UISessionLimitsExhaustedResponseAction Cancel { get; } = new("cancel"); + /// Workspace summary repository is hosted on Azure DevOps. + public static WorkspaceSummaryHostType Ado { get; } = new("ado"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(UISessionLimitsExhaustedResponseAction left, UISessionLimitsExhaustedResponseAction right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(WorkspaceSummaryHostType left, WorkspaceSummaryHostType right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(UISessionLimitsExhaustedResponseAction left, UISessionLimitsExhaustedResponseAction right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(WorkspaceSummaryHostType left, WorkspaceSummaryHostType right) => !(left == right); /// - public override bool Equals(object? obj) => obj is UISessionLimitsExhaustedResponseAction other && Equals(other); + public override bool Equals(object? obj) => obj is WorkspaceSummaryHostType other && Equals(other); /// - public bool Equals(UISessionLimitsExhaustedResponseAction other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(WorkspaceSummaryHostType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -18173,68 +21117,62 @@ public UISessionLimitsExhaustedResponseAction(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override UISessionLimitsExhaustedResponseAction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override WorkspaceSummaryHostType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, UISessionLimitsExhaustedResponseAction value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, WorkspaceSummaryHostType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UISessionLimitsExhaustedResponseAction)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(WorkspaceSummaryHostType)); } } } -/// The action the user selected. Defaults to 'autopilot' when autoApproveEdits is true, otherwise 'interactive'. +/// Hosting platform type of the repository. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct UIExitPlanModeAction : IEquatable +public readonly struct SessionWorkingDirectoryContextHostType : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public UIExitPlanModeAction(string value) + public SessionWorkingDirectoryContextHostType(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Exit plan mode without starting implementation. - public static UIExitPlanModeAction ExitOnly { get; } = new("exit_only"); - - /// Exit plan mode and continue interactively. - public static UIExitPlanModeAction Interactive { get; } = new("interactive"); - - /// Exit plan mode and continue in autopilot mode. - public static UIExitPlanModeAction Autopilot { get; } = new("autopilot"); + /// The working directory repository is hosted on GitHub. + public static SessionWorkingDirectoryContextHostType GitHub { get; } = new("github"); - /// Exit plan mode and continue in autopilot mode with parallel subagent execution. - public static UIExitPlanModeAction AutopilotFleet { get; } = new("autopilot_fleet"); + /// The working directory repository is hosted on Azure DevOps. + public static SessionWorkingDirectoryContextHostType Ado { get; } = new("ado"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(UIExitPlanModeAction left, UIExitPlanModeAction right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SessionWorkingDirectoryContextHostType left, SessionWorkingDirectoryContextHostType right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(UIExitPlanModeAction left, UIExitPlanModeAction right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SessionWorkingDirectoryContextHostType left, SessionWorkingDirectoryContextHostType right) => !(left == right); /// - public override bool Equals(object? obj) => obj is UIExitPlanModeAction other && Equals(other); + public override bool Equals(object? obj) => obj is SessionWorkingDirectoryContextHostType other && Equals(other); /// - public bool Equals(UIExitPlanModeAction other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(SessionWorkingDirectoryContextHostType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -18242,62 +21180,113 @@ public UIExitPlanModeAction(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override UIExitPlanModeAction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override SessionWorkingDirectoryContextHostType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, UIExitPlanModeAction value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, SessionWorkingDirectoryContextHostType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(UIExitPlanModeAction)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionWorkingDirectoryContextHostType)); } } } -/// Allowed values for the `PermissionsConfigureAdditionalContentExclusionPolicyScope` enumeration. +/// Rust-owned settings predicates exposed across the SDK boundary. Raw feature-flag names are intentionally not part of the contract. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct PermissionsConfigureAdditionalContentExclusionPolicyScope : IEquatable +public readonly struct SessionSettingsPredicateName : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public PermissionsConfigureAdditionalContentExclusionPolicyScope(string value) + public SessionSettingsPredicateName(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The content exclusion policy applies to the current repository. - public static PermissionsConfigureAdditionalContentExclusionPolicyScope Repo { get; } = new("repo"); + /// Whether the security-tools feature flag enables security tool wiring. + public static SessionSettingsPredicateName SecurityToolsEnabled { get; } = new("securityToolsEnabled"); - /// The content exclusion policy applies across all repositories. - public static PermissionsConfigureAdditionalContentExclusionPolicyScope All { get; } = new("all"); + /// Whether third-party security tools should receive the security prompt. + public static SessionSettingsPredicateName ThirdPartySecurityPromptEnabled { get; } = new("thirdPartySecurityPromptEnabled"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(PermissionsConfigureAdditionalContentExclusionPolicyScope left, PermissionsConfigureAdditionalContentExclusionPolicyScope right) => left.Equals(right); + /// Whether validation may run in parallel. + public static SessionSettingsPredicateName ParallelValidationEnabled { get; } = new("parallelValidationEnabled"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(PermissionsConfigureAdditionalContentExclusionPolicyScope left, PermissionsConfigureAdditionalContentExclusionPolicyScope right) => !(left == right); + /// Whether runtime timing telemetry is enabled. + public static SessionSettingsPredicateName RuntimeTimingTelemetryEnabled { get; } = new("runtimeTimingTelemetryEnabled"); + + /// Whether the co-author hook is enabled. + public static SessionSettingsPredicateName CoAuthorHookEnabled { get; } = new("coAuthorHookEnabled"); + + /// Whether Chronicle integration is enabled. + public static SessionSettingsPredicateName ChronicleEnabled { get; } = new("chronicleEnabled"); + + /// Whether content-exclusion policy may self-fetch data. + public static SessionSettingsPredicateName ContentExclusionSelfFetchEnabled { get; } = new("contentExclusionSelfFetchEnabled"); + + /// Whether Claude Opus token-limit caps should be applied. + public static SessionSettingsPredicateName CapClaudeOpusTokenLimitsEnabled { get; } = new("capClaudeOpusTokenLimitsEnabled"); + + /// Whether code-review behavior is enabled. + public static SessionSettingsPredicateName CodeReviewFeatureEnabled { get; } = new("codeReviewFeatureEnabled"); + + /// Whether CCA should use the TypeScript autofind behavior. + public static SessionSettingsPredicateName CcaUseTsAutofindEnabled { get; } = new("ccaUseTsAutofindEnabled"); + + /// Whether the dependency checker is enabled. + public static SessionSettingsPredicateName DependencyCheckerEnabled { get; } = new("dependencyCheckerEnabled"); + + /// Whether the Dependabot checker is enabled. + public static SessionSettingsPredicateName DependabotCheckerEnabled { get; } = new("dependabotCheckerEnabled"); + + /// Whether the CodeQL checker is enabled. + public static SessionSettingsPredicateName CodeqlCheckerEnabled { get; } = new("codeqlCheckerEnabled"); + + /// Whether trivial-change handling is enabled. + public static SessionSettingsPredicateName TrivialChangeEnabled { get; } = new("trivialChangeEnabled"); + + /// Whether trivial-change skip behavior is enabled. + public static SessionSettingsPredicateName TrivialChangeSkipEnabled { get; } = new("trivialChangeSkipEnabled"); + + /// Whether trivial-change handling is enabled for code review. + public static SessionSettingsPredicateName TrivialChangeEnabledForCodeReview { get; } = new("trivialChangeEnabledForCodeReview"); + + /// Whether trivial-change skip behavior is enabled for code review. + public static SessionSettingsPredicateName TrivialChangeSkipEnabledForCodeReview { get; } = new("trivialChangeSkipEnabledForCodeReview"); + + /// Whether trivial-change handling is enabled for a specific tool. + public static SessionSettingsPredicateName TrivialChangeEnabledForTool { get; } = new("trivialChangeEnabledForTool"); + + /// Whether trivial-change skip behavior is enabled for a specific tool. + public static SessionSettingsPredicateName TrivialChangeSkipEnabledForTool { get; } = new("trivialChangeSkipEnabledForTool"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SessionSettingsPredicateName left, SessionSettingsPredicateName right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SessionSettingsPredicateName left, SessionSettingsPredicateName right) => !(left == right); /// - public override bool Equals(object? obj) => obj is PermissionsConfigureAdditionalContentExclusionPolicyScope other && Equals(other); + public override bool Equals(object? obj) => obj is SessionSettingsPredicateName other && Equals(other); /// - public bool Equals(PermissionsConfigureAdditionalContentExclusionPolicyScope other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(SessionSettingsPredicateName other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -18305,68 +21294,65 @@ public PermissionsConfigureAdditionalContentExclusionPolicyScope(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override PermissionsConfigureAdditionalContentExclusionPolicyScope Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override SessionSettingsPredicateName Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, PermissionsConfigureAdditionalContentExclusionPolicyScope value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, SessionSettingsPredicateName value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsConfigureAdditionalContentExclusionPolicyScope)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionSettingsPredicateName)); } } } -/// Optional source for allow-all telemetry. Defaults to `rpc` when omitted for SDK callers. +/// Signal to send (default: SIGTERM). [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct PermissionsSetApproveAllSource : IEquatable +public readonly struct ShellKillSignal : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public PermissionsSetApproveAllSource(string value) + public ShellKillSignal(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Allow-all was enabled from a CLI command-line flag. - public static PermissionsSetApproveAllSource CliFlag { get; } = new("cli_flag"); - - /// Allow-all was enabled by a slash command. - public static PermissionsSetApproveAllSource SlashCommand { get; } = new("slash_command"); + /// Request graceful process termination. + public static ShellKillSignal SIGTERM { get; } = new("SIGTERM"); - /// Allow-all was enabled by confirming autopilot behavior. - public static PermissionsSetApproveAllSource AutopilotConfirmation { get; } = new("autopilot_confirmation"); + /// Forcefully terminate the process. + public static ShellKillSignal SIGKILL { get; } = new("SIGKILL"); - /// Allow-all was enabled through an RPC caller. - public static PermissionsSetApproveAllSource Rpc { get; } = new("rpc"); + /// Send an interrupt signal to the process. + public static ShellKillSignal SIGINT { get; } = new("SIGINT"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(PermissionsSetApproveAllSource left, PermissionsSetApproveAllSource right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(ShellKillSignal left, ShellKillSignal right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(PermissionsSetApproveAllSource left, PermissionsSetApproveAllSource right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(ShellKillSignal left, ShellKillSignal right) => !(left == right); /// - public override bool Equals(object? obj) => obj is PermissionsSetApproveAllSource other && Equals(other); + public override bool Equals(object? obj) => obj is ShellKillSignal other && Equals(other); /// - public bool Equals(PermissionsSetApproveAllSource other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(ShellKillSignal other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -18374,65 +21360,61 @@ public PermissionsSetApproveAllSource(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override PermissionsSetApproveAllSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override ShellKillSignal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, PermissionsSetApproveAllSource value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, ShellKillSignal value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsSetApproveAllSource)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ShellKillSignal)); } } } -/// Current or requested allow-all mode. -[Experimental(Diagnostics.Experimental)] +/// What initiated this compaction request, recorded as the `trigger` on the persisted `session.compaction_start` / `session.compaction_complete` events. When absent, the compaction is persisted without trigger attribution (initiator unknown). [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct PermissionsAllowAllMode : IEquatable +public readonly struct SessionHistoryCompactRequestTrigger : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public PermissionsAllowAllMode(string value) + public SessionHistoryCompactRequestTrigger(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Permission requests follow the normal approval flow. - public static PermissionsAllowAllMode Off { get; } = new("off"); - - /// Tool, path, and URL permission requests are automatically approved. - public static PermissionsAllowAllMode On { get; } = new("on"); + /// User-requested compaction, e.g. the /compact command or a direct history.compact call. + public static SessionHistoryCompactRequestTrigger Manual { get; } = new("manual"); - /// Permission requests follow the normal approval flow with an LLM advisory recommendation attached; clients may choose to auto-approve requests the judge evaluated as acceptable. - public static PermissionsAllowAllMode Auto { get; } = new("auto"); + /// Compaction requested while switching to a model with a smaller context window. + public static SessionHistoryCompactRequestTrigger ModelSwitch { get; } = new("model_switch"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(PermissionsAllowAllMode left, PermissionsAllowAllMode right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SessionHistoryCompactRequestTrigger left, SessionHistoryCompactRequestTrigger right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(PermissionsAllowAllMode left, PermissionsAllowAllMode right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SessionHistoryCompactRequestTrigger left, SessionHistoryCompactRequestTrigger right) => !(left == right); /// - public override bool Equals(object? obj) => obj is PermissionsAllowAllMode other && Equals(other); + public override bool Equals(object? obj) => obj is SessionHistoryCompactRequestTrigger other && Equals(other); /// - public bool Equals(PermissionsAllowAllMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(SessionHistoryCompactRequestTrigger other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -18440,68 +21422,61 @@ public PermissionsAllowAllMode(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override PermissionsAllowAllMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override SessionHistoryCompactRequestTrigger Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, PermissionsAllowAllMode value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, SessionHistoryCompactRequestTrigger value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsAllowAllMode)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionHistoryCompactRequestTrigger)); } } } -/// Optional source for allow-all telemetry. Defaults to `rpc` when omitted for SDK callers. -[Experimental(Diagnostics.Experimental)] +/// What initiated this compaction request, recorded as the `trigger` on the persisted `session.compaction_start` / `session.compaction_complete` events. When absent, the compaction is persisted without trigger attribution (initiator unknown). [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct PermissionsSetAllowAllSource : IEquatable +public readonly struct SessionHistoryCompactRequestWithSessionTrigger : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public PermissionsSetAllowAllSource(string value) + public SessionHistoryCompactRequestWithSessionTrigger(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Allow-all was enabled from a CLI command-line flag. - public static PermissionsSetAllowAllSource CliFlag { get; } = new("cli_flag"); - - /// Allow-all was enabled by a slash command. - public static PermissionsSetAllowAllSource SlashCommand { get; } = new("slash_command"); - - /// Allow-all was enabled by confirming autopilot behavior. - public static PermissionsSetAllowAllSource AutopilotConfirmation { get; } = new("autopilot_confirmation"); + /// User-requested compaction, e.g. the /compact command or a direct history.compact call. + public static SessionHistoryCompactRequestWithSessionTrigger Manual { get; } = new("manual"); - /// Allow-all was enabled through an RPC caller. - public static PermissionsSetAllowAllSource Rpc { get; } = new("rpc"); + /// Compaction requested while switching to a model with a smaller context window. + public static SessionHistoryCompactRequestWithSessionTrigger ModelSwitch { get; } = new("model_switch"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(PermissionsSetAllowAllSource left, PermissionsSetAllowAllSource right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SessionHistoryCompactRequestWithSessionTrigger left, SessionHistoryCompactRequestWithSessionTrigger right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(PermissionsSetAllowAllSource left, PermissionsSetAllowAllSource right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SessionHistoryCompactRequestWithSessionTrigger left, SessionHistoryCompactRequestWithSessionTrigger right) => !(left == right); /// - public override bool Equals(object? obj) => obj is PermissionsSetAllowAllSource other && Equals(other); + public override bool Equals(object? obj) => obj is SessionHistoryCompactRequestWithSessionTrigger other && Equals(other); /// - public bool Equals(PermissionsSetAllowAllSource other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(SessionHistoryCompactRequestWithSessionTrigger other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -18509,62 +21484,65 @@ public PermissionsSetAllowAllSource(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override PermissionsSetAllowAllSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override SessionHistoryCompactRequestWithSessionTrigger Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, PermissionsSetAllowAllSource value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, SessionHistoryCompactRequestWithSessionTrigger value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsSetAllowAllSource)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionHistoryCompactRequestWithSessionTrigger)); } } } -/// Whether the change applies to ephemeral session-scoped rules (cleared at session end) or to location-scoped rules persisted via the location-permissions config file. +/// Aggregate file change represented by a rewind preview. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct PermissionsModifyRulesScope : IEquatable +public readonly struct HistoryRewindChangeType : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public PermissionsModifyRulesScope(string value) + public HistoryRewindChangeType(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Apply the rule change only to this session. - public static PermissionsModifyRulesScope Session { get; } = new("session"); + /// The discarded turns created the file. + public static HistoryRewindChangeType Created { get; } = new("created"); - /// Persist the rule change for this project location. - public static PermissionsModifyRulesScope Location { get; } = new("location"); + /// The discarded turns deleted the file. + public static HistoryRewindChangeType Deleted { get; } = new("deleted"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(PermissionsModifyRulesScope left, PermissionsModifyRulesScope right) => left.Equals(right); + /// The discarded turns modified the file. + public static HistoryRewindChangeType Modified { get; } = new("modified"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(PermissionsModifyRulesScope left, PermissionsModifyRulesScope right) => !(left == right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(HistoryRewindChangeType left, HistoryRewindChangeType right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(HistoryRewindChangeType left, HistoryRewindChangeType right) => !(left == right); /// - public override bool Equals(object? obj) => obj is PermissionsModifyRulesScope other && Equals(other); + public override bool Equals(object? obj) => obj is HistoryRewindChangeType other && Equals(other); /// - public bool Equals(PermissionsModifyRulesScope other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(HistoryRewindChangeType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -18572,62 +21550,83 @@ public PermissionsModifyRulesScope(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override PermissionsModifyRulesScope Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override HistoryRewindChangeType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, PermissionsModifyRulesScope value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, HistoryRewindChangeType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionsModifyRulesScope)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(HistoryRewindChangeType)); } } } -/// Whether the location is a git repo or directory. +/// Outcome of a rewind request. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct PermissionLocationType : IEquatable +public readonly struct HistoryRewindOutcome : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public PermissionLocationType(string value) + public HistoryRewindOutcome(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The permission location is persisted at the git repository root. - public static PermissionLocationType Repo { get; } = new("repo"); + /// The requested rewind completed; reachable in either mode. + public static HistoryRewindOutcome Success { get; } = new("success"); - /// The permission location is persisted at the working directory. - public static PermissionLocationType Dir { get; } = new("dir"); + /// The session still has work that may mutate files or history; reachable in either mode. + public static HistoryRewindOutcome SessionBusy { get; } = new("session-busy"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(PermissionLocationType left, PermissionLocationType right) => left.Equals(right); + /// A conversation-and-files rewind was requested for a session that did not enable capture; conversation-only rewinds never produce this. + public static HistoryRewindOutcome FileChangeTrackingDisabled { get; } = new("file-change-tracking-disabled"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(PermissionLocationType left, PermissionLocationType right) => !(left == right); + /// Remote-backed rewind routing is not supported; reachable in either mode. + public static HistoryRewindOutcome UnsupportedRemoteSession { get; } = new("unsupported-remote-session"); + + /// File restore failed and all applied file changes were rolled back; only conversation-and-files rewinds produce this. + public static HistoryRewindOutcome FilesRolledBack { get; } = new("files-rolled-back"); + + /// File restore failed and its rollback could not fully restore the pre-rewind state; only conversation-and-files rewinds produce this. + public static HistoryRewindOutcome RollbackIncomplete { get; } = new("rollback-incomplete"); + + /// Conversation truncation failed. In conversation-and-files mode any files that were restored are left in place because conversation history cannot be un-truncated; in conversation-only mode no files are restored. Consult restoredFiles for what, if anything, was applied. + public static HistoryRewindOutcome TruncationFailed { get; } = new("truncation-failed"); + + /// The conversation was rewound (and, in conversation-and-files mode, captured files were restored), but persisted checkpoints could not be cleaned up; reachable in either mode. + public static HistoryRewindOutcome CheckpointCleanupFailed { get; } = new("checkpoint-cleanup-failed"); + + /// Files and conversation were rewound, but obsolete file snapshots could not be removed; only conversation-and-files rewinds produce this. + public static HistoryRewindOutcome SnapshotPruneFailed { get; } = new("snapshot-prune-failed"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(HistoryRewindOutcome left, HistoryRewindOutcome right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(HistoryRewindOutcome left, HistoryRewindOutcome right) => !(left == right); /// - public override bool Equals(object? obj) => obj is PermissionLocationType other && Equals(other); + public override bool Equals(object? obj) => obj is HistoryRewindOutcome other && Equals(other); /// - public bool Equals(PermissionLocationType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(HistoryRewindOutcome other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -18635,65 +21634,62 @@ public PermissionLocationType(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override PermissionLocationType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override HistoryRewindOutcome Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, PermissionLocationType value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, HistoryRewindOutcome value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(PermissionLocationType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(HistoryRewindOutcome)); } } } -/// The current agent mode for this session (e.g., 'interactive', 'plan', 'autopilot'). +/// Reason a captured file was not restored. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct MetadataSnapshotCurrentMode : IEquatable +public readonly struct HistoryFileRestoreSkipReason : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public MetadataSnapshotCurrentMode(string value) + public HistoryFileRestoreSkipReason(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The agent is responding interactively to the user. - public static MetadataSnapshotCurrentMode Interactive { get; } = new("interactive"); - - /// The agent is preparing a plan before making changes. - public static MetadataSnapshotCurrentMode Plan { get; } = new("plan"); + /// The file changed after Copilot's last captured write. + public static HistoryFileRestoreSkipReason UserModified { get; } = new("user-modified"); - /// The agent is working autonomously toward task completion. - public static MetadataSnapshotCurrentMode Autopilot { get; } = new("autopilot"); + /// A faithful preimage was not captured. + public static HistoryFileRestoreSkipReason SkippedCapture { get; } = new("skipped-capture"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(MetadataSnapshotCurrentMode left, MetadataSnapshotCurrentMode right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(HistoryFileRestoreSkipReason left, HistoryFileRestoreSkipReason right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(MetadataSnapshotCurrentMode left, MetadataSnapshotCurrentMode right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(HistoryFileRestoreSkipReason left, HistoryFileRestoreSkipReason right) => !(left == right); /// - public override bool Equals(object? obj) => obj is MetadataSnapshotCurrentMode other && Equals(other); + public override bool Equals(object? obj) => obj is HistoryFileRestoreSkipReason other && Equals(other); /// - public bool Equals(MetadataSnapshotCurrentMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(HistoryFileRestoreSkipReason other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -18701,62 +21697,62 @@ public MetadataSnapshotCurrentMode(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override MetadataSnapshotCurrentMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override HistoryFileRestoreSkipReason Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, MetadataSnapshotCurrentMode value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, HistoryFileRestoreSkipReason value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(MetadataSnapshotCurrentMode)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(HistoryFileRestoreSkipReason)); } } } -/// Whether the remote task originated from Copilot Coding Agent (cca) or a CLI `--remote` invocation. +/// Scope of a rewind operation. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct MetadataSnapshotRemoteMetadataTaskType : IEquatable +public readonly struct HistoryRewindMode : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public MetadataSnapshotRemoteMetadataTaskType(string value) + public HistoryRewindMode(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Remote task originated from Copilot Coding Agent. - public static MetadataSnapshotRemoteMetadataTaskType Cca { get; } = new("cca"); + /// Discard conversation events while leaving files unchanged. + public static HistoryRewindMode Conversation { get; } = new("conversation"); - /// Remote task originated from a CLI remote-session invocation. - public static MetadataSnapshotRemoteMetadataTaskType Cli { get; } = new("cli"); + /// Discard conversation events and restore captured files changed by those turns. + public static HistoryRewindMode ConversationAndFiles { get; } = new("conversation-and-files"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(MetadataSnapshotRemoteMetadataTaskType left, MetadataSnapshotRemoteMetadataTaskType right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(HistoryRewindMode left, HistoryRewindMode right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(MetadataSnapshotRemoteMetadataTaskType left, MetadataSnapshotRemoteMetadataTaskType right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(HistoryRewindMode left, HistoryRewindMode right) => !(left == right); /// - public override bool Equals(object? obj) => obj is MetadataSnapshotRemoteMetadataTaskType other && Equals(other); + public override bool Equals(object? obj) => obj is HistoryRewindMode other && Equals(other); /// - public bool Equals(MetadataSnapshotRemoteMetadataTaskType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(HistoryRewindMode other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -18764,62 +21760,62 @@ public MetadataSnapshotRemoteMetadataTaskType(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override MetadataSnapshotRemoteMetadataTaskType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override HistoryRewindMode Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, MetadataSnapshotRemoteMetadataTaskType value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, HistoryRewindMode value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(MetadataSnapshotRemoteMetadataTaskType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(HistoryRewindMode)); } } } -/// Repository host type, if known. +/// Whether this item is a queued user message or a queued slash command / model change. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct WorkspaceSummaryHostType : IEquatable +public readonly struct QueuePendingItemsKind : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public WorkspaceSummaryHostType(string value) + public QueuePendingItemsKind(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Workspace summary repository is hosted on GitHub. - public static WorkspaceSummaryHostType GitHub { get; } = new("github"); + /// A queued user message. + public static QueuePendingItemsKind Message { get; } = new("message"); - /// Workspace summary repository is hosted on Azure DevOps. - public static WorkspaceSummaryHostType Ado { get; } = new("ado"); + /// A queued slash command or model-change command. + public static QueuePendingItemsKind Command { get; } = new("command"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(WorkspaceSummaryHostType left, WorkspaceSummaryHostType right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(QueuePendingItemsKind left, QueuePendingItemsKind right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(WorkspaceSummaryHostType left, WorkspaceSummaryHostType right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(QueuePendingItemsKind left, QueuePendingItemsKind right) => !(left == right); /// - public override bool Equals(object? obj) => obj is WorkspaceSummaryHostType other && Equals(other); + public override bool Equals(object? obj) => obj is QueuePendingItemsKind other && Equals(other); /// - public bool Equals(WorkspaceSummaryHostType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(QueuePendingItemsKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -18827,62 +21823,62 @@ public WorkspaceSummaryHostType(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override WorkspaceSummaryHostType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override QueuePendingItemsKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, WorkspaceSummaryHostType value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, QueuePendingItemsKind value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(WorkspaceSummaryHostType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(QueuePendingItemsKind)); } } } -/// Hosting platform type of the repository. +/// Cursor status: 'ok' means the cursor was applied successfully; 'expired' means the cursor referred to an event that no longer exists in history (e.g. truncated or compacted away) and the read started from the beginning of the remaining history. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct SessionWorkingDirectoryContextHostType : IEquatable +public readonly struct EventsCursorStatus : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public SessionWorkingDirectoryContextHostType(string value) + public EventsCursorStatus(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The working directory repository is hosted on GitHub. - public static SessionWorkingDirectoryContextHostType GitHub { get; } = new("github"); + /// The cursor was applied successfully. + public static EventsCursorStatus Ok { get; } = new("ok"); - /// The working directory repository is hosted on Azure DevOps. - public static SessionWorkingDirectoryContextHostType Ado { get; } = new("ado"); + /// The cursor referred to history that is no longer available. + public static EventsCursorStatus Expired { get; } = new("expired"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(SessionWorkingDirectoryContextHostType left, SessionWorkingDirectoryContextHostType right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(EventsCursorStatus left, EventsCursorStatus right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(SessionWorkingDirectoryContextHostType left, SessionWorkingDirectoryContextHostType right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(EventsCursorStatus left, EventsCursorStatus right) => !(left == right); /// - public override bool Equals(object? obj) => obj is SessionWorkingDirectoryContextHostType other && Equals(other); + public override bool Equals(object? obj) => obj is EventsCursorStatus other && Equals(other); /// - public bool Equals(SessionWorkingDirectoryContextHostType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(EventsCursorStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -18890,113 +21886,62 @@ public SessionWorkingDirectoryContextHostType(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override SessionWorkingDirectoryContextHostType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override EventsCursorStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, SessionWorkingDirectoryContextHostType value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, EventsCursorStatus value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionWorkingDirectoryContextHostType)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(EventsCursorStatus)); } } } -/// Rust-owned settings predicates exposed across the SDK boundary. Raw feature-flag names are intentionally not part of the contract. +/// 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. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct SessionSettingsPredicateName : IEquatable +public readonly struct EventsAgentScope : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public SessionSettingsPredicateName(string value) + public EventsAgentScope(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Whether the security-tools feature flag enables security tool wiring. - public static SessionSettingsPredicateName SecurityToolsEnabled { get; } = new("securityToolsEnabled"); - - /// Whether third-party security tools should receive the security prompt. - public static SessionSettingsPredicateName ThirdPartySecurityPromptEnabled { get; } = new("thirdPartySecurityPromptEnabled"); - - /// Whether validation may run in parallel. - public static SessionSettingsPredicateName ParallelValidationEnabled { get; } = new("parallelValidationEnabled"); - - /// Whether runtime timing telemetry is enabled. - public static SessionSettingsPredicateName RuntimeTimingTelemetryEnabled { get; } = new("runtimeTimingTelemetryEnabled"); - - /// Whether the co-author hook is enabled. - public static SessionSettingsPredicateName CoAuthorHookEnabled { get; } = new("coAuthorHookEnabled"); - - /// Whether Chronicle integration is enabled. - public static SessionSettingsPredicateName ChronicleEnabled { get; } = new("chronicleEnabled"); - - /// Whether content-exclusion policy may self-fetch data. - public static SessionSettingsPredicateName ContentExclusionSelfFetchEnabled { get; } = new("contentExclusionSelfFetchEnabled"); - - /// Whether Claude Opus token-limit caps should be applied. - public static SessionSettingsPredicateName CapClaudeOpusTokenLimitsEnabled { get; } = new("capClaudeOpusTokenLimitsEnabled"); - - /// Whether code-review behavior is enabled. - public static SessionSettingsPredicateName CodeReviewFeatureEnabled { get; } = new("codeReviewFeatureEnabled"); - - /// Whether CCA should use the TypeScript autofind behavior. - public static SessionSettingsPredicateName CcaUseTsAutofindEnabled { get; } = new("ccaUseTsAutofindEnabled"); - - /// Whether the dependency checker is enabled. - public static SessionSettingsPredicateName DependencyCheckerEnabled { get; } = new("dependencyCheckerEnabled"); - - /// Whether the Dependabot checker is enabled. - public static SessionSettingsPredicateName DependabotCheckerEnabled { get; } = new("dependabotCheckerEnabled"); - - /// Whether the CodeQL checker is enabled. - public static SessionSettingsPredicateName CodeqlCheckerEnabled { get; } = new("codeqlCheckerEnabled"); - - /// Whether trivial-change handling is enabled. - public static SessionSettingsPredicateName TrivialChangeEnabled { get; } = new("trivialChangeEnabled"); - - /// Whether trivial-change skip behavior is enabled. - public static SessionSettingsPredicateName TrivialChangeSkipEnabled { get; } = new("trivialChangeSkipEnabled"); - - /// Whether trivial-change handling is enabled for code review. - public static SessionSettingsPredicateName TrivialChangeEnabledForCodeReview { get; } = new("trivialChangeEnabledForCodeReview"); - - /// Whether trivial-change skip behavior is enabled for code review. - public static SessionSettingsPredicateName TrivialChangeSkipEnabledForCodeReview { get; } = new("trivialChangeSkipEnabledForCodeReview"); - - /// Whether trivial-change handling is enabled for a specific tool. - public static SessionSettingsPredicateName TrivialChangeEnabledForTool { get; } = new("trivialChangeEnabledForTool"); - - /// Whether trivial-change skip behavior is enabled for a specific tool. - public static SessionSettingsPredicateName TrivialChangeSkipEnabledForTool { get; } = new("trivialChangeSkipEnabledForTool"); + /// Return main-agent events and typed subagent lifecycle events. + public static EventsAgentScope Primary { get; } = new("primary"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(SessionSettingsPredicateName left, SessionSettingsPredicateName right) => left.Equals(right); + /// Return events from all agents. + public static EventsAgentScope All { get; } = new("all"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(SessionSettingsPredicateName left, SessionSettingsPredicateName right) => !(left == right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(EventsAgentScope left, EventsAgentScope right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(EventsAgentScope left, EventsAgentScope right) => !(left == right); /// - public override bool Equals(object? obj) => obj is SessionSettingsPredicateName other && Equals(other); + public override bool Equals(object? obj) => obj is EventsAgentScope other && Equals(other); /// - public bool Equals(SessionSettingsPredicateName other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(EventsAgentScope other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -19004,65 +21949,62 @@ public SessionSettingsPredicateName(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override SessionSettingsPredicateName Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override EventsAgentScope Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, SessionSettingsPredicateName value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, EventsAgentScope value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionSettingsPredicateName)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(EventsAgentScope)); } } } -/// Signal to send (default: SIGTERM). +/// Client population used for the prediction baseline. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct ShellKillSignal : IEquatable +public readonly struct SessionLimitPredictionClientType : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public ShellKillSignal(string value) + public SessionLimitPredictionClientType(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Request graceful process termination. - public static ShellKillSignal SIGTERM { get; } = new("SIGTERM"); - - /// Forcefully terminate the process. - public static ShellKillSignal SIGKILL { get; } = new("SIGKILL"); + /// Interactive CLI sessions where a user can accept, edit, or top up the limit. + public static SessionLimitPredictionClientType CliInteractive { get; } = new("cli-interactive"); - /// Send an interrupt signal to the process. - public static ShellKillSignal SIGINT { get; } = new("SIGINT"); + /// Prompt/non-interactive CLI sessions where the initial limit must cover more of the run. + public static SessionLimitPredictionClientType CliPrompt { get; } = new("cli-prompt"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(ShellKillSignal left, ShellKillSignal right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SessionLimitPredictionClientType left, SessionLimitPredictionClientType right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(ShellKillSignal left, ShellKillSignal right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SessionLimitPredictionClientType left, SessionLimitPredictionClientType right) => !(left == right); /// - public override bool Equals(object? obj) => obj is ShellKillSignal other && Equals(other); + public override bool Equals(object? obj) => obj is SessionLimitPredictionClientType other && Equals(other); /// - public bool Equals(ShellKillSignal other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(SessionLimitPredictionClientType other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -19070,62 +22012,68 @@ public ShellKillSignal(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override ShellKillSignal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override SessionLimitPredictionClientType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, ShellKillSignal value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, SessionLimitPredictionClientType value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ShellKillSignal)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionLimitPredictionClientType)); } } } -/// Whether this item is a queued user message or a queued slash command / model change. +/// Semantic usage tier used for a recommended cap or additional headroom. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct QueuePendingItemsKind : IEquatable +public readonly struct SessionLimitPredictionTier : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public QueuePendingItemsKind(string value) + public SessionLimitPredictionTier(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// A queued user message. - public static QueuePendingItemsKind Message { get; } = new("message"); + /// Recommended starting tier. + public static SessionLimitPredictionTier Recommended { get; } = new("recommended"); - /// A queued slash command or model-change command. - public static QueuePendingItemsKind Command { get; } = new("command"); + /// Additional headroom for longer-running sessions. + public static SessionLimitPredictionTier AdditionalHeadroom { get; } = new("additional_headroom"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(QueuePendingItemsKind left, QueuePendingItemsKind right) => left.Equals(right); + /// Generous headroom for unusually high usage. + public static SessionLimitPredictionTier GenerousHeadroom { get; } = new("generous_headroom"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(QueuePendingItemsKind left, QueuePendingItemsKind right) => !(left == right); + /// Maximum available headroom tier. + public static SessionLimitPredictionTier MaximumHeadroom { get; } = new("maximum_headroom"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SessionLimitPredictionTier left, SessionLimitPredictionTier right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SessionLimitPredictionTier left, SessionLimitPredictionTier right) => !(left == right); /// - public override bool Equals(object? obj) => obj is QueuePendingItemsKind other && Equals(other); + public override bool Equals(object? obj) => obj is SessionLimitPredictionTier other && Equals(other); /// - public bool Equals(QueuePendingItemsKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(SessionLimitPredictionTier other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -19133,62 +22081,65 @@ public QueuePendingItemsKind(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override QueuePendingItemsKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override SessionLimitPredictionTier Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, QueuePendingItemsKind value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, SessionLimitPredictionTier value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(QueuePendingItemsKind)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionLimitPredictionTier)); } } } -/// Cursor status: 'ok' means the cursor was applied successfully; 'expired' means the cursor referred to an event that no longer exists in history (e.g. truncated or compacted away) and the read started from the beginning of the remaining history. +/// Baseline fallback level used to create the prediction. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct EventsCursorStatus : IEquatable +public readonly struct SessionLimitPredictionSource : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public EventsCursorStatus(string value) + public SessionLimitPredictionSource(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The cursor was applied successfully. - public static EventsCursorStatus Ok { get; } = new("ok"); + /// The prediction used the exact resolved model's baseline cell. + public static SessionLimitPredictionSource Model { get; } = new("model"); - /// The cursor referred to history that is no longer available. - public static EventsCursorStatus Expired { get; } = new("expired"); + /// The exact model was unavailable, so the prediction used the model family's baseline cell. + public static SessionLimitPredictionSource Family { get; } = new("family"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(EventsCursorStatus left, EventsCursorStatus right) => left.Equals(right); + /// No model or family cell was available, so the prediction used the global client-type baseline cell. + public static SessionLimitPredictionSource Global { get; } = new("global"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(EventsCursorStatus left, EventsCursorStatus right) => !(left == right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SessionLimitPredictionSource left, SessionLimitPredictionSource right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SessionLimitPredictionSource left, SessionLimitPredictionSource right) => !(left == right); /// - public override bool Equals(object? obj) => obj is EventsCursorStatus other && Equals(other); + public override bool Equals(object? obj) => obj is SessionLimitPredictionSource other && Equals(other); /// - public bool Equals(EventsCursorStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(SessionLimitPredictionSource other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -19196,62 +22147,62 @@ public EventsCursorStatus(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override EventsCursorStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override SessionLimitPredictionSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, EventsCursorStatus value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, SessionLimitPredictionSource value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(EventsCursorStatus)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionLimitPredictionSource)); } } } -/// 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. +/// Reason a prediction could not be computed. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct EventsAgentScope : IEquatable +public readonly struct SessionLimitPredictionUnavailableReason : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public EventsAgentScope(string value) + public SessionLimitPredictionUnavailableReason(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Return main-agent events and typed subagent lifecycle events. - public static EventsAgentScope Primary { get; } = new("primary"); + /// The current model is auto and has not resolved to a concrete model yet. + public static SessionLimitPredictionUnavailableReason AutoUnresolved { get; } = new("auto_unresolved"); - /// Return events from all agents. - public static EventsAgentScope All { get; } = new("all"); + /// No model was provided and the session does not currently have a selected model. + public static SessionLimitPredictionUnavailableReason NoModel { get; } = new("no_model"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(EventsAgentScope left, EventsAgentScope right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SessionLimitPredictionUnavailableReason left, SessionLimitPredictionUnavailableReason right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(EventsAgentScope left, EventsAgentScope right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SessionLimitPredictionUnavailableReason left, SessionLimitPredictionUnavailableReason right) => !(left == right); /// - public override bool Equals(object? obj) => obj is EventsAgentScope other && Equals(other); + public override bool Equals(object? obj) => obj is SessionLimitPredictionUnavailableReason other && Equals(other); /// - public bool Equals(EventsAgentScope other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(SessionLimitPredictionUnavailableReason other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -19259,20 +22210,20 @@ public EventsAgentScope(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override EventsAgentScope Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override SessionLimitPredictionUnavailableReason Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, EventsAgentScope value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, SessionLimitPredictionUnavailableReason value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(EventsAgentScope)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionLimitPredictionUnavailableReason)); } } } @@ -19599,6 +22550,72 @@ public override void Write(Utf8JsonWriter writer, SessionFsSqliteQueryType value } +/// SQLite transaction failure classification. +[Experimental(Diagnostics.Experimental)] +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct SessionFsSqliteTransactionErrorClass : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public SessionFsSqliteTransactionErrorClass(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// SQLite reported BUSY or LOCKED before commit; the transaction was rolled back and may be retried. + public static SessionFsSqliteTransactionErrorClass BusyOrLocked { get; } = new("busyOrLocked"); + + /// The statement, database, or provider failed definitively and must not be retried automatically. + public static SessionFsSqliteTransactionErrorClass Fatal { get; } = new("fatal"); + + /// The transport failed after the provider may have committed; retrying could duplicate effects. + public static SessionFsSqliteTransactionErrorClass PostCommitAmbiguous { get; } = new("postCommitAmbiguous"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SessionFsSqliteTransactionErrorClass left, SessionFsSqliteTransactionErrorClass right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SessionFsSqliteTransactionErrorClass left, SessionFsSqliteTransactionErrorClass right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is SessionFsSqliteTransactionErrorClass other && Equals(other); + + /// + public bool Equals(SessionFsSqliteTransactionErrorClass other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override SessionFsSqliteTransactionErrorClass Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, SessionFsSqliteTransactionErrorClass value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionFsSqliteTransactionErrorClass)); + } + } +} + + /// Transport the runtime would otherwise use for this request. `http` (the default when absent) covers plain HTTP and SSE responses; `websocket` indicates a full-duplex message channel where each body chunk maps to one WebSocket message and the `binary` flag distinguishes text from binary frames. The SDK consumer uses this to decide whether to service the request with an HTTP client or a WebSocket client. It is the one piece of request metadata the consumer cannot reliably infer from the URL or headers alone. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] @@ -19685,7 +22702,7 @@ public async Task PingAsync(string? message = null, CancellationToke /// Performs the SDK server connection handshake and validates the optional connection token. Marked internal because this is JSON-RPC transport plumbing invoked automatically by an SDK client's own `connect()` wrapper, not a user-facing method. Stays internal as long as the SDK client owns the handshake; would only become public if the SDK ever exposed the raw schema surface to consumers without a connection wrapper. /// Connection token; required when the server was started with COPILOT_CONNECTION_TOKEN. - /// Opt this connection in to GitHub telemetry forwarding for its lifetime. When set, the runtime forwards every internal telemetry event it emits — across all sessions, plus sessionless events — to this connection over the `gitHubTelemetry.event` notification, in addition to the runtime's normal GitHub/CTS emission (dual-write). Intended for first-party hosts that re-emit the events into their own telemetry stores. Both unrestricted and restricted events are forwarded, each tagged with a `restricted` discriminator; a backstop drops restricted events when restricted telemetry is disabled. + /// Opt this connection in to GitHub telemetry forwarding for its lifetime. When set, the runtime forwards every internal telemetry event it emits — across all sessions, plus sessionless events — to this connection over the `gitHubTelemetry.event` notification. Regular events are also written to the runtime's normal GitHub/CTS path (dual-write); host-only compatibility events are forward-only and intentionally skip that path. Intended for first-party hosts that re-emit the events into their own telemetry stores. Both unrestricted and restricted events are forwarded, each tagged with a `restricted` discriminator; a backstop drops restricted events when restricted telemetry is disabled — using the process-global gate for ordinary events and an explicit session-scoped decision for host-only events. /// The to monitor for cancellation requests. The default is . /// Handshake result reporting the server's protocol version and package version on success. [Experimental(Diagnostics.Experimental)] @@ -19812,6 +22829,14 @@ public async Task ListAsync(string? gitHubToken = null, CancellationT var request = new ModelsListRequest { GitHubToken = gitHubToken }; return await CopilotClient.InvokeRpcAsync(_rpc, "models.list", [request], cancellationToken); } + + /// Returns the running runtime's complete catalog of well-known built-in model IDs without authentication or network access. + /// The to monitor for cancellation requests. The default is . + /// The running runtime's complete catalog of well-known built-in model IDs, including supported models and additional IDs with built-in metadata. + public async Task GetBuiltInCatalogAsync(CancellationToken cancellationToken = default) + { + return await CopilotClient.InvokeRpcAsync(_rpc, "models.getBuiltInCatalog", [], cancellationToken); + } } /// Provides server-scoped Tools APIs. @@ -20569,6 +23594,28 @@ public async Task ListAsync(SessionSource? source = null, long? met return await CopilotClient.InvokeRpcAsync(_rpc, "sessions.list", [request], cancellationToken); } + /// Reads lightweight persisted metadata for one local session without opening it. + /// Session ID to inspect. + /// The to monitor for cancellation requests. The default is . + /// Persisted local session metadata when the session exists. + internal async Task GetMetadataAsync(string sessionId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(sessionId); + + var request = new SessionsGetMetadataRequest { SessionId = sessionId }; + return await CopilotClient.InvokeRpcAsync(_rpc, "sessions.getMetadata", [request], cancellationToken); + } + + /// Lists recent local session IDs that contain user-visible history, omitting housekeeping-only sessions. + /// Maximum number of session IDs to return. + /// The to monitor for cancellation requests. The default is . + /// Recent local session IDs that contain user-visible history. + internal async Task ListNonEmptySessionIdsAsync(long? limit = null, CancellationToken cancellationToken = default) + { + var request = new SessionsListNonEmptySessionIdsRequest { Limit = limit }; + return await CopilotClient.InvokeRpcAsync(_rpc, "sessions.listNonEmptySessionIds", [request], cancellationToken); + } + /// Finds the local session bound to a GitHub task ID, if any. /// GitHub task ID to look up. /// The to monitor for cancellation requests. The default is . @@ -20671,6 +23718,18 @@ public async Task BulkDeleteAsync(IList session return await CopilotClient.InvokeRpcAsync(_rpc, "sessions.bulkDelete", [request], cancellationToken); } + /// Deletes one local session from disk after running the same lifecycle hooks as the session manager. + /// Session ID to delete. + /// Internal resolved session directory path to delete. + /// The to monitor for cancellation requests. The default is . + internal async Task DeleteAsync(string sessionId, string? sessionPath = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(sessionId); + + var request = new SessionsDeleteRequest { SessionId = sessionId, SessionPath = sessionPath }; + await CopilotClient.InvokeRpcAsync(_rpc, "sessions.delete", [request], cancellationToken); + } + /// Deletes sessions older than the given threshold, with optional dry-run and exclusion list. /// Delete sessions whose modifiedTime is at least this many days old. /// When true, only report what would be deleted without performing any deletion. @@ -21062,6 +24121,12 @@ internal SessionRpc(CopilotSession session) Interlocked.CompareExchange(ref field, new(_session), null) ?? field; + /// ContentExclusion APIs. + public ContentExclusionApi ContentExclusion => + field ?? + Interlocked.CompareExchange(ref field, new(_session), null) ?? + field; + /// Shell APIs. public ShellApi Shell => field ?? @@ -21092,6 +24157,12 @@ internal SessionRpc(CopilotSession session) Interlocked.CompareExchange(ref field, new(_session), null) ?? field; + /// LimitPrediction APIs. + public LimitPredictionApi LimitPrediction => + field ?? + Interlocked.CompareExchange(ref field, new(_session), null) ?? + field; + /// Remote APIs. public RemoteApi Remote => field ?? @@ -21129,12 +24200,12 @@ public async Task SuspendAsync(CancellationToken cancellationToken = default) /// If true, adds the message to the front of the queue instead of the end. /// If false, this message will not trigger a Premium Request Unit charge. User messages default to billable. /// If set, the request will fail if the named tool is not available when this message is among the user messages at the start of the current exchange. - /// Optional provenance tag copied to the resulting user.message event. Must match one of three forms: the literal `system`, `command-<command-id>` for messages originating from a command (e.g. slash command, Mission Control command), or `schedule-<numeric-id>` for messages originating from a scheduled job. + /// Optional provenance tag copied to the resulting user.message event. Must be `user`, `system`, `command-<command-id>` for command-originated messages, `schedule-<numeric-id>` for scheduled prompts, or `agent-<agent-id>` for prompts sent by another agent. /// The UI mode the agent was in when this message was sent. Defaults to the session's current mode. /// 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. /// W3C Trace Context traceparent header for distributed tracing of this agent turn. /// W3C Trace Context tracestate header for distributed tracing. - /// If true, await completion of the agentic loop for this message before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageId`; the caller can rely on the agent having processed the message before the call resolves. + /// If true, await completion of the agentic loop for this message before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageId`; the caller can rely on the agent having processed the message before the call resolves. Transport-dependent tail semantics: on a LOCAL (in-process) session the wait additionally blocks until the completed turn's event tail has been dispatched to this session's in-process subscribers, so a subsequent read of subscriber state already reflects the turn; on a REMOTE session the wait resolves once the loop completes and mirrored delivery follows over the wire. Callers that need the stronger local guarantee on remote sessions should await the event stream explicitly. /// The to monitor for cancellation requests. The default is . /// Result of sending a user message. [Experimental(Diagnostics.Experimental)] @@ -21155,7 +24226,7 @@ public async Task SendAsync(string prompt, string? displayPrompt = n /// 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. /// W3C Trace Context traceparent header for distributed tracing of this agent turn. /// W3C Trace Context tracestate header for distributed tracing. - /// If true, await completion of the agentic loop for this turn before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageIds`; the caller can rely on the agent having processed the messages before the call resolves. + /// If true, await completion of the agentic loop for this turn before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageIds`; the caller can rely on the agent having processed the messages before the call resolves. Transport-dependent tail semantics: on a LOCAL (in-process) session the wait additionally blocks until the completed turn's event tail has been dispatched to this session's in-process subscribers, so a subsequent read of subscriber state already reflects the turn; on a REMOTE session the wait resolves once the loop completes and mirrored delivery follows over the wire. Callers that need the stronger local guarantee on remote sessions should await the event stream explicitly. /// The to monitor for cancellation requests. The default is . /// Result of sending zero or more user messages. [Experimental(Diagnostics.Experimental)] @@ -21168,6 +24239,21 @@ public async Task SendMessagesAsync(IList m return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.sendMessages", [request], cancellationToken); } + /// Queues or sends an internal system notification to the session according to its passive policy. + /// Notification text to deliver to the model. + /// Optional structured notification kind. + /// Internal delivery options, including passive policy. + /// The to monitor for cancellation requests. The default is . + [Experimental(Diagnostics.Experimental)] + internal async Task SendSystemNotificationAsync(string message, object? kind = null, object? options = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(message); + _session.ThrowIfDisposed(); + + var request = new SendSystemNotificationRequest { SessionId = _session.SessionId, Message = message, Kind = CopilotClient.ToJsonElementForWire(kind), Options = CopilotClient.ToJsonElementForWire(options) }; + await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.sendSystemNotification", [request], cancellationToken); + } + /// Aborts the current agent turn. /// Finite reason code describing why the current turn was aborted. /// The to monitor for cancellation requests. The default is . @@ -21181,6 +24267,31 @@ public async Task AbortAsync(AbortReason? reason = null, Cancellati return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.abort", [request], cancellationToken); } + /// Interrupts the current main agent turn while leaving running background work (subagents, sidekicks, and promoted attached shells) alive. No-op when the main loop is not processing. + /// When true, the user's queued prompts are preserved and run as the next turn once the interrupted turn unwinds; when false (the default), the queue is cleared like a plain abort. + /// The to monitor for cancellation requests. The default is . + /// Result of interrupting the main agent turn. + [Experimental(Diagnostics.Experimental)] + public async Task InterruptMainTurnAsync(bool? flushQueued = null, CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new InterruptMainTurnRequest { SessionId = _session.SessionId, FlushQueued = flushQueued }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.interruptMainTurn", [request], cancellationToken); + } + + /// Cancels every running background agent (task-registry subagents plus sidekick agents) without interrupting the main agent loop. Promoted attached shells are left running. + /// The to monitor for cancellation requests. The default is . + /// The number of running background agents (task-registry agents) that were cancelled. + [Experimental(Diagnostics.Experimental)] + public async Task CancelAllBackgroundAgentsAsync(CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new SessionCancelAllBackgroundAgentsRequest { SessionId = _session.SessionId }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.cancelAllBackgroundAgents", [request], cancellationToken); + } + /// Shuts down the session and persists its final state. Awaits any deferred sessionEnd hooks before resolving so user-supplied hook scripts complete before the runtime tears down. /// Why the session is being shut down. Defaults to "routine" when omitted. /// Optional human-readable reason. Typically the message of the error that triggered shutdown when type is 'error'. @@ -21400,6 +24511,20 @@ public async Task RunAsync(string name, object args, RunOption return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.run", [request], cancellationToken); } + /// Resumes a factory run using its persisted name, arguments, journal, and accounting. + /// Factory run identifier. + /// Optional per-invocation resource ceiling overrides. + /// The to monitor for cancellation requests. The default is . + /// Resolved persisted factory identity and resumed run envelope. + public async Task ResumeAsync(string runId, FactoryRunLimits? limits = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(runId); + _session.ThrowIfDisposed(); + + var request = new FactoryResumeRequest { SessionId = _session.SessionId, RunId = runId, Limits = limits }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.resume", [request], cancellationToken); + } + /// Gets the current or settled envelope for a factory run. /// Factory run identifier. /// The to monitor for cancellation requests. The default is . @@ -21413,6 +24538,47 @@ public async Task GetRunAsync(string runId, CancellationToken return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.getRun", [request], cancellationToken); } + /// Lists durable factory runs for this session in creation order. + /// The to monitor for cancellation requests. The default is . + /// Factory runs in durable creation order. + public async Task ListRunsAsync(CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new FactoryListRunsRequest { SessionId = _session.SessionId }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.listRuns", [request], cancellationToken); + } + + /// Gets durable and live observability detail for one factory run. + /// Factory run identifier. + /// The to monitor for cancellation requests. The default is . + /// Full factory run observability detail. + public async Task GetRunDetailAsync(string runId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(runId); + _session.ThrowIfDisposed(); + + var request = new FactoryGetRunRequest { SessionId = _session.SessionId, RunId = runId }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.getRunDetail", [request], cancellationToken); + } + + /// Pages durable progress for one factory run. + /// Factory run identifier. + /// Optional phase identifier used to scope records and cursors. + /// Exclusive forward cursor. + /// Exclusive backward cursor. + /// Maximum records to return. Defaults to 200 and is capped at 500. + /// The to monitor for cancellation requests. The default is . + /// A bidirectional page of factory progress. + public async Task GetRunProgressAsync(string runId, string? phaseId = null, long? afterSeq = null, long? beforeSeq = null, int? limit = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(runId); + _session.ThrowIfDisposed(); + + var request = new FactoryGetRunProgressRequest { SessionId = _session.SessionId, RunId = runId, PhaseId = phaseId, AfterSeq = afterSeq, BeforeSeq = beforeSeq, Limit = limit }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.getRunProgress", [request], cancellationToken); + } + /// Requests cancellation of a factory run and returns its run envelope. /// Factory run identifier. /// The to monitor for cancellation requests. The default is . @@ -21428,33 +24594,37 @@ public async Task CancelAsync(string runId, CancellationToken /// Records a batch of ordered factory progress lines. /// Factory run identifier. + /// Opaque token identifying the current factory execution attempt. /// Ordered progress lines to append. /// The to monitor for cancellation requests. The default is . /// Acknowledgement that a factory request was accepted. - public async Task LogAsync(string runId, IList lines, CancellationToken cancellationToken = default) + public async Task LogAsync(string runId, string executionToken, IList lines, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(runId); + ArgumentNullException.ThrowIfNull(executionToken); ArgumentNullException.ThrowIfNull(lines); _session.ThrowIfDisposed(); - var request = new FactoryLogRequest { SessionId = _session.SessionId, RunId = runId, Lines = lines }; + var request = new FactoryLogRequest { SessionId = _session.SessionId, RunId = runId, ExecutionToken = executionToken, Lines = lines }; return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.log", [request], cancellationToken); } /// Runs one factory-scoped subagent and returns its result. /// Factory run identifier that owns the subagent. + /// Opaque token identifying the current factory execution attempt. /// Prompt to send to the subagent. /// Subagent execution options. /// The to monitor for cancellation requests. The default is . /// Result of one factory-scoped subagent call. - public async Task AgentAsync(string factoryRunId, string prompt, FactoryAgentOptions opts, CancellationToken cancellationToken = default) + public async Task AgentAsync(string factoryRunId, string executionToken, string prompt, FactoryAgentOptions opts, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(factoryRunId); + ArgumentNullException.ThrowIfNull(executionToken); ArgumentNullException.ThrowIfNull(prompt); ArgumentNullException.ThrowIfNull(opts); _session.ThrowIfDisposed(); - var request = new FactoryAgentRequest { SessionId = _session.SessionId, FactoryRunId = factoryRunId, Prompt = prompt, Opts = opts }; + var request = new FactoryAgentRequest { SessionId = _session.SessionId, FactoryRunId = factoryRunId, ExecutionToken = executionToken, Prompt = prompt, Opts = opts }; return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.agent", [request], cancellationToken); } @@ -21478,33 +24648,37 @@ internal FactoryJournalApi(CopilotSession session) /// Reads a memoized factory journal entry. /// Factory run identifier. + /// Opaque token identifying the current factory execution attempt. /// Namespaced journal key. /// The to monitor for cancellation requests. The default is . /// Result of reading a factory journal entry. - public async Task GetAsync(string runId, string key, CancellationToken cancellationToken = default) + public async Task GetAsync(string runId, string executionToken, string key, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(runId); + ArgumentNullException.ThrowIfNull(executionToken); ArgumentNullException.ThrowIfNull(key); _session.ThrowIfDisposed(); - var request = new FactoryJournalGetRequest { SessionId = _session.SessionId, RunId = runId, Key = key }; + var request = new FactoryJournalGetRequest { SessionId = _session.SessionId, RunId = runId, ExecutionToken = executionToken, Key = key }; return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.journal.get", [request], cancellationToken); } /// Stores a memoized factory journal entry. /// Factory run identifier. + /// Opaque token identifying the current factory execution attempt. /// Namespaced journal key. /// JSON result to memoize. /// The to monitor for cancellation requests. The default is . /// Acknowledgement that a factory request was accepted. - public async Task PutAsync(string runId, string key, object resultJson, CancellationToken cancellationToken = default) + public async Task PutAsync(string runId, string executionToken, string key, object resultJson, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(runId); + ArgumentNullException.ThrowIfNull(executionToken); ArgumentNullException.ThrowIfNull(key); ArgumentNullException.ThrowIfNull(resultJson); _session.ThrowIfDisposed(); - var request = new FactoryJournalPutRequest { SessionId = _session.SessionId, RunId = runId, Key = key, ResultJson = CopilotClient.ToJsonElementForWire(resultJson)!.Value }; + var request = new FactoryJournalPutRequest { SessionId = _session.SessionId, RunId = runId, ExecutionToken = executionToken, Key = key, ResultJson = CopilotClient.ToJsonElementForWire(resultJson)!.Value }; return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.journal.put", [request], cancellationToken); } } @@ -21538,14 +24712,15 @@ public async Task GetCurrentAsync(CancellationToken cancellationTo /// Output verbosity level to request for supported models. /// Override individual model capabilities resolved by the runtime. /// Explicit context tier for the selected model. `"default"` / `"long_context"` apply the requested tier; omit this field to use normal model behavior with no explicit tier. + /// When true, defer this switch (enqueue it) if another model change is already queued, even when no turn is active — so it drains last (FIFO) and wins over the already-queued change. Intended for genuine user-initiated model selections; internal restore/reapply switches omit it and apply immediately when no turn is active. When no other model change is queued this has no effect (a switch still applies immediately unless a turn is active). /// The to monitor for cancellation requests. The default is . /// The model identifier active on the session after the switch. - public async Task SwitchToAsync(string modelId, string? reasoningEffort = null, ReasoningSummary? reasoningSummary = null, Verbosity? verbosity = null, ModelCapabilitiesOverride? modelCapabilities = null, ContextTier? contextTier = null, CancellationToken cancellationToken = default) + public async Task SwitchToAsync(string modelId, string? reasoningEffort = null, ReasoningSummary? reasoningSummary = null, Verbosity? verbosity = null, ModelCapabilitiesOverride? modelCapabilities = null, ContextTier? contextTier = null, bool? deferIfModelChangeQueued = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(modelId); _session.ThrowIfDisposed(); - var request = new ModelSwitchToRequest { SessionId = _session.SessionId, ModelId = modelId, ReasoningEffort = reasoningEffort, ReasoningSummary = reasoningSummary, Verbosity = verbosity, ModelCapabilities = modelCapabilities, ContextTier = contextTier }; + var request = new ModelSwitchToRequest { SessionId = _session.SessionId, ModelId = modelId, ReasoningEffort = reasoningEffort, ReasoningSummary = reasoningSummary, Verbosity = verbosity, ModelCapabilities = modelCapabilities, ContextTier = contextTier, DeferIfModelChangeQueued = deferIfModelChangeQueued }; return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.model.switchTo", [request], cancellationToken); } @@ -21566,11 +24741,11 @@ public async Task SetReasoningEffortAsync(string /// Optional listing options. /// The to monitor for cancellation requests. The default is . /// The list of models available to this session. - public async Task ListAsync(ModelListRequest? request = null, CancellationToken cancellationToken = default) + public async Task ListAsync(SessionModelListRequest? request = null, CancellationToken cancellationToken = default) { _session.ThrowIfDisposed(); - var rpcRequest = new ModelListRequestWithSession { SessionId = _session.SessionId, SkipCache = request?.SkipCache }; + var rpcRequest = new SessionModelListRequestWithSession { SessionId = _session.SessionId, SkipCache = request?.SkipCache }; return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.model.list", [rpcRequest], cancellationToken); } } @@ -21732,18 +24907,43 @@ public sealed class WorkspacesApi internal WorkspacesApi(CopilotSession session) { - _session = session; + _session = session; + } + + /// Gets current workspace metadata for the session. + /// The to monitor for cancellation requests. The default is . + /// Current workspace metadata for the session, including its absolute filesystem path when available. + public async Task GetWorkspaceAsync(CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new SessionWorkspacesGetWorkspaceRequest { SessionId = _session.SessionId }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.workspaces.getWorkspace", [request], cancellationToken); + } + + /// Updates workspace metadata for a local session and returns the refreshed workspace. + /// Opaque workspace context supplied by the session host. + /// Optional workspace display name override. + /// The to monitor for cancellation requests. The default is . + /// Current workspace metadata for the session, including its absolute filesystem path when available. + public async Task UpdateMetadataAsync(object? context = null, string? name = null, CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new WorkspacesUpdateMetadataRequest { SessionId = _session.SessionId, Context = CopilotClient.ToJsonElementForWire(context), Name = name }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.workspaces.updateMetadata", [request], cancellationToken); } - /// Gets current workspace metadata for the session. + /// Ensures a local session workspace exists and returns it. + /// Opaque workspace context supplied by the session host. /// The to monitor for cancellation requests. The default is . /// Current workspace metadata for the session, including its absolute filesystem path when available. - public async Task GetWorkspaceAsync(CancellationToken cancellationToken = default) + public async Task EnsureAsync(object? context = null, CancellationToken cancellationToken = default) { _session.ThrowIfDisposed(); - var request = new SessionWorkspacesGetWorkspaceRequest { SessionId = _session.SessionId }; - return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.workspaces.getWorkspace", [request], cancellationToken); + var request = new WorkspacesEnsureRequest { SessionId = _session.SessionId, Context = CopilotClient.ToJsonElementForWire(context) }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.workspaces.ensure", [request], cancellationToken); } /// Lists files stored in the session workspace files directory. @@ -21807,6 +25007,79 @@ public async Task ReadCheckpointAsync(long numbe return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.workspaces.readCheckpoint", [request], cancellationToken); } + /// Adds a compaction summary checkpoint to the local session workspace. + /// Summary title shown in checkpoint listings. + /// Markdown summary content to persist. + /// The to monitor for cancellation requests. The default is . + /// Persisted summary metadata and refreshed workspace metadata. + public async Task AddSummaryAsync(string title, string content, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(title); + ArgumentNullException.ThrowIfNull(content); + _session.ThrowIfDisposed(); + + var request = new WorkspacesAddSummaryRequest { SessionId = _session.SessionId, Title = title, Content = content }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.workspaces.addSummary", [request], cancellationToken); + } + + /// Truncates local workspace compaction summaries after a rollback. + /// Number of newest summaries to keep. + /// The to monitor for cancellation requests. The default is . + /// Current workspace metadata for the session, including its absolute filesystem path when available. + public async Task TruncateSummariesAsync(long keepCount, CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new WorkspacesTruncateSummariesRequest { SessionId = _session.SessionId, KeepCount = keepCount }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.workspaces.truncateSummaries", [request], cancellationToken); + } + + /// Reads the autopilot objective state file from the local session workspace. + /// The to monitor for cancellation requests. The default is . + /// Autopilot objective file content, or null when missing. + public async Task ReadAutopilotObjectiveAsync(CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new SessionWorkspacesReadAutopilotObjectiveRequest { SessionId = _session.SessionId }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.workspaces.readAutopilotObjective", [request], cancellationToken); + } + + /// Writes the autopilot objective state file in the local session workspace. + /// Autopilot objective file content. + /// The to monitor for cancellation requests. The default is . + /// Result of writing the autopilot objective file. + public async Task WriteAutopilotObjectiveAsync(string content, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(content); + _session.ThrowIfDisposed(); + + var request = new WorkspacesWriteAutopilotObjectiveRequest { SessionId = _session.SessionId, Content = content }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.workspaces.writeAutopilotObjective", [request], cancellationToken); + } + + /// Deletes the autopilot objective state file from the local session workspace. + /// The to monitor for cancellation requests. The default is . + /// Result of deleting the autopilot objective file. + public async Task DeleteAutopilotObjectiveAsync(CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new SessionWorkspacesDeleteAutopilotObjectiveRequest { SessionId = _session.SessionId }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.workspaces.deleteAutopilotObjective", [request], cancellationToken); + } + + /// Checks whether the local session workspace has an autopilot objective state file. + /// The to monitor for cancellation requests. The default is . + /// Whether the autopilot objective file exists. + public async Task AutopilotObjectiveExistsAsync(CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new SessionWorkspacesAutopilotObjectiveExistsRequest { SessionId = _session.SessionId }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.workspaces.autopilotObjectiveExists", [request], cancellationToken); + } + /// Saves pasted content as a UTF-8 file in the session workspace. /// Pasted content to save as a UTF-8 file. /// The to monitor for cancellation requests. The default is . @@ -21820,7 +25093,7 @@ public async Task SaveLargePasteAsync(string con return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.workspaces.saveLargePaste", [request], cancellationToken); } - /// Computes a diff for the session workspace. + /// Computes a diff for the session workspace. Never rejects for a busy session: a `session`-mode diff that cannot read the session's file-change captures falls back to an unstaged git diff with `isFallback: true` and reports why in `unavailableReason`. /// Diff mode requested by the client. /// When true, ignore whitespace-only changes (git `--ignore-all-space`). Defaults to false. /// The to monitor for cancellation requests. The default is . @@ -21929,15 +25202,16 @@ internal AgentApi(CopilotSession session) _session = session; } - /// Lists custom agents available to the session. + /// Lists agents available to the session. Defaults to custom agents only; pass includeBuiltInAgents to include the effective built-in agents. + /// Controls whether built-in agents and authored prompt text are included. /// The to monitor for cancellation requests. The default is . - /// Custom agents available to the session. - public async Task ListAsync(CancellationToken cancellationToken = default) + /// Agents available to the session. + public async Task ListAsync(SessionAgentListRequest? request = null, CancellationToken cancellationToken = default) { _session.ThrowIfDisposed(); - var request = new SessionAgentListRequest { SessionId = _session.SessionId }; - return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.agent.list", [request], cancellationToken); + var rpcRequest = new SessionAgentListRequestWithSession { SessionId = _session.SessionId, IncludeBuiltInAgents = request?.IncludeBuiltInAgents, IncludePrompt = request?.IncludePrompt }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.agent.list", [rpcRequest], cancellationToken); } /// Gets the currently selected custom agent for the session. @@ -22369,17 +25643,16 @@ internal async Task ConfigureGitHubAsync(object authIn return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.mcp.configureGitHub", [request], cancellationToken); } - /// Starts an individual MCP server on the live session from a caller-supplied config. Session-scoped and ephemeral: the server is added to this session's running set only and is reaped when the session ends. Does NOT modify persistent user configuration (`mcp.config.*`), so it does not affect future sessions. The server surfaces through `session.mcp.list` and the `session.mcp_servers_loaded` / `session.mcp_server_status_changed` events like any other server. + /// Starts an individual MCP server on the live session. Omit `config` for a config-free start-by-name of an already-configured server (reuses the server's already-registered configuration); supply `config` to start from a caller-supplied configuration. Session-scoped and ephemeral: the server is added to this session's running set only and is reaped when the session ends. Does NOT modify persistent user configuration (`mcp.config.*`), so it does not affect future sessions. The server surfaces through `session.mcp.list` and the `session.mcp_servers_loaded` / `session.mcp_server_status_changed` events like any other server. /// Name of the MCP server to start. - /// MCP server configuration (stdio process or remote HTTP/SSE). + /// MCP server configuration (stdio process or remote HTTP/SSE). Omit to start the server with its already-registered configuration (config-free start-by-name). /// The to monitor for cancellation requests. The default is . - public async Task StartServerAsync(string serverName, object config, CancellationToken cancellationToken = default) + public async Task StartServerAsync(string serverName, object? config = null, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(serverName); - ArgumentNullException.ThrowIfNull(config); _session.ThrowIfDisposed(); - var request = new McpStartServerRequest { SessionId = _session.SessionId, ServerName = serverName, Config = CopilotClient.ToJsonElementForWire(config)!.Value }; + var request = new McpStartServerRequest { SessionId = _session.SessionId, ServerName = serverName, Config = CopilotClient.ToJsonElementForWire(config) }; await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.mcp.startServer", [request], cancellationToken); } @@ -22521,6 +25794,19 @@ public async Task LoginAsync(string serverName, bool? force var request = new McpOauthLoginRequest { SessionId = _session.SessionId, ServerName = serverName, ForceReauth = forceReauth, ClientName = clientName, CallbackSuccessMessage = callbackSuccessMessage, ClientId = clientId, ClientSecret = clientSecret, PublicClient = publicClient, GrantType = grantType }; return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.mcp.oauth.login", [request], cancellationToken); } + + /// Responds to a pending MCP OAuth authorization request by its request id. + /// OAuth request identifier from the mcp.oauth_required event. + /// The to monitor for cancellation requests. The default is . + /// Indicates whether the pending MCP OAuth response was accepted. + public async Task RespondAsync(string requestId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(requestId); + _session.ThrowIfDisposed(); + + var request = new McpOauthRespondRequest { SessionId = _session.SessionId, RequestId = requestId }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.mcp.oauth.respond", [request], cancellationToken); + } } /// Provides session-scoped McpHeaders APIs. @@ -22726,11 +26012,11 @@ public async Task ListAsync(CancellationToken cancellationToken = de /// Reloads the session's plugin set, refreshing MCP servers, custom agents, hooks, and skills cache so SDK-driven changes via `server.plugins.*` take effect immediately. /// Optional flags controlling which side effects the reload performs. /// The to monitor for cancellation requests. The default is . - public async Task ReloadAsync(PluginsReloadRequest? request = null, CancellationToken cancellationToken = default) + public async Task ReloadAsync(SessionPluginsReloadRequest? request = null, CancellationToken cancellationToken = default) { _session.ThrowIfDisposed(); - var rpcRequest = new PluginsReloadRequestWithSession { SessionId = _session.SessionId, ReloadMcp = request?.ReloadMcp, ReloadCustomAgents = request?.ReloadCustomAgents, ReloadHooks = request?.ReloadHooks, ReloadExtensions = request?.ReloadExtensions, DeferRepoHooks = request?.DeferRepoHooks }; + var rpcRequest = new SessionPluginsReloadRequestWithSession { SessionId = _session.SessionId, ReloadMcp = request?.ReloadMcp, ReloadCustomAgents = request?.ReloadCustomAgents, ReloadHooks = request?.ReloadHooks, ReloadExtensions = request?.ReloadExtensions, DeferRepoHooks = request?.DeferRepoHooks }; await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.plugins.reload", [rpcRequest], cancellationToken); } } @@ -22750,11 +26036,11 @@ internal ProviderApi(CopilotSession session) /// Optional model identifier to scope the endpoint snapshot to. /// The to monitor for cancellation requests. The default is . /// A snapshot of the provider endpoint the session is currently configured to talk to. - public async Task GetEndpointAsync(ProviderGetEndpointRequest? request = null, CancellationToken cancellationToken = default) + public async Task GetEndpointAsync(SessionProviderGetEndpointRequest? request = null, CancellationToken cancellationToken = default) { _session.ThrowIfDisposed(); - var rpcRequest = new ProviderGetEndpointRequestWithSession { SessionId = _session.SessionId, ModelId = request?.ModelId }; + var rpcRequest = new SessionProviderGetEndpointRequestWithSession { SessionId = _session.SessionId, ModelId = request?.ModelId }; return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.provider.getEndpoint", [rpcRequest], cancellationToken); } @@ -22803,15 +26089,16 @@ internal OptionsApi(CopilotSession session) /// Built-in subagent names to exclude from this session. Excluded built-ins are hidden from agent discovery and cannot be dispatched unless a custom agent with the same name is available. /// Controls how availableTools (allowlist) and excludedTools (denylist) combine when both are set. /// Whether shell-script safety heuristics are enabled. - /// Shell init profile (`None` or `NonInteractive`). - /// Per-shell process flags (e.g., `pwsh` arguments). + /// Per-session settings for built-in shell tools. + /// Use shell.initProfile instead. Shell init profile (`None` or `NonInteractive`). + /// PowerShell process flags applied to built-in and user-requested shell commands. /// Resolved sandbox configuration. /// Whether interactive shell sessions are logged. /// How env values are passed to MCP servers (`direct` inlines literal values; `indirect` resolves at launch). /// Whether to include instructions from every MCP server in the system prompt instead of only allowlisted servers. /// Additional directories to search for skills. /// Skill IDs that should be excluded from this session. - /// Whether to discover custom instructions on demand after successful file views (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md surfacing). Combined with `skipCustomInstructions` and the runtime-side `ON_DEMAND_INSTRUCTIONS` feature flag. + /// Whether to discover custom instructions on demand after successful file views (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md surfacing). Combined with `skipCustomInstructions`. /// Maximum decoded byte size of a single model-facing binary tool result (e.g. an image) persisted inline in session events and re-presented to the model on later turns / resume. Larger results are persisted as a metadata-only marker and shown to the model as a short text note. Defaults to 10 MB. /// Full set of installed plugins for the session. Replaces the existing list; the runtime invalidates the skills cache only when the list materially changes. /// Whether to default custom agents to local-only execution. @@ -22828,6 +26115,7 @@ internal OptionsApi(CopilotSession session) /// Whether to surface reasoning-summary events from the model. /// Runtime context discriminator (e.g., `cli`, `actions`). /// Override directory for the session-events log. When unset, the runtime's default events log directory is used. + /// Whether subagent callback events should be forwarded into the session event log sink. /// Additional content-exclusion policies to merge into the session's policy set. /// 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). /// Replaces the session's capability set with the given list. Use to enable or disable capabilities mid-session (e.g., remove `memory` for reproducible scripted runs). Omit the field to leave the existing capability set unchanged. @@ -22841,11 +26129,11 @@ internal OptionsApi(CopilotSession session) /// Optional session limits. Pass null to clear the session limits. /// 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, ModelCapabilitiesOverride? modelCapabilitiesOverrides = null, string? reasoningEffort = null, OptionsUpdateReasoningSummary? reasoningSummary = null, Verbosity? verbosity = null, string? clientName = null, string? lspClientName = null, string? integrationId = null, IDictionary? featureFlags = null, bool? isExperimentalMode = null, ProviderConfig? provider = null, CapiSessionOptions? capi = null, string? workingDirectory = null, IList? availableTools = null, IList? excludedTools = null, IList? includedBuiltinAgents = null, IList? excludedBuiltinAgents = null, OptionsUpdateToolFilterPrecedence? toolFilterPrecedence = null, bool? enableScriptSafety = null, string? shellInitProfile = null, IList? shellProcessFlags = null, SandboxConfig? sandboxConfig = null, bool? logInteractiveShells = null, OptionsUpdateEnvValueMode? envValueMode = null, bool? allowAllMcpServerInstructions = null, IList? skillDirectories = null, IList? disabledSkills = null, bool? enableOnDemandInstructionDiscovery = null, long? maxInlineBinaryBytes = null, IList? installedPlugins = null, bool? customAgentsLocalOnly = null, bool? suppressCustomAgentPrompt = 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, IList? sessionCapabilities = null, bool? skipEmbeddingRetrieval = null, string? organizationCustomInstructions = null, bool? enableFileHooks = null, bool? enableHostGitOperations = null, bool? enableSessionStore = null, bool? enableSkills = null, OptionsUpdateContextTier? contextTier = null, SessionLimitsConfig? sessionLimits = null, CancellationToken cancellationToken = default) + public async Task UpdateAsync(string? model = null, ModelCapabilitiesOverride? modelCapabilitiesOverrides = null, string? reasoningEffort = null, OptionsUpdateReasoningSummary? reasoningSummary = null, Verbosity? verbosity = null, string? clientName = null, string? lspClientName = null, string? integrationId = null, IDictionary? featureFlags = null, bool? isExperimentalMode = null, ProviderConfig? provider = null, CapiSessionOptions? capi = null, string? workingDirectory = null, IList? availableTools = null, IList? excludedTools = null, IList? includedBuiltinAgents = null, IList? excludedBuiltinAgents = null, OptionsUpdateToolFilterPrecedence? toolFilterPrecedence = null, bool? enableScriptSafety = null, ShellOptions? shell = null, string? shellInitProfile = null, IList? shellProcessFlags = null, SandboxConfig? sandboxConfig = null, bool? logInteractiveShells = null, OptionsUpdateEnvValueMode? envValueMode = null, bool? allowAllMcpServerInstructions = null, IList? skillDirectories = null, IList? disabledSkills = null, bool? enableOnDemandInstructionDiscovery = null, long? maxInlineBinaryBytes = null, IList? installedPlugins = null, bool? customAgentsLocalOnly = null, bool? suppressCustomAgentPrompt = 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, bool? eventsLogIncludesSubagents = null, IList? additionalContentExclusionPolicies = null, bool? manageScheduleEnabled = null, IList? sessionCapabilities = null, bool? skipEmbeddingRetrieval = null, string? organizationCustomInstructions = null, bool? enableFileHooks = null, bool? enableHostGitOperations = null, bool? enableSessionStore = null, bool? enableSkills = null, OptionsUpdateContextTier? contextTier = null, SessionLimitsConfig? sessionLimits = null, CancellationToken cancellationToken = default) { _session.ThrowIfDisposed(); - var request = new SessionUpdateOptionsParams { SessionId = _session.SessionId, Model = model, ModelCapabilitiesOverrides = modelCapabilitiesOverrides, ReasoningEffort = reasoningEffort, ReasoningSummary = reasoningSummary, Verbosity = verbosity, ClientName = clientName, LspClientName = lspClientName, IntegrationId = integrationId, FeatureFlags = featureFlags, IsExperimentalMode = isExperimentalMode, Provider = provider, Capi = capi, WorkingDirectory = workingDirectory, AvailableTools = availableTools, ExcludedTools = excludedTools, IncludedBuiltinAgents = includedBuiltinAgents, ExcludedBuiltinAgents = excludedBuiltinAgents, ToolFilterPrecedence = toolFilterPrecedence, EnableScriptSafety = enableScriptSafety, ShellInitProfile = shellInitProfile, ShellProcessFlags = shellProcessFlags, SandboxConfig = sandboxConfig, LogInteractiveShells = logInteractiveShells, EnvValueMode = envValueMode, AllowAllMcpServerInstructions = allowAllMcpServerInstructions, SkillDirectories = skillDirectories, DisabledSkills = disabledSkills, EnableOnDemandInstructionDiscovery = enableOnDemandInstructionDiscovery, MaxInlineBinaryBytes = maxInlineBinaryBytes, InstalledPlugins = installedPlugins, CustomAgentsLocalOnly = customAgentsLocalOnly, SuppressCustomAgentPrompt = suppressCustomAgentPrompt, 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, SessionCapabilities = sessionCapabilities, SkipEmbeddingRetrieval = skipEmbeddingRetrieval, OrganizationCustomInstructions = organizationCustomInstructions, EnableFileHooks = enableFileHooks, EnableHostGitOperations = enableHostGitOperations, EnableSessionStore = enableSessionStore, EnableSkills = enableSkills, ContextTier = contextTier, SessionLimits = sessionLimits }; + var request = new SessionUpdateOptionsParams { SessionId = _session.SessionId, Model = model, ModelCapabilitiesOverrides = modelCapabilitiesOverrides, ReasoningEffort = reasoningEffort, ReasoningSummary = reasoningSummary, Verbosity = verbosity, ClientName = clientName, LspClientName = lspClientName, IntegrationId = integrationId, FeatureFlags = featureFlags, IsExperimentalMode = isExperimentalMode, Provider = provider, Capi = capi, WorkingDirectory = workingDirectory, AvailableTools = availableTools, ExcludedTools = excludedTools, IncludedBuiltinAgents = includedBuiltinAgents, ExcludedBuiltinAgents = excludedBuiltinAgents, ToolFilterPrecedence = toolFilterPrecedence, EnableScriptSafety = enableScriptSafety, Shell = shell, ShellInitProfile = shellInitProfile, ShellProcessFlags = shellProcessFlags, SandboxConfig = sandboxConfig, LogInteractiveShells = logInteractiveShells, EnvValueMode = envValueMode, AllowAllMcpServerInstructions = allowAllMcpServerInstructions, SkillDirectories = skillDirectories, DisabledSkills = disabledSkills, EnableOnDemandInstructionDiscovery = enableOnDemandInstructionDiscovery, MaxInlineBinaryBytes = maxInlineBinaryBytes, InstalledPlugins = installedPlugins, CustomAgentsLocalOnly = customAgentsLocalOnly, SuppressCustomAgentPrompt = suppressCustomAgentPrompt, SkipCustomInstructions = skipCustomInstructions, DisabledInstructionSources = disabledInstructionSources, CoauthorEnabled = coauthorEnabled, TrajectoryFile = trajectoryFile, EnableStreaming = enableStreaming, CopilotUrl = copilotUrl, AskUserDisabled = askUserDisabled, ContinueOnAutoMode = continueOnAutoMode, RunningInInteractiveMode = runningInInteractiveMode, EnableReasoningSummaries = enableReasoningSummaries, AgentContext = agentContext, EventsLogDirectory = eventsLogDirectory, EventsLogIncludesSubagents = eventsLogIncludesSubagents, AdditionalContentExclusionPolicies = additionalContentExclusionPolicies, ManageScheduleEnabled = manageScheduleEnabled, SessionCapabilities = sessionCapabilities, SkipEmbeddingRetrieval = skipEmbeddingRetrieval, OrganizationCustomInstructions = organizationCustomInstructions, EnableFileHooks = enableFileHooks, EnableHostGitOperations = enableHostGitOperations, EnableSessionStore = enableSessionStore, EnableSkills = enableSkills, ContextTier = contextTier, SessionLimits = sessionLimits }; return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.options.update", [request], cancellationToken); } } @@ -23021,11 +26309,11 @@ internal CommandsApi(CopilotSession session) /// Optional filters controlling which command sources to include in the listing. /// The to monitor for cancellation requests. The default is . /// Slash commands available in the session, after applying any include/exclude filters. - public async Task ListAsync(CommandsListRequest? request = null, CancellationToken cancellationToken = default) + public async Task ListAsync(SessionCommandsListRequest? request = null, CancellationToken cancellationToken = default) { _session.ThrowIfDisposed(); - var rpcRequest = new CommandsListRequestWithSession { SessionId = _session.SessionId, IncludeBuiltins = request?.IncludeBuiltins, IncludeSkills = request?.IncludeSkills, IncludeClientCommands = request?.IncludeClientCommands }; + var rpcRequest = new SessionCommandsListRequestWithSession { SessionId = _session.SessionId, IncludeBuiltins = request?.IncludeBuiltins, IncludeSkills = request?.IncludeSkills, IncludeClientCommands = request?.IncludeClientCommands }; return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.commands.list", [rpcRequest], cancellationToken); } @@ -23411,13 +26699,14 @@ public async Task SetRequiredAsync(bool required, } /// Clears session-scoped tool permission approvals. + /// Whether location-scoped approvals are cleared too. Defaults to `true`. /// The to monitor for cancellation requests. The default is . /// Indicates whether the operation succeeded. - public async Task ResetSessionApprovalsAsync(CancellationToken cancellationToken = default) + public async Task ResetSessionApprovalsAsync(bool? includeLocation = null, CancellationToken cancellationToken = default) { _session.ThrowIfDisposed(); - var request = new PermissionsResetSessionApprovalsRequest { SessionId = _session.SessionId }; + var request = new PermissionsResetSessionApprovalsRequest { SessionId = _session.SessionId, IncludeLocation = includeLocation }; return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.permissions.resetSessionApprovals", [request], cancellationToken); } @@ -23806,6 +27095,31 @@ internal async Task EvaluatePredicateAsy } } +/// Provides session-scoped ContentExclusion APIs. +[Experimental(Diagnostics.Experimental)] +public sealed class ContentExclusionApi +{ + private readonly CopilotSession _session; + + internal ContentExclusionApi(CopilotSession session) + { + _session = session; + } + + /// Checks local file system absolute paths within the session working directory against its content-exclusion policy. Results preserve input order. Unsupported paths/filesystems and unavailable policy evaluation return available false, and callers must treat every requested path as excluded. + /// Local file system absolute paths within the session working directory to check. Results are returned in the same order, including duplicates. + /// The to monitor for cancellation requests. The default is . + /// Batch content-exclusion result. Callers must fail closed when policy evaluation is unavailable. + public async Task CheckPathsAsync(IList paths, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(paths); + _session.ThrowIfDisposed(); + + var request = new ContentExclusionCheckPathsRequest { SessionId = _session.SessionId, Paths = paths }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.contentExclusion.checkPaths", [request], cancellationToken); + } +} + /// Provides session-scoped Shell APIs. [Experimental(Diagnostics.Experimental)] public sealed class ShellApi @@ -23817,7 +27131,7 @@ internal ShellApi(CopilotSession session) _session = session; } - /// Starts a shell command and streams output through session notifications. + /// Starts a shell command and streams output through session notifications. The command runs as the leader of its own process group (POSIX) or in a dedicated job object (Windows), so a forced termination — via "shell.kill", the request timeout, or session disposal — signals that whole group/job rather than only the direct child. Two gaps are worth planning for: a command that exits on its own does not trigger that teardown, and on POSIX a descendant that moves itself into a new session or process group (for example via "setsid") leaves the signalled group, so either can leave a background process running. /// Shell command to execute. /// Working directory (defaults to session working directory). /// Timeout in milliseconds (default: 30000). @@ -23832,7 +27146,7 @@ public async Task ExecAsync(string command, string? cwd = null, return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.shell.exec", [request], cancellationToken); } - /// Sends a signal to a shell process previously started via "shell.exec". + /// Sends a signal to a shell process previously started via "shell.exec". The signal targets the command's whole process group (POSIX) or job object (Windows), so descendants still in that group are signalled too, not just the direct child. On POSIX a descendant that moved itself into a new session or process group (for example via "setsid") is no longer in the signalled group and survives. /// Process identifier returned by shell.exec. /// Signal to send (default: SIGTERM). /// The to monitor for cancellation requests. The default is . @@ -23890,11 +27204,11 @@ internal HistoryApi(CopilotSession session) /// 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(HistoryCompactRequest? request = null, CancellationToken cancellationToken = default) + public async Task CompactAsync(SessionHistoryCompactRequest? request = null, CancellationToken cancellationToken = default) { _session.ThrowIfDisposed(); - var rpcRequest = new HistoryCompactRequestWithSession { SessionId = _session.SessionId, CustomInstructions = request?.CustomInstructions }; + var rpcRequest = new SessionHistoryCompactRequestWithSession { SessionId = _session.SessionId, CustomInstructions = request?.CustomInstructions, Trigger = request?.Trigger, TokenLimit = request?.TokenLimit }; return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.history.compact", [rpcRequest], cancellationToken); } @@ -23911,6 +27225,44 @@ public async Task TruncateAsync(string eventId, Cancellat return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.history.truncate", [request], cancellationToken); } + /// Lists the user turns that the session can rewind to. Never rejects for a busy session: rewind reads need the session's file-change captures to be settled, so a session that still holds active work answers with `unavailableReason: "session-busy"` and no points, which the caller can retry. + /// The to monitor for cancellation requests. The default is . + /// Rewind points and file-change-tracking availability for the session. + public async Task ListRewindPointsAsync(CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new SessionHistoryListRewindPointsRequest { SessionId = _session.SessionId }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.history.listRewindPoints", [request], cancellationToken); + } + + /// Previews the files that a conversation-and-files rewind would restore. + /// ID of the user.message event that begins the discarded suffix. + /// The to monitor for cancellation requests. The default is . + /// Files and aggregate changes for a prospective rewind. + public async Task PreviewRewindAsync(string eventId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(eventId); + _session.ThrowIfDisposed(); + + var request = new HistoryPreviewRewindRequest { SessionId = _session.SessionId, EventId = eventId }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.history.previewRewind", [request], cancellationToken); + } + + /// Rewinds the session conversation, optionally restoring files changed by the discarded turns. Not crash-atomic: file restore and conversation truncation are separate stores, applied in that order, so a process crash between them can leave the workspace rewound while the conversation still contains the discarded turns. There is no recovery journal; re-running the same rewind is the recovery path for a crash before truncation lands, since file restore is idempotent (already-restored files are reported as skipped) and truncation is re-derived from the still-retained boundary event. After truncation lands that boundary no longer exists, so the same request is rejected; the only stage that can still be outstanding is snapshot pruning, whose failure leaves orphan snapshots the capture store tolerates. The reverse inconsistency cannot occur, because truncation is never applied before file restore succeeds. + /// ID of the user.message event that begins the discarded suffix. + /// Whether to rewind only conversation history or also restore captured files. + /// The to monitor for cancellation requests. The default is . + /// Structured outcome of a rewind request. + public async Task RewindAsync(string eventId, HistoryRewindMode mode, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(eventId); + _session.ThrowIfDisposed(); + + var request = new HistoryRewindRequest { SessionId = _session.SessionId, EventId = eventId, Mode = mode }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.history.rewind", [request], cancellationToken); + } + /// Cancels any in-progress background compaction on a local session. /// The to monitor for cancellation requests. The default is . /// Indicates whether an in-progress background compaction was cancelled. @@ -23967,6 +27319,158 @@ public async Task PendingItemsAsync(CancellationToken c return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.queue.pendingItems", [request], cancellationToken); } + /// Returns the internal native queue snapshot for in-process session orchestration. + /// The to monitor for cancellation requests. The default is . + /// Internal snapshot of native queue state for local session orchestration. + internal async Task SnapshotAsync(CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new SessionQueueSnapshotRequest { SessionId = _session.SessionId }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.queue.snapshot", [request], cancellationToken); + } + + /// Moves an addressable queued item to a public visible position. + /// Stable opaque queued-item id. + /// Zero-based target position in the public visible queue. Values outside the queue clamp to an end. + /// The to monitor for cancellation requests. The default is . + /// Result of moving a queued item. + public async Task MoveItemAsync(string id, long toPosition, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(id); + _session.ThrowIfDisposed(); + + var request = new QueueMoveItemRequest { SessionId = _session.SessionId, Id = id, ToPosition = toPosition }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.queue.moveItem", [request], cancellationToken); + } + + /// Inserts a new queued message at a public visible position. + /// Zero-based position in the public visible queue. Values outside the queue clamp to an end. + /// The message parameter. + /// The to monitor for cancellation requests. The default is . + /// Result of inserting a queued message. + public async Task InsertAtAsync(long position, QueueInsertMessage message, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(message); + _session.ThrowIfDisposed(); + + var request = new QueueInsertAtRequest { SessionId = _session.SessionId, Position = position, Message = message }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.queue.insertAt", [request], cancellationToken); + } + + /// Removes an addressable queued item by its stable id. + /// The id parameter. + /// The to monitor for cancellation requests. The default is . + /// Result of removing a queued item. + public async Task RemoveAtAsync(string id, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(id); + _session.ThrowIfDisposed(); + + var request = new QueueRemoveAtRequest { SessionId = _session.SessionId, Id = id }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.queue.removeAt", [request], cancellationToken); + } + + /// Updates the text of an addressable single-message queue item. + /// The id parameter. + /// The prompt parameter. + /// The displayPrompt parameter. + /// The to monitor for cancellation requests. The default is . + /// Result of editing a queued message. + public async Task UpdateTextAsync(string id, string prompt, string? displayPrompt = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(id); + ArgumentNullException.ThrowIfNull(prompt); + _session.ThrowIfDisposed(); + + var request = new QueueUpdateTextRequest { SessionId = _session.SessionId, Id = id, Prompt = prompt, DisplayPrompt = displayPrompt }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.queue.updateText", [request], cancellationToken); + } + + /// Duplicates an addressable queued item immediately after its source. + /// The id parameter. + /// The to monitor for cancellation requests. The default is . + /// Result of duplicating a queued item. + public async Task DuplicateAtAsync(string id, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(id); + _session.ThrowIfDisposed(); + + var request = new QueueDuplicateAtRequest { SessionId = _session.SessionId, Id = id }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.queue.duplicateAt", [request], cancellationToken); + } + + /// Acquires or releases the queued-lane drain pause. + /// The paused parameter. + /// The to monitor for cancellation requests. The default is . + public async Task SetDrainPausedAsync(bool paused, CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new QueueSetDrainPausedRequest { SessionId = _session.SessionId, Paused = paused }; + await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.queue.setDrainPaused", [request], cancellationToken); + } + + /// Moves an addressable queued message into the live turn's steering lane. + /// The id parameter. + /// The to monitor for cancellation requests. The default is . + /// Result of trying to steer a queued message into a live turn. + public async Task SendNowAsync(string id, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(id); + _session.ThrowIfDisposed(); + + var request = new QueueSendNowRequest { SessionId = _session.SessionId, Id = id }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.queue.sendNow", [request], cancellationToken); + } + + /// Reports whether the local session has native queued work pending. + /// The to monitor for cancellation requests. The default is . + /// Whether the native queue has pending work. + internal async Task HasPendingAsync(CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new SessionQueueHasPendingRequest { SessionId = _session.SessionId }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.queue.hasPending", [request], cancellationToken); + } + + /// Begins a native deferred-idle drain when background work has quiesced. + /// Whether the host still has active background work. + /// The to monitor for cancellation requests. The default is . + /// Whether a deferred-idle drain should run. + internal async Task BeginDeferredIdleDrainAsync(bool activeBackgroundWork, CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new QueueBeginDeferredIdleDrainRequest { SessionId = _session.SessionId, ActiveBackgroundWork = activeBackgroundWork }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.queue.beginDeferredIdleDrain", [request], cancellationToken); + } + + /// Finishes a native deferred-idle drain and reports whether to drain queue work or emit idle. + /// Whether the host still has active background work. + /// Whether native queued work remains. + /// The to monitor for cancellation requests. The default is . + /// Action selected by the native deferred-idle drain. + internal async Task FinishDeferredIdleDrainAsync(bool activeBackgroundWork, bool hasPending, CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new QueueFinishDeferredIdleDrainRequest { SessionId = _session.SessionId, ActiveBackgroundWork = activeBackgroundWork, HasPending = hasPending }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.queue.finishDeferredIdleDrain", [request], cancellationToken); + } + + /// Marks session.idle as deferred by native background work state. + /// Whether the deferred idle was caused by an aborted foreground turn. + /// The to monitor for cancellation requests. The default is . + internal async Task DeferSessionIdleAsync(bool aborted, CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new QueueDeferSessionIdleRequest { SessionId = _session.SessionId, Aborted = aborted }; + await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.queue.deferSessionIdle", [request], cancellationToken); + } + /// Removes the most recently queued user-facing item (LIFO). /// The to monitor for cancellation requests. The default is . /// Indicates whether a user-facing pending item was removed. @@ -23987,6 +27491,40 @@ public async Task ClearAsync(CancellationToken cancellationToken = default) var request = new SessionQueueClearRequest { SessionId = _session.SessionId }; await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.queue.clear", [request], cancellationToken); } + + /// Consumes queued native system notifications matching an internal filter. + /// Opaque runtime-owned filter object. + /// The to monitor for cancellation requests. The default is . + /// Indicates whether a user-facing pending item was removed. + internal async Task ConsumeSystemNotificationsAsync(object filter, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(filter); + _session.ThrowIfDisposed(); + + var request = new QueueConsumeSystemNotificationsRequest { SessionId = _session.SessionId, Filter = CopilotClient.ToJsonElementForWire(filter)!.Value }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.queue.consumeSystemNotifications", [request], cancellationToken); + } + + /// Enqueues the internal resume-pending wake item when orphan handling needs a follow-up turn. + /// The to monitor for cancellation requests. The default is . + /// Result of enqueueing the resume-pending wake item. + internal async Task EnqueueResumePendingAsync(CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new SessionQueueEnqueueResumePendingRequest { SessionId = _session.SessionId }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.queue.enqueueResumePending", [request], cancellationToken); + } + + /// Drains the native local-session work queue for in-process session orchestration. + /// The to monitor for cancellation requests. The default is . + internal async Task ProcessAsync(CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new SessionQueueProcessRequest { SessionId = _session.SessionId }; + await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.queue.process", [request], cancellationToken); + } } /// Provides session-scoped EventLog APIs. @@ -24006,13 +27544,14 @@ internal EventLogApi(CopilotSession session) /// 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. /// 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. + /// When false, skip ephemeral events entirely and return only durable (persisted) events. History-backfill callers that discard ephemerals anyway should set this so the read is bounded by the durable log length instead of racing the ephemeral ring on a busy session. Defaults to true (ephemerals are interleaved with durable events in creation order). /// 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, long? max = null, TimeSpan? waitMs = null, object? types = null, EventsAgentScope? agentScope = null, CancellationToken cancellationToken = default) + public async Task ReadAsync(string? cursor = null, long? max = null, TimeSpan? waitMs = null, object? types = null, EventsAgentScope? agentScope = null, bool? includeEphemeral = null, CancellationToken cancellationToken = default) { _session.ThrowIfDisposed(); - var request = new EventLogReadRequest { SessionId = _session.SessionId, Cursor = cursor, Max = max, Wait = waitMs, Types = CopilotClient.ToJsonElementForWire(types), AgentScope = agentScope }; + var request = new EventLogReadRequest { SessionId = _session.SessionId, Cursor = cursor, Max = max, Wait = waitMs, Types = CopilotClient.ToJsonElementForWire(types), AgentScope = agentScope, IncludeEphemeral = includeEphemeral }; return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.eventLog.read", [request], cancellationToken); } @@ -24077,6 +27616,30 @@ public async Task GetMetricsAsync(CancellationToken cance } } +/// Provides session-scoped LimitPrediction APIs. +[Experimental(Diagnostics.Experimental)] +public sealed class LimitPredictionApi +{ + private readonly CopilotSession _session; + + internal LimitPredictionApi(CopilotSession session) + { + _session = session; + } + + /// Predicts an AI-credit session limit for the session's resolved model. Returns an unavailable result instead of falling back when the current model is unresolved auto. + /// Parameters for predicting an AI-credit session limit. Omitting `modelId` uses the session's currently selected model. + /// The to monitor for cancellation requests. The default is . + /// Prediction result. Available results include prediction details; unavailable results include an explicit reason. + public async Task PredictAsync(SessionLimitPredictionPredictRequest? request = null, CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var rpcRequest = new SessionLimitPredictionPredictRequestWithSession { SessionId = _session.SessionId, ModelId = request?.ModelId, ClientType = request?.ClientType }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.limitPrediction.predict", [rpcRequest], cancellationToken); + } +} + /// Provides session-scoped Remote APIs. [Experimental(Diagnostics.Experimental)] public sealed class RemoteApi @@ -24180,6 +27743,105 @@ public async Task ListAsync(CancellationToken cancellationToken = return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.schedule.list", [request], cancellationToken); } + /// Hydrates the native schedule registry from persisted session events. + /// The to monitor for cancellation requests. The default is . + internal async Task HydrateAsync(CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new SessionScheduleHydrateRequest { SessionId = _session.SessionId }; + await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.schedule.hydrate", [request], cancellationToken); + } + + /// Reports whether the session has an active self-paced scheduled prompt. + /// The to monitor for cancellation requests. The default is . + /// Whether the session currently has an active self-paced schedule. + internal async Task HasSelfPacedAsync(CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new SessionScheduleHasSelfPacedRequest { SessionId = _session.SessionId }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.schedule.hasSelfPaced", [request], cancellationToken); + } + + /// Registers a relative-interval scheduled prompt. + /// Human-readable interval such as `30s`, `5m`, or `2h`. + /// Prompt text to enqueue when the schedule fires. + /// Whether the schedule should re-arm after each tick. Defaults to true. + /// Optional display-only prompt label. + /// The to monitor for cancellation requests. The default is . + /// Result of registering or re-arming a scheduled prompt. + internal async Task AddAsync(string interval, string prompt, bool? recurring = null, string? displayPrompt = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(interval); + ArgumentNullException.ThrowIfNull(prompt); + _session.ThrowIfDisposed(); + + var request = new ScheduleAddRequest { SessionId = _session.SessionId, Interval = interval, Prompt = prompt, Recurring = recurring, DisplayPrompt = displayPrompt }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.schedule.add", [request], cancellationToken); + } + + /// Registers a recurring cron scheduled prompt. + /// 5-field cron expression. + /// Prompt text to enqueue when the schedule fires. + /// Whether the schedule should re-arm after each tick. Defaults to true. + /// Optional display-only prompt label. + /// IANA timezone for evaluating the cron expression. + /// The to monitor for cancellation requests. The default is . + /// Result of registering or re-arming a scheduled prompt. + internal async Task AddCronAsync(string cron, string prompt, bool? recurring = null, string? displayPrompt = null, string? tz = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(cron); + ArgumentNullException.ThrowIfNull(prompt); + _session.ThrowIfDisposed(); + + var request = new ScheduleAddCronRequest { SessionId = _session.SessionId, Cron = cron, Prompt = prompt, Recurring = recurring, DisplayPrompt = displayPrompt, Tz = tz }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.schedule.addCron", [request], cancellationToken); + } + + /// Registers an absolute-time scheduled prompt. + /// Epoch milliseconds when the prompt should fire. + /// Prompt text to enqueue when the schedule fires. + /// Whether the schedule should re-arm after each tick. Defaults to false. + /// Optional display-only prompt label. + /// The to monitor for cancellation requests. The default is . + /// Result of registering or re-arming a scheduled prompt. + internal async Task AddAtAsync(long at, string prompt, bool? recurring = null, string? displayPrompt = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(prompt); + _session.ThrowIfDisposed(); + + var request = new ScheduleAddAtRequest { SessionId = _session.SessionId, At = at, Prompt = prompt, Recurring = recurring, DisplayPrompt = displayPrompt }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.schedule.addAt", [request], cancellationToken); + } + + /// Registers a self-paced scheduled prompt. + /// Prompt text to enqueue when the schedule fires. + /// Optional display-only prompt label. + /// The to monitor for cancellation requests. The default is . + /// Result of registering or re-arming a scheduled prompt. + internal async Task AddSelfPacedAsync(string prompt, string? displayPrompt = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(prompt); + _session.ThrowIfDisposed(); + + var request = new ScheduleAddSelfPacedRequest { SessionId = _session.SessionId, Prompt = prompt, DisplayPrompt = displayPrompt }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.schedule.addSelfPaced", [request], cancellationToken); + } + + /// Re-arms an active self-paced scheduled prompt. + /// Id of the self-paced scheduled prompt. + /// Epoch milliseconds when the prompt should next fire. + /// The to monitor for cancellation requests. The default is . + /// Result of registering or re-arming a scheduled prompt. + internal async Task RearmSelfPacedAsync(long id, long at, CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new ScheduleRearmSelfPacedRequest { SessionId = _session.SessionId, Id = id, At = at }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.schedule.rearmSelfPaced", [request], cancellationToken); + } + /// Removes a scheduled prompt by id. /// Id of the scheduled prompt to remove. /// The to monitor for cancellation requests. The default is . @@ -24274,11 +27936,16 @@ public interface ISessionFsHandler /// The to monitor for cancellation requests. The default is . /// Describes a filesystem error. Task RenameAsync(SessionFsRenameRequest request, CancellationToken cancellationToken = default); - /// Executes a SQLite query against the per-session database. - /// SQL query, query type, and optional bind parameters for executing a SQLite query against the per-session database. + /// Executes a SQLite query against the per-session database. Providers apply busy handling for every call. + /// SQL query, query type, and optional bind parameters for executing a SQLite query against the per-session database. The provider applies its SQLite busy timeout for every call. /// The to monitor for cancellation requests. The default is . /// Query results including rows, columns, and rows affected, or a filesystem error if execution failed. Task SqliteQueryAsync(SessionFsSqliteQueryRequest request, CancellationToken cancellationToken = default); + /// Executes SQLite statements atomically on the provider-owned connection. + /// Statements to execute atomically. Providers apply busy handling for every call. + /// The to monitor for cancellation requests. The default is . + /// Per-statement results, or a classified transaction error. + Task SqliteTransactionAsync(SessionFsSqliteTransactionRequest request, CancellationToken cancellationToken = default); /// Checks whether the per-session SQLite database already exists, without creating it. /// Identifies the target session. /// The to monitor for cancellation requests. The default is . @@ -24416,6 +28083,12 @@ public static void RegisterClientSessionApiHandlers(JsonRpc rpc, Func>)(async (request, cancellationToken) => + { + var handler = getHandlers(request.SessionId).SessionFs; + if (handler is null) throw new InvalidOperationException($"No sessionFs handler registered for session: {request.SessionId}"); + return await handler.SqliteTransactionAsync(request, cancellationToken); + }), singleObjectParam: true); rpc.SetLocalRpcMethod("sessionFs.sqliteExists", (Func>)(async (request, cancellationToken) => { var handler = getHandlers(request.SessionId).SessionFs; @@ -24577,6 +28250,7 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.AttachmentSelectionDetails), TypeInfoPropertyName = "SessionEventsAttachmentSelectionDetails")] [JsonSerializable(typeof(GitHub.Copilot.AttachmentSelectionDetailsEnd), TypeInfoPropertyName = "SessionEventsAttachmentSelectionDetailsEnd")] [JsonSerializable(typeof(GitHub.Copilot.AttachmentSelectionDetailsStart), TypeInfoPropertyName = "SessionEventsAttachmentSelectionDetailsStart")] +[JsonSerializable(typeof(GitHub.Copilot.AutoApprovalJudgeFailureReason), TypeInfoPropertyName = "SessionEventsAutoApprovalJudgeFailureReason")] [JsonSerializable(typeof(GitHub.Copilot.AutoApprovalRecommendation), TypeInfoPropertyName = "SessionEventsAutoApprovalRecommendation")] [JsonSerializable(typeof(GitHub.Copilot.AutoModeResolvedReasoningBucket), TypeInfoPropertyName = "SessionEventsAutoModeResolvedReasoningBucket")] [JsonSerializable(typeof(GitHub.Copilot.AutoModeSwitchCompletedData), TypeInfoPropertyName = "SessionEventsAutoModeSwitchCompletedData")] @@ -24615,6 +28289,7 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.CommandsChangedEvent), TypeInfoPropertyName = "SessionEventsCommandsChangedEvent")] [JsonSerializable(typeof(GitHub.Copilot.CompactionCompleteCompactionTokensUsed), TypeInfoPropertyName = "SessionEventsCompactionCompleteCompactionTokensUsed")] [JsonSerializable(typeof(GitHub.Copilot.CompactionCompleteCompactionTokensUsedCopilotUsageTokenDetail), TypeInfoPropertyName = "SessionEventsCompactionCompleteCompactionTokensUsedCopilotUsageTokenDetail")] +[JsonSerializable(typeof(GitHub.Copilot.CompactionTrigger), TypeInfoPropertyName = "SessionEventsCompactionTrigger")] [JsonSerializable(typeof(GitHub.Copilot.ContextTier), TypeInfoPropertyName = "SessionEventsContextTier")] [JsonSerializable(typeof(GitHub.Copilot.CustomAgentsUpdatedAgent), TypeInfoPropertyName = "SessionEventsCustomAgentsUpdatedAgent")] [JsonSerializable(typeof(GitHub.Copilot.ElicitationCompletedAction), TypeInfoPropertyName = "SessionEventsElicitationCompletedAction")] @@ -24638,6 +28313,8 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.ExternalToolCompletedEvent), TypeInfoPropertyName = "SessionEventsExternalToolCompletedEvent")] [JsonSerializable(typeof(GitHub.Copilot.ExternalToolRequestedData), TypeInfoPropertyName = "SessionEventsExternalToolRequestedData")] [JsonSerializable(typeof(GitHub.Copilot.ExternalToolRequestedEvent), TypeInfoPropertyName = "SessionEventsExternalToolRequestedEvent")] +[JsonSerializable(typeof(GitHub.Copilot.FactoryRunUpdatedData), TypeInfoPropertyName = "SessionEventsFactoryRunUpdatedData")] +[JsonSerializable(typeof(GitHub.Copilot.FactoryRunUpdatedEvent), TypeInfoPropertyName = "SessionEventsFactoryRunUpdatedEvent")] [JsonSerializable(typeof(GitHub.Copilot.GitHubRepoRef), TypeInfoPropertyName = "SessionEventsGitHubRepoRef")] [JsonSerializable(typeof(GitHub.Copilot.HandoffRepository), TypeInfoPropertyName = "SessionEventsHandoffRepository")] [JsonSerializable(typeof(GitHub.Copilot.HandoffSourceType), TypeInfoPropertyName = "SessionEventsHandoffSourceType")] @@ -24722,6 +28399,7 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.PermissionRequestRead), TypeInfoPropertyName = "SessionEventsPermissionRequestRead")] [JsonSerializable(typeof(GitHub.Copilot.PermissionRequestShell), TypeInfoPropertyName = "SessionEventsPermissionRequestShell")] [JsonSerializable(typeof(GitHub.Copilot.PermissionRequestShellCommand), TypeInfoPropertyName = "SessionEventsPermissionRequestShellCommand")] +[JsonSerializable(typeof(GitHub.Copilot.PermissionRequestShellCommandSegment), TypeInfoPropertyName = "SessionEventsPermissionRequestShellCommandSegment")] [JsonSerializable(typeof(GitHub.Copilot.PermissionRequestShellPossibleUrl), TypeInfoPropertyName = "SessionEventsPermissionRequestShellPossibleUrl")] [JsonSerializable(typeof(GitHub.Copilot.PermissionRequestUrl), TypeInfoPropertyName = "SessionEventsPermissionRequestUrl")] [JsonSerializable(typeof(GitHub.Copilot.PermissionRequestWrite), TypeInfoPropertyName = "SessionEventsPermissionRequestWrite")] @@ -24738,6 +28416,7 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.SamplingCompletedEvent), TypeInfoPropertyName = "SessionEventsSamplingCompletedEvent")] [JsonSerializable(typeof(GitHub.Copilot.SamplingRequestedData), TypeInfoPropertyName = "SessionEventsSamplingRequestedData")] [JsonSerializable(typeof(GitHub.Copilot.SamplingRequestedEvent), TypeInfoPropertyName = "SessionEventsSamplingRequestedEvent")] +[JsonSerializable(typeof(GitHub.Copilot.ScheduleOrigin), TypeInfoPropertyName = "SessionEventsScheduleOrigin")] [JsonSerializable(typeof(GitHub.Copilot.SessionEvent), TypeInfoPropertyName = "SessionEventsSessionEvent")] [JsonSerializable(typeof(GitHub.Copilot.SessionLimitsConfig), TypeInfoPropertyName = "SessionEventsSessionLimitsConfig")] [JsonSerializable(typeof(GitHub.Copilot.SessionLimitsExhaustedCompletedData), TypeInfoPropertyName = "SessionEventsSessionLimitsExhaustedCompletedData")] @@ -24783,6 +28462,8 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.SystemNotificationNewInboxMessage), TypeInfoPropertyName = "SessionEventsSystemNotificationNewInboxMessage")] [JsonSerializable(typeof(GitHub.Copilot.SystemNotificationShellCompleted), TypeInfoPropertyName = "SessionEventsSystemNotificationShellCompleted")] [JsonSerializable(typeof(GitHub.Copilot.SystemNotificationShellDetachedCompleted), TypeInfoPropertyName = "SessionEventsSystemNotificationShellDetachedCompleted")] +[JsonSerializable(typeof(GitHub.Copilot.SystemNotificationUnclassified), TypeInfoPropertyName = "SessionEventsSystemNotificationUnclassified")] +[JsonSerializable(typeof(GitHub.Copilot.TaskCompletionOutcome), TypeInfoPropertyName = "SessionEventsTaskCompletionOutcome")] [JsonSerializable(typeof(GitHub.Copilot.ToolExecutionCompleteContent), TypeInfoPropertyName = "SessionEventsToolExecutionCompleteContent")] [JsonSerializable(typeof(GitHub.Copilot.ToolExecutionCompleteContentAudio), TypeInfoPropertyName = "SessionEventsToolExecutionCompleteContentAudio")] [JsonSerializable(typeof(GitHub.Copilot.ToolExecutionCompleteContentImage), TypeInfoPropertyName = "SessionEventsToolExecutionCompleteContentImage")] @@ -24874,6 +28555,8 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(AllowAllPermissionSetResult))] [JsonSerializable(typeof(AllowAllPermissionState))] [JsonSerializable(typeof(AuthInfo))] +[JsonSerializable(typeof(BuiltInModelCatalog))] +[JsonSerializable(typeof(BuiltInModelCatalogEntry))] [JsonSerializable(typeof(CancelUserRequestedShellCommandResult))] [JsonSerializable(typeof(CanvasAction))] [JsonSerializable(typeof(CanvasActionInvokeRequest))] @@ -24894,8 +28577,6 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(CommandsHandlePendingCommandRequest))] [JsonSerializable(typeof(CommandsHandlePendingCommandResult))] [JsonSerializable(typeof(CommandsInvokeRequest))] -[JsonSerializable(typeof(CommandsListRequest))] -[JsonSerializable(typeof(CommandsListRequestWithSession))] [JsonSerializable(typeof(CommandsRespondToQueuedCommandRequest))] [JsonSerializable(typeof(CommandsRespondToQueuedCommandResult))] [JsonSerializable(typeof(CompletionsGetTriggerCharactersResult))] @@ -24907,6 +28588,9 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(ConnectResult))] [JsonSerializable(typeof(ConnectedRemoteSessionMetadata))] [JsonSerializable(typeof(ConnectedRemoteSessionMetadataRepository))] +[JsonSerializable(typeof(ContentExclusionCheckPathsRequest))] +[JsonSerializable(typeof(ContentExclusionCheckPathsResult))] +[JsonSerializable(typeof(ContentExclusionPathCheck))] [JsonSerializable(typeof(ContextHeaviestMessage))] [JsonSerializable(typeof(CopilotUserResponse))] [JsonSerializable(typeof(CopilotUserResponseEndpoints))] @@ -24943,19 +28627,34 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(FactoryAgentOptions))] [JsonSerializable(typeof(FactoryAgentRequest))] [JsonSerializable(typeof(FactoryAgentResult))] +[JsonSerializable(typeof(FactoryAgentSummary))] [JsonSerializable(typeof(FactoryCancelRequest))] +[JsonSerializable(typeof(FactoryCurrentPhase))] +[JsonSerializable(typeof(FactoryDeclaredLimits))] [JsonSerializable(typeof(FactoryExecuteRequest))] [JsonSerializable(typeof(FactoryExecuteResult))] +[JsonSerializable(typeof(FactoryGetRunProgressRequest))] [JsonSerializable(typeof(FactoryGetRunRequest))] [JsonSerializable(typeof(FactoryJournalGetRequest))] [JsonSerializable(typeof(FactoryJournalGetResult))] [JsonSerializable(typeof(FactoryJournalPutRequest))] +[JsonSerializable(typeof(FactoryListRunsRequest))] +[JsonSerializable(typeof(FactoryListRunsResult))] [JsonSerializable(typeof(FactoryLogLine))] [JsonSerializable(typeof(FactoryLogRequest))] +[JsonSerializable(typeof(FactoryPhaseObservation))] +[JsonSerializable(typeof(FactoryProgressLine))] +[JsonSerializable(typeof(FactoryProgressPage))] +[JsonSerializable(typeof(FactoryResumeRequest))] +[JsonSerializable(typeof(FactoryResumeResult))] +[JsonSerializable(typeof(FactoryRunConsumed))] +[JsonSerializable(typeof(FactoryRunDetail))] [JsonSerializable(typeof(FactoryRunFailure))] [JsonSerializable(typeof(FactoryRunLimits))] [JsonSerializable(typeof(FactoryRunRequest))] [JsonSerializable(typeof(FactoryRunResult))] +[JsonSerializable(typeof(FactoryRunSummary))] +[JsonSerializable(typeof(FactoryRunTerminal))] [JsonSerializable(typeof(FleetStartRequest))] [JsonSerializable(typeof(FleetStartResult))] [JsonSerializable(typeof(FolderTrustAddParams))] @@ -24969,9 +28668,15 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(HistoryAbortManualCompactionResult))] [JsonSerializable(typeof(HistoryCancelBackgroundCompactionResult))] [JsonSerializable(typeof(HistoryCompactContextWindow))] -[JsonSerializable(typeof(HistoryCompactRequest))] -[JsonSerializable(typeof(HistoryCompactRequestWithSession))] [JsonSerializable(typeof(HistoryCompactResult))] +[JsonSerializable(typeof(HistoryListRewindPointsResult))] +[JsonSerializable(typeof(HistoryPreviewRewindRequest))] +[JsonSerializable(typeof(HistoryPreviewRewindResult))] +[JsonSerializable(typeof(HistoryRewindFilePreview))] +[JsonSerializable(typeof(HistoryRewindPoint))] +[JsonSerializable(typeof(HistoryRewindRequest))] +[JsonSerializable(typeof(HistoryRewindResult))] +[JsonSerializable(typeof(HistorySkippedFileRestore))] [JsonSerializable(typeof(HistorySummarizeForHandoffResult))] [JsonSerializable(typeof(HistoryTruncateRequest))] [JsonSerializable(typeof(HistoryTruncateResult))] @@ -24985,6 +28690,8 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(InstructionsDiscoverRequest))] [JsonSerializable(typeof(InstructionsGetDiscoveryPathsRequest))] [JsonSerializable(typeof(InstructionsGetSourcesResult))] +[JsonSerializable(typeof(InterruptMainTurnRequest))] +[JsonSerializable(typeof(InterruptMainTurnResult))] [JsonSerializable(typeof(LlmInferenceHttpRequestChunkRequest))] [JsonSerializable(typeof(LlmInferenceHttpRequestChunkResult))] [JsonSerializable(typeof(LlmInferenceHttpRequestStartRequest))] @@ -25053,6 +28760,8 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(McpOauthLoginRequest))] [JsonSerializable(typeof(McpOauthLoginResult))] [JsonSerializable(typeof(McpOauthPendingRequestResponse))] +[JsonSerializable(typeof(McpOauthRespondRequest))] +[JsonSerializable(typeof(McpOauthRespondResult))] [JsonSerializable(typeof(McpRegisterExternalClientRequest))] [JsonSerializable(typeof(McpReloadWithConfigRequest))] [JsonSerializable(typeof(McpRemoveGitHubResult))] @@ -25114,8 +28823,6 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(ModelCapabilitiesOverrideSupports))] [JsonSerializable(typeof(ModelCapabilitiesSupports))] [JsonSerializable(typeof(ModelList))] -[JsonSerializable(typeof(ModelListRequest))] -[JsonSerializable(typeof(ModelListRequestWithSession))] [JsonSerializable(typeof(ModelPolicy))] [JsonSerializable(typeof(ModelSetReasoningEffortRequest))] [JsonSerializable(typeof(ModelSetReasoningEffortResult))] @@ -25201,8 +28908,6 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(PluginsMarketplacesBrowseRequest))] [JsonSerializable(typeof(PluginsMarketplacesRefreshRequest))] [JsonSerializable(typeof(PluginsMarketplacesRemoveRequest))] -[JsonSerializable(typeof(PluginsReloadRequest))] -[JsonSerializable(typeof(PluginsReloadRequestWithSession))] [JsonSerializable(typeof(PluginsUninstallRequest))] [JsonSerializable(typeof(PluginsUpdateRequest))] [JsonSerializable(typeof(ProviderAddRequest))] @@ -25210,8 +28915,6 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(ProviderConfig))] [JsonSerializable(typeof(ProviderConfigAzure))] [JsonSerializable(typeof(ProviderEndpoint))] -[JsonSerializable(typeof(ProviderGetEndpointRequest))] -[JsonSerializable(typeof(ProviderGetEndpointRequestWithSession))] [JsonSerializable(typeof(ProviderModelConfig))] [JsonSerializable(typeof(ProviderSessionToken))] [JsonSerializable(typeof(ProviderTokenAcquireRequest))] @@ -25224,9 +28927,32 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(PushAttachmentSelectionDetailsEnd))] [JsonSerializable(typeof(PushAttachmentSelectionDetailsStart))] [JsonSerializable(typeof(PushGitHubRepoRef))] +[JsonSerializable(typeof(QueueBeginDeferredIdleDrainRequest))] +[JsonSerializable(typeof(QueueBeginDeferredIdleDrainResult))] +[JsonSerializable(typeof(QueueConsumeSystemNotificationsRequest))] +[JsonSerializable(typeof(QueueDeferSessionIdleRequest))] +[JsonSerializable(typeof(QueueDuplicateAtRequest))] +[JsonSerializable(typeof(QueueDuplicateAtResult))] +[JsonSerializable(typeof(QueueEnqueueResumePendingResult))] +[JsonSerializable(typeof(QueueFinishDeferredIdleDrainRequest))] +[JsonSerializable(typeof(QueueFinishDeferredIdleDrainResult))] +[JsonSerializable(typeof(QueueHasPendingResult))] +[JsonSerializable(typeof(QueueInsertAtRequest))] +[JsonSerializable(typeof(QueueInsertAtResult))] +[JsonSerializable(typeof(QueueInsertMessage))] +[JsonSerializable(typeof(QueueMoveItemRequest))] +[JsonSerializable(typeof(QueueMoveItemResult))] [JsonSerializable(typeof(QueuePendingItems))] [JsonSerializable(typeof(QueuePendingItemsResult))] +[JsonSerializable(typeof(QueueRemoveAtRequest))] +[JsonSerializable(typeof(QueueRemoveAtResult))] [JsonSerializable(typeof(QueueRemoveMostRecentResult))] +[JsonSerializable(typeof(QueueSendNowRequest))] +[JsonSerializable(typeof(QueueSendNowResult))] +[JsonSerializable(typeof(QueueSetDrainPausedRequest))] +[JsonSerializable(typeof(QueueSnapshotResult))] +[JsonSerializable(typeof(QueueUpdateTextRequest))] +[JsonSerializable(typeof(QueueUpdateTextResult))] [JsonSerializable(typeof(QueuedCommandResult))] [JsonSerializable(typeof(RegisterEventInterestParams))] [JsonSerializable(typeof(RegisterEventInterestResult))] @@ -25253,9 +28979,17 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(SandboxConfigUserPolicyExperimentalSeatbelt))] [JsonSerializable(typeof(SandboxConfigUserPolicyFilesystem))] [JsonSerializable(typeof(SandboxConfigUserPolicyNetwork))] +[JsonSerializable(typeof(SandboxConfigUserPolicyNetworkProxy))] [JsonSerializable(typeof(SandboxConfigUserPolicySeatbelt))] +[JsonSerializable(typeof(ScheduleAddAtRequest))] +[JsonSerializable(typeof(ScheduleAddCronRequest))] +[JsonSerializable(typeof(ScheduleAddRequest))] +[JsonSerializable(typeof(ScheduleAddResult))] +[JsonSerializable(typeof(ScheduleAddSelfPacedRequest))] [JsonSerializable(typeof(ScheduleEntry))] +[JsonSerializable(typeof(ScheduleHasSelfPacedResult))] [JsonSerializable(typeof(ScheduleList))] +[JsonSerializable(typeof(ScheduleRearmSelfPacedRequest))] [JsonSerializable(typeof(ScheduleStopRequest))] [JsonSerializable(typeof(ScheduleStopResult))] [JsonSerializable(typeof(SecretsAddFilterValuesRequest))] @@ -25266,6 +29000,7 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(SendMessagesResult))] [JsonSerializable(typeof(SendRequest))] [JsonSerializable(typeof(SendResult))] +[JsonSerializable(typeof(SendSystemNotificationRequest))] [JsonSerializable(typeof(ServerAgentList))] [JsonSerializable(typeof(ServerInstructionSourceList))] [JsonSerializable(typeof(ServerSkill))] @@ -25274,11 +29009,15 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(SessionAgentDeselectRequest))] [JsonSerializable(typeof(SessionAgentGetCurrentRequest))] [JsonSerializable(typeof(SessionAgentListRequest))] +[JsonSerializable(typeof(SessionAgentListRequestWithSession))] [JsonSerializable(typeof(SessionAgentReloadRequest))] [JsonSerializable(typeof(SessionAuthStatus))] [JsonSerializable(typeof(SessionBulkDeleteResult))] +[JsonSerializable(typeof(SessionCancelAllBackgroundAgentsRequest))] [JsonSerializable(typeof(SessionCanvasListOpenRequest))] [JsonSerializable(typeof(SessionCanvasListRequest))] +[JsonSerializable(typeof(SessionCommandsListRequest))] +[JsonSerializable(typeof(SessionCommandsListRequestWithSession))] [JsonSerializable(typeof(SessionCompletionItem))] [JsonSerializable(typeof(SessionCompletionsGetTriggerCharactersRequest))] [JsonSerializable(typeof(SessionContext))] @@ -25307,15 +29046,28 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(SessionFsSqliteExistsResult))] [JsonSerializable(typeof(SessionFsSqliteQueryRequest))] [JsonSerializable(typeof(SessionFsSqliteQueryResult))] +[JsonSerializable(typeof(SessionFsSqliteTransactionError))] +[JsonSerializable(typeof(SessionFsSqliteTransactionRequest))] +[JsonSerializable(typeof(SessionFsSqliteTransactionResult))] +[JsonSerializable(typeof(SessionFsSqliteTransactionStatement))] [JsonSerializable(typeof(SessionFsStatRequest))] [JsonSerializable(typeof(SessionFsStatResult))] [JsonSerializable(typeof(SessionFsWriteFileRequest))] [JsonSerializable(typeof(SessionGitHubAuthGetStatusRequest))] [JsonSerializable(typeof(SessionHistoryAbortManualCompactionRequest))] [JsonSerializable(typeof(SessionHistoryCancelBackgroundCompactionRequest))] +[JsonSerializable(typeof(SessionHistoryCompactRequest))] +[JsonSerializable(typeof(SessionHistoryCompactRequestWithSession))] +[JsonSerializable(typeof(SessionHistoryListRewindPointsRequest))] [JsonSerializable(typeof(SessionHistorySummarizeForHandoffRequest))] [JsonSerializable(typeof(SessionInstalledPlugin))] [JsonSerializable(typeof(SessionInstructionsGetSourcesRequest))] +[JsonSerializable(typeof(SessionLimitPredictionBaselineData))] +[JsonSerializable(typeof(SessionLimitPredictionDetails))] +[JsonSerializable(typeof(SessionLimitPredictionPredictRequest))] +[JsonSerializable(typeof(SessionLimitPredictionPredictRequestWithSession))] +[JsonSerializable(typeof(SessionLimitPredictionResult))] +[JsonSerializable(typeof(SessionLimitPredictionTierOption))] [JsonSerializable(typeof(SessionList))] [JsonSerializable(typeof(SessionListEntry))] [JsonSerializable(typeof(SessionListFilter))] @@ -25333,6 +29085,8 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(SessionModeGetRequest))] [JsonSerializable(typeof(SessionModelGetCurrentRequest))] [JsonSerializable(typeof(SessionModelList))] +[JsonSerializable(typeof(SessionModelListRequest))] +[JsonSerializable(typeof(SessionModelListRequestWithSession))] [JsonSerializable(typeof(SessionModelPriceCategory))] [JsonSerializable(typeof(SessionNameGetRequest))] [JsonSerializable(typeof(SessionOpenResult))] @@ -25341,11 +29095,21 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(SessionPlanReadSqlTodosRequest))] [JsonSerializable(typeof(SessionPlanReadSqlTodosWithDependenciesRequest))] [JsonSerializable(typeof(SessionPluginsListRequest))] +[JsonSerializable(typeof(SessionPluginsReloadRequest))] +[JsonSerializable(typeof(SessionPluginsReloadRequestWithSession))] +[JsonSerializable(typeof(SessionProviderGetEndpointRequest))] +[JsonSerializable(typeof(SessionProviderGetEndpointRequestWithSession))] [JsonSerializable(typeof(SessionPruneResult))] [JsonSerializable(typeof(SessionQueueClearRequest))] +[JsonSerializable(typeof(SessionQueueEnqueueResumePendingRequest))] +[JsonSerializable(typeof(SessionQueueHasPendingRequest))] [JsonSerializable(typeof(SessionQueuePendingItemsRequest))] +[JsonSerializable(typeof(SessionQueueProcessRequest))] [JsonSerializable(typeof(SessionQueueRemoveMostRecentRequest))] +[JsonSerializable(typeof(SessionQueueSnapshotRequest))] [JsonSerializable(typeof(SessionRemoteDisableRequest))] +[JsonSerializable(typeof(SessionScheduleHasSelfPacedRequest))] +[JsonSerializable(typeof(SessionScheduleHydrateRequest))] [JsonSerializable(typeof(SessionScheduleListRequest))] [JsonSerializable(typeof(SessionSetCredentialsParams))] [JsonSerializable(typeof(SessionSetCredentialsResult))] @@ -25380,14 +29144,18 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(SessionUsageGetMetricsRequest))] [JsonSerializable(typeof(SessionVisibilityGetRequest))] [JsonSerializable(typeof(SessionWorkingDirectoryContext))] +[JsonSerializable(typeof(SessionWorkspacesAutopilotObjectiveExistsRequest))] +[JsonSerializable(typeof(SessionWorkspacesDeleteAutopilotObjectiveRequest))] [JsonSerializable(typeof(SessionWorkspacesGetWorkspaceRequest))] [JsonSerializable(typeof(SessionWorkspacesListCheckpointsRequest))] [JsonSerializable(typeof(SessionWorkspacesListFilesRequest))] +[JsonSerializable(typeof(SessionWorkspacesReadAutopilotObjectiveRequest))] [JsonSerializable(typeof(SessionsBulkDeleteRequest))] [JsonSerializable(typeof(SessionsCheckInUseRequest))] [JsonSerializable(typeof(SessionsCheckInUseResult))] [JsonSerializable(typeof(SessionsCloseRequest))] [JsonSerializable(typeof(SessionsCloseResult))] +[JsonSerializable(typeof(SessionsDeleteRequest))] [JsonSerializable(typeof(SessionsEnrichMetadataRequest))] [JsonSerializable(typeof(SessionsFindByPrefixRequest))] [JsonSerializable(typeof(SessionsFindByPrefixResult))] @@ -25401,8 +29169,12 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(SessionsGetEventFilePathResult))] [JsonSerializable(typeof(SessionsGetLastForContextRequest))] [JsonSerializable(typeof(SessionsGetLastForContextResult))] +[JsonSerializable(typeof(SessionsGetMetadataRequest))] +[JsonSerializable(typeof(SessionsGetMetadataResult))] [JsonSerializable(typeof(SessionsGetPersistedRemoteSteerableRequest))] [JsonSerializable(typeof(SessionsGetPersistedRemoteSteerableResult))] +[JsonSerializable(typeof(SessionsListNonEmptySessionIdsRequest))] +[JsonSerializable(typeof(SessionsListNonEmptySessionIdsResult))] [JsonSerializable(typeof(SessionsListRequest))] [JsonSerializable(typeof(SessionsLoadDeferredRepoHooksRequest))] [JsonSerializable(typeof(SessionsOpenProgress))] @@ -25424,8 +29196,10 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(ShellExecRequest))] [JsonSerializable(typeof(ShellExecResult))] [JsonSerializable(typeof(ShellExecuteUserRequestedRequest))] +[JsonSerializable(typeof(ShellInitScript))] [JsonSerializable(typeof(ShellKillRequest))] [JsonSerializable(typeof(ShellKillResult))] +[JsonSerializable(typeof(ShellOptions))] [JsonSerializable(typeof(ShutdownRequest))] [JsonSerializable(typeof(Skill))] [JsonSerializable(typeof(SkillDiscoveryPath))] @@ -25511,13 +29285,21 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(VisibilitySetResult))] [JsonSerializable(typeof(WorkspaceDiffFileChange))] [JsonSerializable(typeof(WorkspaceDiffResult))] +[JsonSerializable(typeof(WorkspacesAddSummaryRequest))] +[JsonSerializable(typeof(WorkspacesAddSummaryResult))] +[JsonSerializable(typeof(WorkspacesAddSummaryResultSummary))] +[JsonSerializable(typeof(WorkspacesAddSummaryResultWorkspace))] +[JsonSerializable(typeof(WorkspacesAutopilotObjectiveExistsResult))] [JsonSerializable(typeof(WorkspacesCheckpoints))] [JsonSerializable(typeof(WorkspacesCreateFileRequest))] +[JsonSerializable(typeof(WorkspacesDeleteAutopilotObjectiveResult))] [JsonSerializable(typeof(WorkspacesDiffRequest))] +[JsonSerializable(typeof(WorkspacesEnsureRequest))] [JsonSerializable(typeof(WorkspacesGetWorkspaceResult))] [JsonSerializable(typeof(WorkspacesGetWorkspaceResultWorkspace))] [JsonSerializable(typeof(WorkspacesListCheckpointsResult))] [JsonSerializable(typeof(WorkspacesListFilesResult))] +[JsonSerializable(typeof(WorkspacesReadAutopilotObjectiveResult))] [JsonSerializable(typeof(WorkspacesReadCheckpointRequest))] [JsonSerializable(typeof(WorkspacesReadCheckpointResult))] [JsonSerializable(typeof(WorkspacesReadFileRequest))] @@ -25525,4 +29307,8 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(WorkspacesSaveLargePasteRequest))] [JsonSerializable(typeof(WorkspacesSaveLargePasteResult))] [JsonSerializable(typeof(WorkspacesSaveLargePasteResultSaved))] +[JsonSerializable(typeof(WorkspacesTruncateSummariesRequest))] +[JsonSerializable(typeof(WorkspacesUpdateMetadataRequest))] +[JsonSerializable(typeof(WorkspacesWriteAutopilotObjectiveRequest))] +[JsonSerializable(typeof(WorkspacesWriteAutopilotObjectiveResult))] internal partial class RpcJsonContext : JsonSerializerContext; \ No newline at end of file diff --git a/dotnet/src/Generated/SessionEvents.cs b/dotnet/src/Generated/SessionEvents.cs index a8c70df7cc..5f89d3195a 100644 --- a/dotnet/src/Generated/SessionEvents.cs +++ b/dotnet/src/Generated/SessionEvents.cs @@ -52,6 +52,7 @@ namespace GitHub.Copilot; [JsonDerivedType(typeof(ExitPlanModeRequestedEvent), "exit_plan_mode.requested")] [JsonDerivedType(typeof(ExternalToolCompletedEvent), "external_tool.completed")] [JsonDerivedType(typeof(ExternalToolRequestedEvent), "external_tool.requested")] +[JsonDerivedType(typeof(FactoryRunUpdatedEvent), "factory.run_updated")] [JsonDerivedType(typeof(HookEndEvent), "hook.end")] [JsonDerivedType(typeof(HookProgressEvent), "hook.progress")] [JsonDerivedType(typeof(HookStartEvent), "hook.start")] @@ -1444,6 +1445,20 @@ public sealed partial class SessionBackgroundTasksChangedEvent : SessionEvent public required SessionBackgroundTasksChangedData Data { get; set; } } +/// Ephemeral invalidation signal for a changed factory run. +/// Represents the factory.run_updated event. +[Experimental(Diagnostics.Experimental)] +public sealed partial class FactoryRunUpdatedEvent : SessionEvent +{ + /// + [JsonIgnore] + public override string Type => "factory.run_updated"; + + /// The factory.run_updated event payload. + [JsonPropertyName("data")] + public required FactoryRunUpdatedData Data { get; set; } +} + /// Payload of `session.skills_loaded` listing resolved skill metadata. /// Represents the session.skills_loaded event. public sealed partial class SessionSkillsLoadedEvent : SessionEvent @@ -1750,7 +1765,7 @@ public sealed partial class SessionResumeData [JsonPropertyName("contextTier")] public ContextTier? ContextTier { get; set; } - /// When true, tool calls and permission requests left in flight by the previous session lifetime remain pending after resume and the agentic loop awaits their results. User sends are queued behind the pending work until all such requests reach a terminal state. When false (the default), any such tool calls and permission requests are immediately marked as interrupted on resume. + /// When true, tool calls and permission requests left in flight by the previous session lifetime remain pending after resume and the agentic loop awaits their results. User sends are queued behind the pending work until all such requests reach a terminal state. When false or omitted, pending work is normally marked as interrupted unless the resume passively joined live work owned by another client; sessionWasActive distinguishes that case. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("continuePendingWork")] public bool? ContinuePendingWork { get; set; } @@ -1793,7 +1808,7 @@ public sealed partial class SessionResumeData [JsonPropertyName("sessionLimits")] public SessionLimitsConfig? SessionLimits { get; set; } - /// True when this resume attached to a session that the runtime already had running in-memory (for example, an extension joining a session another client was actively driving). False (or omitted) for cold resumes — the runtime had to reconstitute the session from its persisted event log. + /// True when this resume passively joined a session that already had live work running in the runtime - an agent turn, a native queue run, a queued resume continuation, or an in-flight send (for example, an extension joining a session another client was actively driving). False (or omitted) when the session had no live work or when the resume explicitly abandoned pending work, including cold resumes and suspended sessions that remain resident in memory. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("sessionWasActive")] public bool? SessionWasActive { get; set; } @@ -1904,6 +1919,11 @@ public sealed partial class SessionScheduleCreatedData [JsonPropertyName("intervalMs")] public TimeSpan? Interval { get; set; } + /// Who created the schedule (`user` or `model`). Persisted so a resumed session keeps gating non-user schedules from firing skills that opted out of model invocation. Absent on entries created before this field existed; a missing origin fails closed (treated the same as a non-user origin), so such a schedule may not resolve a `disable-model-invocation` skill. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("origin")] + public ScheduleOrigin? Origin { get; set; } + /// Prompt text that gets enqueued on every tick. [JsonPropertyName("prompt")] public required string Prompt { get; set; } @@ -2337,6 +2357,11 @@ public sealed partial class SessionContextChangedData [JsonPropertyName("hostType")] public WorkingDirectoryContextHostType? HostType { get; set; } + /// Set on the immediate preliminary event of a working-directory change, before the git context is resolved. A settled follow-up event (enriched with git context, or cwd-only for a non-repository) is always emitted afterward, so observers may defer to it. Absent on standalone/final events (e.g. relay context changes). + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("pendingGitContext")] + public bool? PendingGitContext { get; set; } + /// Repository identifier derived from the git remote URL ("owner/name" for GitHub, "org/project/repo" for Azure DevOps). [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("repository")] @@ -2392,6 +2417,11 @@ public sealed partial class SessionCompactionStartData [JsonPropertyName("conversationTokens")] public long? ConversationTokens { get; set; } + /// Total context tokens (system + conversation + tool definitions) at compaction start, when known. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("currentTokens")] + public long? CurrentTokens { get; set; } + /// Model identifier used for compaction, when known. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("model")] @@ -2402,10 +2432,20 @@ public sealed partial class SessionCompactionStartData [JsonPropertyName("systemTokens")] public long? SystemTokens { get; set; } + /// Model context window token limit the compaction is targeting, when known. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("tokenLimit")] + public long? TokenLimit { get; set; } + /// Token count from tool definitions at compaction start. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("toolDefinitionsTokens")] public long? ToolDefinitionsTokens { get; set; } + + /// What initiated this compaction, when known. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("trigger")] + public CompactionTrigger? Trigger { get; set; } } /// Conversation compaction results including success status, metrics, and optional error details. @@ -2490,6 +2530,11 @@ public sealed partial class SessionCompactionCompleteData [JsonPropertyName("systemTokens")] public long? SystemTokens { get; set; } + /// Model context window token limit the compaction was targeting, when known. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("tokenLimit")] + public long? TokenLimit { get; set; } + /// Number of tokens removed during compaction. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("tokensRemoved")] @@ -2499,12 +2544,32 @@ public sealed partial class SessionCompactionCompleteData [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("toolDefinitionsTokens")] public long? ToolDefinitionsTokens { get; set; } + + /// What initiated this compaction, when known. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("trigger")] + public CompactionTrigger? Trigger { get; set; } } /// Task completion notification with summary from the agent. public sealed partial class SessionTaskCompleteData { - /// Whether the tool call succeeded. False when validation failed (e.g., invalid arguments). + /// Active autopilot objective ID evaluated by the completion reviewer. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("objectiveId")] + public long? ObjectiveId { get; set; } + + /// Semantic completion decision. Absent on legacy events and invalid tool calls. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("outcome")] + public TaskCompletionOutcome? Outcome { get; set; } + + /// Label-safe runtime rationale for the completion decision (e.g. a cancellation or pause/resume downgrade), when one applies. Reviewer-authored rationale is intentionally omitted here because this event has no IFC label channel; the reviewer's findings remain available through its own labeled sub-agent events. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("reason")] + public string? Reason { get; set; } + + /// Whether the task was accepted as complete. False when validation failed or completion was rejected or blocked by the reviewer. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("success")] public bool? Success { get; set; } @@ -2557,7 +2622,7 @@ public sealed partial class UserMessageData [JsonPropertyName("parentAgentTaskId")] public string? ParentAgentTaskId { get; set; } - /// Origin of this message, used for timeline filtering (e.g., "skill-pdf" for skill-injected messages that should be hidden from the user). + /// Origin of this message, used for timeline filtering and attribution (e.g., `skill-pdf` for hidden skill injection or `agent-<agent-id>` for an inter-agent prompt). [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("source")] public string? Source { get; set; } @@ -2648,6 +2713,11 @@ public sealed partial class AssistantReasoningData /// Unique identifier for this reasoning block. [JsonPropertyName("reasoningId")] public required string ReasoningId { get; set; } + + /// Gets or sets the rte value. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("rte")] + public bool? Rte { get; set; } } /// Streaming reasoning delta for incremental extended thinking updates. @@ -2773,6 +2843,11 @@ public sealed partial class AssistantMessageData [JsonPropertyName("requestId")] public string? RequestId { get; set; } + /// Gets or sets the rte value. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("rte")] + public bool? Rte { get; set; } + /// Neutral provider-tagged server-side tool-use payload (tool search, advisor) for verbatim round-tripping. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("serverTools")] @@ -2915,6 +2990,11 @@ public sealed partial class AssistantUsageData [JsonPropertyName("inputTokens")] public long? InputTokens { get; set; } + /// Coarse classification of the interaction that produced this call, mirroring the session's per-request agent context (e.g. `conversation-agent`, `conversation-subagent`, `conversation-sampling`, `conversation-background`, `conversation-compaction`, `conversation-user`). Non-billing; lets consumers attribute a model call to a call class (e.g. sub-agent/sidekick) independently of the billing initiator. Absent when the runtime did not classify the request. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("interactionType")] + public string? InteractionType { get; set; } + /// Average inter-token latency in milliseconds. Only available for streaming requests. [JsonConverter(typeof(MillisecondsTimeSpanConverter))] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -2960,6 +3040,11 @@ public sealed partial class AssistantUsageData [JsonPropertyName("reasoningTokens")] public long? ReasoningTokens { get; set; } + /// Gets or sets the rte value. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("rte")] + public bool? Rte { get; set; } + /// Copilot service request ID (x-copilot-service-request-id header) for CAPI log correlation. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("serviceRequestId")] @@ -3067,6 +3152,11 @@ public sealed partial class ModelCallFailureData [JsonPropertyName("requestFingerprint")] public ModelCallFailureRequestFingerprint? RequestFingerprint { get; set; } + /// Gets or sets the rte value. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("rte")] + public bool? Rte { get; set; } + /// Copilot service request ID (x-copilot-service-request-id header) for CAPI log correlation. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("serviceRequestId")] @@ -3095,6 +3185,12 @@ public sealed partial class ModelCallStartData [JsonPropertyName("model")] public string? Model { get; set; } + /// Previous response or interaction identifier included in the model request, when present. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonInclude] + [JsonPropertyName("previousResponseId")] + internal string? PreviousResponseId { get; set; } + /// Identifier of the assistant turn that initiated the model call. [JsonPropertyName("turnId")] public required string TurnId { get; set; } @@ -3162,6 +3258,11 @@ public sealed partial class ToolExecutionStartData [JsonPropertyName("parentToolCallId")] public string? ParentToolCallId { get; set; } + /// Gets or sets the rte value. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("rte")] + public bool? Rte { get; set; } + /// Shell-tool path hints derived from the command at start time for shell tools (bash/powershell/local_shell). Produced by the same shell-aware extractor as PermissionRequestShell.possiblePaths, so it is present even when the command is auto-approved and no permission request fires. Absent for non-shell tools. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("shellToolInfo")] @@ -3253,6 +3354,11 @@ public sealed partial class ToolExecutionCompleteData [JsonPropertyName("result")] public ToolExecutionCompleteResult? Result { get; set; } + /// Gets or sets the rte value. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("rte")] + public bool? Rte { get; set; } + /// Whether this tool execution ran inside a sandbox container. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("sandboxed")] @@ -3567,6 +3673,11 @@ public sealed partial class SystemMessageData [JsonPropertyName("content")] public required string Content { get; set; } + /// Logical interaction identifier for the model run receiving this prompt. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("interactionId")] + public string? InteractionId { get; set; } + /// Metadata about the prompt template and its construction. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("metadata")] @@ -3614,6 +3725,11 @@ public sealed partial class PermissionRequestedData [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("resolvedByHook")] public bool? ResolvedByHook { get; set; } + + /// Neutral risk metadata supplied by the tool host. Consumers may display this value but must not use it to bypass the permission decision. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("riskAssessment")] + public JsonElement? RiskAssessment { get; set; } } /// Permission request completion notification signaling UI dismissal. @@ -4021,6 +4137,11 @@ public sealed partial class SessionLimitsExhaustedCompletedData [Experimental(Diagnostics.Experimental)] public sealed partial class SessionAutoModeResolvedData { + /// Models offered to the router for this resolution. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("availableModels")] + public string[]? AvailableModels { get; set; } + /// Ordered candidate model list the router returned, when not a fallback. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("candidateModels")] @@ -4035,11 +4156,36 @@ public sealed partial class SessionAutoModeResolvedData [JsonPropertyName("chosenModel")] public required string ChosenModel { get; set; } + /// The chosen model's score shortfall relative to the top candidate. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("chosenShortfall")] + public double? ChosenShortfall { get; set; } + /// Classifier confidence for the predicted label, when available. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("confidence")] public double? Confidence { get; set; } + /// End-to-end client wait time for the router request in milliseconds. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("endToEndLatencyMs")] + public double? EndToEndLatencyMs { get; set; } + + /// Whether the router fell back to the standard Auto selection. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("fallback")] + public bool? Fallback { get; set; } + + /// Server-provided reason for falling back, when available. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("fallbackReason")] + public string? FallbackReason { get; set; } + + /// Whether the routed prompt contained an image. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("hasImage")] + public bool? HasImage { get; set; } + /// The predicted classifier label (e.g. `needs_reasoning`), when available. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("predictedLabel")] @@ -4049,6 +4195,21 @@ public sealed partial class SessionAutoModeResolvedData [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("reasoningBucket")] public AutoModeResolvedReasoningBucket? ReasoningBucket { get; set; } + + /// Server-reported router processing time in milliseconds. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("routerLatencyMs")] + public double? RouterLatencyMs { get; set; } + + /// The routing method the server applied, when Auto Intent ran. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("routingMethod")] + public string? RoutingMethod { get; set; } + + /// Whether a sticky model choice overrode the router result. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("stickyOverride")] + public bool? StickyOverride { get; set; } } /// Enterprise managed-settings resolution: the effective managed settings the session applied and where they came from, so SDK clients can show users what is enterprise-managed and by which authority. Fires whenever managed policy is (re)applied — at session start, on resume, and on account switch. This is an ephemeral live snapshot (delivered to subscribers but not persisted to the session event log), because at session start it resolves before `session.start` is emitted; for a session-independent pull, use the SDK `getManagedSettings()` API, which returns the identical payload. Managed settings have a single authoritative source, so the highest-authority present layer (server > device) wins wholesale; `bypassPermissionsDisabled` is deny-wins across layers. Marked experimental while the managed-settings surface stabilizes. @@ -4071,6 +4232,11 @@ public sealed partial class SessionManagedSettingsResolvedData [JsonPropertyName("managedKeys")] public required string[] ManagedKeys { get; set; } + /// Whether server and device each supplied a permission allowlist, so enforcement intersects them and the flattened settings payload omits `permissions.allow`. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("permissionsAllowIntersected")] + public bool? PermissionsAllowIntersected { get; set; } + /// Whether the server (account/org) managed-settings layer was present. [JsonPropertyName("serverManaged")] public required bool ServerManaged { get; set; } @@ -4193,6 +4359,19 @@ public sealed partial class SessionBackgroundTasksChangedData { } +/// Ephemeral invalidation signal for a changed factory run. +[Experimental(Diagnostics.Experimental)] +public sealed partial class FactoryRunUpdatedData +{ + /// Monotonic revision now available for the run. + [JsonPropertyName("revision")] + public required long Revision { get; set; } + + /// Gets or sets the runId value. + [JsonPropertyName("runId")] + public required string RunId { get; set; } +} + /// Payload of `session.skills_loaded` listing resolved skill metadata. public sealed partial class SessionSkillsLoadedData { @@ -4497,6 +4676,11 @@ public sealed partial class WorkingDirectoryContext [JsonPropertyName("hostType")] public WorkingDirectoryContextHostType? HostType { get; set; } + /// Set on the immediate preliminary event of a working-directory change, before the git context is resolved. A settled follow-up event (enriched with git context, or cwd-only for a non-repository) is always emitted afterward, so observers may defer to it. Absent on standalone/final events (e.g. relay context changes). + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("pendingGitContext")] + public bool? PendingGitContext { get; set; } + /// Repository identifier derived from the git remote URL ("owner/name" for GitHub, "org/project/repo" for Azure DevOps). [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("repository")] @@ -6670,6 +6854,20 @@ public sealed partial class SystemNotificationInstructionDiscovered : SystemNoti public required string TriggerTool { get; set; } } +/// System notification metadata from an external host that does not match a runtime-owned notification kind. +/// The unclassified variant of . +public sealed partial class SystemNotificationUnclassified : SystemNotification +{ + /// + [JsonIgnore] + public override string Type => "unclassified"; + + /// Opaque metadata supplied by the external host, when present. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("metadata")] + public JsonElement? Metadata { get; set; } +} + /// Structured metadata identifying what triggered this notification. /// Polymorphic base type discriminated by type. [JsonPolymorphic( @@ -6681,6 +6879,7 @@ public sealed partial class SystemNotificationInstructionDiscovered : SystemNoti [JsonDerivedType(typeof(SystemNotificationShellCompleted), "shell_completed")] [JsonDerivedType(typeof(SystemNotificationShellDetachedCompleted), "shell_detached_completed")] [JsonDerivedType(typeof(SystemNotificationInstructionDiscovered), "instruction_discovered")] +[JsonDerivedType(typeof(SystemNotificationUnclassified), "unclassified")] public partial class SystemNotification { /// The type discriminator. @@ -6702,6 +6901,19 @@ public sealed partial class PermissionRequestShellCommand public required bool ReadOnly { get; set; } } +/// A parsed shell command segment used for argument-aware managed policy matching. +/// Nested data type for PermissionRequestShellCommandSegment. +public sealed partial class PermissionRequestShellCommandSegment +{ + /// Full text of this command segment, including arguments. + [JsonPropertyName("fullCommandText")] + public required string FullCommandText { get; set; } + + /// Command identifier (e.g., executable name). + [JsonPropertyName("identifier")] + public required string Identifier { get; set; } +} + /// A URL that may be accessed by a command in a shell permission request. /// Nested data type for PermissionRequestShellPossibleUrl. public sealed partial class PermissionRequestShellPossibleUrl @@ -6727,6 +6939,11 @@ public sealed partial class PermissionRequestShell : PermissionRequest [JsonPropertyName("commands")] public required PermissionRequestShellCommand[] Commands { get; set; } + /// Parsed command segments, including arguments, used for managed policy matching. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("commandSegments")] + public PermissionRequestShellCommandSegment[]? CommandSegments { get; set; } + /// The complete shell command text to be executed. [JsonPropertyName("fullCommandText")] public required string FullCommandText { get; set; } @@ -6739,6 +6956,11 @@ public sealed partial class PermissionRequestShell : PermissionRequest [JsonPropertyName("intention")] public required string Intention { get; set; } + /// Whether managed policy requires a human response and forbids host auto-approval. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("managedApprovalRequired")] + public bool? ManagedApprovalRequired { get; set; } + /// File paths that may be read or written by the command. [JsonPropertyName("possiblePaths")] public required string[] PossiblePaths { get; set; } @@ -6792,6 +7014,11 @@ public sealed partial class PermissionRequestWrite : PermissionRequest [JsonPropertyName("intention")] public required string Intention { get; set; } + /// Whether managed policy requires a human response and forbids host auto-approval. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("managedApprovalRequired")] + public bool? ManagedApprovalRequired { get; set; } + /// Complete new file contents for newly created files. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("newFileContents")] @@ -6825,6 +7052,11 @@ public sealed partial class PermissionRequestRead : PermissionRequest [JsonPropertyName("intention")] public required string Intention { get; set; } + /// Whether managed policy requires a human response and forbids host auto-approval. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("managedApprovalRequired")] + public bool? ManagedApprovalRequired { get; set; } + /// Path of the file or directory being read. [JsonPropertyName("path")] public required string Path { get; set; } @@ -6892,6 +7124,16 @@ public sealed partial class PermissionRequestUrl : PermissionRequest [JsonPropertyName("intention")] public required string Intention { get; set; } + /// Whether managed policy requires a human response and forbids host auto-approval. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("managedApprovalRequired")] + public bool? ManagedApprovalRequired { get; set; } + + /// Immediately preceding URL when this request is for a redirect target. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("redirectedFrom")] + public string? RedirectedFrom { get; set; } + /// True when this URL fetch is requesting to bypass the sandbox network policy: either the model set requestSandboxBypass: true, or the tool re-issued the request as an interactive bypass after the network policy denied the approved URL (host opted in via sandbox.allowBypass). This is a request, not a grant: the fetch runs only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("requestSandboxBypass")] @@ -7083,6 +7325,16 @@ public partial class PermissionRequest [Experimental(Diagnostics.Experimental)] public sealed partial class PermissionAutoApproval { + /// Classified cause of an `error` recommendation. Absent for every other recommendation. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("failureReason")] + public AutoApprovalJudgeFailureReason? FailureReason { get; set; } + + /// Model id that produced the recommendation, when the judge was consulted and reported one. Absent for `excluded` (the judge was not consulted) and for failures that occurred before a model was selected. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("model")] + public string? Model { get; set; } + /// Human-readable reason for the judge's recommendation, when available. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("reason")] @@ -7123,6 +7375,11 @@ public sealed partial class PermissionPromptRequestCommands : PermissionPromptRe [JsonPropertyName("intention")] public required string Intention { get; set; } + /// Whether managed policy requires a human response and forbids host auto-approval. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("managedApprovalRequired")] + public bool? ManagedApprovalRequired { get; set; } + /// Tool call ID that triggered this permission request. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("toolCallId")] @@ -7164,6 +7421,11 @@ public sealed partial class PermissionPromptRequestWrite : PermissionPromptReque [JsonPropertyName("intention")] public required string Intention { get; set; } + /// Whether managed policy requires a human response and forbids host auto-approval. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("managedApprovalRequired")] + public bool? ManagedApprovalRequired { get; set; } + /// Complete new file contents for newly created files. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("newFileContents")] @@ -7193,6 +7455,11 @@ public sealed partial class PermissionPromptRequestRead : PermissionPromptReques [JsonPropertyName("intention")] public required string Intention { get; set; } + /// Whether managed policy requires a human response and forbids host auto-approval. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("managedApprovalRequired")] + public bool? ManagedApprovalRequired { get; set; } + /// Path of the file or directory being read. [JsonPropertyName("path")] public required string Path { get; set; } @@ -7258,6 +7525,16 @@ public sealed partial class PermissionPromptRequestUrl : PermissionPromptRequest [JsonPropertyName("intention")] public required string Intention { get; set; } + /// Whether managed policy requires a human response and forbids host auto-approval. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("managedApprovalRequired")] + public bool? ManagedApprovalRequired { get; set; } + + /// Immediately preceding URL when this prompt is for a redirect target. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("redirectedFrom")] + public string? RedirectedFrom { get; set; } + /// True when this URL fetch is requesting to bypass the sandbox network policy: either the model set requestSandboxBypass: true, or the tool re-issued the request as an interactive bypass after the network policy denied the approved URL (host opted in via sandbox.allowBypass). This is a request, not a grant: the fetch runs only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("requestSandboxBypass")] @@ -8412,6 +8689,67 @@ public override void Write(Utf8JsonWriter writer, Verbosity value, JsonSerialize } } +/// Who created the schedule: `user` (an explicit user action such as `/every` or `/after`) or `model` (the agent via the `manage_schedule` tool). Gates whether a scheduled skill that opted out of model invocation may fire: only user-created schedules may. +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct ScheduleOrigin : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public ScheduleOrigin(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// The schedule was created by an explicit user action, such as `/every` or `/after`. + public static ScheduleOrigin User { get; } = new("user"); + + /// The schedule was created by the agent via the `manage_schedule` tool. + public static ScheduleOrigin Model { get; } = new("model"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(ScheduleOrigin left, ScheduleOrigin right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(ScheduleOrigin left, ScheduleOrigin right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is ScheduleOrigin other && Equals(other); + + /// + public bool Equals(ScheduleOrigin other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override ScheduleOrigin Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, ScheduleOrigin value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(ScheduleOrigin)); + } + } +} + /// The type of operation performed on the autopilot objective state file. [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] @@ -8919,6 +9257,140 @@ public override void Write(Utf8JsonWriter writer, ShutdownType value, JsonSerial } } +/// What initiated a conversation compaction. +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct CompactionTrigger : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public CompactionTrigger(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// Background compaction started automatically because context utilization crossed the background threshold. + public static CompactionTrigger Threshold { get; } = new("threshold"); + + /// Compaction forced by a context-limit model response (e.g. HTTP 413) before retrying the request. + public static CompactionTrigger ContextLimitRetry { get; } = new("context_limit_retry"); + + /// User-requested compaction, e.g. the /compact command or the history.compact API. + public static CompactionTrigger Manual { get; } = new("manual"); + + /// Emergency compaction triggered by high process memory usage. + public static CompactionTrigger MemoryPressure { get; } = new("memory_pressure"); + + /// Compaction requested while switching to a model with a smaller context window. + public static CompactionTrigger ModelSwitch { get; } = new("model_switch"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(CompactionTrigger left, CompactionTrigger right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(CompactionTrigger left, CompactionTrigger right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is CompactionTrigger other && Equals(other); + + /// + public bool Equals(CompactionTrigger other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override CompactionTrigger Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, CompactionTrigger value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(CompactionTrigger)); + } + } +} + +/// Semantic result of evaluating a task completion request. +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct TaskCompletionOutcome : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public TaskCompletionOutcome(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// The completion request was accepted and the objective is complete. + public static TaskCompletionOutcome Completed { get; } = new("completed"); + + /// The completion request was rejected because more work or validation remains. + public static TaskCompletionOutcome Continue { get; } = new("continue"); + + /// Completion cannot proceed without intervention; the active objective is paused when one is identified. + public static TaskCompletionOutcome Blocked { get; } = new("blocked"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(TaskCompletionOutcome left, TaskCompletionOutcome right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(TaskCompletionOutcome left, TaskCompletionOutcome right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is TaskCompletionOutcome other && Equals(other); + + /// + public bool Equals(TaskCompletionOutcome other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override TaskCompletionOutcome Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, TaskCompletionOutcome value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(TaskCompletionOutcome)); + } + } +} + /// The agent mode that was active when this message was sent. [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] @@ -10414,6 +10886,77 @@ public override void Write(Utf8JsonWriter writer, PermissionRequestMemoryDirecti } } +/// Why the auto-approval judge produced no usable recommendation. Present only alongside an `error` recommendation, where the human-readable reason is a fixed string and therefore cannot distinguish these cases. Intended to make a judge failure reportable by a consumer that has no access to the host's logs. +[Experimental(Diagnostics.Experimental)] +[JsonConverter(typeof(Converter))] +[DebuggerDisplay("{Value,nq}")] +public readonly struct AutoApprovalJudgeFailureReason : IEquatable +{ + private readonly string? _value; + + /// Initializes a new instance of the struct. + /// The value to associate with this . + [JsonConstructor] + public AutoApprovalJudgeFailureReason(string value) + { + ArgumentException.ThrowIfNullOrWhiteSpace(value); + _value = value; + } + + /// Gets the value associated with this . + public string Value => _value ?? string.Empty; + + /// The judge model call exceeded its deadline. + public static AutoApprovalJudgeFailureReason Timeout { get; } = new("timeout"); + + /// The judge model call was cancelled before it returned. + public static AutoApprovalJudgeFailureReason Abort { get; } = new("abort"); + + /// The judge model call completed but returned no content. + public static AutoApprovalJudgeFailureReason EmptyResponse { get; } = new("empty_response"); + + /// The judge model call failed (for example a transport, authentication, or rate-limit error). + public static AutoApprovalJudgeFailureReason ModelError { get; } = new("model_error"); + + /// The judge model replied, but the reply carried no ALLOW/DENY verdict. + public static AutoApprovalJudgeFailureReason ParseError { get; } = new("parse_error"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(AutoApprovalJudgeFailureReason left, AutoApprovalJudgeFailureReason right) => left.Equals(right); + + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(AutoApprovalJudgeFailureReason left, AutoApprovalJudgeFailureReason right) => !(left == right); + + /// + public override bool Equals(object? obj) => obj is AutoApprovalJudgeFailureReason other && Equals(other); + + /// + public bool Equals(AutoApprovalJudgeFailureReason other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + + /// + public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + + /// + public override string ToString() => Value; + + /// Provides a for serializing instances. + [EditorBrowsable(EditorBrowsableState.Never)] + public sealed class Converter : JsonConverter + { + /// + public override AutoApprovalJudgeFailureReason Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); + } + + /// + public override void Write(Utf8JsonWriter writer, AutoApprovalJudgeFailureReason value, JsonSerializerOptions options) + { + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AutoApprovalJudgeFailureReason)); + } + } +} + /// Outcome of the auto-approval safety judge for a permission request. Present only when auto mode is enabled; its absence means the judge did not evaluate the request (auto mode was off). [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] @@ -11908,6 +12451,8 @@ public override void Write(Utf8JsonWriter writer, ExtensionsLoadedExtensionStatu [JsonSerializable(typeof(ExternalToolCompletedEvent))] [JsonSerializable(typeof(ExternalToolRequestedData))] [JsonSerializable(typeof(ExternalToolRequestedEvent))] +[JsonSerializable(typeof(FactoryRunUpdatedData))] +[JsonSerializable(typeof(FactoryRunUpdatedEvent))] [JsonSerializable(typeof(GitHubRepoRef))] [JsonSerializable(typeof(HandoffRepository))] [JsonSerializable(typeof(HeaderEntry))] @@ -11974,6 +12519,7 @@ public override void Write(Utf8JsonWriter writer, ExtensionsLoadedExtensionStatu [JsonSerializable(typeof(PermissionRequestRead))] [JsonSerializable(typeof(PermissionRequestShell))] [JsonSerializable(typeof(PermissionRequestShellCommand))] +[JsonSerializable(typeof(PermissionRequestShellCommandSegment))] [JsonSerializable(typeof(PermissionRequestShellPossibleUrl))] [JsonSerializable(typeof(PermissionRequestUrl))] [JsonSerializable(typeof(PermissionRequestWrite))] @@ -12130,6 +12676,7 @@ public override void Write(Utf8JsonWriter writer, ExtensionsLoadedExtensionStatu [JsonSerializable(typeof(SystemNotificationNewInboxMessage))] [JsonSerializable(typeof(SystemNotificationShellCompleted))] [JsonSerializable(typeof(SystemNotificationShellDetachedCompleted))] +[JsonSerializable(typeof(SystemNotificationUnclassified))] [JsonSerializable(typeof(ToolExecutionCompleteContent))] [JsonSerializable(typeof(ToolExecutionCompleteContentAudio))] [JsonSerializable(typeof(ToolExecutionCompleteContentImage))] diff --git a/go/rpc/zrpc.go b/go/rpc/zrpc.go index 634efbca23..341eb6f617 100644 --- a/go/rpc/zrpc.go +++ b/go/rpc/zrpc.go @@ -162,7 +162,7 @@ type AgentGetCurrentResult struct { Agent *AgentInfo `json:"agent,omitempty"` } -// Custom agent metadata, including identifiers, display details, source, tools, model, MCP +// Agent metadata, including identifiers, display details, source, tools, model, MCP // servers, skills, and file path. // Experimental: AgentInfo is part of an experimental API and may change or be removed. type AgentInfo struct { @@ -178,13 +178,17 @@ type AgentInfo struct { // 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,omitzero"` - // Preferred model id for this agent. When omitted, inherits the outer agent's model. + // Authored preferred model id for this agent. Runtime model selection may choose a + // different model; omitted means no authored preference. Model *string `json:"model,omitempty"` - // Unique identifier of the custom agent + // Name of the agent. Use `id` as the stable selection identifier. Name string `json:"name"` // Absolute local file path of the agent definition. Only set for file-based agents loaded // from disk; remote agents do not have a path. Path *string `json:"path,omitempty"` + // Authored base prompt for the agent. Runtime prompt assembly may add dynamic context at + // invocation time. Omitted from `session.agent.list` unless `includePrompt` is true. + Prompt *string `json:"prompt,omitempty"` // Skill names preloaded into this agent's context. Omitted means none. Skills []string `json:"skills,omitzero"` // Where the agent definition was loaded from @@ -196,13 +200,25 @@ type AgentInfo struct { UserInvocable *bool `json:"userInvocable,omitempty"` } -// Custom agents available to the session. +// Agents available to the session. // Experimental: AgentList is part of an experimental API and may change or be removed. type AgentList struct { - // Available custom agents + // Available agents Agents []AgentInfo `json:"agents"` } +type AgentListRequest struct { + // When true, request the session's configured built-in agents alongside custom agents. + // Listing applies feature, context, inclusion, exclusion, and user-disabled-agent policy, + // but does not evaluate transient invocation requirements such as model availability. + // Built-in metadata may be omitted when the session cannot project it, such as a relay + // session. + IncludeBuiltInAgents *bool `json:"includeBuiltInAgents,omitempty"` + // When true, request authored base prompt text on each AgentInfo. Prompt text may be + // omitted when unavailable, such as for agents projected through a relay session. + IncludePrompt *bool `json:"includePrompt,omitempty"` +} + // Full registry entry for the spawned child. Lets the controller call // `handleLiveTargetSelected(entry)` directly without re-reading the registry (avoids a // TOCTOU window). @@ -999,6 +1015,25 @@ func (UserAuthInfo) Type() AuthInfoType { return AuthInfoTypeUser } +// The running runtime's complete catalog of well-known built-in model IDs, including +// supported models and additional IDs with built-in metadata. +// Experimental: BuiltInModelCatalog is part of an experimental API and may change or be +// removed. +type BuiltInModelCatalog struct { + // Built-in model entries. + Models []BuiltInModelCatalogEntry `json:"models"` +} + +// A well-known model in the runtime's built-in catalog. +// Experimental: BuiltInModelCatalogEntry is part of an experimental API and may change or +// be removed. +type BuiltInModelCatalogEntry struct { + // Well-known runtime model ID suitable for `ProviderConfig.modelId` or + // `ProviderModelConfig.modelId`. This is not necessarily the provider-facing deployment or + // model name and does not indicate CAPI entitlement or provider availability. + ID string `json:"id"` +} + // Cancellation result for a user-requested shell command. // Experimental: CancelUserRequestedShellCommandResult is part of an experimental API and // may change or be removed. @@ -1230,7 +1265,6 @@ type CommandsInvokeRequest struct { Name string `json:"name"` } -// Optional filters controlling which command sources to include in the listing. // Experimental: CommandsListRequest is part of an experimental API and may change or be // removed. type CommandsListRequest struct { @@ -1363,11 +1397,14 @@ type ConnectRemoteSessionParams struct { type ConnectRequest struct { // Opt this connection in to GitHub telemetry forwarding for its lifetime. When set, the // runtime forwards every internal telemetry event it emits — across all sessions, plus - // sessionless events — to this connection over the `gitHubTelemetry.event` notification, in - // addition to the runtime's normal GitHub/CTS emission (dual-write). Intended for - // first-party hosts that re-emit the events into their own telemetry stores. Both - // unrestricted and restricted events are forwarded, each tagged with a `restricted` - // discriminator; a backstop drops restricted events when restricted telemetry is disabled. + // sessionless events — to this connection over the `gitHubTelemetry.event` notification. + // Regular events are also written to the runtime's normal GitHub/CTS path (dual-write); + // host-only compatibility events are forward-only and intentionally skip that path. + // Intended for first-party hosts that re-emit the events into their own telemetry stores. + // Both unrestricted and restricted events are forwarded, each tagged with a `restricted` + // discriminator; a backstop drops restricted events when restricted telemetry is disabled — + // using the process-global gate for ordinary events and an explicit session-scoped decision + // for host-only events. EnableGitHubTelemetryForwarding *bool `json:"enableGitHubTelemetryForwarding,omitempty"` // Connection token; required when the server was started with COPILOT_CONNECTION_TOKEN Token *string `json:"token,omitempty"` @@ -1385,6 +1422,38 @@ type ConnectResult struct { Version string `json:"version"` } +// Local file system absolute paths within the session working directory to check against +// its content-exclusion policy. +// Experimental: ContentExclusionCheckPathsRequest is part of an experimental API and may +// change or be removed. +type ContentExclusionCheckPathsRequest struct { + // Local file system absolute paths within the session working directory to check. Results + // are returned in the same order, including duplicates. + Paths []string `json:"paths"` +} + +// Batch content-exclusion result. Callers must fail closed when policy evaluation is +// unavailable. +// Experimental: ContentExclusionCheckPathsResult is part of an experimental API and may +// change or be removed. +type ContentExclusionCheckPathsResult struct { + // Whether the session's policy service was available for the complete batch. When false, + // checks is empty and callers must treat every requested path as excluded. + Available bool `json:"available"` + // Per-path decisions in request order. Empty when available is false. + Checks []ContentExclusionPathCheck `json:"checks"` +} + +// Content-exclusion decision for one requested path. +// Experimental: ContentExclusionPathCheck is part of an experimental API and may change or +// be removed. +type ContentExclusionPathCheck struct { + // Whether the session's complete content-exclusion policy excludes the path. + Excluded bool `json:"excluded"` + // The path supplied by the caller. + Path string `json:"path"` +} + // A single large message currently in context. // Experimental: ContextHeaviestMessage is part of an experimental API and may change or be // removed. @@ -1839,6 +1908,11 @@ type EventLogReadRequest struct { // Opaque cursor returned by a previous read. Omit on the first call to start from the // beginning of the session's persisted history. Cursor *string `json:"cursor,omitempty"` + // When false, skip ephemeral events entirely and return only durable (persisted) events. + // History-backfill callers that discard ephemerals anyway should set this so the read is + // bounded by the durable log length instead of racing the ephemeral ring on a busy session. + // Defaults to true (ephemerals are interleaved with durable events in creation order). + IncludeEphemeral *bool `json:"includeEphemeral,omitempty"` // Maximum number of events to return in this batch (1–1000, default 200). Max *int64 `json:"max,omitempty"` // Either '*' to receive all event types, or a non-empty list of event types to receive @@ -1891,10 +1965,11 @@ type EventsReadResult struct { // referred to an event that no longer exists in history (e.g. truncated or compacted away) // and the read started from the beginning of the remaining history. CursorStatus EventsCursorStatus `json:"cursorStatus"` - // Events are delivered in two batches per read: persisted events first (in append order), - // then ephemeral events (in seq order). When `waitMs > 0` and the catch-up batches were - // empty, post-wait events follow the same two-batch ordering. Persisted and ephemeral - // events do not interleave within a single read. + // Session events for this batch, merged into a single stream in creation order: durable + // (persisted) events and ephemeral events interleave exactly as they were emitted. Set + // `includeEphemeral: false` to receive only durable events. Ephemeral events are never + // replayable once pruned from the in-memory ring, so a consumer that needs them should keep + // reading with a non-zero `waitMs`. Events []SessionEvent `json:"events"` // True when the read returned `max` events and more events are available immediately. When // false, the next read with a non-zero `waitMs` will block until a new event arrives or the @@ -2246,6 +2321,8 @@ type FactoryAgentOptions struct { // Experimental: FactoryAgentRequest is part of an experimental API and may change or be // removed. type FactoryAgentRequest struct { + // Opaque token identifying the current factory execution attempt. + ExecutionToken string `json:"executionToken"` // Factory run identifier that owns the subagent. FactoryRunID string `json:"factoryRunId"` // Subagent execution options. @@ -2262,6 +2339,25 @@ type FactoryAgentResult struct { Result any `json:"result,omitempty"` } +// Prompt-safe durable identity and live status for a direct factory agent. +// Experimental: FactoryAgentSummary is part of an experimental API and may change or be +// removed. +type FactoryAgentSummary struct { + ActiveMs int64 `json:"activeMs"` + Activity *string `json:"activity,omitempty"` + AgentID string `json:"agentId"` + AgentType string `json:"agentType"` + CompletedAt *int64 `json:"completedAt,omitempty"` + Label string `json:"label"` + PhaseID *string `json:"phaseId"` + RequestedModel *string `json:"requestedModel,omitempty"` + ResolvedModel *string `json:"resolvedModel,omitempty"` + RunID string `json:"runId"` + StartedAt *int64 `json:"startedAt,omitempty"` + Status string `json:"status"` + ToolCallID string `json:"toolCallId"` +} + // Parameters for cancelling a factory run. // Experimental: FactoryCancelRequest is part of an experimental API and may change or be // removed. @@ -2270,12 +2366,32 @@ type FactoryCancelRequest struct { RunID string `json:"runId"` } +// Current factory phase identity. +// Experimental: FactoryCurrentPhase is part of an experimental API and may change or be +// removed. +type FactoryCurrentPhase struct { + ID string `json:"id"` + Ordinal *int64 `json:"ordinal"` +} + +// Declared or approved factory resource ceilings. +// Experimental: FactoryDeclaredLimits is part of an experimental API and may change or be +// removed. +type FactoryDeclaredLimits struct { + MaxAiCredits *float64 `json:"maxAiCredits,omitempty"` + MaxConcurrentSubagents *int64 `json:"maxConcurrentSubagents,omitempty"` + MaxTotalSubagents *int64 `json:"maxTotalSubagents,omitempty"` + TimeoutSeconds *float64 `json:"timeoutSeconds,omitempty"` +} + // Parameters sent to the owning extension to execute a factory closure. // Experimental: FactoryExecuteRequest is part of an experimental API and may change or be // removed. type FactoryExecuteRequest struct { // Factory input value. Args any `json:"args"` + // Opaque token identifying this factory execution attempt. + ExecutionToken string `json:"executionToken"` // Registered factory name. Name string `json:"name"` // Factory run identifier. @@ -2289,7 +2405,23 @@ type FactoryExecuteRequest struct { // removed. type FactoryExecuteResult struct { // Factory result value. - Result any `json:"result"` + Result any `json:"result,omitempty"` +} + +// Parameters for paging factory progress. +// Experimental: FactoryGetRunProgressRequest is part of an experimental API and may change +// or be removed. +type FactoryGetRunProgressRequest struct { + // Exclusive forward cursor. + AfterSeq *int64 `json:"afterSeq,omitempty"` + // Exclusive backward cursor. + BeforeSeq *int64 `json:"beforeSeq,omitempty"` + // Maximum records to return. Defaults to 200 and is capped at 500. + Limit *int32 `json:"limit,omitempty"` + // Optional phase identifier used to scope records and cursors. + PhaseID *string `json:"phaseId,omitempty"` + // Factory run identifier. + RunID string `json:"runId"` } // Parameters for retrieving a factory run. @@ -2304,6 +2436,8 @@ type FactoryGetRunRequest struct { // Experimental: FactoryJournalGetRequest is part of an experimental API and may change or // be removed. type FactoryJournalGetRequest struct { + // Opaque token identifying the current factory execution attempt. + ExecutionToken string `json:"executionToken"` // Namespaced journal key. Key string `json:"key"` // Factory run identifier. @@ -2324,6 +2458,8 @@ type FactoryJournalGetResult struct { // Experimental: FactoryJournalPutRequest is part of an experimental API and may change or // be removed. type FactoryJournalPutRequest struct { + // Opaque token identifying the current factory execution attempt. + ExecutionToken string `json:"executionToken"` // Namespaced journal key. Key string `json:"key"` // JSON result to memoize. @@ -2332,6 +2468,19 @@ type FactoryJournalPutRequest struct { RunID string `json:"runId"` } +// Empty parameters for listing factory runs. +// Experimental: FactoryListRunsRequest is part of an experimental API and may change or be +// removed. +type FactoryListRunsRequest struct { +} + +// Factory runs in durable creation order. +// Experimental: FactoryListRunsResult is part of an experimental API and may change or be +// removed. +type FactoryListRunsResult struct { + Runs []FactoryRunSummary `json:"runs"` +} + // One ordered factory progress line. // Experimental: FactoryLogLine is part of an experimental API and may change or be removed. type FactoryLogLine struct { @@ -2347,12 +2496,121 @@ type FactoryLogLine struct { // Experimental: FactoryLogRequest is part of an experimental API and may change or be // removed. type FactoryLogRequest struct { + // Opaque token identifying the current factory execution attempt. + ExecutionToken string `json:"executionToken"` // Ordered progress lines to append. Lines []FactoryLogLine `json:"lines"` // Factory run identifier. RunID string `json:"runId"` } +// Durable lifecycle and timing for one factory phase. +// Experimental: FactoryPhaseObservation is part of an experimental API and may change or be +// removed. +type FactoryPhaseObservation struct { + AccumulatedActiveMs int64 `json:"accumulatedActiveMs"` + CompletedAt *int64 `json:"completedAt,omitempty"` + CurrentActiveMs int64 `json:"currentActiveMs"` + Detail *string `json:"detail,omitempty"` + EntryCount int64 `json:"entryCount"` + ID string `json:"id"` + LastEnteredRunAttempt int64 `json:"lastEnteredRunAttempt"` + LiveAgentCount int64 `json:"liveAgentCount"` + Ordinal *int64 `json:"ordinal"` + StartedAt *int64 `json:"startedAt,omitempty"` + Status FactoryPhaseStatus `json:"status"` + Title string `json:"title"` + TotalAgentCount int64 `json:"totalAgentCount"` +} + +// One durable factory progress record. +// Experimental: FactoryProgressLine is part of an experimental API and may change or be +// removed. +type FactoryProgressLine struct { + // Resume attempt that emitted this record. + Attempt int64 `json:"attempt"` + // Progress record kind. + Kind FactoryLogLineKind `json:"kind"` + // Phase active when the record was emitted, or null before any phase. + PhaseID *string `json:"phaseId"` + // Epoch milliseconds when the record was persisted. + RecordedAt int64 `json:"recordedAt"` + // Global monotonic sequence number within the run. + Seq int64 `json:"seq"` + // Prompt-safe progress text. + Text string `json:"text"` +} + +// A bidirectional page of factory progress. +// Experimental: FactoryProgressPage is part of an experimental API and may change or be +// removed. +type FactoryProgressPage struct { + HasMoreNewer bool `json:"hasMoreNewer"` + HasMoreOlder bool `json:"hasMoreOlder"` + NewestSeq *int64 `json:"newestSeq"` + OldestSeq *int64 `json:"oldestSeq"` + Records []FactoryProgressLine `json:"records"` + // Run revision reflected by this page. + Revision int64 `json:"revision"` +} + +// Parameters for resuming a factory run from its persisted identity. +// Experimental: FactoryResumeRequest is part of an experimental API and may change or be +// removed. +type FactoryResumeRequest struct { + // Optional per-invocation resource ceiling overrides. + Limits *FactoryRunLimits `json:"limits,omitempty"` + // Factory run identifier. + RunID string `json:"runId"` +} + +// Resolved persisted factory identity and resumed run envelope. +// Experimental: FactoryResumeResult is part of an experimental API and may change or be +// removed. +type FactoryResumeResult struct { + // Persisted factory name resolved for the resumed run. + FactoryName string `json:"factoryName"` + // Terminal resumed run envelope. + Run FactoryRunResult `json:"run"` +} + +// Durable factory resource consumption. +// Experimental: FactoryRunConsumed is part of an experimental API and may change or be +// removed. +type FactoryRunConsumed struct { + ActiveMs int64 `json:"activeMs"` + NanoAiu int64 `json:"nanoAiu"` + Subagents int64 `json:"subagents"` +} + +// Full factory run observability detail. +// Experimental: FactoryRunDetail is part of an experimental API and may change or be +// removed. +type FactoryRunDetail struct { + ActiveSegmentStartedAt *int64 `json:"activeSegmentStartedAt"` + Agents []FactoryAgentSummary `json:"agents"` + Approved *FactoryDeclaredLimits `json:"approved"` + CompletedAt *int64 `json:"completedAt"` + Consumed FactoryRunConsumed `json:"consumed"` + CreatedAt int64 `json:"createdAt"` + CurrentPhase *FactoryCurrentPhase `json:"currentPhase"` + DeclaredLimits FactoryDeclaredLimits `json:"declaredLimits"` + DeclaredPhaseCount int64 `json:"declaredPhaseCount"` + Description string `json:"description"` + FactoryName string `json:"factoryName"` + LiveAgentCount int64 `json:"liveAgentCount"` + ObservedAt int64 `json:"observedAt"` + Phases []FactoryPhaseObservation `json:"phases"` + Progress FactoryProgressPage `json:"progress"` + Revision int64 `json:"revision"` + RunID string `json:"runId"` + StartedAt *int64 `json:"startedAt"` + Status FactoryRunStatus `json:"status"` + Terminal *FactoryRunTerminal `json:"terminal"` + TotalSpawnedAgentCount int64 `json:"totalSpawnedAgentCount"` + UpdatedAt int64 `json:"updatedAt"` +} + // Machine-readable factory run failure. // Experimental: FactoryRunFailure is part of an experimental API and may change or be // removed. @@ -2371,6 +2629,20 @@ func (r RawFactoryRunFailureData) Type() FactoryRunFailureType { return r.Discriminator } +type FactoryRunFailureFactoryDurableFailure struct { + // Stable failure code. + Code string `json:"code"` + // Execution-critical durable operation that failed. + Operation FactoryDurableOperation `json:"operation"` + // Factory run identifier. + RunID string `json:"runId"` +} + +func (FactoryRunFailureFactoryDurableFailure) factoryRunFailure() {} +func (FactoryRunFailureFactoryDurableFailure) Type() FactoryRunFailureType { + return FactoryRunFailureTypeFactoryDurableFailure +} + type FactoryRunFailureFactoryLimitReached struct { // Resource ceiling that stopped the run. Kind FactoryRunFailureKind `json:"kind"` @@ -2401,12 +2673,17 @@ func (FactoryRunFailureFactoryResumeDeclined) Type() FactoryRunFailureType { // Experimental: FactoryRunLimits is part of an experimental API and may change or be // removed. type FactoryRunLimits struct { + // Maximum AI credits consumed by factory subagents and their descendants. The post-paid + // ceiling is soft: parallel turns can settle beyond it before the run stops. + MaxAiCredits *float64 `json:"maxAiCredits,omitempty"` // Maximum number of factory subagents that may run concurrently. MaxConcurrentSubagents *int64 `json:"maxConcurrentSubagents,omitempty"` // Maximum total number of factory subagents that may be admitted. MaxTotalSubagents *int64 `json:"maxTotalSubagents,omitempty"` - // Factory active-run timeout in milliseconds. - Timeout *float64 `json:"timeout,omitempty"` + // Maximum accumulated active-execution time in seconds. Active execution includes the + // entire extension body, subprocess waits, queued-agent waits, and sleeps; time between + // resumed attempts is not counted. + TimeoutSeconds *float64 `json:"timeoutSeconds,omitempty"` } // Parameters for invoking a registered factory. @@ -2441,6 +2718,41 @@ type FactoryRunResult struct { Status FactoryRunStatus `json:"status"` } +// Durable factory run summary with read-time live overlays. +// Experimental: FactoryRunSummary is part of an experimental API and may change or be +// removed. +type FactoryRunSummary struct { + ActiveSegmentStartedAt *int64 `json:"activeSegmentStartedAt"` + Approved *FactoryDeclaredLimits `json:"approved"` + CompletedAt *int64 `json:"completedAt"` + Consumed FactoryRunConsumed `json:"consumed"` + CreatedAt int64 `json:"createdAt"` + CurrentPhase *FactoryCurrentPhase `json:"currentPhase"` + DeclaredLimits FactoryDeclaredLimits `json:"declaredLimits"` + DeclaredPhaseCount int64 `json:"declaredPhaseCount"` + Description string `json:"description"` + FactoryName string `json:"factoryName"` + LiveAgentCount int64 `json:"liveAgentCount"` + ObservedAt int64 `json:"observedAt"` + Revision int64 `json:"revision"` + RunID string `json:"runId"` + StartedAt *int64 `json:"startedAt"` + Status FactoryRunStatus `json:"status"` + Terminal *FactoryRunTerminal `json:"terminal"` + TotalSpawnedAgentCount int64 `json:"totalSpawnedAgentCount"` + UpdatedAt int64 `json:"updatedAt"` +} + +// Prompt-safe terminal factory outcome. +// Experimental: FactoryRunTerminal is part of an experimental API and may change or be +// removed. +type FactoryRunTerminal struct { + Error *string `json:"error,omitempty"` + Failure FactoryRunFailure `json:"failure,omitempty"` + Reason *string `json:"reason,omitempty"` + ResultPreview *string `json:"resultPreview,omitempty"` +} + // 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. @@ -2639,12 +2951,21 @@ 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"` + // Context window token limit this compaction is targeting, recorded as the `tokenLimit` on + // the persisted `session.compaction_start` / `session.compaction_complete` events. Set it + // when the compaction targets a window other than the compacting model's own, e.g. + // switching to a model with a smaller context window: the compaction still runs on the + // current model, so the limit that motivated it would otherwise be lost. When absent, the + // events record the compacting model's own resolved limit. Attribution metadata only - it + // does not change how much the compaction removes. + TokenLimit *int64 `json:"tokenLimit,omitempty"` + // What initiated this compaction request, recorded as the `trigger` on the persisted + // `session.compaction_start` / `session.compaction_complete` events. When absent, the + // compaction is persisted without trigger attribution (initiator unknown). + Trigger *HistoryCompactRequestTrigger `json:"trigger,omitempty"` } // Compaction outcome with the number of tokens and messages removed, summary text, and the @@ -2665,6 +2986,141 @@ type HistoryCompactResult struct { TokensRemoved int64 `json:"tokensRemoved"` } +// Rewind points and file-change-tracking availability for the session. +// Experimental: HistoryListRewindPointsResult is part of an experimental API and may change +// or be removed. +type HistoryListRewindPointsResult struct { + // Whether this session captured file changes from its first turn. + FileChangeTrackingEnabled bool `json:"fileChangeTrackingEnabled"` + // Root user turns in chronological order. Empty when `unavailableReason` is set. + Points []HistoryRewindPoint `json:"points"` + // Why the listed points could not be produced, when applicable; the points list is empty + // whenever it is set. `unsupported-remote-session` is permanent for the session and comes + // with `fileChangeTrackingEnabled: false`. `session-busy` is transient and only ever + // reported by a session that *is* tracking (`fileChangeTrackingEnabled: true`), because the + // file-change captures cannot be read while work that may still mutate them is in flight; + // the same request succeeds once the session settles, so a client that wants points should + // retry rather than treat it as a failure. It is never `file-change-tracking-disabled`: an + // untracked local session still lists conversation-only points and reports that through + // `fileChangeTrackingEnabled: false`. + UnavailableReason *HistoryRewindUnavailableReason `json:"unavailableReason,omitempty"` +} + +// Event boundary to preview for conversation-and-files rewind. +// Experimental: HistoryPreviewRewindRequest is part of an experimental API and may change +// or be removed. +type HistoryPreviewRewindRequest struct { + // ID of the user.message event that begins the discarded suffix. + EventID string `json:"eventId"` +} + +// Files and aggregate changes for a prospective rewind. +// Experimental: HistoryPreviewRewindResult is part of an experimental API and may change or +// be removed. +type HistoryPreviewRewindResult struct { + // Whether file restore is available for this session. This is authoritative: switch on it + // and read `reason` only when it is false. + Available bool `json:"available"` + // Number of unique files in the preview. + FileCount int64 `json:"fileCount"` + // Files ordered by path. + Files []HistoryRewindFilePreview `json:"files"` + // Why file restore is unavailable, when applicable. Populated only when `available` is + // false and never set when `available` is true. + Reason *HistoryRewindUnavailableReason `json:"reason,omitempty"` +} + +// A file that a conversation-and-files rewind would restore. +// Experimental: HistoryRewindFilePreview is part of an experimental API and may change or +// be removed. +type HistoryRewindFilePreview struct { + // Aggregate change made across the discarded turns. + ChangeType HistoryRewindChangeType `json:"changeType"` + // Lines added across the discarded turns. + LinesAdded int64 `json:"linesAdded"` + // Lines removed across the discarded turns. + LinesRemoved int64 `json:"linesRemoved"` + // Absolute path of the captured file. + Path string `json:"path"` +} + +// A root user turn that the session can rewind to. +// Experimental: HistoryRewindPoint is part of an experimental API and may change or be +// removed. +type HistoryRewindPoint struct { + // Whether at least one file in this turn or a later turn can be restored. + CanRestoreFiles bool `json:"canRestoreFiles"` + // ID of the user.message event that begins the discarded suffix. + EventID string `json:"eventId"` + // Number of unique files in this turn and all later turns that have captured changes. + FileCount int64 `json:"fileCount"` + // Whether this turn was an automatically injected autopilot continuation. + IsAutopilotContinuation bool `json:"isAutopilotContinuation"` + // Lines added by this turn's captured file changes. + LinesAdded int64 `json:"linesAdded"` + // Lines removed by this turn's captured file changes. + LinesRemoved int64 `json:"linesRemoved"` + // ISO timestamp of the user turn. + Timestamp string `json:"timestamp"` + // Whether this turn itself captured any file changes. + TurnChangedFiles bool `json:"turnChangedFiles"` + // User-visible message text for the turn. + UserMessage string `json:"userMessage"` +} + +// Boundary and mode for rewinding session history. +// Experimental: HistoryRewindRequest is part of an experimental API and may change or be +// removed. +type HistoryRewindRequest struct { + // ID of the user.message event that begins the discarded suffix. + EventID string `json:"eventId"` + // Whether to rewind only conversation history or also restore captured files. + Mode HistoryRewindMode `json:"mode"` +} + +// Structured outcome of a rewind request. +// Experimental: HistoryRewindResult is part of an experimental API and may change or be +// removed. +type HistoryRewindResult struct { + // Failure detail. Set only for the failure and partial-failure outcomes + // (`files-rolled-back`, `rollback-incomplete`, `truncation-failed`, + // `checkpoint-cleanup-failed`, `snapshot-prune-failed`); omitted for `success` and for the + // unavailable outcomes (`session-busy`, `file-change-tracking-disabled`, + // `unsupported-remote-session`). + Error *string `json:"error,omitempty"` + // Number of persisted events removed by conversation truncation. Present only when + // truncation succeeded (outcomes `success`, `checkpoint-cleanup-failed`, and + // `snapshot-prune-failed`); omitted for every unavailable outcome (`session-busy`, + // `file-change-tracking-disabled`, `unsupported-remote-session`) and for + // `truncation-failed`, `files-rolled-back`, and `rollback-incomplete`. + EventsRemoved *int64 `json:"eventsRemoved,omitempty"` + // Overall rewind outcome. This discriminates the result: it governs which of the remaining + // fields are populated, so consumers must switch on it before reading `eventsRemoved`, + // `restoredFiles`, `skippedFiles`, or `error`. See each field for the outcomes that + // populate it. + Outcome HistoryRewindOutcome `json:"outcome"` + // Absolute paths restored to their captured preimages. Always empty for conversation-only + // rewinds and for the unavailable outcomes (`session-busy`, + // `file-change-tracking-disabled`, `unsupported-remote-session`); only + // conversation-and-files outcomes that reached the file-restore stage populate it. + RestoredFiles []string `json:"restoredFiles"` + // Captured files intentionally left unchanged. Always empty for conversation-only rewinds + // and for the unavailable outcomes (`session-busy`, `file-change-tracking-disabled`, + // `unsupported-remote-session`); only conversation-and-files outcomes that reached the + // file-restore stage populate it. + SkippedFiles []HistorySkippedFileRestore `json:"skippedFiles"` +} + +// A captured file that rewind intentionally left unchanged. +// Experimental: HistorySkippedFileRestore is part of an experimental API and may change or +// be removed. +type HistorySkippedFileRestore struct { + // Absolute path of the skipped file. + Path string `json:"path"` + // Reason the file was not restored. + Reason HistoryFileRestoreSkipReason `json:"reason"` +} + // Markdown summary of the conversation context (empty when not available). // Experimental: HistorySummarizeForHandoffResult is part of an experimental API and may // change or be removed. @@ -2686,6 +3142,12 @@ type HistoryTruncateRequest struct { // Experimental: HistoryTruncateResult is part of an experimental API and may change or be // removed. type HistoryTruncateResult struct { + // Failure detail when checkpointCleanupFailed is true. + CheckpointCleanupError *string `json:"checkpointCleanupError,omitempty"` + // True when conversation truncation succeeded but post-truncation workspace checkpoint + // cleanup failed. History is already truncated; callers may still prune snapshots but + // should report a checkpoint-cleanup rather than a truncation failure. + CheckpointCleanupFailed *bool `json:"checkpointCleanupFailed,omitempty"` // Number of events that were removed EventsRemoved int64 `json:"eventsRemoved"` } @@ -2759,14 +3221,16 @@ type InstalledPluginSource struct { String *string } -// Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref, -// and optional subpath. +// Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref or +// full commit SHA, and optional subpath. // Experimental: InstalledPluginSourceGitHub is part of an experimental API and may change // or be removed. type InstalledPluginSourceGitHub struct { Path *string `json:"path,omitempty"` Ref *string `json:"ref,omitempty"` Repo string `json:"repo"` + // Optional full 40-character hexadecimal commit SHA. + Sha *string `json:"sha,omitempty"` // Constant value. Always "github". Source InstalledPluginSourceGitHubSource `json:"source"` } @@ -2780,13 +3244,15 @@ type InstalledPluginSourceLocal struct { Source InstalledPluginSourceLocalSource `json:"source"` } -// Source descriptor for a direct URL plugin install, with URL, optional ref, and optional -// subpath. +// Source descriptor for a direct URL plugin install, with URL, optional ref or full commit +// SHA, and optional subpath. // Experimental: InstalledPluginSourceURL is part of an experimental API and may change or // be removed. type InstalledPluginSourceURL struct { Path *string `json:"path,omitempty"` Ref *string `json:"ref,omitempty"` + // Optional full 40-character hexadecimal commit SHA. + Sha *string `json:"sha,omitempty"` // Constant value. Always "url". Source InstalledPluginSourceURLSource `json:"source"` URL string `json:"url"` @@ -2873,9 +3339,8 @@ type InstructionSource struct { // Where this source lives — used for UI grouping Location InstructionSourceLocation `json:"location"` // The project path this source was discovered from. Only set by sessionless discovery for - // repository/working-directory sources, where it disambiguates same-named files (e.g. - // .github/copilot-instructions.md) across multiple workspace roots. The session-scoped - // getSources leaves it unset. + // repository, working-directory, and project-scoped plugin sources, where it disambiguates + // sources across multiple workspace roots. The session-scoped getSources leaves it unset. ProjectPath *string `json:"projectPath,omitempty"` // File path relative to repo or absolute for home SourcePath string `json:"sourcePath"` @@ -2883,6 +3348,25 @@ type InstructionSource struct { Type InstructionSourceType `json:"type"` } +// Parameters for interrupting the main agent turn. +// Experimental: InterruptMainTurnRequest is part of an experimental API and may change or +// be removed. +type InterruptMainTurnRequest struct { + // When true, the user's queued prompts are preserved and run as the next turn once the + // interrupted turn unwinds; when false (the default), the queue is cleared like a plain + // abort. + FlushQueued *bool `json:"flushQueued,omitempty"` +} + +// Result of interrupting the main agent turn. +// Experimental: InterruptMainTurnResult is part of an experimental API and may change or be +// removed. +type InterruptMainTurnResult struct { + // Whether an in-flight main agent turn was interrupted. False when the main loop was not + // processing. + Interrupted bool `json:"interrupted"` +} + // HTTP headers as a map from lowercased header name to a list of values. Multi-valued // headers (e.g. Set-Cookie) preserve all values. // Experimental: LlmInferenceHeaders is part of an experimental API and may change or be @@ -3571,12 +4055,12 @@ type MCPExecuteSamplingRequest struct { type MCPExecuteSamplingResult struct { } -// MCP server filtered by policy, with name, reason, optional redacted reason, and -// enterprise login. +// MCP server filtered by policy, with name, reason, and optional redacted reason. // Experimental: MCPFilteredServer is part of an experimental API and may change or be // removed. type MCPFilteredServer struct { - // Enterprise login associated with an allowlist policy + // Deprecated. This field is no longer populated. + // Deprecated: EnterpriseName is deprecated. EnterpriseName *string `json:"enterpriseName,omitempty"` // Filtered server name Name string `json:"name"` @@ -3654,7 +4138,7 @@ type MCPHostState struct { DisabledServers []string `json:"disabledServers"` // Map of server name to recorded connection failure. FailedServers map[string]MCPServerFailureInfo `json:"failedServers"` - // Configured servers filtered out by enterprise allowlist policy. + // Configured servers filtered out by MCP server policy. FilteredServers []string `json:"filteredServers"` // Whether third-party MCP servers are policy-enabled for this session. Mcp3pEnabled bool `json:"mcp3pEnabled"` @@ -3805,6 +4289,23 @@ func (MCPOauthPendingRequestResponseToken) Kind() MCPOauthPendingRequestResponse return MCPOauthPendingRequestResponseKindToken } +// Pending MCP OAuth request id to respond to. +// Experimental: MCPOauthRespondRequest is part of an experimental API and may change or be +// removed. +type MCPOauthRespondRequest struct { + // OAuth request identifier from the mcp.oauth_required event + RequestID string `json:"requestId"` +} + +// Indicates whether the pending MCP OAuth response was accepted. +// Experimental: MCPOauthRespondResult is part of an experimental API and may change or be +// removed. +type MCPOauthRespondResult struct { + // Whether the response was accepted. False if the request was unknown, timed out, or + // already resolved. + Success bool `json:"success"` +} + // Registration parameters for an external MCP client. // Experimental: MCPRegisterExternalClientRequest is part of an experimental API and may // change or be removed. @@ -4095,6 +4596,9 @@ type MCPServerConfigHTTP struct { // Controls if tools provided by this server can be loaded on demand via tool search (auto) // or always included in the initial tool list (never) DeferTools *MCPServerConfigDeferTools `json:"deferTools,omitempty"` + // Set to true to disable persisted MCP tool snapshots for this server. Live tool discovery + // is unaffected. + DisableToolCache *bool `json:"disableToolCache,omitempty"` // Content filtering mode to apply to all tools, or a map of tool name to content filtering // mode. FilterMapping FilterMapping `json:"filterMapping,omitempty"` @@ -4138,6 +4642,9 @@ type MCPServerConfigStdio struct { // Controls if tools provided by this server can be loaded on demand via tool search (auto) // or always included in the initial tool list (never) DeferTools *MCPServerConfigDeferTools `json:"deferTools,omitempty"` + // Set to true to disable persisted MCP tool snapshots for this server. Live tool discovery + // is unaffected. + DisableToolCache *bool `json:"disableToolCache,omitempty"` // Environment variables to pass to the Stdio MCP server process. Env map[string]string `json:"env,omitzero"` // Content filtering mode to apply to all tools, or a map of tool name to content filtering @@ -4203,12 +4710,14 @@ type MCPSetEnvValueModeResult struct { Mode MCPSetEnvValueModeDetails `json:"mode"` } -// Server name and configuration for an individual MCP server start. +// Server name and optional configuration for an individual MCP server start. Omit `config` +// for a config-free start-by-name of an already-configured server. // Experimental: MCPStartServerRequest is part of an experimental API and may change or be // removed. type MCPStartServerRequest struct { - // MCP server configuration (stdio process or remote HTTP/SSE) - Config MCPServerConfig `json:"config"` + // MCP server configuration (stdio process or remote HTTP/SSE). Omit to start the server + // with its already-registered configuration (config-free start-by-name). + Config MCPServerConfig `json:"config,omitempty"` // Name of the MCP server to start ServerName string `json:"serverName"` } @@ -4469,26 +4978,26 @@ type ModelBilling struct { // Billing cost multiplier relative to the base rate Multiplier *float64 `json:"multiplier,omitempty"` // Active server-driven promotion for this model, if any. Present when the model is being - // promoted with a time-boxed discount. + // promoted with a discount, which may be time-boxed or open-ended. Promo *ModelBillingPromo `json:"promo,omitempty"` // Token-level pricing information for this model TokenPrices *ModelBillingTokenPrices `json:"tokenPrices,omitempty"` } -// Active server-driven promotion for a model, including its discount and expiry. +// Active server-driven promotion for a model, including its discount and optional expiry. // Experimental: ModelBillingPromo is part of an experimental API and may change or be // removed. type ModelBillingPromo struct { // Percentage discount (0-100) applied while the promotion is active. May be fractional. DiscountPercent *float64 `json:"discountPercent,omitempty"` - // UTC ISO 8601 timestamp marking when the promotion ends. Always present: the API only - // surfaces a promo whose expiry parses and is in the future. Consumers should treat a past - // value as expired. - EndsAt string `json:"endsAt"` + // UTC ISO 8601 timestamp marking when the promotion ends. Optional: an open-ended promotion + // omits this field. When present, the API only surfaces a promo whose expiry parses and is + // in the future, so consumers should treat a past value as expired. + EndsAt *string `json:"endsAt,omitempty"` // Stable identifier for the promotion campaign. ID *string `json:"id,omitempty"` // Human-readable promotion message. Does not include the expiry timestamp; consumers may - // format endsAt and append it. + // format endsAt and append it when present. Message *string `json:"message,omitempty"` } @@ -4650,9 +5159,6 @@ type ModelList struct { Models []Model `json:"models"` } -// Optional listing options. -// Experimental: ModelListRequest is part of an experimental API and may change or be -// removed. type ModelListRequest struct { // If true, bypasses the per-session model list cache and re-fetches from CAPI. SkipCache *bool `json:"skipCache,omitempty"` @@ -4702,6 +5208,12 @@ type ModelSwitchToRequest struct { // Explicit context tier for the selected model. `"default"` / `"long_context"` apply the // requested tier; omit this field to use normal model behavior with no explicit tier. ContextTier *ContextTier `json:"contextTier,omitempty"` + // When true, defer this switch (enqueue it) if another model change is already queued, even + // when no turn is active — so it drains last (FIFO) and wins over the already-queued + // change. Intended for genuine user-initiated model selections; internal restore/reapply + // switches omit it and apply immediately when no turn is active. When no other model change + // is queued this has no effect (a switch still applies immediately unless a turn is active). + DeferIfModelChangeQueued *bool `json:"deferIfModelChangeQueued,omitempty"` // Override individual model capabilities resolved by the runtime ModelCapabilities *ModelCapabilitiesOverride `json:"modelCapabilities,omitempty"` // Model selection id to switch to, as returned by `list`. A bare id (e.g. @@ -4720,6 +5232,11 @@ type ModelSwitchToRequest struct { // Experimental: ModelSwitchToResult is part of an experimental API and may change or be // removed. type ModelSwitchToResult struct { + // True when the switch was deferred (enqueued as a cancellable `/model` command) because a + // turn was active or another model change was already queued, rather than applied + // immediately. When true, the session's live model is unchanged until the queued change + // drains. + Deferred *bool `json:"deferred,omitempty"` // Currently active model identifier after the switch ModelID *string `json:"modelId,omitempty"` } @@ -4975,6 +5492,8 @@ func (PermissionDecisionApproveForSession) Kind() PermissionDecisionKind { // Experimental: PermissionDecisionApproveOnce is part of an experimental API and may change // or be removed. type PermissionDecisionApproveOnce struct { + // True only when a host surfaced this request to a user who approved it. + ApprovedInteractively *bool `json:"approvedInteractively,omitempty"` } func (PermissionDecisionApproveOnce) permissionDecision() {} @@ -5877,10 +6396,12 @@ type PermissionsPathsUpdatePrimaryResult struct { type PermissionsPendingRequestsRequest struct { } -// No parameters; clears all session-scoped tool permission approvals. +// Clears session-scoped tool permission approvals, and optionally the location-scoped ones. // Experimental: PermissionsResetSessionApprovalsRequest is part of an experimental API and // may change or be removed. type PermissionsResetSessionApprovalsRequest struct { + // Whether location-scoped approvals are cleared too. Defaults to `true`. + IncludeLocation *bool `json:"includeLocation,omitempty"` } // Indicates whether the operation succeeded. @@ -6187,9 +6708,6 @@ type PluginsMarketplacesRemoveRequest struct { Name string `json:"name"` } -// Optional flags controlling which side effects the reload performs. -// Experimental: PluginsReloadRequest is part of an experimental API and may change or be -// removed. type PluginsReloadRequest struct { // When true, skip repo-level hooks during the hook reload. Use before folder trust is // confirmed; load them post-trust via `sessions.loadDeferredRepoHooks`. @@ -6372,9 +6890,6 @@ type ProviderEndpoint struct { WireAPI *ProviderEndpointWireAPI `json:"wireApi,omitempty"` } -// Optional model identifier to scope the endpoint snapshot to. -// Experimental: ProviderGetEndpointRequest is part of an experimental API and may change or -// be removed. type ProviderGetEndpointRequest struct { // Model identifier the caller intends to use against the returned endpoint. Used to pick // the correct wire shape. Omit to use whichever model the session is currently using. @@ -6812,6 +7327,30 @@ type PushGitHubRepoRef struct { Owner string `json:"owner"` } +// Inputs for starting a deferred-idle drain. +// Experimental: QueueBeginDeferredIdleDrainRequest is part of an experimental API and may +// change or be removed. +type QueueBeginDeferredIdleDrainRequest struct { + // Whether the host still has active background work. + ActiveBackgroundWork bool `json:"activeBackgroundWork"` +} + +// Whether a deferred-idle drain should run. +// Experimental: QueueBeginDeferredIdleDrainResult is part of an experimental API and may +// change or be removed. +type QueueBeginDeferredIdleDrainResult struct { + // True when the host should run finishDeferredIdleDrain asynchronously. + ShouldDrain bool `json:"shouldDrain"` +} + +// Internal filter for consuming queued system notifications. +// Experimental: QueueConsumeSystemNotificationsRequest is part of an experimental API and +// may change or be removed. +type QueueConsumeSystemNotificationsRequest struct { + // Opaque runtime-owned filter object. + Filter any `json:"filter"` +} + // Result of the queued command execution. // Experimental: QueuedCommandResult is part of an experimental API and may change or be // removed. @@ -6847,13 +7386,151 @@ func (QueuedCommandNotHandled) Handled() bool { return false } +// Inputs for marking session.idle deferred in native state. +// Experimental: QueueDeferSessionIdleRequest is part of an experimental API and may change +// or be removed. +type QueueDeferSessionIdleRequest struct { + // Whether the deferred idle was caused by an aborted foreground turn. + Aborted bool `json:"aborted"` +} + +// Parameters for duplicating a queued item. +// Experimental: QueueDuplicateAtRequest is part of an experimental API and may change or be +// removed. +type QueueDuplicateAtRequest struct { + ID string `json:"id"` +} + +// Result of duplicating a queued item. +// Experimental: QueueDuplicateAtResult is part of an experimental API and may change or be +// removed. +type QueueDuplicateAtResult struct { + // Fresh stable opaque id assigned to the duplicate. + ID string `json:"id"` +} + +// Result of enqueueing the resume-pending wake item. +// Experimental: QueueEnqueueResumePendingResult is part of an experimental API and may +// change or be removed. +type QueueEnqueueResumePendingResult struct { + // True when a wake item was newly queued. + Queued bool `json:"queued"` +} + +// Inputs for completing a deferred-idle drain. +// Experimental: QueueFinishDeferredIdleDrainRequest is part of an experimental API and may +// change or be removed. +type QueueFinishDeferredIdleDrainRequest struct { + // Whether the host still has active background work. + ActiveBackgroundWork bool `json:"activeBackgroundWork"` + // Whether native queued work remains. + HasPending bool `json:"hasPending"` +} + +// Action selected by the native deferred-idle drain. +// Experimental: QueueFinishDeferredIdleDrainResult is part of an experimental API and may +// change or be removed. +type QueueFinishDeferredIdleDrainResult struct { + // Whether the deferred idle was caused by an aborted foreground turn. + Aborted bool `json:"aborted"` + // One of none, processQueue, or emitSessionIdle. + Action string `json:"action"` +} + +// Whether the native queue has pending work. +// Experimental: QueueHasPendingResult is part of an experimental API and may change or be +// removed. +type QueueHasPendingResult struct { + // True when queued or immediate native work is pending. + HasPending bool `json:"hasPending"` +} + +// Parameters for inserting a queued message at a public visible position. +// Experimental: QueueInsertAtRequest is part of an experimental API and may change or be +// removed. +type QueueInsertAtRequest struct { + Message QueueInsertMessage `json:"message"` + // Zero-based position in the public visible queue. Values outside the queue clamp to an end. + Position int64 `json:"position"` +} + +// Result of inserting a queued message. +// Experimental: QueueInsertAtResult is part of an experimental API and may change or be +// removed. +type QueueInsertAtResult struct { + // Fresh stable opaque id assigned to the inserted item. + ID string `json:"id"` +} + +// Serializable message fields accepted by queue.insertAt. +// Experimental: QueueInsertMessage is part of an experimental API and may change or be +// removed. +type QueueInsertMessage struct { + // Optional explicit agent mode. When omitted, the session's current mode is assigned. + AgentMode *SendAgentMode `json:"agentMode,omitempty"` + // Optional attachments for the message. + Attachments []Attachment `json:"attachments,omitzero"` + // Whether the message is billable. + Billable *bool `json:"billable,omitempty"` + // Accepted for internal SendOptions compatibility but ignored; delivery is derived from + // current session activity. + Delivery *string `json:"delivery,omitempty"` + // Optional user-facing display text. + DisplayPrompt *string `json:"displayPrompt,omitempty"` + // Accepted for SendOptions compatibility but ignored; inserted items always use queued + // delivery semantics. + Mode *SendMode `json:"mode,omitempty"` + // Accepted for SendOptions compatibility but ignored; the requested public position + // controls placement. + Prepend *bool `json:"prepend,omitempty"` + // The user message text. + Prompt string `json:"prompt"` + // Per-turn request headers. + RequestHeaders map[string]string `json:"requestHeaders,omitzero"` + // Required tool name for the turn, when any. + RequiredTool *string `json:"requiredTool,omitempty"` + // Optional provenance source. `system` is rejected: it would hide the inserted row from + // `pendingItems` and make it unaddressable while still executing, so inserted items must + // stay visible. + Source *string `json:"source,omitempty"` + // Accepted for SendOptions compatibility but ignored; insertion scheduling is controlled by + // the queue drain state. + Wait *bool `json:"wait,omitempty"` +} + +// Parameters for moving a queued item by stable id. +// Experimental: QueueMoveItemRequest is part of an experimental API and may change or be +// removed. +type QueueMoveItemRequest struct { + // Stable opaque queued-item id. + ID string `json:"id"` + // Zero-based target position in the public visible queue. Values outside the queue clamp to + // an end. + ToPosition int64 `json:"toPosition"` +} + +// Result of moving a queued item. +// Experimental: QueueMoveItemResult is part of an experimental API and may change or be +// removed. +type QueueMoveItemResult struct { + // True when the item changed position; false when it was already at the requested position. + Changed bool `json:"changed"` +} + // User-facing pending queue entry, with kind and display text for a queued message, slash // command, or model change. // Experimental: QueuePendingItems is part of an experimental API and may change or be // removed. type QueuePendingItems struct { + // Agent mode stored on this queued entry, as stamped when it was enqueued. Items without an + // explicit mode report interactive. This is not necessarily the mode that will constrain + // the turn: a plan or autopilot session applies its own write gate, continuation loop and + // permission posture to every drained item regardless of the mode stored here. + AgentMode SendAgentMode `json:"agentMode"` // Human-readable text to display for this queue entry in the UI DisplayText string `json:"displayText"` + // Stable opaque id for the canonical queued item. Batch rows share one id. + ID string `json:"id"` // Whether this item is a queued user message or a queued slash command / model change Kind QueuePendingItemsKind `json:"kind"` } @@ -6870,6 +7547,21 @@ type QueuePendingItemsResult struct { SteeringMessages []string `json:"steeringMessages"` } +// Parameters for removing a queued item by stable id. +// Experimental: QueueRemoveAtRequest is part of an experimental API and may change or be +// removed. +type QueueRemoveAtRequest struct { + ID string `json:"id"` +} + +// Result of removing a queued item. +// Experimental: QueueRemoveAtResult is part of an experimental API and may change or be +// removed. +type QueueRemoveAtResult struct { + // True when the addressed item was removed. + Removed bool `json:"removed"` +} + // Indicates whether a user-facing pending item was removed. // Experimental: QueueRemoveMostRecentResult is part of an experimental API and may change // or be removed. @@ -6879,6 +7571,64 @@ type QueueRemoveMostRecentResult struct { Removed bool `json:"removed"` } +// Parameters for steering a queued message into a live turn. +// Experimental: QueueSendNowRequest is part of an experimental API and may change or be +// removed. +type QueueSendNowRequest struct { + ID string `json:"id"` +} + +// Result of trying to steer a queued message into a live turn. +// Experimental: QueueSendNowResult is part of an experimental API and may change or be +// removed. +type QueueSendNowResult struct { + // True when the item was accepted into the steering lane; false when no main turn was live. + Steered bool `json:"steered"` +} + +// Parameters for acquiring or releasing the queued-lane drain pause. Acquisition is +// exclusive and non-idempotent: `paused: true` against an already-paused session fails with +// `queue_already_paused`. The pause is never released automatically — it is not tied to the +// caller's lifetime, so a client that exits without sending `paused: false` leaves the lane +// frozen. Release is unowned: `paused: false` clears the pause for any caller, including +// one that never acquired it. +// Experimental: QueueSetDrainPausedRequest is part of an experimental API and may change or +// be removed. +type QueueSetDrainPausedRequest struct { + Paused bool `json:"paused"` +} + +// Internal snapshot of native queue state for local session orchestration. +// Experimental: QueueSnapshotResult is part of an experimental API and may change or be +// removed. +type QueueSnapshotResult struct { + // Insertion orders for queued items, aligned with `items`. + ItemOrders []int64 `json:"itemOrders,omitzero"` + // User-facing pending items in FIFO order. + Items []QueuePendingItems `json:"items"` + // Insertion orders for immediate steering messages, aligned with `steeringMessages`. + SteeringMessageOrders []int64 `json:"steeringMessageOrders,omitzero"` + // Immediate steering messages waiting for an active turn. + SteeringMessages []string `json:"steeringMessages"` +} + +// Parameters for editing a single queued message. +// Experimental: QueueUpdateTextRequest is part of an experimental API and may change or be +// removed. +type QueueUpdateTextRequest struct { + DisplayPrompt *string `json:"displayPrompt,omitempty"` + ID string `json:"id"` + Prompt string `json:"prompt"` +} + +// Result of editing a queued message. +// Experimental: QueueUpdateTextResult is part of an experimental API and may change or be +// removed. +type QueueUpdateTextResult struct { + // True when the stored text changed. + Updated bool `json:"updated"` +} + // Event type to register consumer interest for, used by runtime gating logic. // Experimental: RegisterEventInterestParams is part of an experimental API and may change // or be removed. @@ -7255,6 +8005,36 @@ type SandboxConfigUserPolicyNetwork struct { AllowLocalNetwork *bool `json:"allowLocalNetwork,omitempty"` // Whether outbound network traffic is allowed at all. AllowOutbound *bool `json:"allowOutbound,omitempty"` + // HTTP proxy the sandboxed process routes traffic through. Enforced on Windows and + // cooperative (honored by well-behaved tools, not strictly enforced) on Linux and macOS. + // Credentials go in the separate `username`/`password` fields. A credential-free http:// + // loopback proxy URL is routed through the localhost proxy automatically; an https:// or + // authenticated loopback URL is used as-is. + Proxy *SandboxConfigUserPolicyNetworkProxy `json:"proxy,omitempty"` +} + +// HTTP proxy configuration for sandboxed traffic. +// Experimental: SandboxConfigUserPolicyNetworkProxy is part of an experimental API and may +// change or be removed. +type SandboxConfigUserPolicyNetworkProxy struct { + // Optional password for proxy authentication, combined with the URL at spawn time. The + // persisted value may be a literal password, a `${secret:…}` reference resolved from the OS + // keychain, or a `${VAR}`/`$VAR` environment reference; it is resolved just before the + // sandboxed process routes through the proxy. The /sandbox dialog stores a real password in + // the OS keychain and persists only a `${secret:…}` placeholder (never plaintext in + // settings.json); the field is masked in the dialog and redacted by /settings show. + Password *string `json:"password,omitempty"` + // Proxy URL (e.g. http://proxy.example.com:8080). The port is optional and defaults to the + // scheme's standard port when omitted. Credentials must not be embedded here — a + // `user:pass@` authority is rejected; put them in the separate `username`/`password` + // fields. A credential-free http:// loopback URL is routed through the localhost proxy + // automatically; loopback covers localhost and any *.localhost subdomain, the whole + // 127.0.0.0/8 range, ::1, and IPv4-mapped loopback (::ffff:127.0.0.1). An https:// URL, or + // one with a username/password set, is used as-is. + URL string `json:"url"` + // Optional username for proxy authentication. Combined with the URL (and `password`) into + // `user:pass@host` when the sandboxed process routes through the proxy. + Username *string `json:"username,omitempty"` } // macOS seatbelt-specific options. @@ -7265,6 +8045,70 @@ type SandboxConfigUserPolicySeatbelt struct { KeychainAccess *bool `json:"keychainAccess,omitempty"` } +// Register an absolute-time scheduled prompt. +// Experimental: ScheduleAddAtRequest is part of an experimental API and may change or be +// removed. +type ScheduleAddAtRequest struct { + // Epoch milliseconds when the prompt should fire. + At int64 `json:"at"` + // Optional display-only prompt label. + DisplayPrompt *string `json:"displayPrompt,omitempty"` + // Prompt text to enqueue when the schedule fires. + Prompt string `json:"prompt"` + // Whether the schedule should re-arm after each tick. Defaults to false. + Recurring *bool `json:"recurring,omitempty"` +} + +// Register a cron scheduled prompt. +// Experimental: ScheduleAddCronRequest is part of an experimental API and may change or be +// removed. +type ScheduleAddCronRequest struct { + // 5-field cron expression. + Cron string `json:"cron"` + // Optional display-only prompt label. + DisplayPrompt *string `json:"displayPrompt,omitempty"` + // Prompt text to enqueue when the schedule fires. + Prompt string `json:"prompt"` + // Whether the schedule should re-arm after each tick. Defaults to true. + Recurring *bool `json:"recurring,omitempty"` + // IANA timezone for evaluating the cron expression. + Tz *string `json:"tz,omitempty"` +} + +// Register a relative-interval scheduled prompt. +// Experimental: ScheduleAddRequest is part of an experimental API and may change or be +// removed. +type ScheduleAddRequest struct { + // Optional display-only prompt label. + DisplayPrompt *string `json:"displayPrompt,omitempty"` + // Human-readable interval such as `30s`, `5m`, or `2h`. + Interval string `json:"interval"` + // Prompt text to enqueue when the schedule fires. + Prompt string `json:"prompt"` + // Whether the schedule should re-arm after each tick. Defaults to true. + Recurring *bool `json:"recurring,omitempty"` +} + +// Result of registering or re-arming a scheduled prompt. +// Experimental: ScheduleAddResult is part of an experimental API and may change or be +// removed. +type ScheduleAddResult struct { + // The registered or updated schedule entry. + Entry *ScheduleEntry `json:"entry,omitempty"` + // User-facing validation error, when registration failed. + Error *string `json:"error,omitempty"` +} + +// Register a self-paced scheduled prompt. +// Experimental: ScheduleAddSelfPacedRequest is part of an experimental API and may change +// or be removed. +type ScheduleAddSelfPacedRequest struct { + // Optional display-only prompt label. + DisplayPrompt *string `json:"displayPrompt,omitempty"` + // Prompt text to enqueue when the schedule fires. + Prompt string `json:"prompt"` +} + // Scheduled prompt entry with ID, timing (`intervalMs`, `cron`, or `at`), prompt text, // recurrence, and next run time. // Experimental: ScheduleEntry is part of an experimental API and may change or be removed. @@ -7294,6 +8138,14 @@ type ScheduleEntry struct { Tz *string `json:"tz,omitempty"` } +// Whether the session currently has an active self-paced schedule. +// Experimental: ScheduleHasSelfPacedResult is part of an experimental API and may change or +// be removed. +type ScheduleHasSelfPacedResult struct { + // True when at least one active schedule is self-paced. + HasSelfPaced bool `json:"hasSelfPaced"` +} + // Snapshot of the currently active recurring prompts for this session. // Experimental: ScheduleList is part of an experimental API and may change or be removed. type ScheduleList struct { @@ -7301,6 +8153,16 @@ type ScheduleList struct { Entries []ScheduleEntry `json:"entries"` } +// Re-arm a self-paced scheduled prompt. +// Experimental: ScheduleRearmSelfPacedRequest is part of an experimental API and may change +// or be removed. +type ScheduleRearmSelfPacedRequest struct { + // Epoch milliseconds when the prompt should next fire. + At int64 `json:"at"` + // Id of the self-paced scheduled prompt. + ID int64 `json:"id"` +} + // Identifier of the scheduled prompt to remove. // Experimental: ScheduleStopRequest is part of an experimental API and may change or be // removed. @@ -7365,10 +8227,9 @@ type SendMessageItem struct { // If set, the request will fail if the named tool is not available when this message is // among the user messages at the start of the current exchange RequiredTool *string `json:"requiredTool,omitempty"` - // Optional provenance tag copied to the resulting user.message event. Must match one of - // three forms: the literal `system`, `command-` for messages originating from a - // command (e.g. slash command, Mission Control command), or `schedule-` for - // messages originating from a scheduled job. + // Optional provenance tag copied to the resulting user.message event. Must be `user`, + // `system`, `command-` for command-originated messages, `schedule-` + // for scheduled prompts, or `agent-` for prompts sent by another agent. // Internal: Source is part of the SDK's internal API surface and is not intended for // external use. Source *string `json:"source,omitempty"` @@ -7402,6 +8263,12 @@ type SendMessagesRequest struct { // If true, await completion of the agentic loop for this turn before returning. Defaults to // false (fire-and-forget). When true, the result still contains the same `messageIds`; the // caller can rely on the agent having processed the messages before the call resolves. + // Transport-dependent tail semantics: on a LOCAL (in-process) session the wait additionally + // blocks until the completed turn's event tail has been dispatched to this session's + // in-process subscribers, so a subsequent read of subscriber state already reflects the + // turn; on a REMOTE session the wait resolves once the loop completes and mirrored delivery + // follows over the wire. Callers that need the stronger local guarantee on remote sessions + // should await the event stream explicitly. Wait *bool `json:"wait,omitempty"` } @@ -7442,10 +8309,9 @@ type SendRequest struct { // If set, the request will fail if the named tool is not available when this message is // among the user messages at the start of the current exchange RequiredTool *string `json:"requiredTool,omitempty"` - // Optional provenance tag copied to the resulting user.message event. Must match one of - // three forms: the literal `system`, `command-` for messages originating from a - // command (e.g. slash command, Mission Control command), or `schedule-` for - // messages originating from a scheduled job. + // Optional provenance tag copied to the resulting user.message event. Must be `user`, + // `system`, `command-` for command-originated messages, `schedule-` + // for scheduled prompts, or `agent-` for prompts sent by another agent. // Internal: Source is part of the SDK's internal API surface and is not intended for // external use. Source *string `json:"source,omitempty"` @@ -7456,6 +8322,12 @@ type SendRequest struct { // If true, await completion of the agentic loop for this message before returning. Defaults // to false (fire-and-forget). When true, the result still contains the same `messageId`; // the caller can rely on the agent having processed the message before the call resolves. + // Transport-dependent tail semantics: on a LOCAL (in-process) session the wait additionally + // blocks until the completed turn's event tail has been dispatched to this session's + // in-process subscribers, so a subsequent read of subscriber state already reflects the + // turn; on a REMOTE session the wait resolves once the loop completes and mirrored delivery + // follows over the wire. Callers that need the stronger local guarantee on remote sessions + // should await the event stream explicitly. Wait *bool `json:"wait,omitempty"` } @@ -7466,9 +8338,21 @@ type SendResult struct { MessageID string `json:"messageId"` } -// Agents discovered across user, project, plugin, and remote sources. -// Experimental: ServerAgentList is part of an experimental API and may change or be removed. -type ServerAgentList struct { +// Internal request for sending a system notification. +// Experimental: SendSystemNotificationRequest is part of an experimental API and may change +// or be removed. +type SendSystemNotificationRequest struct { + // Optional structured notification kind. + Kind any `json:"kind,omitempty"` + // Notification text to deliver to the model. + Message string `json:"message"` + // Internal delivery options, including passive policy. + Options any `json:"options,omitempty"` +} + +// Agents discovered across user, project, plugin, and remote sources. +// Experimental: ServerAgentList is part of an experimental API and may change or be removed. +type ServerAgentList struct { // All discovered agents across all sources Agents []AgentInfo `json:"agents"` } @@ -7528,6 +8412,20 @@ type SessionActivity struct { type SessionAgentDeselectResult struct { } +// Experimental: SessionAgentListRequest is part of an experimental API and may change or be +// removed. +type SessionAgentListRequest struct { + // When true, request the session's configured built-in agents alongside custom agents. + // Listing applies feature, context, inclusion, exclusion, and user-disabled-agent policy, + // but does not evaluate transient invocation requirements such as model availability. + // Built-in metadata may be omitted when the session cannot project it, such as a relay + // session. + IncludeBuiltInAgents *bool `json:"includeBuiltInAgents,omitempty"` + // When true, request authored base prompt text on each AgentInfo. Prompt text may be + // omitted when unavailable, such as for agents projected through a relay session. + IncludePrompt *bool `json:"includePrompt,omitempty"` +} + // Authentication status and account metadata for the session. // Experimental: SessionAuthStatus is part of an experimental API and may change or be // removed. @@ -7556,11 +8454,27 @@ type SessionBulkDeleteResult struct { FreedBytes map[string]int64 `json:"freedBytes"` } +// The number of running background agents (task-registry agents) that were cancelled. +// Experimental: SessionCancelAllBackgroundAgentsResult is part of an experimental API and +// may change or be removed. +type SessionCancelAllBackgroundAgentsResult int64 + // Experimental: SessionCanvasCloseResult is part of an experimental API and may change or // be removed. type SessionCanvasCloseResult struct { } +// Experimental: SessionCommandsListRequest is part of an experimental API and may change or +// be removed. +type SessionCommandsListRequest struct { + // Include runtime built-in commands + IncludeBuiltins *bool `json:"includeBuiltins,omitempty"` + // Include commands registered by protocol clients, including SDK clients and extensions + IncludeClientCommands *bool `json:"includeClientCommands,omitempty"` + // Include enabled user-invocable skills and commands + IncludeSkills *bool `json:"includeSkills,omitempty"` +} + // A single host-driven completion. Accepting an item replaces `[rangeStart, rangeEnd)` // (UTF-16 code units) in the composer with `insertText`; when the range is absent, the // active token around the cursor is replaced. @@ -7905,7 +8819,7 @@ type SessionFSSqliteExistsResult struct { } // SQL query, query type, and optional bind parameters for executing a SQLite query against -// the per-session database. +// the per-session database. The provider applies its SQLite busy timeout for every call. // Experimental: SessionFSSqliteQueryRequest is part of an experimental API and may change // or be removed. type SessionFSSqliteQueryRequest struct { @@ -7937,6 +8851,44 @@ type SessionFSSqliteQueryResult struct { RowsAffected int64 `json:"rowsAffected"` } +// Classified SQLite transaction failure. busyOrLocked guarantees rollback; +// postCommitAmbiguous must never be retried. +// Experimental: SessionFSSqliteTransactionError is part of an experimental API and may +// change or be removed. +type SessionFSSqliteTransactionError struct { + ErrorClass SessionFSSqliteTransactionErrorClass `json:"errorClass"` + Message string `json:"message"` +} + +// Statements to execute atomically. Providers apply busy handling for every call. +// Experimental: SessionFSSqliteTransactionRequest is part of an experimental API and may +// change or be removed. +type SessionFSSqliteTransactionRequest struct { + // Target session identifier + SessionID string `json:"sessionId"` + Statements []SessionFSSqliteTransactionStatement `json:"statements"` +} + +// Per-statement results, or a classified transaction error. +// Experimental: SessionFSSqliteTransactionResult is part of an experimental API and may +// change or be removed. +type SessionFSSqliteTransactionResult struct { + Error *SessionFSSqliteTransactionError `json:"error,omitempty"` + Results []SessionFSSqliteQueryResult `json:"results"` +} + +// One statement in an atomic SQLite transaction. +// Experimental: SessionFSSqliteTransactionStatement is part of an experimental API and may +// change or be removed. +type SessionFSSqliteTransactionStatement struct { + // Optional named bind parameters. + Params map[string]any `json:"params,omitzero"` + // SQL statement to execute. + Query string `json:"query"` + // How to execute the statement. + QueryType SessionFSSqliteQueryType `json:"queryType"` +} + // Path whose metadata should be returned from the client-provided session filesystem. // Experimental: SessionFSStatRequest is part of an experimental API and may change or be // removed. @@ -7979,6 +8931,25 @@ type SessionFSWriteFileRequest struct { SessionID string `json:"sessionId"` } +// Experimental: SessionHistoryCompactRequest is part of an experimental API and may change +// or be removed. +type SessionHistoryCompactRequest struct { + // Optional user-provided instructions to focus the compaction summary + CustomInstructions *string `json:"customInstructions,omitempty"` + // Context window token limit this compaction is targeting, recorded as the `tokenLimit` on + // the persisted `session.compaction_start` / `session.compaction_complete` events. Set it + // when the compaction targets a window other than the compacting model's own, e.g. + // switching to a model with a smaller context window: the compaction still runs on the + // current model, so the limit that motivated it would otherwise be lost. When absent, the + // events record the compacting model's own resolved limit. Attribution metadata only - it + // does not change how much the compaction removes. + TokenLimit *int64 `json:"tokenLimit,omitempty"` + // What initiated this compaction request, recorded as the `trigger` on the persisted + // `session.compaction_start` / `session.compaction_complete` events. When absent, the + // compaction is persisted without trigger attribution (initiator unknown). + Trigger *SessionHistoryCompactRequestTrigger `json:"trigger,omitempty"` +} + // Installed plugin record for a session, with marketplace, version, install time, enabled // state, cache path, and source. // Experimental: SessionInstalledPlugin is part of an experimental API and may change or be @@ -8010,14 +8981,16 @@ type SessionInstalledPluginSource struct { String *string } -// Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref, -// and optional subpath. +// Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref or +// full commit SHA, and optional subpath. // Experimental: SessionInstalledPluginSourceGitHub is part of an experimental API and may // change or be removed. type SessionInstalledPluginSourceGitHub struct { Path *string `json:"path,omitempty"` Ref *string `json:"ref,omitempty"` Repo string `json:"repo"` + // Optional full 40-character hexadecimal commit SHA. + Sha *string `json:"sha,omitempty"` // Constant value. Always "github". Source SessionInstalledPluginSourceGitHubSource `json:"source"` } @@ -8031,18 +9004,118 @@ type SessionInstalledPluginSourceLocal struct { Source SessionInstalledPluginSourceLocalSource `json:"source"` } -// Source descriptor for a direct URL plugin install, with URL, optional ref, and optional -// subpath. +// Source descriptor for a direct URL plugin install, with URL, optional ref or full commit +// SHA, and optional subpath. // Experimental: SessionInstalledPluginSourceURL is part of an experimental API and may // change or be removed. type SessionInstalledPluginSourceURL struct { Path *string `json:"path,omitempty"` Ref *string `json:"ref,omitempty"` + // Optional full 40-character hexadecimal commit SHA. + Sha *string `json:"sha,omitempty"` // Constant value. Always "url". Source SessionInstalledPluginSourceURLSource `json:"source"` URL string `json:"url"` } +// Baseline data provenance for a prediction. +// Experimental: SessionLimitPredictionBaselineData is part of an experimental API and may +// change or be removed. +type SessionLimitPredictionBaselineData struct { + // End of the baseline data slice. + WindowEnd string `json:"windowEnd"` + // Start of the baseline data slice. + WindowStart string `json:"windowStart"` +} + +// Explainable AI-credit session-limit prediction. +// Experimental: SessionLimitPredictionDetails is part of an experimental API and may change +// or be removed. +type SessionLimitPredictionDetails struct { + // Baseline data provenance. + BaselineData SessionLimitPredictionBaselineData `json:"baselineData"` + // Client population used for the prediction. + ClientType SessionLimitPredictionClientType `json:"clientType"` + // Resolved model family when known. + Family *string `json:"family,omitempty"` + // Model identifier used for lookup. + ModelID string `json:"modelId"` + // Recommended maximum AI credits for this session. + RecommendedCap float64 `json:"recommendedCap"` + // Tier chosen as the recommended cap. + RecommendedTier SessionLimitPredictionTier `json:"recommendedTier"` + // Baseline fallback level used to create the prediction. + Source SessionLimitPredictionSource `json:"source"` + // Key matched at the source level, such as a model id, family id, or `global`. + SourceKey string `json:"sourceKey"` + // Ordered usage tiers and their AI-credit caps. + Tiers []SessionLimitPredictionTierOption `json:"tiers"` +} + +// Experimental: SessionLimitPredictionPredictRequest is part of an experimental API and may +// change or be removed. +type SessionLimitPredictionPredictRequest struct { + // Client type to size for. Defaults to `cli-interactive`. + ClientType *SessionLimitPredictionClientType `json:"clientType,omitempty"` + // Optional model identifier override. If omitted, the session's current model is used. + ModelID *string `json:"modelId,omitempty"` +} + +type SessionLimitPredictionRequest struct { + // Client type to size for. Defaults to `cli-interactive`. + ClientType *SessionLimitPredictionClientType `json:"clientType,omitempty"` + // Optional model identifier override. If omitted, the session's current model is used. + ModelID *string `json:"modelId,omitempty"` +} + +// Prediction result. Available results include prediction details; unavailable results +// include an explicit reason. +// Experimental: SessionLimitPredictionResult is part of an experimental API and may change +// or be removed. +type SessionLimitPredictionResult interface { + sessionLimitPredictionResult() + Kind() SessionLimitPredictionResultKind +} + +type RawSessionLimitPredictionResultData struct { + Discriminator SessionLimitPredictionResultKind + Raw json.RawMessage +} + +func (RawSessionLimitPredictionResultData) sessionLimitPredictionResult() {} +func (r RawSessionLimitPredictionResultData) Kind() SessionLimitPredictionResultKind { + return r.Discriminator +} + +type SessionLimitPredictionResultAvailable struct { + // Predicted session limit details. + Prediction SessionLimitPredictionDetails `json:"prediction"` +} + +func (SessionLimitPredictionResultAvailable) sessionLimitPredictionResult() {} +func (SessionLimitPredictionResultAvailable) Kind() SessionLimitPredictionResultKind { + return SessionLimitPredictionResultKindAvailable +} + +type SessionLimitPredictionResultUnavailable struct { + // Reason no prediction is available. + Reason SessionLimitPredictionUnavailableReason `json:"reason"` +} + +func (SessionLimitPredictionResultUnavailable) sessionLimitPredictionResult() {} +func (SessionLimitPredictionResultUnavailable) Kind() SessionLimitPredictionResultKind { + return SessionLimitPredictionResultKindUnavailable +} + +// Semantic usage tier and its AI-credit cap. +// Experimental: SessionLimitPredictionTierOption is part of an experimental API and may +// change or be removed. +type SessionLimitPredictionTierOption struct { + // AI-credit cap for this tier. + Cap float64 `json:"cap"` + Tier SessionLimitPredictionTier `json:"tier"` +} + // Optional session limits. // Experimental: SessionLimitsConfig is part of an experimental API and may change or be // removed. @@ -8254,6 +9327,13 @@ type SessionModelList struct { QuotaSnapshots map[string]any `json:"quotaSnapshots,omitzero"` } +// Experimental: SessionModelListRequest is part of an experimental API and may change or be +// removed. +type SessionModelListRequest struct { + // If true, bypasses the per-session model list cache and re-fetches from CAPI. + SkipCache *bool `json:"skipCache,omitempty"` +} + // Cost-category metadata for a CAPI model. // Experimental: SessionModelPriceCategory is part of an experimental API and may change or // be removed. @@ -8280,6 +9360,14 @@ type SessionOpenOptions struct { // Experimental: AdditionalContentExclusionPolicies is part of an experimental API and may // change or be removed. AdditionalContentExclusionPolicies []SessionOpenOptionsAdditionalContentExclusionPolicy `json:"additionalContentExclusionPolicies,omitzero"` + // Additional directories the agent may access beyond the working directory. Each entry is + // granted to the session's file-access allow-list and surfaced to the model (system prompt + // context and `@`-mention completion). Absolute paths are recommended; a relative path is + // resolved against the session's working directory. Nonexistent or unresolvable entries are + // skipped with a warning. This is applied on both session creation and resume, and is not + // persisted: a resumed session that omits this option does not retain previously supplied + // directories (re-supply them, exactly as the CLI re-passes `--add-dir`). + AdditionalDirectories []string `json:"additionalDirectories,omitzero"` // Runtime context discriminator for agent filtering. AgentContext *string `json:"agentContext,omitempty"` // Whether to include instructions from every MCP server in the system prompt instead of @@ -8320,6 +9408,27 @@ type SessionOpenOptions struct { // surface is experimental. // Experimental: EnableCitations is part of an experimental API and may change or be removed. EnableCitations *bool `json:"enableCitations,omitempty"` + // Opt in to capturing file changes for session rewind and session diff. Capture cannot + // reconstruct changes made before it was enabled. On create it starts capture from the + // first turn. It is also honored on resume: for a session that already has tracked prior + // turns, tracking continues automatically even if this is omitted; passing it on resume + // additionally enables tracking for an eligible session that has no prior root turn yet. + // Resuming a session whose prior root turns were never tracked has no restorable baseline, + // so tracking stays disabled for it and rewind reports file change tracking as unavailable; + // the resume itself still succeeds, so sessions that predate tracking remain loadable. The + // opt-in is only rejected when the session can never track (a subagent session, or one + // without local session storage). It is intentionally absent from the mutable options + // update because enabling it after edits have occurred would create an incomplete, + // misleading baseline. Subagents share the parent session's capture store and are not + // tracked as separate rewind points: a file a subagent writes is attributed to whichever + // root user turn was open when the capture was staged, just before the tool body ran. A + // turn cannot open while a staged capture is still in flight, so a subagent tool that + // staged under the spawning turn stays attributed to it however late the write lands, while + // a capture it stages after the user's next message belongs to that later turn. Attribution + // decides which turn's rewind point counts and file preview include that write; it does not + // narrow which rewinds revert it, because a rewind restores every capture from the selected + // turn onward, so the earlier spawning turn reverts it as well. + EnableFileChangeTracking *bool `json:"enableFileChangeTracking,omitempty"` // Opt-in: self-fetch and enforce enterprise managed settings at session bootstrap. EnableManagedSettings *bool `json:"enableManagedSettings,omitempty"` // Whether on-demand custom instruction discovery is enabled. @@ -8332,6 +9441,8 @@ type SessionOpenOptions struct { EnvValueMode *SessionOpenOptionsEnvValueMode `json:"envValueMode,omitempty"` // Override directory for session event logs. EventsLogDirectory *string `json:"eventsLogDirectory,omitempty"` + // Whether subagent callback events should be forwarded into the session event log sink. + EventsLogIncludesSubagents *bool `json:"eventsLogIncludesSubagents,omitempty"` // Built-in subagent names to exclude from this session. Excluded built-ins are hidden from // agent discovery and cannot be dispatched unless a custom agent with the same name is // available. @@ -8402,9 +9513,12 @@ type SessionOpenOptions struct { SessionID *string `json:"sessionId,omitempty"` // Initial session limits. SessionLimits *SessionLimitsConfig `json:"sessionLimits,omitempty"` - // Shell init profile. + // Per-session settings for built-in shell tools. + Shell *ShellOptions `json:"shell,omitempty"` + // Use shell.initProfile instead. Shell init profile. + // Deprecated: ShellInitProfile is deprecated. ShellInitProfile *string `json:"shellInitProfile,omitempty"` - // Per-shell process flags. + // PowerShell process flags applied to built-in and user-requested shell commands. ShellProcessFlags []string `json:"shellProcessFlags,omitzero"` // Additional directories to search for skills. SkillDirectories []string `json:"skillDirectories,omitzero"` @@ -8649,11 +9763,38 @@ type SessionPlanDeleteResult struct { type SessionPlanUpdateResult struct { } +// Experimental: SessionPluginsReloadRequest is part of an experimental API and may change +// or be removed. +type SessionPluginsReloadRequest struct { + // When true, skip repo-level hooks during the hook reload. Use before folder trust is + // confirmed; load them post-trust via `sessions.loadDeferredRepoHooks`. + DeferRepoHooks *bool `json:"deferRepoHooks,omitempty"` + // Re-run custom-agent discovery after refreshing plugins. Defaults to true. + ReloadCustomAgents *bool `json:"reloadCustomAgents,omitempty"` + // Re-discover and relaunch subprocess extensions (including plugin-shipped extensions) + // after refreshing plugins. Defaults to true. Has no effect when the session has no active + // extension controller (e.g. extensions were not requested for the session). + ReloadExtensions *bool `json:"reloadExtensions,omitempty"` + // Re-load user, plugin, and (subject to `deferRepoHooks`) repo hooks. Defaults to true. Has + // no effect when the host has not registered a hook reloader (e.g. remote sessions). + ReloadHooks *bool `json:"reloadHooks,omitempty"` + // Reload MCP server connections after refreshing plugins. Defaults to true. + ReloadMCP *bool `json:"reloadMcp,omitempty"` +} + // Experimental: SessionPluginsReloadResult is part of an experimental API and may change or // be removed. type SessionPluginsReloadResult struct { } +// Experimental: SessionProviderGetEndpointRequest is part of an experimental API and may +// change or be removed. +type SessionProviderGetEndpointRequest struct { + // Model identifier the caller intends to use against the returned endpoint. Used to pick + // the correct wire shape. Omit to use whichever model the session is currently using. + ModelID *string `json:"modelId,omitempty"` +} + // Outcome of the prune operation: deleted IDs, dry-run candidates, skipped IDs, total bytes // freed, and the dry-run flag. // Experimental: SessionPruneResult is part of an experimental API and may change or be @@ -8676,6 +9817,21 @@ type SessionPruneResult struct { type SessionQueueClearResult struct { } +// Experimental: SessionQueueDeferSessionIdleResult is part of an experimental API and may +// change or be removed. +type SessionQueueDeferSessionIdleResult struct { +} + +// Experimental: SessionQueueProcessResult is part of an experimental API and may change or +// be removed. +type SessionQueueProcessResult struct { +} + +// Experimental: SessionQueueSetDrainPausedResult is part of an experimental API and may +// change or be removed. +type SessionQueueSetDrainPausedResult struct { +} + // Experimental: SessionRemoteDisableResult is part of an experimental API and may change or // be removed. type SessionRemoteDisableResult struct { @@ -8706,6 +9862,11 @@ type SessionsCheckInUseResult struct { InUse []string `json:"inUse"` } +// Experimental: SessionScheduleHydrateResult is part of an experimental API and may change +// or be removed. +type SessionScheduleHydrateResult struct { +} + // Session ID to close. // Experimental: SessionsCloseRequest is part of an experimental API and may change or be // removed. @@ -8727,6 +9888,26 @@ type SessionsCloseResult struct { type SessionsConfigureSessionExtensionsResult struct { } +// Session ID to delete from disk. +// Experimental: SessionsDeleteRequest is part of an experimental API and may change or be +// removed. +type SessionsDeleteRequest struct { + // Session ID to delete + SessionID string `json:"sessionId"` + // Internal resolved session directory path to delete + SessionPath *string `json:"sessionPath,omitempty"` +} + +// Experimental: SessionsDeleteResult is part of an experimental API and may change or be +// removed. +type SessionsDeleteResult struct { +} + +// Experimental: SessionSendSystemNotificationResult is part of an experimental API and may +// change or be removed. +type SessionSendSystemNotificationResult struct { +} + // Session metadata records to enrich with summary and context information. // Experimental: SessionsEnrichMetadataRequest is part of an experimental API and may change // or be removed. @@ -8976,6 +10157,22 @@ type SessionsGetLastForContextResult struct { SessionID *string `json:"sessionId,omitempty"` } +// Session ID whose persisted metadata should be read. +// Experimental: SessionsGetMetadataRequest is part of an experimental API and may change or +// be removed. +type SessionsGetMetadataRequest struct { + // Session ID to inspect + SessionID string `json:"sessionId"` +} + +// Persisted local session metadata when the session exists. +// Experimental: SessionsGetMetadataResult is part of an experimental API and may change or +// be removed. +type SessionsGetMetadataResult struct { + // Local session metadata, omitted when the session does not exist. + Session *LocalSessionMetadataValue `json:"session,omitempty"` +} + // Session ID to look up the persisted remote-steerable flag for. // Experimental: SessionsGetPersistedRemoteSteerableRequest is part of an experimental API // and may change or be removed. @@ -9021,6 +10218,22 @@ type SessionSkillsEnableResult struct { type SessionSkillsEnsureLoadedResult struct { } +// Limit for non-empty local session IDs. +// Experimental: SessionsListNonEmptySessionIDsRequest is part of an experimental API and +// may change or be removed. +type SessionsListNonEmptySessionIDsRequest struct { + // Maximum number of session IDs to return. + Limit *int64 `json:"limit,omitempty"` +} + +// Recent local session IDs that contain user-visible history. +// Experimental: SessionsListNonEmptySessionIDsResult is part of an experimental API and may +// change or be removed. +type SessionsListNonEmptySessionIDsResult struct { + // Session IDs ordered newest-first. + SessionIDs []string `json:"sessionIds"` +} + // Optional source filter, metadata-load limit, and context filter applied to the returned // sessions. // Experimental: SessionsListRequest is part of an experimental API and may change or be @@ -9259,7 +10472,7 @@ type SessionUpdateOptionsParams struct { EnableHostGitOperations *bool `json:"enableHostGitOperations,omitempty"` // Whether to discover custom instructions on demand after successful file views (AGENTS.md // / CLAUDE.md / .github/copilot-instructions.md surfacing). Combined with - // `skipCustomInstructions` and the runtime-side `ON_DEMAND_INSTRUCTIONS` feature flag. + // `skipCustomInstructions`. EnableOnDemandInstructionDiscovery *bool `json:"enableOnDemandInstructionDiscovery,omitempty"` // Whether to surface reasoning-summary events from the model. EnableReasoningSummaries *bool `json:"enableReasoningSummaries,omitempty"` @@ -9278,6 +10491,8 @@ type SessionUpdateOptionsParams struct { // Override directory for the session-events log. When unset, the runtime's default events // log directory is used. EventsLogDirectory *string `json:"eventsLogDirectory,omitempty"` + // Whether subagent callback events should be forwarded into the session event log sink. + EventsLogIncludesSubagents *bool `json:"eventsLogIncludesSubagents,omitempty"` // Built-in subagent names to exclude from this session. Excluded built-ins are hidden from // agent discovery and cannot be dispatched unless a custom agent with the same name is // available. @@ -9332,9 +10547,12 @@ type SessionUpdateOptionsParams struct { SessionCapabilities []SessionCapability `json:"sessionCapabilities,omitzero"` // Optional session limits. Pass null to clear the session limits. SessionLimits *SessionLimitsConfig `json:"sessionLimits,omitempty"` - // Shell init profile (`None` or `NonInteractive`). + // Per-session settings for built-in shell tools. + Shell *ShellOptions `json:"shell,omitempty"` + // Use shell.initProfile instead. Shell init profile (`None` or `NonInteractive`). + // Deprecated: ShellInitProfile is deprecated. ShellInitProfile *string `json:"shellInitProfile,omitempty"` - // Per-shell process flags (e.g., `pwsh` arguments). + // PowerShell process flags applied to built-in and user-requested shell commands. ShellProcessFlags []string `json:"shellProcessFlags,omitzero"` // Additional directories to search for skills. SkillDirectories []string `json:"skillDirectories,omitzero"` @@ -9434,6 +10652,16 @@ type ShellExecuteUserRequestedRequest struct { RequestID string `json:"requestId"` } +// A host-provided script sourced before each built-in shell command when its shell target +// matches the active shell. +// Experimental: ShellInitScript is part of an experimental API and may change or be removed. +type ShellInitScript struct { + // Path to the script to source. + Path string `json:"path"` + // Built-in shell that may source this script. + Shell ShellInitScriptShell `json:"shell"` +} + // Identifier of a process previously returned by "shell.exec" and the signal to send. // Experimental: ShellKillRequest is part of an experimental API and may change or be // removed. @@ -9452,6 +10680,34 @@ type ShellKillResult struct { Killed bool `json:"killed"` } +// Per-session settings for built-in shell tools. +// Experimental: ShellOptions is part of an experimental API and may change or be removed. +type ShellOptions struct { + // Controls automatic non-interactive profile loading where supported. Explicit initScripts + // are unaffected. + InitProfile *ShellInitProfile `json:"initProfile,omitempty"` + // Ordered host-provided script paths sourced before each built-in shell command when the + // entry's shell target matches the active shell. Use these for rc files, environment setup + // scripts, + // or other custom scripts. A script that returns a nonzero status is reported, and later + // scripts + // and the user command continue while the shell remains running. Because scripts are + // sourced into + // the command shell, `exit`, `exec`, failures under `set -e`, or other shell-terminating + // behavior + // can prevent continuation. Script standard output is preserved; Bash script stderr is + // discarded, + // PowerShell exception messages are replaced, and runtime-generated failure notices omit + // configured script paths. When sandboxing is enabled, each script must already be readable + // under + // the active sandbox filesystem policy. Pass an empty array to clear the list. + InitScripts []ShellInitScript `json:"initScripts,omitzero"` + // Flags passed to the active built-in shell process on startup, replacing its default flags. + // When omitted, the built-in Bash shell uses `--norc --noprofile`, + // and the built-in PowerShell shell uses `-NoProfile -NoLogo`. + ProcessFlags []string `json:"processFlags,omitzero"` +} + // Parameters for shutting down the session // Experimental: ShutdownRequest is part of an experimental API and may change or be removed. type ShutdownRequest struct { @@ -10497,6 +11753,11 @@ type UIExitPlanModeResponse struct { Approved bool `json:"approved"` // Whether subsequent edits should be auto-approved without confirmation. AutoApproveEdits *bool `json:"autoApproveEdits,omitempty"` + // When true, the agent is instructed to end its turn without starting implementation so the + // client can restore the session model and auto-submit a fresh implementation turn on it. + // Set only when a distinct plan configuration (a different model, reasoning effort, or + // context tier) actually ran the planning turn. + DeferImplementation *bool `json:"deferImplementation,omitempty"` // Feedback from the user when they declined the plan or requested changes. Feedback *string `json:"feedback,omitempty"` // The action the user selected. Defaults to 'autopilot' when autoApproveEdits is true, @@ -10995,7 +12256,9 @@ type WorkspaceDiffFileChange struct { IsTruncated *bool `json:"isTruncated,omitempty"` // Original file path for renamed files. OldPath *string `json:"oldPath,omitempty"` - // Path to the changed file, relative to the workspace root. + // Path to the changed file, relative to the workspace root when the file lives under it. A + // file changed outside the workspace root keeps a `../`-relative path, or an absolute path + // when no relative path exists (for example a different Windows drive). Path string `json:"path"` } @@ -11007,12 +12270,47 @@ type WorkspaceDiffResult struct { BaseBranch *string `json:"baseBranch,omitempty"` // Changed files and their unified diffs. Changes []WorkspaceDiffFileChange `json:"changes"` - // Whether a requested branch diff fell back to unstaged changes because branch diff failed. + // Whether the requested diff fell back to unstaged changes, either because branch diff + // failed or session diff was unavailable. IsFallback bool `json:"isFallback"` // Effective mode used for the returned changes. Mode WorkspaceDiffMode `json:"mode"` // Diff mode requested by the client. RequestedMode WorkspaceDiffMode `json:"requestedMode"` + // Why the session diff could not be produced, when applicable. Set only when `session` mode + // was requested and `isFallback` is true, so a client can tell the permanent + // `file-change-tracking-disabled` apart from the transient `session-busy`, which the same + // request answers once the session settles. Never set for `unstaged` or `branch` mode, and + // never `unsupported-remote-session`: a remote session's captures live on its own host, so + // a `session`-mode diff is rejected for one rather than answered with a controller-side + // fallback. + UnavailableReason *HistoryRewindUnavailableReason `json:"unavailableReason,omitempty"` +} + +// Compaction summary checkpoint to persist. +// Experimental: WorkspacesAddSummaryRequest is part of an experimental API and may change +// or be removed. +type WorkspacesAddSummaryRequest struct { + // Markdown summary content to persist. + Content string `json:"content"` + // Summary title shown in checkpoint listings. + Title string `json:"title"` +} + +// Persisted summary metadata and refreshed workspace metadata. +// Experimental: WorkspacesAddSummaryResult is part of an experimental API and may change or +// be removed. +type WorkspacesAddSummaryResult struct { + Summary any `json:"summary,omitempty"` + Workspace any `json:"workspace,omitempty"` +} + +// Whether the autopilot objective file exists. +// Experimental: WorkspacesAutopilotObjectiveExistsResult is part of an experimental API and +// may change or be removed. +type WorkspacesAutopilotObjectiveExistsResult struct { + // True when the objective file exists. + Exists bool `json:"exists"` } // Workspace checkpoint metadata with assigned number, human-readable title, and checkpoint @@ -11038,6 +12336,14 @@ type WorkspacesCreateFileRequest struct { Path string `json:"path"` } +// Result of deleting the autopilot objective file. +// Experimental: WorkspacesDeleteAutopilotObjectiveResult is part of an experimental API and +// may change or be removed. +type WorkspacesDeleteAutopilotObjectiveResult struct { + // True when a file was deleted. + Deleted bool `json:"deleted"` +} + // Parameters for computing a workspace diff. // Experimental: WorkspacesDiffRequest is part of an experimental API and may change or be // removed. @@ -11048,6 +12354,14 @@ type WorkspacesDiffRequest struct { Mode WorkspaceDiffMode `json:"mode"` } +// Optional session context used when creating a local workspace. +// Experimental: WorkspacesEnsureRequest is part of an experimental API and may change or be +// removed. +type WorkspacesEnsureRequest struct { + // Opaque workspace context supplied by the session host. + Context any `json:"context,omitempty"` +} + // Current workspace metadata for the session, including its absolute filesystem path when // available. // Experimental: WorkspacesGetWorkspaceResult is part of an experimental API and may change @@ -11097,6 +12411,14 @@ type WorkspacesListFilesResult struct { Files []string `json:"files"` } +// Autopilot objective file content, or null when missing. +// Experimental: WorkspacesReadAutopilotObjectiveResult is part of an experimental API and +// may change or be removed. +type WorkspacesReadAutopilotObjectiveResult struct { + // Autopilot objective file content, or null when missing. + Content *string `json:"content"` +} + // Checkpoint number to read. // Experimental: WorkspacesReadCheckpointRequest is part of an experimental API and may // change or be removed. @@ -11155,6 +12477,14 @@ type WorkspacesSaveLargePasteResultSaved struct { SizeBytes int64 `json:"sizeBytes"` } +// Rollback point for local workspace summaries. +// Experimental: WorkspacesTruncateSummariesRequest is part of an experimental API and may +// change or be removed. +type WorkspacesTruncateSummariesRequest struct { + // Number of newest summaries to keep. + KeepCount int64 `json:"keepCount"` +} + // Public-facing projection of workspace metadata for SDK / TUI consumers // Experimental: WorkspaceSummary is part of an experimental API and may change or be // removed. @@ -11181,6 +12511,32 @@ type WorkspaceSummary struct { UserNamed *bool `json:"user_named,omitempty"` } +// Workspace metadata fields to update. +// Experimental: WorkspacesUpdateMetadataRequest is part of an experimental API and may +// change or be removed. +type WorkspacesUpdateMetadataRequest struct { + // Opaque workspace context supplied by the session host. + Context any `json:"context,omitempty"` + // Optional workspace display name override. + Name *string `json:"name,omitempty"` +} + +// Autopilot objective file content to persist. +// Experimental: WorkspacesWriteAutopilotObjectiveRequest is part of an experimental API and +// may change or be removed. +type WorkspacesWriteAutopilotObjectiveRequest struct { + // Autopilot objective file content. + Content string `json:"content"` +} + +// Result of writing the autopilot objective file. +// Experimental: WorkspacesWriteAutopilotObjectiveResult is part of an experimental API and +// may change or be removed. +type WorkspacesWriteAutopilotObjectiveResult struct { + // Filesystem operation performed. + Operation string `json:"operation"` +} + // Finite reason code describing why the current turn was aborted // Experimental: AbortReason is part of an experimental API and may change or be removed. type AbortReason string @@ -11654,6 +13010,34 @@ const ( ExternalToolTextResultForLlmContentTypeText ExternalToolTextResultForLlmContentType = "text" ) +// Execution-critical factory storage operation. +// Experimental: FactoryDurableOperation is part of an experimental API and may change or be +// removed. +type FactoryDurableOperation string + +const ( + // Persisting active execution time. + FactoryDurableOperationAddElapsed FactoryDurableOperation = "addElapsed" + // Persisting an idempotent model-usage charge. + FactoryDurableOperationChargeCredit FactoryDurableOperation = "chargeCredit" + // Creating the durable run and declared phases. + FactoryDurableOperationCreateRun FactoryDurableOperation = "createRun" + // Persisting the terminal run envelope. + FactoryDurableOperationFinishRun FactoryDurableOperation = "finishRun" + // Reading a journal entry without treating storage failure as a cache miss. + FactoryDurableOperationJournalGet FactoryDurableOperation = "journalGet" + // Persisting a journal entry before reporting success. + FactoryDurableOperationJournalPut FactoryDurableOperation = "journalPut" + // Persisting the transition to running. + FactoryDurableOperationMarkRunStarted FactoryDurableOperation = "markRunStarted" + // Reading the authoritative AI-credit total. + FactoryDurableOperationReconcileCreditTotal FactoryDurableOperation = "reconcileCreditTotal" + // Rolling back an uncommitted subagent admission. + FactoryDurableOperationReleaseAgent FactoryDurableOperation = "releaseAgent" + // Persisting subagent admission accounting. + FactoryDurableOperationReserveAgent FactoryDurableOperation = "reserveAgent" +) + // Kind of factory progress line. // Experimental: FactoryLogLineKind is part of an experimental API and may change or be // removed. @@ -11666,22 +13050,43 @@ const ( FactoryLogLineKindPhase FactoryLogLineKind = "phase" ) +// Derived lifecycle state of a factory phase. +// Experimental: FactoryPhaseStatus is part of an experimental API and may change or be +// removed. +type FactoryPhaseStatus string + +const ( + // The phase is currently entered and accumulating active time. + FactoryPhaseStatusActive FactoryPhaseStatus = "active" + // The phase was entered and has since been closed. + FactoryPhaseStatusCompleted FactoryPhaseStatus = "completed" + // The phase has not been entered yet. + FactoryPhaseStatusPending FactoryPhaseStatus = "pending" + // The phase was never entered because a later phase was entered or the run reached a + // terminal state. + FactoryPhaseStatusSkipped FactoryPhaseStatus = "skipped" +) + // Cumulative resource ceiling that stopped a factory run. // Experimental: FactoryRunFailureKind is part of an experimental API and may change or be // removed. type FactoryRunFailureKind string const ( + // The run's settled subagent model usage exceeded the approved AI-credit ceiling, or no + // headroom remained for another subagent. + FactoryRunFailureKindMaxAiCredits FactoryRunFailureKind = "maxAiCredits" // The run admitted the approved maximum total number of subagents. FactoryRunFailureKindMaxTotalSubagents FactoryRunFailureKind = "maxTotalSubagents" - // The run reached the approved timeout deadline. - FactoryRunFailureKindTimeout FactoryRunFailureKind = "timeout" + // The run reached the approved accumulated active-execution time in seconds. + FactoryRunFailureKindTimeoutSeconds FactoryRunFailureKind = "timeoutSeconds" ) // Type discriminator for FactoryRunFailure. type FactoryRunFailureType string const ( + FactoryRunFailureTypeFactoryDurableFailure FactoryRunFailureType = "factory_durable_failure" FactoryRunFailureTypeFactoryLimitReached FactoryRunFailureType = "factory_limit_reached" FactoryRunFailureTypeFactoryResumeDeclined FactoryRunFailureType = "factory_resume_declined" ) @@ -11706,6 +13111,107 @@ const ( FactoryRunStatusRunning FactoryRunStatus = "running" ) +// What initiated this compaction request, recorded as the `trigger` on the persisted +// `session.compaction_start` / `session.compaction_complete` events. When absent, the +// compaction is persisted without trigger attribution (initiator unknown). +type HistoryCompactRequestTrigger string + +const ( + // User-requested compaction, e.g. the /compact command or a direct history.compact call. + HistoryCompactRequestTriggerManual HistoryCompactRequestTrigger = "manual" + // Compaction requested while switching to a model with a smaller context window. + HistoryCompactRequestTriggerModelSwitch HistoryCompactRequestTrigger = "model_switch" +) + +// Reason a captured file was not restored. +// Experimental: HistoryFileRestoreSkipReason is part of an experimental API and may change +// or be removed. +type HistoryFileRestoreSkipReason string + +const ( + // A faithful preimage was not captured. + HistoryFileRestoreSkipReasonSkippedCapture HistoryFileRestoreSkipReason = "skipped-capture" + // The file changed after Copilot's last captured write. + HistoryFileRestoreSkipReasonUserModified HistoryFileRestoreSkipReason = "user-modified" +) + +// Aggregate file change represented by a rewind preview. +// Experimental: HistoryRewindChangeType is part of an experimental API and may change or be +// removed. +type HistoryRewindChangeType string + +const ( + // The discarded turns created the file. + HistoryRewindChangeTypeCreated HistoryRewindChangeType = "created" + // The discarded turns deleted the file. + HistoryRewindChangeTypeDeleted HistoryRewindChangeType = "deleted" + // The discarded turns modified the file. + HistoryRewindChangeTypeModified HistoryRewindChangeType = "modified" +) + +// Scope of a rewind operation. +// Experimental: HistoryRewindMode is part of an experimental API and may change or be +// removed. +type HistoryRewindMode string + +const ( + // Discard conversation events while leaving files unchanged. + HistoryRewindModeConversation HistoryRewindMode = "conversation" + // Discard conversation events and restore captured files changed by those turns. + HistoryRewindModeConversationAndFiles HistoryRewindMode = "conversation-and-files" +) + +// Outcome of a rewind request. +// Experimental: HistoryRewindOutcome is part of an experimental API and may change or be +// removed. +type HistoryRewindOutcome string + +const ( + // The conversation was rewound (and, in conversation-and-files mode, captured files were + // restored), but persisted checkpoints could not be cleaned up; reachable in either mode. + HistoryRewindOutcomeCheckpointCleanupFailed HistoryRewindOutcome = "checkpoint-cleanup-failed" + // A conversation-and-files rewind was requested for a session that did not enable capture; + // conversation-only rewinds never produce this. + HistoryRewindOutcomeFileChangeTrackingDisabled HistoryRewindOutcome = "file-change-tracking-disabled" + // File restore failed and all applied file changes were rolled back; only + // conversation-and-files rewinds produce this. + HistoryRewindOutcomeFilesRolledBack HistoryRewindOutcome = "files-rolled-back" + // File restore failed and its rollback could not fully restore the pre-rewind state; only + // conversation-and-files rewinds produce this. + HistoryRewindOutcomeRollbackIncomplete HistoryRewindOutcome = "rollback-incomplete" + // The session still has work that may mutate files or history; reachable in either mode. + HistoryRewindOutcomeSessionBusy HistoryRewindOutcome = "session-busy" + // Files and conversation were rewound, but obsolete file snapshots could not be removed; + // only conversation-and-files rewinds produce this. + HistoryRewindOutcomeSnapshotPruneFailed HistoryRewindOutcome = "snapshot-prune-failed" + // The requested rewind completed; reachable in either mode. + HistoryRewindOutcomeSuccess HistoryRewindOutcome = "success" + // Conversation truncation failed. In conversation-and-files mode any files that were + // restored are left in place because conversation history cannot be un-truncated; in + // conversation-only mode no files are restored. Consult restoredFiles for what, if + // anything, was applied. + HistoryRewindOutcomeTruncationFailed HistoryRewindOutcome = "truncation-failed" + // Remote-backed rewind routing is not supported; reachable in either mode. + HistoryRewindOutcomeUnsupportedRemoteSession HistoryRewindOutcome = "unsupported-remote-session" +) + +// Reason a rewind read (rewind points, file-restore preview, or session diff) could not be +// answered from the session's file-change captures. +// Experimental: HistoryRewindUnavailableReason is part of an experimental API and may +// change or be removed. +type HistoryRewindUnavailableReason string + +const ( + // The session did not opt into file-change tracking before its first turn. + HistoryRewindUnavailableReasonFileChangeTrackingDisabled HistoryRewindUnavailableReason = "file-change-tracking-disabled" + // The session still has work that may mutate files or history. Transient: the same request + // succeeds once the session settles, so callers should retry rather than treat it as a + // failure. + HistoryRewindUnavailableReasonSessionBusy HistoryRewindUnavailableReason = "session-busy" + // Remote-backed rewind routing is not supported. + HistoryRewindUnavailableReasonUnsupportedRemoteSession HistoryRewindUnavailableReason = "unsupported-remote-session" +) + // Authentication host. HMAC auth always targets the public GitHub host. type HMACAuthInfoHost string @@ -12714,6 +14220,35 @@ const ( SessionFSSqliteQueryTypeRun SessionFSSqliteQueryType = "run" ) +// SQLite transaction failure classification. +// Experimental: SessionFSSqliteTransactionErrorClass is part of an experimental API and may +// change or be removed. +type SessionFSSqliteTransactionErrorClass string + +const ( + // SQLite reported BUSY or LOCKED before commit; the transaction was rolled back and may be + // retried. + SessionFSSqliteTransactionErrorClassBusyOrLocked SessionFSSqliteTransactionErrorClass = "busyOrLocked" + // The statement, database, or provider failed definitively and must not be retried + // automatically. + SessionFSSqliteTransactionErrorClassFatal SessionFSSqliteTransactionErrorClass = "fatal" + // The transport failed after the provider may have committed; retrying could duplicate + // effects. + SessionFSSqliteTransactionErrorClassPostCommitAmbiguous SessionFSSqliteTransactionErrorClass = "postCommitAmbiguous" +) + +// What initiated this compaction request, recorded as the `trigger` on the persisted +// `session.compaction_start` / `session.compaction_complete` events. When absent, the +// compaction is persisted without trigger attribution (initiator unknown). +type SessionHistoryCompactRequestTrigger string + +const ( + // User-requested compaction, e.g. the /compact command or a direct history.compact call. + SessionHistoryCompactRequestTriggerManual SessionHistoryCompactRequestTrigger = "manual" + // Compaction requested while switching to a model with a smaller context window. + SessionHistoryCompactRequestTriggerModelSwitch SessionHistoryCompactRequestTrigger = "model_switch" +) + // Constant value. Always "github". type SessionInstalledPluginSourceGitHubSource string @@ -12735,6 +14270,69 @@ const ( SessionInstalledPluginSourceURLSourceURL SessionInstalledPluginSourceURLSource = "url" ) +// Client population used for the prediction baseline. +// Experimental: SessionLimitPredictionClientType is part of an experimental API and may +// change or be removed. +type SessionLimitPredictionClientType string + +const ( + // Interactive CLI sessions where a user can accept, edit, or top up the limit. + SessionLimitPredictionClientTypeCLIInteractive SessionLimitPredictionClientType = "cli-interactive" + // Prompt/non-interactive CLI sessions where the initial limit must cover more of the run. + SessionLimitPredictionClientTypeCLIPrompt SessionLimitPredictionClientType = "cli-prompt" +) + +// Kind discriminator for SessionLimitPredictionResult. +type SessionLimitPredictionResultKind string + +const ( + SessionLimitPredictionResultKindAvailable SessionLimitPredictionResultKind = "available" + SessionLimitPredictionResultKindUnavailable SessionLimitPredictionResultKind = "unavailable" +) + +// Baseline fallback level used to create the prediction. +// Experimental: SessionLimitPredictionSource is part of an experimental API and may change +// or be removed. +type SessionLimitPredictionSource string + +const ( + // The exact model was unavailable, so the prediction used the model family's baseline cell. + SessionLimitPredictionSourceFamily SessionLimitPredictionSource = "family" + // No model or family cell was available, so the prediction used the global client-type + // baseline cell. + SessionLimitPredictionSourceGlobal SessionLimitPredictionSource = "global" + // The prediction used the exact resolved model's baseline cell. + SessionLimitPredictionSourceModel SessionLimitPredictionSource = "model" +) + +// Semantic usage tier used for a recommended cap or additional headroom. +// Experimental: SessionLimitPredictionTier is part of an experimental API and may change or +// be removed. +type SessionLimitPredictionTier string + +const ( + // Additional headroom for longer-running sessions. + SessionLimitPredictionTierAdditionalHeadroom SessionLimitPredictionTier = "additional_headroom" + // Generous headroom for unusually high usage. + SessionLimitPredictionTierGenerousHeadroom SessionLimitPredictionTier = "generous_headroom" + // Maximum available headroom tier. + SessionLimitPredictionTierMaximumHeadroom SessionLimitPredictionTier = "maximum_headroom" + // Recommended starting tier. + SessionLimitPredictionTierRecommended SessionLimitPredictionTier = "recommended" +) + +// Reason a prediction could not be computed. +// Experimental: SessionLimitPredictionUnavailableReason is part of an experimental API and +// may change or be removed. +type SessionLimitPredictionUnavailableReason string + +const ( + // The current model is auto and has not resolved to a concrete model yet. + SessionLimitPredictionUnavailableReasonAutoUnresolved SessionLimitPredictionUnavailableReason = "auto_unresolved" + // No model was provided and the session does not currently have a selected model. + SessionLimitPredictionUnavailableReasonNoModel SessionLimitPredictionUnavailableReason = "no_model" +) + // Log severity level. Determines how the message is displayed in the timeline. Defaults to // "info". // Experimental: SessionLogLevel is part of an experimental API and may change or be removed. @@ -12962,9 +14560,35 @@ const ( SessionWorkingDirectoryContextHostTypeGitHub SessionWorkingDirectoryContextHostType = "github" ) -// Signal to send (default: SIGTERM) -// Experimental: ShellKillSignal is part of an experimental API and may change or be removed. -type ShellKillSignal string +// Controls automatic non-interactive profile loading where supported. Explicit initScripts +// are unaffected. +// Experimental: ShellInitProfile is part of an experimental API and may change or be +// removed. +type ShellInitProfile string + +const ( + // Disable automatic non-interactive profile loading. Explicit initScripts still run. + ShellInitProfileNone ShellInitProfile = "none" + // Allow automatic non-interactive profile loading when supported. Explicit initScripts + // still run. + ShellInitProfileNonInteractive ShellInitProfile = "non-interactive" +) + +// Supported built-in shells for initialization scripts. +// Experimental: ShellInitScriptShell is part of an experimental API and may change or be +// removed. +type ShellInitScriptShell string + +const ( + // Source the script in the built-in Bash shell on macOS and Linux. + ShellInitScriptShellBash ShellInitScriptShell = "bash" + // Source the script in the built-in PowerShell shell on Windows. + ShellInitScriptShellPowershell ShellInitScriptShell = "powershell" +) + +// Signal to send (default: SIGTERM) +// Experimental: ShellKillSignal is part of an experimental API and may change or be removed. +type ShellKillSignal string const ( // Send an interrupt signal to the process. @@ -13783,6 +15407,25 @@ func (s *ServerMCPAPI) Config() *ServerMCPConfigAPI { // Experimental: ServerModelsAPI contains experimental APIs that may change or be removed. type ServerModelsAPI serverAPI +// GetBuiltInCatalog returns the running runtime's complete catalog of well-known built-in +// model IDs without authentication or network access. +// +// RPC method: models.getBuiltInCatalog. +// +// Returns: The running runtime's complete catalog of well-known built-in model IDs, +// including supported models and additional IDs with built-in metadata. +func (a *ServerModelsAPI) GetBuiltInCatalog(ctx context.Context) (*BuiltInModelCatalog, error) { + raw, err := a.client.Request(ctx, "models.getBuiltInCatalog", nil) + if err != nil { + return nil, err + } + var result BuiltInModelCatalog + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // Lists Copilot models available to the authenticated user. // // RPC method: models.list. @@ -14849,6 +16492,26 @@ func (a *InternalServerSessionsAPI) ConfigureSessionExtensions(ctx context.Conte return &result, nil } +// Deletes one local session from disk after running the same lifecycle hooks as the session +// manager. +// +// RPC method: sessions.delete. +// +// Parameters: Session ID to delete from disk. +// Internal: Delete is part of the SDK's internal handshake/plumbing; external callers +// should not use it. +func (a *InternalServerSessionsAPI) Delete(ctx context.Context, params *SessionsDeleteRequest) (*SessionsDeleteResult, error) { + raw, err := a.client.Request(ctx, "sessions.delete", params) + if err != nil { + return nil, err + } + var result SessionsDeleteResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // GetBoardEntryCount gets the dynamic-context board entry count associated with a session, // when available. Internal: this exists solely so CLI telemetry events (`rem_spawn_gate`, // `rem_consolidation_complete`) can pair START / END board counts around the detached @@ -14900,6 +16563,27 @@ func (a *InternalServerSessionsAPI) GetEventFilePath(ctx context.Context, params return &result, nil } +// GetMetadata reads lightweight persisted metadata for one local session without opening it. +// +// RPC method: sessions.getMetadata. +// +// Parameters: Session ID whose persisted metadata should be read. +// +// Returns: Persisted local session metadata when the session exists. +// Internal: GetMetadata is part of the SDK's internal handshake/plumbing; external callers +// should not use it. +func (a *InternalServerSessionsAPI) GetMetadata(ctx context.Context, params *SessionsGetMetadataRequest) (*SessionsGetMetadataResult, error) { + raw, err := a.client.Request(ctx, "sessions.getMetadata", params) + if err != nil { + return nil, err + } + var result SessionsGetMetadataResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // GetPersistedRemoteSteerable returns a session's persisted remote-steerable flag, if any // has been recorded. Internal: this is CLI-specific book-keeping used by `--continue` / // `--resume` to inherit the prior session's remote-steerable preference. SDK consumers that @@ -14926,6 +16610,28 @@ func (a *InternalServerSessionsAPI) GetPersistedRemoteSteerable(ctx context.Cont return &result, nil } +// ListNonEmptySessionIds lists recent local session IDs that contain user-visible history, +// omitting housekeeping-only sessions. +// +// RPC method: sessions.listNonEmptySessionIds. +// +// Parameters: Limit for non-empty local session IDs. +// +// Returns: Recent local session IDs that contain user-visible history. +// Internal: ListNonEmptySessionIds is part of the SDK's internal handshake/plumbing; +// external callers should not use it. +func (a *InternalServerSessionsAPI) ListNonEmptySessionIds(ctx context.Context, params *SessionsListNonEmptySessionIDsRequest) (*SessionsListNonEmptySessionIDsResult, error) { + raw, err := a.client.Request(ctx, "sessions.listNonEmptySessionIds", params) + if err != nil { + return nil, err + } + var result SessionsListNonEmptySessionIDsResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // RegisterExtensionToolsOnSession registers extension-provided tools on the given session, // gated by an optional `enabled` callback. Returns an opaque unsubscribe function the // caller must invoke to deregister the tools when the extension is torn down. Marked @@ -15041,13 +16747,28 @@ func (a *AgentAPI) GetCurrent(ctx context.Context) (*AgentGetCurrentResult, erro return &result, nil } -// Lists custom agents available to the session. +// Lists agents available to the session. Defaults to custom agents only; pass +// includeBuiltInAgents to include the effective built-in agents. // // RPC method: session.agent.list. // -// Returns: Custom agents available to the session. -func (a *AgentAPI) List(ctx context.Context) (*AgentList, error) { +// Parameters: Controls whether built-in agents and authored prompt text are included. +// +// Returns: Agents available to the session. +func (a *AgentAPI) List(ctx context.Context, params ...*SessionAgentListRequest) (*AgentList, error) { + var requestParams *SessionAgentListRequest + if len(params) > 0 { + requestParams = params[0] + } req := map[string]any{"sessionId": a.sessionID} + if requestParams != nil { + if requestParams.IncludeBuiltInAgents != nil { + req["includeBuiltInAgents"] = *requestParams.IncludeBuiltInAgents + } + if requestParams.IncludePrompt != nil { + req["includePrompt"] = *requestParams.IncludePrompt + } + } raw, err := a.client.Request(ctx, "session.agent.list", req) if err != nil { return nil, err @@ -15336,8 +17057,8 @@ func (a *CommandsAPI) Invoke(ctx context.Context, params *CommandsInvokeRequest) // // Returns: Slash commands available in the session, after applying any include/exclude // filters. -func (a *CommandsAPI) List(ctx context.Context, params ...*CommandsListRequest) (*CommandList, error) { - var requestParams *CommandsListRequest +func (a *CommandsAPI) List(ctx context.Context, params ...*SessionCommandsListRequest) (*CommandList, error) { + var requestParams *SessionCommandsListRequest if len(params) > 0 { requestParams = params[0] } @@ -15441,6 +17162,38 @@ func (a *CompletionsAPI) Request(ctx context.Context, params *CompletionsRequest return &result, nil } +// Experimental: ContentExclusionAPI contains experimental APIs that may change or be +// removed. +type ContentExclusionAPI sessionAPI + +// CheckPaths checks local file system absolute paths within the session working directory +// against its content-exclusion policy. Results preserve input order. Unsupported +// paths/filesystems and unavailable policy evaluation return available false, and callers +// must treat every requested path as excluded. +// +// RPC method: session.contentExclusion.checkPaths. +// +// Parameters: Local file system absolute paths within the session working directory to +// check against its content-exclusion policy. +// +// Returns: Batch content-exclusion result. Callers must fail closed when policy evaluation +// is unavailable. +func (a *ContentExclusionAPI) CheckPaths(ctx context.Context, params *ContentExclusionCheckPathsRequest) (*ContentExclusionCheckPathsResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["paths"] = params.Paths + } + raw, err := a.client.Request(ctx, "session.contentExclusion.checkPaths", req) + if err != nil { + return nil, err + } + var result ContentExclusionCheckPathsResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // Experimental: DebugAPI contains experimental APIs that may change or be removed. type DebugAPI sessionAPI @@ -15497,6 +17250,9 @@ func (a *EventLogAPI) Read(ctx context.Context, params *EventLogReadRequest) (*E if params.Cursor != nil { req["cursor"] = *params.Cursor } + if params.IncludeEphemeral != nil { + req["includeEphemeral"] = *params.IncludeEphemeral + } if params.Max != nil { req["max"] = *params.Max } @@ -15703,6 +17459,7 @@ type FactoryAPI sessionAPI func (a *FactoryAPI) Agent(ctx context.Context, params *FactoryAgentRequest) (*FactoryAgentResult, error) { req := map[string]any{"sessionId": a.sessionID} if params != nil { + req["executionToken"] = params.ExecutionToken req["factoryRunId"] = params.FactoryRunID req["opts"] = params.Opts req["prompt"] = params.Prompt @@ -15764,6 +17521,82 @@ func (a *FactoryAPI) GetRun(ctx context.Context, params *FactoryGetRunRequest) ( return &result, nil } +// GetRunDetail gets durable and live observability detail for one factory run. +// +// RPC method: session.factory.getRunDetail. +// +// Parameters: Parameters for retrieving a factory run. +// +// Returns: Full factory run observability detail. +func (a *FactoryAPI) GetRunDetail(ctx context.Context, params *FactoryGetRunRequest) (*FactoryRunDetail, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["runId"] = params.RunID + } + raw, err := a.client.Request(ctx, "session.factory.getRunDetail", req) + if err != nil { + return nil, err + } + var result FactoryRunDetail + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// GetRunProgress pages durable progress for one factory run. +// +// RPC method: session.factory.getRunProgress. +// +// Parameters: Parameters for paging factory progress. +// +// Returns: A bidirectional page of factory progress. +func (a *FactoryAPI) GetRunProgress(ctx context.Context, params *FactoryGetRunProgressRequest) (*FactoryProgressPage, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + if params.AfterSeq != nil { + req["afterSeq"] = *params.AfterSeq + } + if params.BeforeSeq != nil { + req["beforeSeq"] = *params.BeforeSeq + } + if params.Limit != nil { + req["limit"] = *params.Limit + } + if params.PhaseID != nil { + req["phaseId"] = *params.PhaseID + } + req["runId"] = params.RunID + } + raw, err := a.client.Request(ctx, "session.factory.getRunProgress", req) + if err != nil { + return nil, err + } + var result FactoryProgressPage + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// ListRuns lists durable factory runs for this session in creation order. +// +// RPC method: session.factory.listRuns. +// +// Returns: Factory runs in durable creation order. +func (a *FactoryAPI) ListRuns(ctx context.Context) (*FactoryListRunsResult, error) { + req := map[string]any{"sessionId": a.sessionID} + raw, err := a.client.Request(ctx, "session.factory.listRuns", req) + if err != nil { + return nil, err + } + var result FactoryListRunsResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // Log records a batch of ordered factory progress lines. // // RPC method: session.factory.log. @@ -15774,6 +17607,7 @@ func (a *FactoryAPI) GetRun(ctx context.Context, params *FactoryGetRunRequest) ( func (a *FactoryAPI) Log(ctx context.Context, params *FactoryLogRequest) (*FactoryAckResult, error) { req := map[string]any{"sessionId": a.sessionID} if params != nil { + req["executionToken"] = params.ExecutionToken req["lines"] = params.Lines req["runId"] = params.RunID } @@ -15788,6 +17622,32 @@ func (a *FactoryAPI) Log(ctx context.Context, params *FactoryLogRequest) (*Facto return &result, nil } +// Resumes a factory run using its persisted name, arguments, journal, and accounting. +// +// RPC method: session.factory.resume. +// +// Parameters: Parameters for resuming a factory run from its persisted identity. +// +// Returns: Resolved persisted factory identity and resumed run envelope. +func (a *FactoryAPI) Resume(ctx context.Context, params *FactoryResumeRequest) (*FactoryResumeResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + if params.Limits != nil { + req["limits"] = *params.Limits + } + req["runId"] = params.RunID + } + raw, err := a.client.Request(ctx, "session.factory.resume", req) + if err != nil { + return nil, err + } + var result FactoryResumeResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // Runs a registered factory by name at the top level. // // RPC method: session.factory.run. @@ -15828,6 +17688,7 @@ type FactoryJournalAPI sessionAPI func (a *FactoryJournalAPI) Get(ctx context.Context, params *FactoryJournalGetRequest) (*FactoryJournalGetResult, error) { req := map[string]any{"sessionId": a.sessionID} if params != nil { + req["executionToken"] = params.ExecutionToken req["key"] = params.Key req["runId"] = params.RunID } @@ -15852,6 +17713,7 @@ func (a *FactoryJournalAPI) Get(ctx context.Context, params *FactoryJournalGetRe func (a *FactoryJournalAPI) Put(ctx context.Context, params *FactoryJournalPutRequest) (*FactoryAckResult, error) { req := map[string]any{"sessionId": a.sessionID} if params != nil { + req["executionToken"] = params.ExecutionToken req["key"] = params.Key req["resultJson"] = params.ResultJSON req["runId"] = params.RunID @@ -15996,8 +17858,8 @@ func (a *HistoryAPI) CancelBackgroundCompaction(ctx context.Context) (*HistoryCa // // 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, params ...*HistoryCompactRequest) (*HistoryCompactResult, error) { - var requestParams *HistoryCompactRequest +func (a *HistoryAPI) Compact(ctx context.Context, params ...*SessionHistoryCompactRequest) (*HistoryCompactResult, error) { + var requestParams *SessionHistoryCompactRequest if len(params) > 0 { requestParams = params[0] } @@ -16006,6 +17868,12 @@ func (a *HistoryAPI) Compact(ctx context.Context, params ...*HistoryCompactReque if requestParams.CustomInstructions != nil { req["customInstructions"] = *requestParams.CustomInstructions } + if requestParams.TokenLimit != nil { + req["tokenLimit"] = *requestParams.TokenLimit + } + if requestParams.Trigger != nil { + req["trigger"] = *requestParams.Trigger + } } raw, err := a.client.Request(ctx, "session.history.compact", req) if err != nil { @@ -16018,6 +17886,84 @@ func (a *HistoryAPI) Compact(ctx context.Context, params ...*HistoryCompactReque return &result, nil } +// ListRewindPoints lists the user turns that the session can rewind to. Never rejects for a +// busy session: rewind reads need the session's file-change captures to be settled, so a +// session that still holds active work answers with `unavailableReason: "session-busy"` and +// no points, which the caller can retry. +// +// RPC method: session.history.listRewindPoints. +// +// Returns: Rewind points and file-change-tracking availability for the session. +func (a *HistoryAPI) ListRewindPoints(ctx context.Context) (*HistoryListRewindPointsResult, error) { + req := map[string]any{"sessionId": a.sessionID} + raw, err := a.client.Request(ctx, "session.history.listRewindPoints", req) + if err != nil { + return nil, err + } + var result HistoryListRewindPointsResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// PreviewRewind previews the files that a conversation-and-files rewind would restore. +// +// RPC method: session.history.previewRewind. +// +// Parameters: Event boundary to preview for conversation-and-files rewind. +// +// Returns: Files and aggregate changes for a prospective rewind. +func (a *HistoryAPI) PreviewRewind(ctx context.Context, params *HistoryPreviewRewindRequest) (*HistoryPreviewRewindResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["eventId"] = params.EventID + } + raw, err := a.client.Request(ctx, "session.history.previewRewind", req) + if err != nil { + return nil, err + } + var result HistoryPreviewRewindResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// Rewinds the session conversation, optionally restoring files changed by the discarded +// turns. Not crash-atomic: file restore and conversation truncation are separate stores, +// applied in that order, so a process crash between them can leave the workspace rewound +// while the conversation still contains the discarded turns. There is no recovery journal; +// re-running the same rewind is the recovery path for a crash before truncation lands, +// since file restore is idempotent (already-restored files are reported as skipped) and +// truncation is re-derived from the still-retained boundary event. After truncation lands +// that boundary no longer exists, so the same request is rejected; the only stage that can +// still be outstanding is snapshot pruning, whose failure leaves orphan snapshots the +// capture store tolerates. The reverse inconsistency cannot occur, because truncation is +// never applied before file restore succeeds. +// +// RPC method: session.history.rewind. +// +// Parameters: Boundary and mode for rewinding session history. +// +// Returns: Structured outcome of a rewind request. +func (a *HistoryAPI) Rewind(ctx context.Context, params *HistoryRewindRequest) (*HistoryRewindResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["eventId"] = params.EventID + req["mode"] = params.Mode + } + raw, err := a.client.Request(ctx, "session.history.rewind", req) + if err != nil { + return nil, err + } + var result HistoryRewindResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // SummarizeForHandoff produces a markdown summary of the session's conversation context for // hand-off scenarios. // @@ -16082,6 +18028,44 @@ func (a *InstructionsAPI) GetSources(ctx context.Context) (*InstructionsGetSourc return &result, nil } +// Experimental: LimitPredictionAPI contains experimental APIs that may change or be removed. +type LimitPredictionAPI sessionAPI + +// Predicts an AI-credit session limit for the session's resolved model. Returns an +// unavailable result instead of falling back when the current model is unresolved auto. +// +// RPC method: session.limitPrediction.predict. +// +// Parameters: Parameters for predicting an AI-credit session limit. Omitting `modelId` uses +// the session's currently selected model. +// +// Returns: Prediction result. Available results include prediction details; unavailable +// results include an explicit reason. +func (a *LimitPredictionAPI) Predict(ctx context.Context, params ...*SessionLimitPredictionPredictRequest) (SessionLimitPredictionResult, error) { + var requestParams *SessionLimitPredictionPredictRequest + if len(params) > 0 { + requestParams = params[0] + } + req := map[string]any{"sessionId": a.sessionID} + if requestParams != nil { + if requestParams.ClientType != nil { + req["clientType"] = *requestParams.ClientType + } + if requestParams.ModelID != nil { + req["modelId"] = *requestParams.ModelID + } + } + raw, err := a.client.Request(ctx, "session.limitPrediction.predict", req) + if err != nil { + return nil, err + } + result, err := unmarshalSessionLimitPredictionResult(raw) + if err != nil { + return nil, err + } + return result, nil +} + // Experimental: LspAPI contains experimental APIs that may change or be removed. type LspAPI sessionAPI @@ -16372,20 +18356,25 @@ func (a *MCPAPI) SetEnvValueMode(ctx context.Context, params *MCPSetEnvValueMode return &result, nil } -// StartServer starts an individual MCP server on the live session from a caller-supplied -// config. Session-scoped and ephemeral: the server is added to this session's running set -// only and is reaped when the session ends. Does NOT modify persistent user configuration -// (`mcp.config.*`), so it does not affect future sessions. The server surfaces through -// `session.mcp.list` and the `session.mcp_servers_loaded` / +// StartServer starts an individual MCP server on the live session. Omit `config` for a +// config-free start-by-name of an already-configured server (reuses the server's +// already-registered configuration); supply `config` to start from a caller-supplied +// configuration. Session-scoped and ephemeral: the server is added to this session's +// running set only and is reaped when the session ends. Does NOT modify persistent user +// configuration (`mcp.config.*`), so it does not affect future sessions. The server +// surfaces through `session.mcp.list` and the `session.mcp_servers_loaded` / // `session.mcp_server_status_changed` events like any other server. // // RPC method: session.mcp.startServer. // -// Parameters: Server name and configuration for an individual MCP server start. +// Parameters: Server name and optional configuration for an individual MCP server start. +// Omit `config` for a config-free start-by-name of an already-configured server. func (a *MCPAPI) StartServer(ctx context.Context, params *MCPStartServerRequest) (*SessionMCPStartServerResult, error) { req := map[string]any{"sessionId": a.sessionID} if params != nil { - req["config"] = params.Config + if params.Config != nil { + req["config"] = params.Config + } req["serverName"] = params.ServerName } raw, err := a.client.Request(ctx, "session.mcp.startServer", req) @@ -16683,6 +18672,29 @@ func (a *MCPOauthAPI) Login(ctx context.Context, params *MCPOauthLoginRequest) ( return &result, nil } +// Responds to a pending MCP OAuth authorization request by its request id. +// +// RPC method: session.mcp.oauth.respond. +// +// Parameters: Pending MCP OAuth request id to respond to. +// +// Returns: Indicates whether the pending MCP OAuth response was accepted. +func (a *MCPOauthAPI) Respond(ctx context.Context, params *MCPOauthRespondRequest) (*MCPOauthRespondResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["requestId"] = params.RequestID + } + raw, err := a.client.Request(ctx, "session.mcp.oauth.respond", req) + if err != nil { + return nil, err + } + var result MCPOauthRespondResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // Experimental: Oauth returns experimental APIs that may change or be removed. func (s *MCPAPI) Oauth() *MCPOauthAPI { return (*MCPOauthAPI)(s) @@ -17087,8 +19099,8 @@ func (a *ModelAPI) GetCurrent(ctx context.Context) (*CurrentModel, error) { // Parameters: Optional listing options. // // Returns: The list of models available to this session. -func (a *ModelAPI) List(ctx context.Context, params ...*ModelListRequest) (*SessionModelList, error) { - var requestParams *ModelListRequest +func (a *ModelAPI) List(ctx context.Context, params ...*SessionModelListRequest) (*SessionModelList, error) { + var requestParams *SessionModelListRequest if len(params) > 0 { requestParams = params[0] } @@ -17149,6 +19161,9 @@ func (a *ModelAPI) SwitchTo(ctx context.Context, params *ModelSwitchToRequest) ( if params.ContextTier != nil { req["contextTier"] = *params.ContextTier } + if params.DeferIfModelChangeQueued != nil { + req["deferIfModelChangeQueued"] = *params.DeferIfModelChangeQueued + } if params.ModelCapabilities != nil { req["modelCapabilities"] = *params.ModelCapabilities } @@ -17326,6 +19341,9 @@ func (a *OptionsAPI) Update(ctx context.Context, params *SessionUpdateOptionsPar if params.EventsLogDirectory != nil { req["eventsLogDirectory"] = *params.EventsLogDirectory } + if params.EventsLogIncludesSubagents != nil { + req["eventsLogIncludesSubagents"] = *params.EventsLogIncludesSubagents + } if params.ExcludedBuiltinAgents != nil { req["excludedBuiltinAgents"] = params.ExcludedBuiltinAgents } @@ -17389,6 +19407,9 @@ func (a *OptionsAPI) Update(ctx context.Context, params *SessionUpdateOptionsPar if params.SessionLimits != nil { req["sessionLimits"] = *params.SessionLimits } + if params.Shell != nil { + req["shell"] = *params.Shell + } if params.ShellInitProfile != nil { req["shellInitProfile"] = *params.ShellInitProfile } @@ -17601,9 +19622,17 @@ func (a *PermissionsAPI) PendingRequests(ctx context.Context) (*PendingPermissio // // RPC method: session.permissions.resetSessionApprovals. // +// Parameters: Clears session-scoped tool permission approvals, and optionally the +// location-scoped ones. +// // Returns: Indicates whether the operation succeeded. -func (a *PermissionsAPI) ResetSessionApprovals(ctx context.Context) (*PermissionsResetSessionApprovalsResult, error) { +func (a *PermissionsAPI) ResetSessionApprovals(ctx context.Context, params *PermissionsResetSessionApprovalsRequest) (*PermissionsResetSessionApprovalsResult, error) { req := map[string]any{"sessionId": a.sessionID} + if params != nil { + if params.IncludeLocation != nil { + req["includeLocation"] = *params.IncludeLocation + } + } raw, err := a.client.Request(ctx, "session.permissions.resetSessionApprovals", req) if err != nil { return nil, err @@ -18123,8 +20152,8 @@ func (a *PluginsAPI) List(ctx context.Context) (*PluginList, error) { // RPC method: session.plugins.reload. // // Parameters: Optional flags controlling which side effects the reload performs. -func (a *PluginsAPI) Reload(ctx context.Context, params ...*PluginsReloadRequest) (*SessionPluginsReloadResult, error) { - var requestParams *PluginsReloadRequest +func (a *PluginsAPI) Reload(ctx context.Context, params ...*SessionPluginsReloadRequest) (*SessionPluginsReloadResult, error) { + var requestParams *SessionPluginsReloadRequest if len(params) > 0 { requestParams = params[0] } @@ -18206,8 +20235,8 @@ func (a *ProviderAPI) Add(ctx context.Context, params *ProviderAddRequest) (*Pro // // Returns: A snapshot of the provider endpoint the session is currently configured to talk // to. -func (a *ProviderAPI) GetEndpoint(ctx context.Context, params ...*ProviderGetEndpointRequest) (*ProviderEndpoint, error) { - var requestParams *ProviderGetEndpointRequest +func (a *ProviderAPI) GetEndpoint(ctx context.Context, params ...*SessionProviderGetEndpointRequest) (*ProviderEndpoint, error) { + var requestParams *SessionProviderGetEndpointRequest if len(params) > 0 { requestParams = params[0] } @@ -18247,8 +20276,79 @@ func (a *QueueAPI) Clear(ctx context.Context) (*SessionQueueClearResult, error) return &result, nil } -// PendingItems returns the local session's pending user-facing queued items and steering -// messages. +// DuplicateAt duplicates an addressable queued item immediately after its source. +// +// RPC method: session.queue.duplicateAt. +// +// Parameters: Parameters for duplicating a queued item. +// +// Returns: Result of duplicating a queued item. +func (a *QueueAPI) DuplicateAt(ctx context.Context, params *QueueDuplicateAtRequest) (*QueueDuplicateAtResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["id"] = params.ID + } + raw, err := a.client.Request(ctx, "session.queue.duplicateAt", req) + if err != nil { + return nil, err + } + var result QueueDuplicateAtResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// InsertAt inserts a new queued message at a public visible position. +// +// RPC method: session.queue.insertAt. +// +// Parameters: Parameters for inserting a queued message at a public visible position. +// +// Returns: Result of inserting a queued message. +func (a *QueueAPI) InsertAt(ctx context.Context, params *QueueInsertAtRequest) (*QueueInsertAtResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["message"] = params.Message + req["position"] = params.Position + } + raw, err := a.client.Request(ctx, "session.queue.insertAt", req) + if err != nil { + return nil, err + } + var result QueueInsertAtResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// MoveItem moves an addressable queued item to a public visible position. +// +// RPC method: session.queue.moveItem. +// +// Parameters: Parameters for moving a queued item by stable id. +// +// Returns: Result of moving a queued item. +func (a *QueueAPI) MoveItem(ctx context.Context, params *QueueMoveItemRequest) (*QueueMoveItemResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["id"] = params.ID + req["toPosition"] = params.ToPosition + } + raw, err := a.client.Request(ctx, "session.queue.moveItem", req) + if err != nil { + return nil, err + } + var result QueueMoveItemResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// PendingItems returns the local session's pending user-facing queued items and steering +// messages. // // RPC method: session.queue.pendingItems. // @@ -18266,6 +20366,29 @@ func (a *QueueAPI) PendingItems(ctx context.Context) (*QueuePendingItemsResult, return &result, nil } +// RemoveAt removes an addressable queued item by its stable id. +// +// RPC method: session.queue.removeAt. +// +// Parameters: Parameters for removing a queued item by stable id. +// +// Returns: Result of removing a queued item. +func (a *QueueAPI) RemoveAt(ctx context.Context, params *QueueRemoveAtRequest) (*QueueRemoveAtResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["id"] = params.ID + } + raw, err := a.client.Request(ctx, "session.queue.removeAt", req) + if err != nil { + return nil, err + } + var result QueueRemoveAtResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // RemoveMostRecent removes the most recently queued user-facing item (LIFO). // // RPC method: session.queue.removeMostRecent. @@ -18284,6 +20407,82 @@ func (a *QueueAPI) RemoveMostRecent(ctx context.Context) (*QueueRemoveMostRecent return &result, nil } +// SendNow moves an addressable queued message into the live turn's steering lane. +// +// RPC method: session.queue.sendNow. +// +// Parameters: Parameters for steering a queued message into a live turn. +// +// Returns: Result of trying to steer a queued message into a live turn. +func (a *QueueAPI) SendNow(ctx context.Context, params *QueueSendNowRequest) (*QueueSendNowResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["id"] = params.ID + } + raw, err := a.client.Request(ctx, "session.queue.sendNow", req) + if err != nil { + return nil, err + } + var result QueueSendNowResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// SetDrainPaused acquires or releases the queued-lane drain pause. +// +// RPC method: session.queue.setDrainPaused. +// +// Parameters: Parameters for acquiring or releasing the queued-lane drain pause. +// Acquisition is exclusive and non-idempotent: `paused: true` against an already-paused +// session fails with `queue_already_paused`. The pause is never released automatically — it +// is not tied to the caller's lifetime, so a client that exits without sending `paused: +// false` leaves the lane frozen. Release is unowned: `paused: false` clears the pause for +// any caller, including one that never acquired it. +func (a *QueueAPI) SetDrainPaused(ctx context.Context, params *QueueSetDrainPausedRequest) (*SessionQueueSetDrainPausedResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["paused"] = params.Paused + } + raw, err := a.client.Request(ctx, "session.queue.setDrainPaused", req) + if err != nil { + return nil, err + } + var result SessionQueueSetDrainPausedResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// UpdateText updates the text of an addressable single-message queue item. +// +// RPC method: session.queue.updateText. +// +// Parameters: Parameters for editing a single queued message. +// +// Returns: Result of editing a queued message. +func (a *QueueAPI) UpdateText(ctx context.Context, params *QueueUpdateTextRequest) (*QueueUpdateTextResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + if params.DisplayPrompt != nil { + req["displayPrompt"] = *params.DisplayPrompt + } + req["id"] = params.ID + req["prompt"] = params.Prompt + } + raw, err := a.client.Request(ctx, "session.queue.updateText", req) + if err != nil { + return nil, err + } + var result QueueUpdateTextResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // Experimental: RemoteAPI contains experimental APIs that may change or be removed. type RemoteAPI sessionAPI @@ -18428,7 +20627,14 @@ func (a *ShellAPI) CancelUserRequested(ctx context.Context, params *ShellCancelU return &result, nil } -// Exec starts a shell command and streams output through session notifications. +// Exec starts a shell command and streams output through session notifications. The command +// runs as the leader of its own process group (POSIX) or in a dedicated job object +// (Windows), so a forced termination — via "shell.kill", the request timeout, or session +// disposal — signals that whole group/job rather than only the direct child. Two gaps are +// worth planning for: a command that exits on its own does not trigger that teardown, and +// on POSIX a descendant that moves itself into a new session or process group (for example +// via "setsid") leaves the signalled group, so either can leave a background process +// running. // // RPC method: session.shell.exec. // @@ -18483,7 +20689,11 @@ func (a *ShellAPI) ExecuteUserRequested(ctx context.Context, params *ShellExecut return &result, nil } -// Kill sends a signal to a shell process previously started via "shell.exec". +// Kill sends a signal to a shell process previously started via "shell.exec". The signal +// targets the command's whole process group (POSIX) or job object (Windows), so descendants +// still in that group are signalled too, not just the direct child. On POSIX a descendant +// that moved itself into a new session or process group (for example via "setsid") is no +// longer in the signalled group and survives. // // RPC method: session.shell.kill. // @@ -19366,6 +21576,49 @@ func (a *VisibilityAPI) Set(ctx context.Context, params *VisibilitySetRequest) ( // Experimental: WorkspacesAPI contains experimental APIs that may change or be removed. type WorkspacesAPI sessionAPI +// AddSummary adds a compaction summary checkpoint to the local session workspace. +// +// RPC method: session.workspaces.addSummary. +// +// Parameters: Compaction summary checkpoint to persist. +// +// Returns: Persisted summary metadata and refreshed workspace metadata. +func (a *WorkspacesAPI) AddSummary(ctx context.Context, params *WorkspacesAddSummaryRequest) (*WorkspacesAddSummaryResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["content"] = params.Content + req["title"] = params.Title + } + raw, err := a.client.Request(ctx, "session.workspaces.addSummary", req) + if err != nil { + return nil, err + } + var result WorkspacesAddSummaryResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// AutopilotObjectiveExists checks whether the local session workspace has an autopilot +// objective state file. +// +// RPC method: session.workspaces.autopilotObjectiveExists. +// +// Returns: Whether the autopilot objective file exists. +func (a *WorkspacesAPI) AutopilotObjectiveExists(ctx context.Context) (*WorkspacesAutopilotObjectiveExistsResult, error) { + req := map[string]any{"sessionId": a.sessionID} + raw, err := a.client.Request(ctx, "session.workspaces.autopilotObjectiveExists", req) + if err != nil { + return nil, err + } + var result WorkspacesAutopilotObjectiveExistsResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // CreateFile creates or overwrites a file in the session workspace files directory. // // RPC method: session.workspaces.createFile. @@ -19388,7 +21641,28 @@ func (a *WorkspacesAPI) CreateFile(ctx context.Context, params *WorkspacesCreate return &result, nil } -// Diff computes a diff for the session workspace. +// DeleteAutopilotObjective deletes the autopilot objective state file from the local +// session workspace. +// +// RPC method: session.workspaces.deleteAutopilotObjective. +// +// Returns: Result of deleting the autopilot objective file. +func (a *WorkspacesAPI) DeleteAutopilotObjective(ctx context.Context) (*WorkspacesDeleteAutopilotObjectiveResult, error) { + req := map[string]any{"sessionId": a.sessionID} + raw, err := a.client.Request(ctx, "session.workspaces.deleteAutopilotObjective", req) + if err != nil { + return nil, err + } + var result WorkspacesDeleteAutopilotObjectiveResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// Diff computes a diff for the session workspace. Never rejects for a busy session: a +// `session`-mode diff that cannot read the session's file-change captures falls back to an +// unstaged git diff with `isFallback: true` and reports why in `unavailableReason`. // // RPC method: session.workspaces.diff. // @@ -19414,6 +21688,32 @@ func (a *WorkspacesAPI) Diff(ctx context.Context, params *WorkspacesDiffRequest) return &result, nil } +// Ensures a local session workspace exists and returns it. +// +// RPC method: session.workspaces.ensure. +// +// Parameters: Optional session context used when creating a local workspace. +// +// Returns: Current workspace metadata for the session, including its absolute filesystem +// path when available. +func (a *WorkspacesAPI) Ensure(ctx context.Context, params *WorkspacesEnsureRequest) (*WorkspacesGetWorkspaceResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + if params.Context != nil { + req["context"] = params.Context + } + } + raw, err := a.client.Request(ctx, "session.workspaces.ensure", req) + if err != nil { + return nil, err + } + var result WorkspacesGetWorkspaceResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // GetWorkspace gets current workspace metadata for the session. // // RPC method: session.workspaces.getWorkspace. @@ -19470,6 +21770,25 @@ func (a *WorkspacesAPI) ListFiles(ctx context.Context) (*WorkspacesListFilesResu return &result, nil } +// ReadAutopilotObjective reads the autopilot objective state file from the local session +// workspace. +// +// RPC method: session.workspaces.readAutopilotObjective. +// +// Returns: Autopilot objective file content, or null when missing. +func (a *WorkspacesAPI) ReadAutopilotObjective(ctx context.Context) (*WorkspacesReadAutopilotObjectiveResult, error) { + req := map[string]any{"sessionId": a.sessionID} + raw, err := a.client.Request(ctx, "session.workspaces.readAutopilotObjective", req) + if err != nil { + return nil, err + } + var result WorkspacesReadAutopilotObjectiveResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // ReadCheckpoint reads the content of a workspace checkpoint by number. // // RPC method: session.workspaces.readCheckpoint. @@ -19540,46 +21859,126 @@ func (a *WorkspacesAPI) SaveLargePaste(ctx context.Context, params *WorkspacesSa return &result, nil } +// TruncateSummaries truncates local workspace compaction summaries after a rollback. +// +// RPC method: session.workspaces.truncateSummaries. +// +// Parameters: Rollback point for local workspace summaries. +// +// Returns: Current workspace metadata for the session, including its absolute filesystem +// path when available. +func (a *WorkspacesAPI) TruncateSummaries(ctx context.Context, params *WorkspacesTruncateSummariesRequest) (*WorkspacesGetWorkspaceResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["keepCount"] = params.KeepCount + } + raw, err := a.client.Request(ctx, "session.workspaces.truncateSummaries", req) + if err != nil { + return nil, err + } + var result WorkspacesGetWorkspaceResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// UpdateMetadata updates workspace metadata for a local session and returns the refreshed +// workspace. +// +// RPC method: session.workspaces.updateMetadata. +// +// Parameters: Workspace metadata fields to update. +// +// Returns: Current workspace metadata for the session, including its absolute filesystem +// path when available. +func (a *WorkspacesAPI) UpdateMetadata(ctx context.Context, params *WorkspacesUpdateMetadataRequest) (*WorkspacesGetWorkspaceResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + if params.Context != nil { + req["context"] = params.Context + } + if params.Name != nil { + req["name"] = *params.Name + } + } + raw, err := a.client.Request(ctx, "session.workspaces.updateMetadata", req) + if err != nil { + return nil, err + } + var result WorkspacesGetWorkspaceResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// WriteAutopilotObjective writes the autopilot objective state file in the local session +// workspace. +// +// RPC method: session.workspaces.writeAutopilotObjective. +// +// Parameters: Autopilot objective file content to persist. +// +// Returns: Result of writing the autopilot objective file. +func (a *WorkspacesAPI) WriteAutopilotObjective(ctx context.Context, params *WorkspacesWriteAutopilotObjectiveRequest) (*WorkspacesWriteAutopilotObjectiveResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["content"] = params.Content + } + raw, err := a.client.Request(ctx, "session.workspaces.writeAutopilotObjective", req) + if err != nil { + return nil, err + } + var result WorkspacesWriteAutopilotObjectiveResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // SessionRPC provides typed session-scoped RPC methods. type SessionRPC struct { // Reuse a single struct instead of allocating one for each service on the heap. common sessionAPI - Agent *AgentAPI - Canvas *CanvasAPI - Commands *CommandsAPI - Completions *CompletionsAPI - Debug *DebugAPI - EventLog *EventLogAPI - Extensions *ExtensionsAPI - Factory *FactoryAPI - Fleet *FleetAPI - GitHubAuth *GitHubAuthAPI - History *HistoryAPI - Instructions *InstructionsAPI - Lsp *LspAPI - MCP *MCPAPI - Metadata *MetadataAPI - Mode *ModeAPI - Model *ModelAPI - Name *NameAPI - Options *OptionsAPI - Permissions *PermissionsAPI - Plan *PlanAPI - Plugins *PluginsAPI - Provider *ProviderAPI - Queue *QueueAPI - Remote *RemoteAPI - Schedule *ScheduleAPI - Shell *ShellAPI - Skills *SkillsAPI - Tasks *TasksAPI - Telemetry *TelemetryAPI - Tools *ToolsAPI - UI *UIAPI - Usage *UsageAPI - Visibility *VisibilityAPI - Workspaces *WorkspacesAPI + Agent *AgentAPI + Canvas *CanvasAPI + Commands *CommandsAPI + Completions *CompletionsAPI + ContentExclusion *ContentExclusionAPI + Debug *DebugAPI + EventLog *EventLogAPI + Extensions *ExtensionsAPI + Factory *FactoryAPI + Fleet *FleetAPI + GitHubAuth *GitHubAuthAPI + History *HistoryAPI + Instructions *InstructionsAPI + LimitPrediction *LimitPredictionAPI + Lsp *LspAPI + MCP *MCPAPI + Metadata *MetadataAPI + Mode *ModeAPI + Model *ModelAPI + Name *NameAPI + Options *OptionsAPI + Permissions *PermissionsAPI + Plan *PlanAPI + Plugins *PluginsAPI + Provider *ProviderAPI + Queue *QueueAPI + Remote *RemoteAPI + Schedule *ScheduleAPI + Shell *ShellAPI + Skills *SkillsAPI + Tasks *TasksAPI + Telemetry *TelemetryAPI + Tools *ToolsAPI + UI *UIAPI + Usage *UsageAPI + Visibility *VisibilityAPI + Workspaces *WorkspacesAPI } // Aborts the current agent turn. @@ -19609,23 +22008,75 @@ func (a *SessionRPC) Abort(ctx context.Context, params *AbortRequest) (*AbortRes return &result, nil } -// Log emits a user-visible session log event. -// -// RPC method: session.log. +// CancelAllBackgroundAgents cancels every running background agent (task-registry subagents +// plus sidekick agents) without interrupting the main agent loop. Promoted attached shells +// are left running. // -// Parameters: Message text, optional severity level, persistence flag, optional follow-up -// URL, and optional tip. +// RPC method: session.cancelAllBackgroundAgents. // -// Returns: Identifier of the session event that was emitted for the log message. -// Experimental: Log is an experimental API and may change or be removed in future versions. -func (a *SessionRPC) Log(ctx context.Context, params *LogRequest) (*LogResult, error) { +// Returns: The number of running background agents (task-registry agents) that were +// cancelled. +// Experimental: CancelAllBackgroundAgents is an experimental API and may change or be +// removed in future versions. +func (a *SessionRPC) CancelAllBackgroundAgents(ctx context.Context) (*SessionCancelAllBackgroundAgentsResult, error) { req := map[string]any{"sessionId": a.common.sessionID} - if params != nil { - if params.Ephemeral != nil { - req["ephemeral"] = *params.Ephemeral - } - if params.Level != nil { - req["level"] = *params.Level + raw, err := a.common.client.Request(ctx, "session.cancelAllBackgroundAgents", req) + if err != nil { + return nil, err + } + var result SessionCancelAllBackgroundAgentsResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// InterruptMainTurn interrupts the current main agent turn while leaving running background +// work (subagents, sidekicks, and promoted attached shells) alive. No-op when the main loop +// is not processing. +// +// RPC method: session.interruptMainTurn. +// +// Parameters: Parameters for interrupting the main agent turn. +// +// Returns: Result of interrupting the main agent turn. +// Experimental: InterruptMainTurn is an experimental API and may change or be removed in +// future versions. +func (a *SessionRPC) InterruptMainTurn(ctx context.Context, params *InterruptMainTurnRequest) (*InterruptMainTurnResult, error) { + req := map[string]any{"sessionId": a.common.sessionID} + if params != nil { + if params.FlushQueued != nil { + req["flushQueued"] = *params.FlushQueued + } + } + raw, err := a.common.client.Request(ctx, "session.interruptMainTurn", req) + if err != nil { + return nil, err + } + var result InterruptMainTurnResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// Log emits a user-visible session log event. +// +// RPC method: session.log. +// +// Parameters: Message text, optional severity level, persistence flag, optional follow-up +// URL, and optional tip. +// +// Returns: Identifier of the session event that was emitted for the log message. +// Experimental: Log is an experimental API and may change or be removed in future versions. +func (a *SessionRPC) Log(ctx context.Context, params *LogRequest) (*LogResult, error) { + req := map[string]any{"sessionId": a.common.sessionID} + if params != nil { + if params.Ephemeral != nil { + req["ephemeral"] = *params.Ephemeral + } + if params.Level != nil { + req["level"] = *params.Level } req["message"] = params.Message if params.Tip != nil { @@ -19816,6 +22267,7 @@ func NewSessionRPC(client *jsonrpc2.Client, sessionID string) *SessionRPC { r.Canvas = (*CanvasAPI)(&r.common) r.Commands = (*CommandsAPI)(&r.common) r.Completions = (*CompletionsAPI)(&r.common) + r.ContentExclusion = (*ContentExclusionAPI)(&r.common) r.Debug = (*DebugAPI)(&r.common) r.EventLog = (*EventLogAPI)(&r.common) r.Extensions = (*ExtensionsAPI)(&r.common) @@ -19824,6 +22276,7 @@ func NewSessionRPC(client *jsonrpc2.Client, sessionID string) *SessionRPC { r.GitHubAuth = (*GitHubAuthAPI)(&r.common) r.History = (*HistoryAPI)(&r.common) r.Instructions = (*InstructionsAPI)(&r.common) + r.LimitPrediction = (*LimitPredictionAPI)(&r.common) r.Lsp = (*LspAPI)(&r.common) r.MCP = (*MCPAPI)(&r.common) r.Metadata = (*MetadataAPI)(&r.common) @@ -19969,6 +22422,385 @@ func (a *InternalMCPAPI) UnregisterExternalClient(ctx context.Context, params *M return &result, nil } +// Experimental: InternalQueueAPI contains experimental APIs that may change or be removed. +type InternalQueueAPI internalSessionAPI + +// BeginDeferredIdleDrain begins a native deferred-idle drain when background work has +// quiesced. +// +// RPC method: session.queue.beginDeferredIdleDrain. +// +// Parameters: Inputs for starting a deferred-idle drain. +// +// Returns: Whether a deferred-idle drain should run. +// Internal: BeginDeferredIdleDrain is part of the SDK's internal handshake/plumbing; +// external callers should not use it. +func (a *InternalQueueAPI) BeginDeferredIdleDrain(ctx context.Context, params *QueueBeginDeferredIdleDrainRequest) (*QueueBeginDeferredIdleDrainResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["activeBackgroundWork"] = params.ActiveBackgroundWork + } + raw, err := a.client.Request(ctx, "session.queue.beginDeferredIdleDrain", req) + if err != nil { + return nil, err + } + var result QueueBeginDeferredIdleDrainResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// ConsumeSystemNotifications consumes queued native system notifications matching an +// internal filter. +// +// RPC method: session.queue.consumeSystemNotifications. +// +// Parameters: Internal filter for consuming queued system notifications. +// +// Returns: Indicates whether a user-facing pending item was removed. +// Internal: ConsumeSystemNotifications is part of the SDK's internal handshake/plumbing; +// external callers should not use it. +func (a *InternalQueueAPI) ConsumeSystemNotifications(ctx context.Context, params *QueueConsumeSystemNotificationsRequest) (*QueueRemoveMostRecentResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["filter"] = params.Filter + } + raw, err := a.client.Request(ctx, "session.queue.consumeSystemNotifications", req) + if err != nil { + return nil, err + } + var result QueueRemoveMostRecentResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// DeferSessionIdle marks session.idle as deferred by native background work state. +// +// RPC method: session.queue.deferSessionIdle. +// +// Parameters: Inputs for marking session.idle deferred in native state. +// Internal: DeferSessionIdle is part of the SDK's internal handshake/plumbing; external +// callers should not use it. +func (a *InternalQueueAPI) DeferSessionIdle(ctx context.Context, params *QueueDeferSessionIdleRequest) (*SessionQueueDeferSessionIdleResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["aborted"] = params.Aborted + } + raw, err := a.client.Request(ctx, "session.queue.deferSessionIdle", req) + if err != nil { + return nil, err + } + var result SessionQueueDeferSessionIdleResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// EnqueueResumePending enqueues the internal resume-pending wake item when orphan handling +// needs a follow-up turn. +// +// RPC method: session.queue.enqueueResumePending. +// +// Returns: Result of enqueueing the resume-pending wake item. +// Internal: EnqueueResumePending is part of the SDK's internal handshake/plumbing; external +// callers should not use it. +func (a *InternalQueueAPI) EnqueueResumePending(ctx context.Context) (*QueueEnqueueResumePendingResult, error) { + req := map[string]any{"sessionId": a.sessionID} + raw, err := a.client.Request(ctx, "session.queue.enqueueResumePending", req) + if err != nil { + return nil, err + } + var result QueueEnqueueResumePendingResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// FinishDeferredIdleDrain finishes a native deferred-idle drain and reports whether to +// drain queue work or emit idle. +// +// RPC method: session.queue.finishDeferredIdleDrain. +// +// Parameters: Inputs for completing a deferred-idle drain. +// +// Returns: Action selected by the native deferred-idle drain. +// Internal: FinishDeferredIdleDrain is part of the SDK's internal handshake/plumbing; +// external callers should not use it. +func (a *InternalQueueAPI) FinishDeferredIdleDrain(ctx context.Context, params *QueueFinishDeferredIdleDrainRequest) (*QueueFinishDeferredIdleDrainResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["activeBackgroundWork"] = params.ActiveBackgroundWork + req["hasPending"] = params.HasPending + } + raw, err := a.client.Request(ctx, "session.queue.finishDeferredIdleDrain", req) + if err != nil { + return nil, err + } + var result QueueFinishDeferredIdleDrainResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// HasPending reports whether the local session has native queued work pending. +// +// RPC method: session.queue.hasPending. +// +// Returns: Whether the native queue has pending work. +// Internal: HasPending is part of the SDK's internal handshake/plumbing; external callers +// should not use it. +func (a *InternalQueueAPI) HasPending(ctx context.Context) (*QueueHasPendingResult, error) { + req := map[string]any{"sessionId": a.sessionID} + raw, err := a.client.Request(ctx, "session.queue.hasPending", req) + if err != nil { + return nil, err + } + var result QueueHasPendingResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// Process drains the native local-session work queue for in-process session orchestration. +// +// RPC method: session.queue.process. +// Internal: Process is part of the SDK's internal handshake/plumbing; external callers +// should not use it. +func (a *InternalQueueAPI) Process(ctx context.Context) (*SessionQueueProcessResult, error) { + req := map[string]any{"sessionId": a.sessionID} + raw, err := a.client.Request(ctx, "session.queue.process", req) + if err != nil { + return nil, err + } + var result SessionQueueProcessResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// Snapshot returns the internal native queue snapshot for in-process session orchestration. +// +// RPC method: session.queue.snapshot. +// +// Returns: Internal snapshot of native queue state for local session orchestration. +// Internal: Snapshot is part of the SDK's internal handshake/plumbing; external callers +// should not use it. +func (a *InternalQueueAPI) Snapshot(ctx context.Context) (*QueueSnapshotResult, error) { + req := map[string]any{"sessionId": a.sessionID} + raw, err := a.client.Request(ctx, "session.queue.snapshot", req) + if err != nil { + return nil, err + } + var result QueueSnapshotResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// Experimental: InternalScheduleAPI contains experimental APIs that may change or be +// removed. +type InternalScheduleAPI internalSessionAPI + +// Add registers a relative-interval scheduled prompt. +// +// RPC method: session.schedule.add. +// +// Parameters: Register a relative-interval scheduled prompt. +// +// Returns: Result of registering or re-arming a scheduled prompt. +// Internal: Add is part of the SDK's internal handshake/plumbing; external callers should +// not use it. +func (a *InternalScheduleAPI) Add(ctx context.Context, params *ScheduleAddRequest) (*ScheduleAddResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + if params.DisplayPrompt != nil { + req["displayPrompt"] = *params.DisplayPrompt + } + req["interval"] = params.Interval + req["prompt"] = params.Prompt + if params.Recurring != nil { + req["recurring"] = *params.Recurring + } + } + raw, err := a.client.Request(ctx, "session.schedule.add", req) + if err != nil { + return nil, err + } + var result ScheduleAddResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// AddAt registers an absolute-time scheduled prompt. +// +// RPC method: session.schedule.addAt. +// +// Parameters: Register an absolute-time scheduled prompt. +// +// Returns: Result of registering or re-arming a scheduled prompt. +// Internal: AddAt is part of the SDK's internal handshake/plumbing; external callers should +// not use it. +func (a *InternalScheduleAPI) AddAt(ctx context.Context, params *ScheduleAddAtRequest) (*ScheduleAddResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["at"] = params.At + if params.DisplayPrompt != nil { + req["displayPrompt"] = *params.DisplayPrompt + } + req["prompt"] = params.Prompt + if params.Recurring != nil { + req["recurring"] = *params.Recurring + } + } + raw, err := a.client.Request(ctx, "session.schedule.addAt", req) + if err != nil { + return nil, err + } + var result ScheduleAddResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// AddCron registers a recurring cron scheduled prompt. +// +// RPC method: session.schedule.addCron. +// +// Parameters: Register a cron scheduled prompt. +// +// Returns: Result of registering or re-arming a scheduled prompt. +// Internal: AddCron is part of the SDK's internal handshake/plumbing; external callers +// should not use it. +func (a *InternalScheduleAPI) AddCron(ctx context.Context, params *ScheduleAddCronRequest) (*ScheduleAddResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["cron"] = params.Cron + if params.DisplayPrompt != nil { + req["displayPrompt"] = *params.DisplayPrompt + } + req["prompt"] = params.Prompt + if params.Recurring != nil { + req["recurring"] = *params.Recurring + } + if params.Tz != nil { + req["tz"] = *params.Tz + } + } + raw, err := a.client.Request(ctx, "session.schedule.addCron", req) + if err != nil { + return nil, err + } + var result ScheduleAddResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// AddSelfPaced registers a self-paced scheduled prompt. +// +// RPC method: session.schedule.addSelfPaced. +// +// Parameters: Register a self-paced scheduled prompt. +// +// Returns: Result of registering or re-arming a scheduled prompt. +// Internal: AddSelfPaced is part of the SDK's internal handshake/plumbing; external callers +// should not use it. +func (a *InternalScheduleAPI) AddSelfPaced(ctx context.Context, params *ScheduleAddSelfPacedRequest) (*ScheduleAddResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + if params.DisplayPrompt != nil { + req["displayPrompt"] = *params.DisplayPrompt + } + req["prompt"] = params.Prompt + } + raw, err := a.client.Request(ctx, "session.schedule.addSelfPaced", req) + if err != nil { + return nil, err + } + var result ScheduleAddResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// HasSelfPaced reports whether the session has an active self-paced scheduled prompt. +// +// RPC method: session.schedule.hasSelfPaced. +// +// Returns: Whether the session currently has an active self-paced schedule. +// Internal: HasSelfPaced is part of the SDK's internal handshake/plumbing; external callers +// should not use it. +func (a *InternalScheduleAPI) HasSelfPaced(ctx context.Context) (*ScheduleHasSelfPacedResult, error) { + req := map[string]any{"sessionId": a.sessionID} + raw, err := a.client.Request(ctx, "session.schedule.hasSelfPaced", req) + if err != nil { + return nil, err + } + var result ScheduleHasSelfPacedResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// Hydrates the native schedule registry from persisted session events. +// +// RPC method: session.schedule.hydrate. +// Internal: Hydrate is part of the SDK's internal handshake/plumbing; external callers +// should not use it. +func (a *InternalScheduleAPI) Hydrate(ctx context.Context) (*SessionScheduleHydrateResult, error) { + req := map[string]any{"sessionId": a.sessionID} + raw, err := a.client.Request(ctx, "session.schedule.hydrate", req) + if err != nil { + return nil, err + } + var result SessionScheduleHydrateResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// RearmSelfPaced re-arms an active self-paced scheduled prompt. +// +// RPC method: session.schedule.rearmSelfPaced. +// +// Parameters: Re-arm a self-paced scheduled prompt. +// +// Returns: Result of registering or re-arming a scheduled prompt. +// Internal: RearmSelfPaced is part of the SDK's internal handshake/plumbing; external +// callers should not use it. +func (a *InternalScheduleAPI) RearmSelfPaced(ctx context.Context, params *ScheduleRearmSelfPacedRequest) (*ScheduleAddResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["at"] = params.At + req["id"] = params.ID + } + raw, err := a.client.Request(ctx, "session.schedule.rearmSelfPaced", req) + if err != nil { + return nil, err + } + var result ScheduleAddResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + // Experimental: InternalSettingsAPI contains experimental APIs that may change or be // removed. type InternalSettingsAPI internalSessionAPI @@ -20036,13 +22868,49 @@ type InternalSessionRPC struct { common internalSessionAPI MCP *InternalMCPAPI + Queue *InternalQueueAPI + Schedule *InternalScheduleAPI Settings *InternalSettingsAPI } +// SendSystemNotification queues or sends an internal system notification to the session +// according to its passive policy. +// +// RPC method: session.sendSystemNotification. +// +// Parameters: Internal request for sending a system notification. +// Experimental: SendSystemNotification is an experimental API and may change or be removed +// in future versions. +// Internal: SendSystemNotification is part of the SDK's internal handshake/plumbing; +// external callers should not use it. +func (a *InternalSessionRPC) SendSystemNotification(ctx context.Context, params *SendSystemNotificationRequest) (*SessionSendSystemNotificationResult, error) { + req := map[string]any{"sessionId": a.common.sessionID} + if params != nil { + if params.Kind != nil { + req["kind"] = params.Kind + } + req["message"] = params.Message + if params.Options != nil { + req["options"] = params.Options + } + } + raw, err := a.common.client.Request(ctx, "session.sendSystemNotification", req) + if err != nil { + return nil, err + } + var result SessionSendSystemNotificationResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + func NewInternalSessionRPC(client *jsonrpc2.Client, sessionID string) *InternalSessionRPC { r := &InternalSessionRPC{} r.common = internalSessionAPI{client: client, sessionID: sessionID} r.MCP = (*InternalMCPAPI)(&r.common) + r.Queue = (*InternalQueueAPI)(&r.common) + r.Schedule = (*InternalScheduleAPI)(&r.common) r.Settings = (*InternalSettingsAPI)(&r.common) return r } @@ -20202,16 +23070,27 @@ type SessionFSHandler interface { // // Returns: Indicates whether the per-session SQLite database already exists. SqliteExists(request *SessionFSSqliteExistsRequest) (*SessionFSSqliteExistsResult, error) - // SqliteQuery executes a SQLite query against the per-session database. + // SqliteQuery executes a SQLite query against the per-session database. Providers apply + // busy handling for every call. // // RPC method: sessionFs.sqliteQuery. // // Parameters: SQL query, query type, and optional bind parameters for executing a SQLite - // query against the per-session database. + // query against the per-session database. The provider applies its SQLite busy timeout for + // every call. // // Returns: Query results including rows, columns, and rows affected, or a filesystem error // if execution failed. SqliteQuery(request *SessionFSSqliteQueryRequest) (*SessionFSSqliteQueryResult, error) + // SqliteTransaction executes SQLite statements atomically on the provider-owned connection. + // + // RPC method: sessionFs.sqliteTransaction. + // + // Parameters: Statements to execute atomically. Providers apply busy handling for every + // call. + // + // Returns: Per-statement results, or a classified transaction error. + SqliteTransaction(request *SessionFSSqliteTransactionRequest) (*SessionFSSqliteTransactionResult, error) // Stat gets metadata for a path in the client-provided session filesystem. // // RPC method: sessionFs.stat. @@ -20559,6 +23438,25 @@ func RegisterClientSessionAPIHandlers(client *jsonrpc2.Client, getHandlers func( } return raw, nil }) + client.SetRequestHandler("sessionFs.sqliteTransaction", func(params json.RawMessage) (json.RawMessage, *jsonrpc2.Error) { + var request SessionFSSqliteTransactionRequest + if err := json.Unmarshal(params, &request); err != nil { + return nil, &jsonrpc2.Error{Code: -32602, Message: fmt.Sprintf("Invalid params: %v", err)} + } + handlers := getHandlers(request.SessionID) + if handlers == nil || handlers.SessionFS == nil { + return nil, &jsonrpc2.Error{Code: -32603, Message: fmt.Sprintf("No sessionFs handler registered for session: %s", request.SessionID)} + } + result, err := handlers.SessionFS.SqliteTransaction(&request) + if err != nil { + return nil, clientSessionHandlerError(err) + } + raw, err := json.Marshal(result) + if err != nil { + return nil, &jsonrpc2.Error{Code: -32603, Message: fmt.Sprintf("Failed to marshal response: %v", err)} + } + return raw, nil + }) client.SetRequestHandler("sessionFs.stat", func(params json.RawMessage) (json.RawMessage, *jsonrpc2.Error) { var request SessionFSStatRequest if err := json.Unmarshal(params, &request); err != nil { diff --git a/go/rpc/zrpc_encoding.go b/go/rpc/zrpc_encoding.go index 82f6e10774..16cf00bab0 100644 --- a/go/rpc/zrpc_encoding.go +++ b/go/rpc/zrpc_encoding.go @@ -1075,6 +1075,12 @@ func unmarshalFactoryRunFailure(data []byte) (FactoryRunFailure, error) { } switch raw.Type { + case FactoryRunFailureTypeFactoryDurableFailure: + var d FactoryRunFailureFactoryDurableFailure + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil case FactoryRunFailureTypeFactoryLimitReached: var d FactoryRunFailureFactoryLimitReached if err := json.Unmarshal(data, &d); err != nil { @@ -1103,6 +1109,17 @@ func (r RawFactoryRunFailureData) MarshalJSON() ([]byte, error) { }) } +func (r FactoryRunFailureFactoryDurableFailure) MarshalJSON() ([]byte, error) { + type alias FactoryRunFailureFactoryDurableFailure + return json.Marshal(struct { + Type FactoryRunFailureType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + func (r FactoryRunFailureFactoryLimitReached) MarshalJSON() ([]byte, error) { type alias FactoryRunFailureFactoryLimitReached return json.Marshal(struct { @@ -1125,6 +1142,30 @@ func (r FactoryRunFailureFactoryResumeDeclined) MarshalJSON() ([]byte, error) { }) } +func (r *FactoryRunTerminal) UnmarshalJSON(data []byte) error { + type rawFactoryRunTerminal struct { + Error *string `json:"error,omitempty"` + Failure json.RawMessage `json:"failure,omitempty"` + Reason *string `json:"reason,omitempty"` + ResultPreview *string `json:"resultPreview,omitempty"` + } + var raw rawFactoryRunTerminal + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + r.Error = raw.Error + if raw.Failure != nil { + value, err := unmarshalFactoryRunFailure(raw.Failure) + if err != nil { + return err + } + r.Failure = value + } + r.Reason = raw.Reason + r.ResultPreview = raw.ResultPreview + return nil +} + func (r *FactoryRunResult) UnmarshalJSON(data []byte) error { type rawFactoryRunResult struct { Error *string `json:"error,omitempty"` @@ -1327,6 +1368,7 @@ func (r *MCPServerConfigHTTP) UnmarshalJSON(data []byte) error { type rawMCPServerConfigHTTP struct { Auth json.RawMessage `json:"auth,omitempty"` DeferTools *MCPServerConfigDeferTools `json:"deferTools,omitempty"` + DisableToolCache *bool `json:"disableToolCache,omitempty"` FilterMapping json.RawMessage `json:"filterMapping,omitempty"` Headers map[string]string `json:"headers,omitzero"` IsDefaultServer *bool `json:"isDefaultServer,omitempty"` @@ -1351,6 +1393,7 @@ func (r *MCPServerConfigHTTP) UnmarshalJSON(data []byte) error { r.Auth = value } r.DeferTools = raw.DeferTools + r.DisableToolCache = raw.DisableToolCache if raw.FilterMapping != nil { value, err := unmarshalFilterMapping(raw.FilterMapping) if err != nil { @@ -1379,17 +1422,18 @@ func (r *MCPServerConfigHTTP) UnmarshalJSON(data []byte) error { func (r *MCPServerConfigStdio) UnmarshalJSON(data []byte) error { type rawMCPServerConfigStdio struct { - Args []string `json:"args,omitzero"` - Auth json.RawMessage `json:"auth,omitempty"` - Command string `json:"command"` - Cwd *string `json:"cwd,omitempty"` - DeferTools *MCPServerConfigDeferTools `json:"deferTools,omitempty"` - Env map[string]string `json:"env,omitzero"` - FilterMapping json.RawMessage `json:"filterMapping,omitempty"` - IsDefaultServer *bool `json:"isDefaultServer,omitempty"` - Oidc json.RawMessage `json:"oidc,omitempty"` - Timeout *int64 `json:"timeout,omitempty"` - Tools []string `json:"tools,omitzero"` + Args []string `json:"args,omitzero"` + Auth json.RawMessage `json:"auth,omitempty"` + Command string `json:"command"` + Cwd *string `json:"cwd,omitempty"` + DeferTools *MCPServerConfigDeferTools `json:"deferTools,omitempty"` + DisableToolCache *bool `json:"disableToolCache,omitempty"` + Env map[string]string `json:"env,omitzero"` + FilterMapping json.RawMessage `json:"filterMapping,omitempty"` + IsDefaultServer *bool `json:"isDefaultServer,omitempty"` + Oidc json.RawMessage `json:"oidc,omitempty"` + Timeout *int64 `json:"timeout,omitempty"` + Tools []string `json:"tools,omitzero"` } var raw rawMCPServerConfigStdio if err := json.Unmarshal(data, &raw); err != nil { @@ -1406,6 +1450,7 @@ func (r *MCPServerConfigStdio) UnmarshalJSON(data []byte) error { r.Command = raw.Command r.Cwd = raw.Cwd r.DeferTools = raw.DeferTools + r.DisableToolCache = raw.DisableToolCache r.Env = raw.Env if raw.FilterMapping != nil { value, err := unmarshalFilterMapping(raw.FilterMapping) @@ -1676,7 +1721,7 @@ func (r *MCPRestartServerRequest) UnmarshalJSON(data []byte) error { func (r *MCPStartServerRequest) UnmarshalJSON(data []byte) error { type rawMCPStartServerRequest struct { - Config json.RawMessage `json:"config"` + Config json.RawMessage `json:"config,omitempty"` ServerName string `json:"serverName"` } var raw rawMCPStartServerRequest @@ -3091,6 +3136,49 @@ func (r PushAttachmentSelection) MarshalJSON() ([]byte, error) { }) } +func (r *QueueInsertMessage) UnmarshalJSON(data []byte) error { + type rawQueueInsertMessage struct { + AgentMode *SendAgentMode `json:"agentMode,omitempty"` + Attachments []json.RawMessage `json:"attachments,omitzero"` + Billable *bool `json:"billable,omitempty"` + Delivery *string `json:"delivery,omitempty"` + DisplayPrompt *string `json:"displayPrompt,omitempty"` + Mode *SendMode `json:"mode,omitempty"` + Prepend *bool `json:"prepend,omitempty"` + Prompt string `json:"prompt"` + RequestHeaders map[string]string `json:"requestHeaders,omitzero"` + RequiredTool *string `json:"requiredTool,omitempty"` + Source *string `json:"source,omitempty"` + Wait *bool `json:"wait,omitempty"` + } + var raw rawQueueInsertMessage + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + r.AgentMode = raw.AgentMode + if raw.Attachments != nil { + r.Attachments = make([]Attachment, 0, len(raw.Attachments)) + for _, rawItem := range raw.Attachments { + value, err := unmarshalAttachment(rawItem) + if err != nil { + return err + } + r.Attachments = append(r.Attachments, value) + } + } + r.Billable = raw.Billable + r.Delivery = raw.Delivery + r.DisplayPrompt = raw.DisplayPrompt + r.Mode = raw.Mode + r.Prepend = raw.Prepend + r.Prompt = raw.Prompt + r.RequestHeaders = raw.RequestHeaders + r.RequiredTool = raw.RequiredTool + r.Source = raw.Source + r.Wait = raw.Wait + return nil +} + func unmarshalRemoteControlStatus(data []byte) (RemoteControlStatus, error) { if string(data) == "null" { return nil, nil @@ -3397,6 +3485,69 @@ func (r *SessionInstalledPluginSource) UnmarshalJSON(data []byte) error { return errors.New("data did not match any union variant for SessionInstalledPluginSource") } +func unmarshalSessionLimitPredictionResult(data []byte) (SessionLimitPredictionResult, error) { + if string(data) == "null" { + return nil, nil + } + type rawUnion struct { + Kind SessionLimitPredictionResultKind `json:"kind"` + } + var raw rawUnion + if err := json.Unmarshal(data, &raw); err != nil { + return nil, err + } + + switch raw.Kind { + case SessionLimitPredictionResultKindAvailable: + var d SessionLimitPredictionResultAvailable + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case SessionLimitPredictionResultKindUnavailable: + var d SessionLimitPredictionResultUnavailable + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + default: + return &RawSessionLimitPredictionResultData{Discriminator: raw.Kind, Raw: data}, nil + } +} + +func (r RawSessionLimitPredictionResultData) MarshalJSON() ([]byte, error) { + if r.Raw != nil { + return r.Raw, nil + } + return json.Marshal(struct { + Kind SessionLimitPredictionResultKind `json:"kind"` + }{ + Kind: r.Discriminator, + }) +} + +func (r SessionLimitPredictionResultAvailable) MarshalJSON() ([]byte, error) { + type alias SessionLimitPredictionResultAvailable + return json.Marshal(struct { + Kind SessionLimitPredictionResultKind `json:"kind"` + alias + }{ + Kind: r.Kind(), + alias: alias(r), + }) +} + +func (r SessionLimitPredictionResultUnavailable) MarshalJSON() ([]byte, error) { + type alias SessionLimitPredictionResultUnavailable + return json.Marshal(struct { + Kind SessionLimitPredictionResultKind `json:"kind"` + alias + }{ + Kind: r.Kind(), + alias: alias(r), + }) +} + func unmarshalSessionListEntry(data []byte) (SessionListEntry, error) { if string(data) == "null" { return nil, nil @@ -3475,6 +3626,7 @@ func (r *SessionList) UnmarshalJSON(data []byte) error { func (r *SessionOpenOptions) UnmarshalJSON(data []byte) error { type rawSessionOpenOptions struct { AdditionalContentExclusionPolicies []SessionOpenOptionsAdditionalContentExclusionPolicy `json:"additionalContentExclusionPolicies,omitzero"` + AdditionalDirectories []string `json:"additionalDirectories,omitzero"` AgentContext *string `json:"agentContext,omitempty"` AllowAllMCPServerInstructions *bool `json:"allowAllMcpServerInstructions,omitempty"` AskUserDisabled *bool `json:"askUserDisabled,omitempty"` @@ -3493,12 +3645,14 @@ func (r *SessionOpenOptions) UnmarshalJSON(data []byte) error { DisabledInstructionSources []string `json:"disabledInstructionSources,omitzero"` DisabledSkills []string `json:"disabledSkills,omitzero"` EnableCitations *bool `json:"enableCitations,omitempty"` + EnableFileChangeTracking *bool `json:"enableFileChangeTracking,omitempty"` EnableManagedSettings *bool `json:"enableManagedSettings,omitempty"` EnableOnDemandInstructionDiscovery *bool `json:"enableOnDemandInstructionDiscovery,omitempty"` EnableScriptSafety *bool `json:"enableScriptSafety,omitempty"` EnableStreaming *bool `json:"enableStreaming,omitempty"` EnvValueMode *SessionOpenOptionsEnvValueMode `json:"envValueMode,omitempty"` EventsLogDirectory *string `json:"eventsLogDirectory,omitempty"` + EventsLogIncludesSubagents *bool `json:"eventsLogIncludesSubagents,omitempty"` ExcludedBuiltinAgents []string `json:"excludedBuiltinAgents,omitzero"` ExcludedTools []string `json:"excludedTools,omitzero"` ExpAssignments any `json:"expAssignments,omitempty"` @@ -3527,6 +3681,7 @@ func (r *SessionOpenOptions) UnmarshalJSON(data []byte) error { SessionCapabilities []SessionCapability `json:"sessionCapabilities,omitzero"` SessionID *string `json:"sessionId,omitempty"` SessionLimits *SessionLimitsConfig `json:"sessionLimits,omitempty"` + Shell *ShellOptions `json:"shell,omitempty"` ShellInitProfile *string `json:"shellInitProfile,omitempty"` ShellProcessFlags []string `json:"shellProcessFlags,omitzero"` SkillDirectories []string `json:"skillDirectories,omitzero"` @@ -3541,6 +3696,7 @@ func (r *SessionOpenOptions) UnmarshalJSON(data []byte) error { return err } r.AdditionalContentExclusionPolicies = raw.AdditionalContentExclusionPolicies + r.AdditionalDirectories = raw.AdditionalDirectories r.AgentContext = raw.AgentContext r.AllowAllMCPServerInstructions = raw.AllowAllMCPServerInstructions r.AskUserDisabled = raw.AskUserDisabled @@ -3565,12 +3721,14 @@ func (r *SessionOpenOptions) UnmarshalJSON(data []byte) error { r.DisabledInstructionSources = raw.DisabledInstructionSources r.DisabledSkills = raw.DisabledSkills r.EnableCitations = raw.EnableCitations + r.EnableFileChangeTracking = raw.EnableFileChangeTracking r.EnableManagedSettings = raw.EnableManagedSettings r.EnableOnDemandInstructionDiscovery = raw.EnableOnDemandInstructionDiscovery r.EnableScriptSafety = raw.EnableScriptSafety r.EnableStreaming = raw.EnableStreaming r.EnvValueMode = raw.EnvValueMode r.EventsLogDirectory = raw.EventsLogDirectory + r.EventsLogIncludesSubagents = raw.EventsLogIncludesSubagents r.ExcludedBuiltinAgents = raw.ExcludedBuiltinAgents r.ExcludedTools = raw.ExcludedTools r.ExpAssignments = raw.ExpAssignments @@ -3599,6 +3757,7 @@ func (r *SessionOpenOptions) UnmarshalJSON(data []byte) error { r.SessionCapabilities = raw.SessionCapabilities r.SessionID = raw.SessionID r.SessionLimits = raw.SessionLimits + r.Shell = raw.Shell r.ShellInitProfile = raw.ShellInitProfile r.ShellProcessFlags = raw.ShellProcessFlags r.SkillDirectories = raw.SkillDirectories diff --git a/go/rpc/zsession_encoding.go b/go/rpc/zsession_encoding.go index fe99126cf7..e472ffe679 100644 --- a/go/rpc/zsession_encoding.go +++ b/go/rpc/zsession_encoding.go @@ -203,6 +203,12 @@ func (e *SessionEvent) UnmarshalJSON(data []byte) error { return err } e.Data = &d + case SessionEventTypeFactoryRunUpdated: + var d FactoryRunUpdatedData + if err := json.Unmarshal(raw.Data, &d); err != nil { + return err + } + e.Data = &d case SessionEventTypeHookEnd: var d HookEndData if err := json.Unmarshal(raw.Data, &d); err != nil { @@ -1370,6 +1376,12 @@ func unmarshalSystemNotification(data []byte) (SystemNotification, error) { return nil, err } return &d, nil + case SystemNotificationTypeUnclassified: + var d SystemNotificationUnclassified + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil default: return &RawSystemNotification{Discriminator: raw.Type, Raw: data}, nil } @@ -1452,6 +1464,17 @@ func (r SystemNotificationShellDetachedCompleted) MarshalJSON() ([]byte, error) }) } +func (r SystemNotificationUnclassified) MarshalJSON() ([]byte, error) { + type alias SystemNotificationUnclassified + return json.Marshal(struct { + Type SystemNotificationType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + func (r *SystemNotificationData) UnmarshalJSON(data []byte) error { type rawSystemNotificationData struct { Content string `json:"content"` @@ -1893,6 +1916,7 @@ func (r *PermissionRequestedData) UnmarshalJSON(data []byte) error { PromptRequest json.RawMessage `json:"promptRequest,omitempty"` RequestID string `json:"requestId"` ResolvedByHook *bool `json:"resolvedByHook,omitempty"` + RiskAssessment any `json:"riskAssessment,omitempty"` } var raw rawPermissionRequestedData if err := json.Unmarshal(data, &raw); err != nil { @@ -1914,6 +1938,7 @@ func (r *PermissionRequestedData) UnmarshalJSON(data []byte) error { } r.RequestID = raw.RequestID r.ResolvedByHook = raw.ResolvedByHook + r.RiskAssessment = raw.RiskAssessment return nil } diff --git a/go/rpc/zsession_events.go b/go/rpc/zsession_events.go index 44f49948f4..f12b3071a4 100644 --- a/go/rpc/zsession_events.go +++ b/go/rpc/zsession_events.go @@ -81,24 +81,27 @@ const ( SessionEventTypeExitPlanModeRequested SessionEventType = "exit_plan_mode.requested" SessionEventTypeExternalToolCompleted SessionEventType = "external_tool.completed" SessionEventTypeExternalToolRequested SessionEventType = "external_tool.requested" - SessionEventTypeHookEnd SessionEventType = "hook.end" - SessionEventTypeHookProgress SessionEventType = "hook.progress" - SessionEventTypeHookStart SessionEventType = "hook.start" - SessionEventTypeMCPAppToolCallComplete SessionEventType = "mcp_app.tool_call_complete" - SessionEventTypeMCPHeadersRefreshCompleted SessionEventType = "mcp.headers_refresh_completed" - SessionEventTypeMCPHeadersRefreshRequired SessionEventType = "mcp.headers_refresh_required" - SessionEventTypeMCPOauthCompleted SessionEventType = "mcp.oauth_completed" - SessionEventTypeMCPOauthRequired SessionEventType = "mcp.oauth_required" - SessionEventTypeMCPPromptsListChanged SessionEventType = "mcp.prompts.list_changed" - SessionEventTypeMCPResourcesListChanged SessionEventType = "mcp.resources.list_changed" - SessionEventTypeMCPToolsListChanged SessionEventType = "mcp.tools.list_changed" - SessionEventTypeModelCallFailure SessionEventType = "model.call_failure" - SessionEventTypeModelCallStart SessionEventType = "model.call_start" - SessionEventTypePendingMessagesModified SessionEventType = "pending_messages.modified" - SessionEventTypePermissionCompleted SessionEventType = "permission.completed" - SessionEventTypePermissionRequested SessionEventType = "permission.requested" - SessionEventTypeSamplingCompleted SessionEventType = "sampling.completed" - SessionEventTypeSamplingRequested SessionEventType = "sampling.requested" + // Experimental: SessionEventTypeFactoryRunUpdated identifies an experimental event that may + // change or be removed. + SessionEventTypeFactoryRunUpdated SessionEventType = "factory.run_updated" + SessionEventTypeHookEnd SessionEventType = "hook.end" + SessionEventTypeHookProgress SessionEventType = "hook.progress" + SessionEventTypeHookStart SessionEventType = "hook.start" + SessionEventTypeMCPAppToolCallComplete SessionEventType = "mcp_app.tool_call_complete" + SessionEventTypeMCPHeadersRefreshCompleted SessionEventType = "mcp.headers_refresh_completed" + SessionEventTypeMCPHeadersRefreshRequired SessionEventType = "mcp.headers_refresh_required" + SessionEventTypeMCPOauthCompleted SessionEventType = "mcp.oauth_completed" + SessionEventTypeMCPOauthRequired SessionEventType = "mcp.oauth_required" + SessionEventTypeMCPPromptsListChanged SessionEventType = "mcp.prompts.list_changed" + SessionEventTypeMCPResourcesListChanged SessionEventType = "mcp.resources.list_changed" + SessionEventTypeMCPToolsListChanged SessionEventType = "mcp.tools.list_changed" + SessionEventTypeModelCallFailure SessionEventType = "model.call_failure" + SessionEventTypeModelCallStart SessionEventType = "model.call_start" + SessionEventTypePendingMessagesModified SessionEventType = "pending_messages.modified" + SessionEventTypePermissionCompleted SessionEventType = "permission.completed" + SessionEventTypePermissionRequested SessionEventType = "permission.requested" + SessionEventTypeSamplingCompleted SessionEventType = "sampling.completed" + SessionEventTypeSamplingRequested SessionEventType = "sampling.requested" // Experimental: SessionEventTypeSessionAutoModeResolved identifies an experimental event // that may change or be removed. SessionEventTypeSessionAutoModeResolved SessionEventType = "session.auto_mode_resolved" @@ -214,6 +217,7 @@ type AssistantReasoningData struct { Content string `json:"content"` // Unique identifier for this reasoning block ReasoningID string `json:"reasoningId"` + Rte *bool `json:"rte,omitempty"` } func (*AssistantReasoningData) sessionEventData() {} @@ -253,6 +257,7 @@ type AssistantMessageData struct { ReasoningWireField *string `json:"reasoningWireField,omitempty"` // GitHub request tracing ID (x-github-request-id header) for correlating with server-side logs RequestID *string `json:"requestId,omitempty"` + Rte *bool `json:"rte,omitempty"` // Neutral provider-tagged server-side tool-use payload (tool search, advisor) for verbatim round-tripping ServerTools *AssistantMessageServerTools `json:"serverTools,omitempty"` // Copilot service request ID (x-copilot-service-request-id header) for CAPI log correlation @@ -269,18 +274,36 @@ func (*AssistantMessageData) Type() SessionEventType { return SessionEventTypeAs // Auto Intent resolution: the concrete model the session settled on for the first prompt of an auto-mode session, and why. Lets SDK clients render the chosen model and the full reason it was picked. The core selection fields (chosenModel/reasoningBucket/categoryScores) are stable; the routing-analytics fields (predictedLabel/confidence/candidateModels) mirror the upstream intent service and may evolve, hence the event's experimental stability. // Experimental: SessionAutoModeResolvedData is part of an experimental API and may change or be removed. type SessionAutoModeResolvedData struct { + // Models offered to the router for this resolution + AvailableModels []string `json:"availableModels,omitzero"` // Ordered candidate model list the router returned, when not a fallback CandidateModels []string `json:"candidateModels,omitzero"` // Per-category classifier scores (0-1) behind the bucket: the granular HYDRA capability scores (reasoning, code_gen, debugging, tool_use), or the binary needs_reasoning/no_reasoning scores when HYDRA didn't run. Lets clients show a breakdown rather than just the bucket. CategoryScores map[string]float64 `json:"categoryScores,omitzero"` // The concrete model the session will use after any intent refinement ChosenModel string `json:"chosenModel"` + // The chosen model's score shortfall relative to the top candidate + ChosenShortfall *float64 `json:"chosenShortfall,omitempty"` // Classifier confidence for the predicted label, when available Confidence *float64 `json:"confidence,omitempty"` + // End-to-end client wait time for the router request in milliseconds + EndToEndLatencyMs *float64 `json:"endToEndLatencyMs,omitempty"` + // Whether the router fell back to the standard Auto selection + Fallback *bool `json:"fallback,omitempty"` + // Server-provided reason for falling back, when available + FallbackReason *string `json:"fallbackReason,omitempty"` + // Whether the routed prompt contained an image + HasImage *bool `json:"hasImage,omitempty"` // The predicted classifier label (e.g. `needs_reasoning`), when available PredictedLabel *string `json:"predictedLabel,omitempty"` // Coarse request-difficulty bucket, for explaining why a model was chosen ("picked X because this looks like high-reasoning work") ReasoningBucket *AutoModeResolvedReasoningBucket `json:"reasoningBucket,omitempty"` + // Server-reported router processing time in milliseconds + RouterLatencyMs *float64 `json:"routerLatencyMs,omitempty"` + // The routing method the server applied, when Auto Intent ran + RoutingMethod *string `json:"routingMethod,omitempty"` + // Whether a sticky model choice overrode the router result + StickyOverride *bool `json:"stickyOverride,omitempty"` } func (*SessionAutoModeResolvedData) sessionEventData() {} @@ -356,12 +379,18 @@ func (*SessionBinaryAssetData) Type() SessionEventType { return SessionEventType type SessionCompactionStartData struct { // Token count from non-system messages (user, assistant, tool) at compaction start ConversationTokens *int64 `json:"conversationTokens,omitempty"` + // Total context tokens (system + conversation + tool definitions) at compaction start, when known + CurrentTokens *int64 `json:"currentTokens,omitempty"` // Model identifier used for compaction, when known Model *string `json:"model,omitempty"` // Token count from system message(s) at compaction start SystemTokens *int64 `json:"systemTokens,omitempty"` + // Model context window token limit the compaction is targeting, when known + TokenLimit *int64 `json:"tokenLimit,omitempty"` // Token count from tool definitions at compaction start ToolDefinitionsTokens *int64 `json:"toolDefinitionsTokens,omitempty"` + // What initiated this compaction, when known + Trigger *CompactionTrigger `json:"trigger,omitempty"` } func (*SessionCompactionStartData) sessionEventData() {} @@ -403,10 +432,14 @@ type SessionCompactionCompleteData struct { SummaryContent *string `json:"summaryContent,omitempty"` // Token count from system message(s) after compaction SystemTokens *int64 `json:"systemTokens,omitempty"` + // Model context window token limit the compaction was targeting, when known + TokenLimit *int64 `json:"tokenLimit,omitempty"` // Number of tokens removed during compaction TokensRemoved *int64 `json:"tokensRemoved,omitempty"` // Token count from tool definitions after compaction ToolDefinitionsTokens *int64 `json:"toolDefinitionsTokens,omitempty"` + // What initiated this compaction, when known + Trigger *CompactionTrigger `json:"trigger,omitempty"` } func (*SessionCompactionCompleteData) sessionEventData() {} @@ -609,6 +642,8 @@ type SessionManagedSettingsResolvedData struct { FailClosed bool `json:"failClosed"` // The setting keys under enterprise management in the effective managed settings (e.g. `model`, `enabledPlugins`, `permissions`). Empty when no managed settings are in force. ManagedKeys []string `json:"managedKeys"` + // Whether server and device each supplied a permission allowlist, so enforcement intersects them and the flattened settings payload omits `permissions.allow`. + PermissionsAllowIntersected *bool `json:"permissionsAllowIntersected,omitempty"` // Whether the server (account/org) managed-settings layer was present ServerManaged bool `json:"serverManaged"` // The effective (resolved) managed settings values, so clients can render exactly what is enforced. Absent when no managed policy is in force. @@ -622,6 +657,17 @@ func (*SessionManagedSettingsResolvedData) Type() SessionEventType { return SessionEventTypeSessionManagedSettingsResolved } +// Ephemeral invalidation signal for a changed factory run. +// Experimental: FactoryRunUpdatedData is part of an experimental API and may change or be removed. +type FactoryRunUpdatedData struct { + // Monotonic revision now available for the run. + Revision int64 `json:"revision"` + RunID string `json:"runId"` +} + +func (*FactoryRunUpdatedData) sessionEventData() {} +func (*FactoryRunUpdatedData) Type() SessionEventType { return SessionEventTypeFactoryRunUpdated } + // Ephemeral progress update from a running hook process type HookProgressData struct { // Human-readable progress message from the hook process @@ -733,6 +779,7 @@ type ModelCallFailureData struct { ReasoningEffort *string `json:"reasoningEffort,omitempty"` // Content-free structural summary of the failing request. Contains only counts and shape flags (no prompt content), so it is safe for unrestricted telemetry. Populated only for client-error (4xx) failures. RequestFingerprint *ModelCallFailureRequestFingerprint `json:"requestFingerprint,omitempty"` + Rte *bool `json:"rte,omitempty"` // Copilot service request ID (x-copilot-service-request-id header) for CAPI log correlation ServiceRequestID *string `json:"serviceRequestId,omitempty"` // Where the failed model call originated @@ -818,6 +865,8 @@ type AssistantUsageData struct { Initiator *string `json:"initiator,omitempty"` // Number of input tokens consumed InputTokens *int64 `json:"inputTokens,omitempty"` + // Coarse classification of the interaction that produced this call, mirroring the session's per-request agent context (e.g. `conversation-agent`, `conversation-subagent`, `conversation-sampling`, `conversation-background`, `conversation-compaction`, `conversation-user`). Non-billing; lets consumers attribute a model call to a call class (e.g. sub-agent/sidekick) independently of the billing initiator. Absent when the runtime did not classify the request. + InteractionType *string `json:"interactionType,omitempty"` // Average inter-token latency in milliseconds. Only available for streaming requests InterTokenLatencyMs *float64 `json:"interTokenLatencyMs,omitempty"` // Model identifier used for this API call @@ -836,6 +885,7 @@ type AssistantUsageData struct { ReasoningEffort *string `json:"reasoningEffort,omitempty"` // Number of output tokens used for reasoning (e.g., chain-of-thought) ReasoningTokens *int64 `json:"reasoningTokens,omitempty"` + Rte *bool `json:"rte,omitempty"` // Copilot service request ID (x-copilot-service-request-id header) for CAPI log correlation ServiceRequestID *string `json:"serviceRequestId,omitempty"` // Time to first token in milliseconds. Only available for streaming requests @@ -926,6 +976,9 @@ func (*AssistantTurnRetryData) Type() SessionEventType { return SessionEventType type ModelCallStartData struct { // Model identifier used for this API call, when known Model *string `json:"model,omitempty"` + // Previous response or interaction identifier included in the model request, when present + // Internal: PreviousResponseID is part of the SDK's internal API surface and is not intended for external use. + PreviousResponseID *string `json:"previousResponseId,omitempty"` // Identifier of the assistant turn that initiated the model call TurnID string `json:"turnId"` } @@ -1213,7 +1266,7 @@ type UserMessageData struct { NativeDocumentPathFallbackPaths []string `json:"nativeDocumentPathFallbackPaths,omitzero"` // Parent agent task ID for background telemetry correlated to this user turn ParentAgentTaskID *string `json:"parentAgentTaskId,omitempty"` - // Origin of this message, used for timeline filtering (e.g., "skill-pdf" for skill-injected messages that should be hidden from the user) + // Origin of this message, used for timeline filtering and attribution (e.g., `skill-pdf` for hidden skill injection or `agent-` for an inter-agent prompt) Source *string `json:"source,omitempty"` // Normalized document MIME types that were sent natively instead of through tagged_files XML SupportedNativeDocumentMIMETypes []string `json:"supportedNativeDocumentMimeTypes,omitzero"` @@ -1247,6 +1300,8 @@ type PermissionRequestedData struct { RequestID string `json:"requestId"` // When true, this permission was already resolved by a permissionRequest hook and requires no client action ResolvedByHook *bool `json:"resolvedByHook,omitempty"` + // Neutral risk metadata supplied by the tool host. Consumers may display this value but must not use it to bypass the permission decision. + RiskAssessment any `json:"riskAssessment,omitempty"` } func (*PermissionRequestedData) sessionEventData() {} @@ -1438,6 +1493,8 @@ type SessionScheduleCreatedData struct { ID int64 `json:"id"` // Interval between ticks in milliseconds (relative-interval schedules) IntervalMs *int64 `json:"intervalMs,omitempty"` + // Who created the schedule (`user` or `model`). Persisted so a resumed session keeps gating non-user schedules from firing skills that opted out of model invocation. Absent on entries created before this field existed; a missing origin fails closed (treated the same as a non-user origin), so such a schedule may not resolve a `disable-model-invocation` skill. + Origin *ScheduleOrigin `json:"origin,omitempty"` // Prompt text that gets enqueued on every tick Prompt string `json:"prompt"` // Whether the schedule re-arms after each tick (`/every`) or fires once (`/after`) @@ -1580,7 +1637,7 @@ type SessionResumeData struct { Context *WorkingDirectoryContext `json:"context,omitempty"` // Context tier currently selected at resume time; null when no tier is active ContextTier *ContextTier `json:"contextTier,omitempty"` - // When true, tool calls and permission requests left in flight by the previous session lifetime remain pending after resume and the agentic loop awaits their results. User sends are queued behind the pending work until all such requests reach a terminal state. When false (the default), any such tool calls and permission requests are immediately marked as interrupted on resume. + // When true, tool calls and permission requests left in flight by the previous session lifetime remain pending after resume and the agentic loop awaits their results. User sends are queued behind the pending work until all such requests reach a terminal state. When false or omitted, pending work is normally marked as interrupted unless the resume passively joined live work owned by another client; sessionWasActive distinguishes that case. ContinuePendingWork *bool `json:"continuePendingWork,omitempty"` // Total number of persisted events in the session at the time of resume EventCount int64 `json:"eventCount"` @@ -1598,7 +1655,7 @@ type SessionResumeData struct { SelectedModel *string `json:"selectedModel,omitempty"` // Session limits currently configured at resume time; null when no limits are active SessionLimits *SessionLimitsConfig `json:"sessionLimits,omitempty"` - // True when this resume attached to a session that the runtime already had running in-memory (for example, an extension joining a session another client was actively driving). False (or omitted) for cold resumes — the runtime had to reconstitute the session from its persisted event log. + // True when this resume passively joined a session that already had live work running in the runtime - an agent turn, a native queue run, a queued resume continuation, or an in-flight send (for example, an extension joining a session another client was actively driving). False (or omitted) when the session had no live work or when the resume explicitly abandoned pending work, including cold resumes and suspended sessions that remain resident in memory. SessionWasActive *bool `json:"sessionWasActive,omitempty"` // Output verbosity level used for model calls, if applicable (e.g. "low", "medium", "high") Verbosity *Verbosity `json:"verbosity,omitempty"` @@ -1861,6 +1918,8 @@ func (*SystemNotificationData) Type() SessionEventType { return SessionEventType type SystemMessageData struct { // The system or developer prompt text sent as model input Content string `json:"content"` + // Logical interaction identifier for the model run receiving this prompt + InteractionID *string `json:"interactionId,omitempty"` // Metadata about the prompt template and its construction Metadata *SystemMessageMetadata `json:"metadata,omitempty"` // Optional name identifier for the message source @@ -1874,7 +1933,13 @@ func (*SystemMessageData) Type() SessionEventType { return SessionEventTypeSyste // Task completion notification with summary from the agent type SessionTaskCompleteData struct { - // Whether the tool call succeeded. False when validation failed (e.g., invalid arguments) + // Active autopilot objective ID evaluated by the completion reviewer + ObjectiveID *int64 `json:"objectiveId,omitempty"` + // Semantic completion decision. Absent on legacy events and invalid tool calls + Outcome *TaskCompletionOutcome `json:"outcome,omitempty"` + // Label-safe runtime rationale for the completion decision (e.g. a cancellation or pause/resume downgrade), when one applies. Reviewer-authored rationale is intentionally omitted here because this event has no IFC label channel; the reviewer's findings remain available through its own labeled sub-agent events + Reason *string `json:"reason,omitempty"` + // Whether the task was accepted as complete. False when validation failed or completion was rejected or blocked by the reviewer Success *bool `json:"success,omitempty"` // Summary of the completed task, provided by the agent Summary *string `json:"summary,omitempty"` @@ -1901,6 +1966,7 @@ type ToolExecutionCompleteData struct { ParentToolCallID *string `json:"parentToolCallId,omitempty"` // Tool execution result on success Result *ToolExecutionCompleteResult `json:"result,omitempty"` + Rte *bool `json:"rte,omitempty"` // Whether this tool execution ran inside a sandbox container Sandboxed *bool `json:"sandboxed,omitempty"` // Whether the tool execution completed successfully @@ -1948,6 +2014,7 @@ type ToolExecutionStartData struct { // Tool call ID of the parent tool invocation when this event originates from a sub-agent // Deprecated: ParentToolCallID is deprecated. ParentToolCallID *string `json:"parentToolCallId,omitempty"` + Rte *bool `json:"rte,omitempty"` // Shell-tool path hints derived from the command at start time for shell tools (bash/powershell/local_shell). Produced by the same shell-aware extractor as PermissionRequestShell.possiblePaths, so it is present even when the command is auto-approved and no permission request fires. Absent for non-shell tools. ShellToolInfo *ToolExecutionStartShellToolInfo `json:"shellToolInfo,omitempty"` // Unique identifier for this tool call @@ -2082,6 +2149,8 @@ type SessionContextChangedData struct { HeadCommit *string `json:"headCommit,omitempty"` // Hosting platform type of the repository (github or ado) HostType *WorkingDirectoryContextHostType `json:"hostType,omitempty"` + // Set on the immediate preliminary event of a working-directory change, before the git context is resolved. A settled follow-up event (enriched with git context, or cwd-only for a non-repository) is always emitted afterward, so observers may defer to it. Absent on standalone/final events (e.g. relay context changes). + PendingGitContext *bool `json:"pendingGitContext,omitempty"` // Repository identifier derived from the git remote URL ("owner/name" for GitHub, "org/project/repo" for Azure DevOps) Repository *string `json:"repository,omitempty"` // Raw host string from the git remote URL (e.g. "github.com", "mycompany.ghe.com", "dev.azure.com") @@ -2566,6 +2635,10 @@ type ModelCallFailureRequestFingerprint struct { // Auto-approval judge information attached to a permission request. Present (non-null) only when the session's allow-all mode is "auto"; its absence means auto mode was off and the judge did not evaluate the request. The `recommendation` conveys the judge's disposition for this request. // Experimental: PermissionAutoApproval is part of an experimental API and may change or be removed. type PermissionAutoApproval struct { + // Classified cause of an `error` recommendation. Absent for every other recommendation. + FailureReason *AutoApprovalJudgeFailureReason `json:"failureReason,omitempty"` + // Model id that produced the recommendation, when the judge was consulted and reported one. Absent for `excluded` (the judge was not consulted) and for failures that occurred before a model was selected. + Model *string `json:"model,omitempty"` // Human-readable reason for the judge's recommendation, when available. Reason *string `json:"reason,omitempty"` // The auto-approval safety judge's outcome for this request. @@ -2601,6 +2674,8 @@ type PermissionPromptRequestCommands struct { FullCommandText string `json:"fullCommandText"` // Human-readable description of what the command intends to do Intention string `json:"intention"` + // Whether managed policy requires a human response and forbids host auto-approval + ManagedApprovalRequired *bool `json:"managedApprovalRequired,omitempty"` // Tool call ID that triggered this permission request ToolCallID *string `json:"toolCallId,omitempty"` // Optional warning message about risks of running this command @@ -2761,6 +2836,8 @@ type PermissionPromptRequestRead struct { AutoApproval *PermissionAutoApproval `json:"autoApproval,omitempty"` // Human-readable description of why the file is being read Intention string `json:"intention"` + // Whether managed policy requires a human response and forbids host auto-approval + ManagedApprovalRequired *bool `json:"managedApprovalRequired,omitempty"` // Path of the file or directory being read Path string `json:"path"` // Tool call ID that triggered this permission request @@ -2779,6 +2856,10 @@ type PermissionPromptRequestURL struct { AutoApproval *PermissionAutoApproval `json:"autoApproval,omitempty"` // Human-readable description of why the URL is being accessed Intention string `json:"intention"` + // Whether managed policy requires a human response and forbids host auto-approval + ManagedApprovalRequired *bool `json:"managedApprovalRequired,omitempty"` + // Immediately preceding URL when this prompt is for a redirect target + RedirectedFrom *string `json:"redirectedFrom,omitempty"` // True when this URL fetch is requesting to bypass the sandbox network policy: either the model set requestSandboxBypass: true, or the tool re-issued the request as an interactive bypass after the network policy denied the approved URL (host opted in via sandbox.allowBypass). This is a request, not a grant: the fetch runs only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. RequestSandboxBypass *bool `json:"requestSandboxBypass,omitempty"` // Model-provided justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. @@ -2807,6 +2888,8 @@ type PermissionPromptRequestWrite struct { FileName string `json:"fileName"` // Human-readable description of the intended file change Intention string `json:"intention"` + // Whether managed policy requires a human response and forbids host auto-approval + ManagedApprovalRequired *bool `json:"managedApprovalRequired,omitempty"` // Complete new file contents for newly created files NewFileContents *string `json:"newFileContents,omitempty"` // Tool call ID that triggered this permission request @@ -2946,6 +3029,8 @@ func (PermissionRequestMemory) Kind() PermissionRequestKind { type PermissionRequestRead struct { // Human-readable description of why the file is being read Intention string `json:"intention"` + // Whether managed policy requires a human response and forbids host auto-approval + ManagedApprovalRequired *bool `json:"managedApprovalRequired,omitempty"` // Path of the file or directory being read Path string `json:"path"` // True when the model has requested to run this search outside the sandbox (it set requestSandboxBypass: true and the host opted in via sandbox.allowBypass). This is a request, not a grant: the search runs unsandboxed only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. @@ -2967,12 +3052,16 @@ type PermissionRequestShell struct { CanOfferSessionApproval bool `json:"canOfferSessionApproval"` // Parsed command identifiers found in the command text Commands []PermissionRequestShellCommand `json:"commands"` + // Parsed command segments, including arguments, used for managed policy matching + CommandSegments []PermissionRequestShellCommandSegment `json:"commandSegments,omitzero"` // The complete shell command text to be executed FullCommandText string `json:"fullCommandText"` // Whether the command includes a file write redirection (e.g., > or >>) HasWriteFileRedirection bool `json:"hasWriteFileRedirection"` // Human-readable description of what the command intends to do Intention string `json:"intention"` + // Whether managed policy requires a human response and forbids host auto-approval + ManagedApprovalRequired *bool `json:"managedApprovalRequired,omitempty"` // File paths that may be read or written by the command PossiblePaths []string `json:"possiblePaths"` // URLs that may be accessed by the command @@ -2996,6 +3085,10 @@ func (PermissionRequestShell) Kind() PermissionRequestKind { type PermissionRequestURL struct { // Human-readable description of why the URL is being accessed Intention string `json:"intention"` + // Whether managed policy requires a human response and forbids host auto-approval + ManagedApprovalRequired *bool `json:"managedApprovalRequired,omitempty"` + // Immediately preceding URL when this request is for a redirect target + RedirectedFrom *string `json:"redirectedFrom,omitempty"` // True when this URL fetch is requesting to bypass the sandbox network policy: either the model set requestSandboxBypass: true, or the tool re-issued the request as an interactive bypass after the network policy denied the approved URL (host opted in via sandbox.allowBypass). This is a request, not a grant: the fetch runs only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. RequestSandboxBypass *bool `json:"requestSandboxBypass,omitempty"` // Model-provided justification for the sandbox-bypass request. Only meaningful when requestSandboxBypass is true. @@ -3021,6 +3114,8 @@ type PermissionRequestWrite struct { FileName string `json:"fileName"` // Human-readable description of the intended file change Intention string `json:"intention"` + // Whether managed policy requires a human response and forbids host auto-approval + ManagedApprovalRequired *bool `json:"managedApprovalRequired,omitempty"` // Complete new file contents for newly created files NewFileContents *string `json:"newFileContents,omitempty"` // True when a built-in file tool (apply_patch / str_replace_editor) asked to write a path the sandbox filesystem policy would block, and the host opted in via sandbox.allowBypass. This is a request, not a grant: the write happens unsandboxed only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. @@ -3044,6 +3139,14 @@ type PermissionRequestShellCommand struct { ReadOnly bool `json:"readOnly"` } +// A parsed shell command segment used for argument-aware managed policy matching. +type PermissionRequestShellCommandSegment struct { + // Full text of this command segment, including arguments + FullCommandText string `json:"fullCommandText"` + // Command identifier (e.g., executable name) + Identifier string `json:"identifier"` +} + // A URL that may be accessed by a command in a shell permission request. type PermissionRequestShellPossibleURL struct { // URL that may be accessed by the command @@ -3460,6 +3563,17 @@ func (SystemNotificationShellDetachedCompleted) Type() SystemNotificationType { return SystemNotificationTypeShellDetachedCompleted } +// System notification metadata from an external host that does not match a runtime-owned notification kind. +type SystemNotificationUnclassified struct { + // Opaque metadata supplied by the external host, when present. + Metadata any `json:"metadata,omitempty"` +} + +func (SystemNotificationUnclassified) systemNotification() {} +func (SystemNotificationUnclassified) Type() SystemNotificationType { + return SystemNotificationTypeUnclassified +} + // A content block within a tool result, which may be text, terminal output, image, audio, or a resource type ToolExecutionCompleteContent interface { toolExecutionCompleteContent() @@ -3778,6 +3892,8 @@ type WorkingDirectoryContext struct { HeadCommit *string `json:"headCommit,omitempty"` // Hosting platform type of the repository (github or ado) HostType *WorkingDirectoryContextHostType `json:"hostType,omitempty"` + // Set on the immediate preliminary event of a working-directory change, before the git context is resolved. A settled follow-up event (enriched with git context, or cwd-only for a non-repository) is always emitted afterward, so observers may defer to it. Absent on standalone/final events (e.g. relay context changes). + PendingGitContext *bool `json:"pendingGitContext,omitempty"` // Repository identifier derived from the git remote URL ("owner/name" for GitHub, "org/project/repo" for Azure DevOps) Repository *string `json:"repository,omitempty"` // Raw host string from the git remote URL (e.g. "github.com", "mycompany.ghe.com", "dev.azure.com") @@ -3808,6 +3924,23 @@ const ( AssistantUsageAPIEndpointWsResponses AssistantUsageAPIEndpoint = "ws:/responses" ) +// Why the auto-approval judge produced no usable recommendation. Present only alongside an `error` recommendation, where the human-readable reason is a fixed string and therefore cannot distinguish these cases. Intended to make a judge failure reportable by a consumer that has no access to the host's logs. +// Experimental: AutoApprovalJudgeFailureReason is part of an experimental API and may change or be removed. +type AutoApprovalJudgeFailureReason string + +const ( + // The judge model call was cancelled before it returned. + AutoApprovalJudgeFailureReasonAbort AutoApprovalJudgeFailureReason = "abort" + // The judge model call completed but returned no content. + AutoApprovalJudgeFailureReasonEmptyResponse AutoApprovalJudgeFailureReason = "empty_response" + // The judge model call failed (for example a transport, authentication, or rate-limit error). + AutoApprovalJudgeFailureReasonModelError AutoApprovalJudgeFailureReason = "model_error" + // The judge model replied, but the reply carried no ALLOW/DENY verdict. + AutoApprovalJudgeFailureReasonParseError AutoApprovalJudgeFailureReason = "parse_error" + // The judge model call exceeded its deadline. + AutoApprovalJudgeFailureReasonTimeout AutoApprovalJudgeFailureReason = "timeout" +) + // Outcome of the auto-approval safety judge for a permission request. Present only when auto mode is enabled; its absence means the judge did not evaluate the request (auto mode was off). // Experimental: AutoApprovalRecommendation is part of an experimental API and may change or be removed. type AutoApprovalRecommendation string @@ -3916,6 +4049,22 @@ const ( CitationProviderOpenai CitationProvider = "openai" ) +// What initiated a conversation compaction +type CompactionTrigger string + +const ( + // Compaction forced by a context-limit model response (e.g. HTTP 413) before retrying the request. + CompactionTriggerContextLimitRetry CompactionTrigger = "context_limit_retry" + // User-requested compaction, e.g. the /compact command or the history.compact API. + CompactionTriggerManual CompactionTrigger = "manual" + // Emergency compaction triggered by high process memory usage. + CompactionTriggerMemoryPressure CompactionTrigger = "memory_pressure" + // Compaction requested while switching to a model with a smaller context window. + CompactionTriggerModelSwitch CompactionTrigger = "model_switch" + // Background compaction started automatically because context utilization crossed the background threshold. + CompactionTriggerThreshold CompactionTrigger = "threshold" +) + // The user action: "accept" (submitted form), "decline" (explicitly refused), or "cancel" (dismissed) type ElicitationCompletedAction string @@ -4278,6 +4427,16 @@ const ( PlanChangedOperationUpdate PlanChangedOperation = "update" ) +// Who created the schedule: `user` (an explicit user action such as `/every` or `/after`) or `model` (the agent via the `manage_schedule` tool). Gates whether a scheduled skill that opted out of model invocation may fire: only user-created schedules may. +type ScheduleOrigin string + +const ( + // The schedule was created by the agent via the `manage_schedule` tool. + ScheduleOriginModel ScheduleOrigin = "model" + // The schedule was created by an explicit user action, such as `/every` or `/after`. + ScheduleOriginUser ScheduleOrigin = "user" +) + // User action selected for an exhausted session limit. type SessionLimitsExhaustedResponseAction string @@ -4334,6 +4493,19 @@ const ( SystemNotificationTypeNewInboxMessage SystemNotificationType = "new_inbox_message" SystemNotificationTypeShellCompleted SystemNotificationType = "shell_completed" SystemNotificationTypeShellDetachedCompleted SystemNotificationType = "shell_detached_completed" + SystemNotificationTypeUnclassified SystemNotificationType = "unclassified" +) + +// Semantic result of evaluating a task completion request +type TaskCompletionOutcome string + +const ( + // Completion cannot proceed without intervention; the active objective is paused when one is identified. + TaskCompletionOutcomeBlocked TaskCompletionOutcome = "blocked" + // The completion request was accepted and the objective is complete. + TaskCompletionOutcomeCompleted TaskCompletionOutcome = "completed" + // The completion request was rejected because more work or validation remains. + TaskCompletionOutcomeContinue TaskCompletionOutcome = "continue" ) // Theme variant this icon is intended for diff --git a/go/zsession_events.go b/go/zsession_events.go index 1d35a0a518..c98ddc7049 100644 --- a/go/zsession_events.go +++ b/go/zsession_events.go @@ -53,6 +53,7 @@ type ( AttachmentSelectionDetailsEnd = rpc.AttachmentSelectionDetailsEnd AttachmentSelectionDetailsStart = rpc.AttachmentSelectionDetailsStart AttachmentType = rpc.AttachmentType + AutoApprovalJudgeFailureReason = rpc.AutoApprovalJudgeFailureReason AutoApprovalRecommendation = rpc.AutoApprovalRecommendation AutoModeResolvedReasoningBucket = rpc.AutoModeResolvedReasoningBucket AutoModeSwitchCompletedData = rpc.AutoModeSwitchCompletedData @@ -85,6 +86,7 @@ type ( CommandsChangedData = rpc.CommandsChangedData CompactionCompleteCompactionTokensUsed = rpc.CompactionCompleteCompactionTokensUsed CompactionCompleteCompactionTokensUsedCopilotUsageTokenDetail = rpc.CompactionCompleteCompactionTokensUsedCopilotUsageTokenDetail + CompactionTrigger = rpc.CompactionTrigger ContextTier = rpc.ContextTier CustomAgentsUpdatedAgent = rpc.CustomAgentsUpdatedAgent ElicitationCompletedAction = rpc.ElicitationCompletedAction @@ -103,6 +105,7 @@ type ( ExtensionsLoadedExtensionStatus = rpc.ExtensionsLoadedExtensionStatus ExternalToolCompletedData = rpc.ExternalToolCompletedData ExternalToolRequestedData = rpc.ExternalToolRequestedData + FactoryRunUpdatedData = rpc.FactoryRunUpdatedData GitHubRepoRef = rpc.GitHubRepoRef HandoffRepository = rpc.HandoffRepository HandoffSourceType = rpc.HandoffSourceType @@ -189,6 +192,7 @@ type ( PermissionRequestRead = rpc.PermissionRequestRead PermissionRequestShell = rpc.PermissionRequestShell PermissionRequestShellCommand = rpc.PermissionRequestShellCommand + PermissionRequestShellCommandSegment = rpc.PermissionRequestShellCommandSegment PermissionRequestShellPossibleURL = rpc.PermissionRequestShellPossibleURL PermissionRequestURL = rpc.PermissionRequestURL PermissionRequestWrite = rpc.PermissionRequestWrite @@ -212,6 +216,7 @@ type ( ReasoningSummary = rpc.ReasoningSummary SamplingCompletedData = rpc.SamplingCompletedData SamplingRequestedData = rpc.SamplingRequestedData + ScheduleOrigin = rpc.ScheduleOrigin SessionAutoModeResolvedData = rpc.SessionAutoModeResolvedData SessionAutopilotObjectiveChangedData = rpc.SessionAutopilotObjectiveChangedData SessionBackgroundTasksChangedData = rpc.SessionBackgroundTasksChangedData @@ -298,6 +303,8 @@ type ( SystemNotificationShellCompleted = rpc.SystemNotificationShellCompleted SystemNotificationShellDetachedCompleted = rpc.SystemNotificationShellDetachedCompleted SystemNotificationType = rpc.SystemNotificationType + SystemNotificationUnclassified = rpc.SystemNotificationUnclassified + TaskCompletionOutcome = rpc.TaskCompletionOutcome ToolExecutionCompleteContent = rpc.ToolExecutionCompleteContent ToolExecutionCompleteContentAudio = rpc.ToolExecutionCompleteContentAudio ToolExecutionCompleteContentImage = rpc.ToolExecutionCompleteContentImage @@ -386,6 +393,11 @@ const ( AttachmentTypeGitHubTreeComparison = rpc.AttachmentTypeGitHubTreeComparison AttachmentTypeGitHubURL = rpc.AttachmentTypeGitHubURL AttachmentTypeSelection = rpc.AttachmentTypeSelection + AutoApprovalJudgeFailureReasonAbort = rpc.AutoApprovalJudgeFailureReasonAbort + AutoApprovalJudgeFailureReasonEmptyResponse = rpc.AutoApprovalJudgeFailureReasonEmptyResponse + AutoApprovalJudgeFailureReasonModelError = rpc.AutoApprovalJudgeFailureReasonModelError + AutoApprovalJudgeFailureReasonParseError = rpc.AutoApprovalJudgeFailureReasonParseError + AutoApprovalJudgeFailureReasonTimeout = rpc.AutoApprovalJudgeFailureReasonTimeout AutoApprovalRecommendationApprove = rpc.AutoApprovalRecommendationApprove AutoApprovalRecommendationError = rpc.AutoApprovalRecommendationError AutoApprovalRecommendationExcluded = rpc.AutoApprovalRecommendationExcluded @@ -413,6 +425,11 @@ const ( CitationProviderAnthropic = rpc.CitationProviderAnthropic CitationProviderClient = rpc.CitationProviderClient CitationProviderOpenai = rpc.CitationProviderOpenai + CompactionTriggerContextLimitRetry = rpc.CompactionTriggerContextLimitRetry + CompactionTriggerManual = rpc.CompactionTriggerManual + CompactionTriggerMemoryPressure = rpc.CompactionTriggerMemoryPressure + CompactionTriggerModelSwitch = rpc.CompactionTriggerModelSwitch + CompactionTriggerThreshold = rpc.CompactionTriggerThreshold ContextTierDefault = rpc.ContextTierDefault ContextTierLongContext = rpc.ContextTierLongContext ElicitationCompletedActionAccept = rpc.ElicitationCompletedActionAccept @@ -534,6 +551,8 @@ const ( ReasoningSummaryConcise = rpc.ReasoningSummaryConcise ReasoningSummaryDetailed = rpc.ReasoningSummaryDetailed ReasoningSummaryNone = rpc.ReasoningSummaryNone + ScheduleOriginModel = rpc.ScheduleOriginModel + ScheduleOriginUser = rpc.ScheduleOriginUser SessionEventTypeAbort = rpc.SessionEventTypeAbort SessionEventTypeAssistantIdle = rpc.SessionEventTypeAssistantIdle SessionEventTypeAssistantIntent = rpc.SessionEventTypeAssistantIntent @@ -562,6 +581,7 @@ const ( SessionEventTypeExitPlanModeRequested = rpc.SessionEventTypeExitPlanModeRequested SessionEventTypeExternalToolCompleted = rpc.SessionEventTypeExternalToolCompleted SessionEventTypeExternalToolRequested = rpc.SessionEventTypeExternalToolRequested + SessionEventTypeFactoryRunUpdated = rpc.SessionEventTypeFactoryRunUpdated SessionEventTypeHookEnd = rpc.SessionEventTypeHookEnd SessionEventTypeHookProgress = rpc.SessionEventTypeHookProgress SessionEventTypeHookStart = rpc.SessionEventTypeHookStart @@ -676,6 +696,10 @@ const ( SystemNotificationTypeNewInboxMessage = rpc.SystemNotificationTypeNewInboxMessage SystemNotificationTypeShellCompleted = rpc.SystemNotificationTypeShellCompleted SystemNotificationTypeShellDetachedCompleted = rpc.SystemNotificationTypeShellDetachedCompleted + SystemNotificationTypeUnclassified = rpc.SystemNotificationTypeUnclassified + TaskCompletionOutcomeBlocked = rpc.TaskCompletionOutcomeBlocked + TaskCompletionOutcomeCompleted = rpc.TaskCompletionOutcomeCompleted + TaskCompletionOutcomeContinue = rpc.TaskCompletionOutcomeContinue ToolExecutionCompleteContentResourceLinkIconThemeDark = rpc.ToolExecutionCompleteContentResourceLinkIconThemeDark ToolExecutionCompleteContentResourceLinkIconThemeLight = rpc.ToolExecutionCompleteContentResourceLinkIconThemeLight ToolExecutionCompleteContentTypeAudio = rpc.ToolExecutionCompleteContentTypeAudio diff --git a/java/pom.xml b/java/pom.xml index 5016a34b9d..4e491e10ac 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -88,7 +88,7 @@ DO NOT EDIT MANUALLY. Updated by the update-copilot-dependency workflow. --> - ^1.0.73 + ^1.0.76-5 diff --git a/java/scripts/codegen/package-lock.json b/java/scripts/codegen/package-lock.json index 107a777851..f751df8fdd 100644 --- a/java/scripts/codegen/package-lock.json +++ b/java/scripts/codegen/package-lock.json @@ -6,7 +6,7 @@ "": { "name": "copilot-sdk-java-codegen", "dependencies": { - "@github/copilot": "^1.0.73", + "@github/copilot": "^1.0.76-5", "json-schema": "^0.4.0", "tsx": "^4.23.1" } @@ -428,9 +428,9 @@ } }, "node_modules/@github/copilot": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot/-/copilot-1.0.73.tgz", - "integrity": "sha512-8I2Ejg2CX/PQA3c2H8W1zuqhniCeR1q1/bD8CrV53/ZLw8GF7DAV0xQpwa8ELYvFgjXb6AADojafCKwdbVef+A==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot/-/copilot-1.0.76-5.tgz", + "integrity": "sha512-hbE+dgYeR59lEGTNFgBi7G2xbMNetzq2G9FFrLVD1k0Z1ZavSeZAfrfAuBbVCXvYjr2cfKE6oSeMYUB0fArFjw==", "license": "SEE LICENSE IN LICENSE.md", "dependencies": { "detect-libc": "^2.1.2" @@ -439,20 +439,20 @@ "copilot": "npm-loader.js" }, "optionalDependencies": { - "@github/copilot-darwin-arm64": "1.0.73", - "@github/copilot-darwin-x64": "1.0.73", - "@github/copilot-linux-arm64": "1.0.73", - "@github/copilot-linux-x64": "1.0.73", - "@github/copilot-linuxmusl-arm64": "1.0.73", - "@github/copilot-linuxmusl-x64": "1.0.73", - "@github/copilot-win32-arm64": "1.0.73", - "@github/copilot-win32-x64": "1.0.73" + "@github/copilot-darwin-arm64": "1.0.76-5", + "@github/copilot-darwin-x64": "1.0.76-5", + "@github/copilot-linux-arm64": "1.0.76-5", + "@github/copilot-linux-x64": "1.0.76-5", + "@github/copilot-linuxmusl-arm64": "1.0.76-5", + "@github/copilot-linuxmusl-x64": "1.0.76-5", + "@github/copilot-win32-arm64": "1.0.76-5", + "@github/copilot-win32-x64": "1.0.76-5" } }, "node_modules/@github/copilot-darwin-arm64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-darwin-arm64/-/copilot-darwin-arm64-1.0.73.tgz", - "integrity": "sha512-5jv7t2sw35/zI0cPze38hG6239NT5/q/Emjx6gLibYkolDqMDJjpm17Ps7tc8oafUEOiMQMb+ar7+qi6rSiGJA==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-darwin-arm64/-/copilot-darwin-arm64-1.0.76-5.tgz", + "integrity": "sha512-kHg7wUP1RJoNHAd520I1g+nE0kHl4bxQtufg7CE18Xa0aNgC10PcSe9BwqcFEe8RiGdMCUMtohGMKJIqKdyv8Q==", "cpu": [ "arm64" ], @@ -466,9 +466,9 @@ } }, "node_modules/@github/copilot-darwin-x64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-darwin-x64/-/copilot-darwin-x64-1.0.73.tgz", - "integrity": "sha512-l794k6Ahb11AG2FQT/P4TEWxWblzM1h8aQQCzG8jBWp8dfwjhyYjJ+d+0CWQzM3Fc1ddNUZRjKXCUsfvFjiZhQ==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-darwin-x64/-/copilot-darwin-x64-1.0.76-5.tgz", + "integrity": "sha512-B01l/9qLn+BI3yjsTn7tPHJaCA+2hM6KrqSF7NR5HgQ+AtwRriC+ufwlbWPUatrwtXneQZIRgaSKCNUwLsBrBw==", "cpu": [ "x64" ], @@ -482,9 +482,9 @@ } }, "node_modules/@github/copilot-linux-arm64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-linux-arm64/-/copilot-linux-arm64-1.0.73.tgz", - "integrity": "sha512-Zu0W5nupJjNeem0brqU/pG+VY0IWr6EWr/FsC90g5SEDiaM4VhVNVWcz8t0E3DQCSYetV6IBaNMtjs/3uIIiDQ==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-linux-arm64/-/copilot-linux-arm64-1.0.76-5.tgz", + "integrity": "sha512-QvZSCcIA5cxOhWtviLAMHHn8em7PNSTM9DMujfgAAGKl9w1AFhbN+hsTOtvOojdZYXVMZuiQlYmtZ8EemyiZOg==", "cpu": [ "arm64" ], @@ -498,9 +498,9 @@ } }, "node_modules/@github/copilot-linux-x64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-linux-x64/-/copilot-linux-x64-1.0.73.tgz", - "integrity": "sha512-k33XIr6/PVp+K+5F/zv3No4PPaNImvHz73mcbIw63oxh5iiacXjgr0WqbBIS5s/rkhOWjNPIkbof/TTPZ7mQjA==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-linux-x64/-/copilot-linux-x64-1.0.76-5.tgz", + "integrity": "sha512-61wmKXleon7KGv7e2WtbUC6oYH/QkpjowTI3YvgriNaey8/SaZo4ODt59D/L47s8PqqpvPCbe/f6zmjGLNNWEw==", "cpu": [ "x64" ], @@ -514,9 +514,9 @@ } }, "node_modules/@github/copilot-linuxmusl-arm64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-arm64/-/copilot-linuxmusl-arm64-1.0.73.tgz", - "integrity": "sha512-HJWzhfD3oaiIgfRAHkNWzp17fELtshqM9HVN5n+lFEmSO2EETCEh0P1lhJc4m+FYfXSJnL0raAqVuyaNMuPoPw==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-arm64/-/copilot-linuxmusl-arm64-1.0.76-5.tgz", + "integrity": "sha512-WUD8c5YFEL3LecdocT+VIj83EqnNKrb3YL7Wqk+FtFzzjNmF3UGrVo1CbMerTuQzWU65QhgIt1mEBKN1bMSJqQ==", "cpu": [ "arm64" ], @@ -530,9 +530,9 @@ } }, "node_modules/@github/copilot-linuxmusl-x64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-x64/-/copilot-linuxmusl-x64-1.0.73.tgz", - "integrity": "sha512-/BpOXSb16wHEu8I1SaKiLszQ4Kvu4+Z4uCn7W0bv4xI4fPZwTEG0u3zgaI2W9Ao3+aBl0XRpPmpWzE9ziYEq+w==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-x64/-/copilot-linuxmusl-x64-1.0.76-5.tgz", + "integrity": "sha512-HM44XEx1TcZfpLDcFPf0ya0Bi/0wxJzrrR7FRhRG6C2VYBr/mfUsXBUF9V7vZZMv7yKDPro27PLjpsuMDJyYsQ==", "cpu": [ "x64" ], @@ -546,9 +546,9 @@ } }, "node_modules/@github/copilot-win32-arm64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-win32-arm64/-/copilot-win32-arm64-1.0.73.tgz", - "integrity": "sha512-DbPeXiYzQjpOy9oboaBvuCzjRwfcL987c3bG09cK1crdCDrKfkTJ7NXpcp1KWRPIRFO1FQm1qToNE89J+L3uvg==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-win32-arm64/-/copilot-win32-arm64-1.0.76-5.tgz", + "integrity": "sha512-cbrnDRo7cYAbJuCt4f+1Cw8SiFfNOkCBg3RR/jAcV7Y5ED3QEEoad3WN8avFaiAOGHyTJYqBRTQJNBkyRTmrEw==", "cpu": [ "arm64" ], @@ -562,9 +562,9 @@ } }, "node_modules/@github/copilot-win32-x64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-win32-x64/-/copilot-win32-x64-1.0.73.tgz", - "integrity": "sha512-8D3E1l5i+N5Eq8HIOQpx+Zbcb3MXdFxszksM2gqq175Z1S7Zna67oY4GoR3psxlbIpSyHKiLEBWYiaps6ayHWw==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-win32-x64/-/copilot-win32-x64-1.0.76-5.tgz", + "integrity": "sha512-ShgpTm07YqQQuRLgJ5BqVzKfSlZ4YMmlz7rl/Br5Ifkz57+/HUF2EJBX2LDt05ha1isOaN1ekZQmWvdzWrVCoQ==", "cpu": [ "x64" ], diff --git a/java/scripts/codegen/package.json b/java/scripts/codegen/package.json index dbe8b5e6ef..df1e74ac5c 100644 --- a/java/scripts/codegen/package.json +++ b/java/scripts/codegen/package.json @@ -7,7 +7,7 @@ "generate:java": "tsx java.ts" }, "dependencies": { - "@github/copilot": "^1.0.73", + "@github/copilot": "^1.0.76-5", "json-schema": "^0.4.0", "tsx": "^4.23.1" } diff --git a/java/src/generated/java/com/github/copilot/generated/AssistantMessageEvent.java b/java/src/generated/java/com/github/copilot/generated/AssistantMessageEvent.java index fdbdc0afd7..6c1a87324a 100644 --- a/java/src/generated/java/com/github/copilot/generated/AssistantMessageEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/AssistantMessageEvent.java @@ -63,6 +63,7 @@ public record AssistantMessageEventData( @JsonProperty("clientRequestId") String clientRequestId, /** Copilot service request ID (x-copilot-service-request-id header) for CAPI log correlation */ @JsonProperty("serviceRequestId") String serviceRequestId, + @JsonProperty("rte") Boolean rte, /** Provider's completion / response identifier; shared across all chunks of a single API call. Used to group multi-chunk assistant utterances. */ @JsonProperty("apiCallId") String apiCallId, /** Neutral provider-tagged server-side tool-use payload (tool search, advisor) for verbatim round-tripping */ diff --git a/java/src/generated/java/com/github/copilot/generated/AssistantReasoningEvent.java b/java/src/generated/java/com/github/copilot/generated/AssistantReasoningEvent.java index 9b69fedac1..52996aeeed 100644 --- a/java/src/generated/java/com/github/copilot/generated/AssistantReasoningEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/AssistantReasoningEvent.java @@ -37,7 +37,8 @@ public record AssistantReasoningEventData( /** Unique identifier for this reasoning block */ @JsonProperty("reasoningId") String reasoningId, /** The complete extended thinking text from the model */ - @JsonProperty("content") String content + @JsonProperty("content") String content, + @JsonProperty("rte") Boolean rte ) { } } diff --git a/java/src/generated/java/com/github/copilot/generated/AssistantUsageEvent.java b/java/src/generated/java/com/github/copilot/generated/AssistantUsageEvent.java index 47bfcbb4c7..a7de95bb4b 100644 --- a/java/src/generated/java/com/github/copilot/generated/AssistantUsageEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/AssistantUsageEvent.java @@ -60,12 +60,15 @@ public record AssistantUsageEventData( @JsonProperty("interTokenLatencyMs") Double interTokenLatencyMs, /** What initiated this API call (e.g., "sub-agent", "mcp-sampling"); absent for user-initiated calls */ @JsonProperty("initiator") String initiator, + /** Coarse classification of the interaction that produced this call, mirroring the session's per-request agent context (e.g. `conversation-agent`, `conversation-subagent`, `conversation-sampling`, `conversation-background`, `conversation-compaction`, `conversation-user`). Non-billing; lets consumers attribute a model call to a call class (e.g. sub-agent/sidekick) independently of the billing initiator. Absent when the runtime did not classify the request. */ + @JsonProperty("interactionType") String interactionType, /** Completion ID from the model provider (e.g., chatcmpl-abc123) */ @JsonProperty("apiCallId") String apiCallId, /** GitHub request tracing ID (x-github-request-id header) for server-side log correlation */ @JsonProperty("providerCallId") String providerCallId, /** Copilot service request ID (x-copilot-service-request-id header) for CAPI log correlation */ @JsonProperty("serviceRequestId") String serviceRequestId, + @JsonProperty("rte") Boolean rte, /** API endpoint used for this model call, matching CAPI supported_endpoints vocabulary */ @JsonProperty("apiEndpoint") AssistantUsageApiEndpoint apiEndpoint, /** Parent tool call ID when this usage originates from a sub-agent */ diff --git a/java/src/generated/java/com/github/copilot/generated/CompactionTrigger.java b/java/src/generated/java/com/github/copilot/generated/CompactionTrigger.java new file mode 100644 index 0000000000..1c77861dcc --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/CompactionTrigger.java @@ -0,0 +1,41 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import javax.annotation.processing.Generated; + +/** + * What initiated a conversation compaction + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum CompactionTrigger { + /** The {@code threshold} variant. */ + THRESHOLD("threshold"), + /** The {@code context_limit_retry} variant. */ + CONTEXT_LIMIT_RETRY("context_limit_retry"), + /** The {@code manual} variant. */ + MANUAL("manual"), + /** The {@code memory_pressure} variant. */ + MEMORY_PRESSURE("memory_pressure"), + /** The {@code model_switch} variant. */ + MODEL_SWITCH("model_switch"); + + private final String value; + CompactionTrigger(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static CompactionTrigger fromValue(String value) { + for (CompactionTrigger v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown CompactionTrigger value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/FactoryRunUpdatedEvent.java b/java/src/generated/java/com/github/copilot/generated/FactoryRunUpdatedEvent.java new file mode 100644 index 0000000000..e9abb1053a --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/FactoryRunUpdatedEvent.java @@ -0,0 +1,42 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Session event "factory.run_updated". Ephemeral invalidation signal for a changed factory run. + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class FactoryRunUpdatedEvent extends SessionEvent { + + @Override + public String getType() { return "factory.run_updated"; } + + @JsonProperty("data") + private FactoryRunUpdatedEventData data; + + public FactoryRunUpdatedEventData getData() { return data; } + public void setData(FactoryRunUpdatedEventData data) { this.data = data; } + + /** Data payload for {@link FactoryRunUpdatedEvent}. */ + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public record FactoryRunUpdatedEventData( + @JsonProperty("runId") String runId, + /** Monotonic revision now available for the run. */ + @JsonProperty("revision") Long revision + ) { + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/ModelCallFailureEvent.java b/java/src/generated/java/com/github/copilot/generated/ModelCallFailureEvent.java index 25c011fe33..f6c399b4c3 100644 --- a/java/src/generated/java/com/github/copilot/generated/ModelCallFailureEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/ModelCallFailureEvent.java @@ -45,6 +45,7 @@ public record ModelCallFailureEventData( @JsonProperty("providerCallId") String providerCallId, /** Copilot service request ID (x-copilot-service-request-id header) for CAPI log correlation */ @JsonProperty("serviceRequestId") String serviceRequestId, + @JsonProperty("rte") Boolean rte, /** HTTP status code from the failed request */ @JsonProperty("statusCode") Long statusCode, /** Duration of the failed API call in milliseconds */ diff --git a/java/src/generated/java/com/github/copilot/generated/ModelCallStartEvent.java b/java/src/generated/java/com/github/copilot/generated/ModelCallStartEvent.java index 6ab9fa5477..9f00e2ac2f 100644 --- a/java/src/generated/java/com/github/copilot/generated/ModelCallStartEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/ModelCallStartEvent.java @@ -37,7 +37,9 @@ public record ModelCallStartEventData( /** Identifier of the assistant turn that initiated the model call */ @JsonProperty("turnId") String turnId, /** Model identifier used for this API call, when known */ - @JsonProperty("model") String model + @JsonProperty("model") String model, + /** Previous response or interaction identifier included in the model request, when present */ + @JsonProperty("previousResponseId") String previousResponseId ) { } } diff --git a/java/src/generated/java/com/github/copilot/generated/PermissionRequestedEvent.java b/java/src/generated/java/com/github/copilot/generated/PermissionRequestedEvent.java index 98eecceb58..b7aae9ec80 100644 --- a/java/src/generated/java/com/github/copilot/generated/PermissionRequestedEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/PermissionRequestedEvent.java @@ -40,6 +40,8 @@ public record PermissionRequestedEventData( @JsonProperty("permissionRequest") Object permissionRequest, /** Derived user-facing permission prompt details for UI consumers */ @JsonProperty("promptRequest") Object promptRequest, + /** Neutral risk metadata supplied by the tool host. Consumers may display this value but must not use it to bypass the permission decision. */ + @JsonProperty("riskAssessment") Object riskAssessment, /** When true, this permission was already resolved by a permissionRequest hook and requires no client action */ @JsonProperty("resolvedByHook") Boolean resolvedByHook ) { diff --git a/java/src/generated/java/com/github/copilot/generated/ScheduleOrigin.java b/java/src/generated/java/com/github/copilot/generated/ScheduleOrigin.java new file mode 100644 index 0000000000..cba65eadb5 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/ScheduleOrigin.java @@ -0,0 +1,35 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import javax.annotation.processing.Generated; + +/** + * Who created the schedule: `user` (an explicit user action such as `/every` or `/after`) or `model` (the agent via the `manage_schedule` tool). Gates whether a scheduled skill that opted out of model invocation may fire: only user-created schedules may. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum ScheduleOrigin { + /** The {@code user} variant. */ + USER("user"), + /** The {@code model} variant. */ + MODEL("model"); + + private final String value; + ScheduleOrigin(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static ScheduleOrigin fromValue(String value) { + for (ScheduleOrigin v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown ScheduleOrigin value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/SessionAutoModeResolvedEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionAutoModeResolvedEvent.java index f79be388ec..88b06f4471 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionAutoModeResolvedEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionAutoModeResolvedEvent.java @@ -47,7 +47,25 @@ public record SessionAutoModeResolvedEventData( /** Classifier confidence for the predicted label, when available */ @JsonProperty("confidence") Double confidence, /** Ordered candidate model list the router returned, when not a fallback */ - @JsonProperty("candidateModels") List candidateModels + @JsonProperty("candidateModels") List candidateModels, + /** The routing method the server applied, when Auto Intent ran */ + @JsonProperty("routingMethod") String routingMethod, + /** Models offered to the router for this resolution */ + @JsonProperty("availableModels") List availableModels, + /** Whether the router fell back to the standard Auto selection */ + @JsonProperty("fallback") Boolean fallback, + /** Server-provided reason for falling back, when available */ + @JsonProperty("fallbackReason") String fallbackReason, + /** Whether a sticky model choice overrode the router result */ + @JsonProperty("stickyOverride") Boolean stickyOverride, + /** Server-reported router processing time in milliseconds */ + @JsonProperty("routerLatencyMs") Double routerLatencyMs, + /** End-to-end client wait time for the router request in milliseconds */ + @JsonProperty("endToEndLatencyMs") Double endToEndLatencyMs, + /** The chosen model's score shortfall relative to the top candidate */ + @JsonProperty("chosenShortfall") Double chosenShortfall, + /** Whether the routed prompt contained an image */ + @JsonProperty("hasImage") Boolean hasImage ) { } } diff --git a/java/src/generated/java/com/github/copilot/generated/SessionCompactionCompleteEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionCompactionCompleteEvent.java index 8771d3114a..d05110abce 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionCompactionCompleteEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionCompactionCompleteEvent.java @@ -69,7 +69,11 @@ public record SessionCompactionCompleteEventData( /** Token count from tool definitions after compaction */ @JsonProperty("toolDefinitionsTokens") Long toolDefinitionsTokens, /** For failed compaction only: the HTTP status code of the compaction LLM call failure, when it carried one. Absent for successful compaction and for failures without an HTTP status (e.g. an empty model response or a transport error). */ - @JsonProperty("statusCode") Long statusCode + @JsonProperty("statusCode") Long statusCode, + /** Model context window token limit the compaction was targeting, when known */ + @JsonProperty("tokenLimit") Long tokenLimit, + /** What initiated this compaction, when known */ + @JsonProperty("trigger") CompactionTrigger trigger ) { } } diff --git a/java/src/generated/java/com/github/copilot/generated/SessionCompactionStartEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionCompactionStartEvent.java index e92a3ac50f..076a124262 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionCompactionStartEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionCompactionStartEvent.java @@ -41,7 +41,13 @@ public record SessionCompactionStartEventData( /** Token count from non-system messages (user, assistant, tool) at compaction start */ @JsonProperty("conversationTokens") Long conversationTokens, /** Token count from tool definitions at compaction start */ - @JsonProperty("toolDefinitionsTokens") Long toolDefinitionsTokens + @JsonProperty("toolDefinitionsTokens") Long toolDefinitionsTokens, + /** Total context tokens (system + conversation + tool definitions) at compaction start, when known */ + @JsonProperty("currentTokens") Long currentTokens, + /** Model context window token limit the compaction is targeting, when known */ + @JsonProperty("tokenLimit") Long tokenLimit, + /** What initiated this compaction, when known */ + @JsonProperty("trigger") CompactionTrigger trigger ) { } } diff --git a/java/src/generated/java/com/github/copilot/generated/SessionContextChangedEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionContextChangedEvent.java index 6fb6a54db9..fc96eff674 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionContextChangedEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionContextChangedEvent.java @@ -49,7 +49,9 @@ public record SessionContextChangedEventData( /** Head commit of current git branch at session start time */ @JsonProperty("headCommit") String headCommit, /** Base commit of current git branch at session start time */ - @JsonProperty("baseCommit") String baseCommit + @JsonProperty("baseCommit") String baseCommit, + /** Set on the immediate preliminary event of a working-directory change, before the git context is resolved. A settled follow-up event (enriched with git context, or cwd-only for a non-repository) is always emitted afterward, so observers may defer to it. Absent on standalone/final events (e.g. relay context changes). */ + @JsonProperty("pendingGitContext") Boolean pendingGitContext ) { } } diff --git a/java/src/generated/java/com/github/copilot/generated/SessionEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionEvent.java index 162572b037..adef027ada 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionEvent.java @@ -122,6 +122,7 @@ @JsonSubTypes.Type(value = ExitPlanModeCompletedEvent.class, name = "exit_plan_mode.completed"), @JsonSubTypes.Type(value = SessionToolsUpdatedEvent.class, name = "session.tools_updated"), @JsonSubTypes.Type(value = SessionBackgroundTasksChangedEvent.class, name = "session.background_tasks_changed"), + @JsonSubTypes.Type(value = FactoryRunUpdatedEvent.class, name = "factory.run_updated"), @JsonSubTypes.Type(value = SessionSkillsLoadedEvent.class, name = "session.skills_loaded"), @JsonSubTypes.Type(value = SessionCustomAgentsUpdatedEvent.class, name = "session.custom_agents_updated"), @JsonSubTypes.Type(value = SessionMcpServersLoadedEvent.class, name = "session.mcp_servers_loaded"), @@ -238,6 +239,7 @@ public abstract sealed class SessionEvent permits ExitPlanModeCompletedEvent, SessionToolsUpdatedEvent, SessionBackgroundTasksChangedEvent, + FactoryRunUpdatedEvent, SessionSkillsLoadedEvent, SessionCustomAgentsUpdatedEvent, SessionMcpServersLoadedEvent, diff --git a/java/src/generated/java/com/github/copilot/generated/SessionManagedSettingsResolvedEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionManagedSettingsResolvedEvent.java index 7cc495269f..7c7a4df738 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionManagedSettingsResolvedEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionManagedSettingsResolvedEvent.java @@ -45,6 +45,8 @@ public record SessionManagedSettingsResolvedEventData( @JsonProperty("failClosed") Boolean failClosed, /** Whether enterprise policy disables bypass-permissions ("yolo") mode for this session. Deny-wins across layers, and forced on when `failClosed` is true. */ @JsonProperty("bypassPermissionsDisabled") Boolean bypassPermissionsDisabled, + /** Whether server and device each supplied a permission allowlist, so enforcement intersects them and the flattened settings payload omits `permissions.allow`. */ + @JsonProperty("permissionsAllowIntersected") Boolean permissionsAllowIntersected, /** The setting keys under enterprise management in the effective managed settings (e.g. `model`, `enabledPlugins`, `permissions`). Empty when no managed settings are in force. */ @JsonProperty("managedKeys") List managedKeys, /** The effective (resolved) managed settings values, so clients can render exactly what is enforced. Absent when no managed policy is in force. */ diff --git a/java/src/generated/java/com/github/copilot/generated/SessionResumeEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionResumeEvent.java index 6efac46f27..a3f39d7696 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionResumeEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionResumeEvent.java @@ -57,11 +57,11 @@ public record SessionResumeEventData( @JsonProperty("context") WorkingDirectoryContext context, /** Whether the session was already in use by another client at resume time */ @JsonProperty("alreadyInUse") Boolean alreadyInUse, - /** True when this resume attached to a session that the runtime already had running in-memory (for example, an extension joining a session another client was actively driving). False (or omitted) for cold resumes — the runtime had to reconstitute the session from its persisted event log. */ + /** True when this resume passively joined a session that already had live work running in the runtime - an agent turn, a native queue run, a queued resume continuation, or an in-flight send (for example, an extension joining a session another client was actively driving). False (or omitted) when the session had no live work or when the resume explicitly abandoned pending work, including cold resumes and suspended sessions that remain resident in memory. */ @JsonProperty("sessionWasActive") Boolean sessionWasActive, /** Whether this session supports remote steering via GitHub */ @JsonProperty("remoteSteerable") Boolean remoteSteerable, - /** When true, tool calls and permission requests left in flight by the previous session lifetime remain pending after resume and the agentic loop awaits their results. User sends are queued behind the pending work until all such requests reach a terminal state. When false (the default), any such tool calls and permission requests are immediately marked as interrupted on resume. */ + /** When true, tool calls and permission requests left in flight by the previous session lifetime remain pending after resume and the agentic loop awaits their results. User sends are queued behind the pending work until all such requests reach a terminal state. When false or omitted, pending work is normally marked as interrupted unless the resume passively joined live work owned by another client; sessionWasActive distinguishes that case. */ @JsonProperty("continuePendingWork") Boolean continuePendingWork ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/SessionScheduleCreatedEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionScheduleCreatedEvent.java index 435a8501e8..cc0b3b165d 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionScheduleCreatedEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionScheduleCreatedEvent.java @@ -51,7 +51,9 @@ public record SessionScheduleCreatedEventData( /** True for a self-paced (`dynamic`) schedule: no fixed cadence; the model arms each next run via the `manage_schedule` `wakeup` action. `nextRunAt` is model-controlled rather than auto-computed. */ @JsonProperty("selfPaced") Boolean selfPaced, /** Optional user-facing label shown in the timeline instead of the actual prompt (e.g. `/skill-name args` when the prompt is a skill invocation expansion) */ - @JsonProperty("displayPrompt") String displayPrompt + @JsonProperty("displayPrompt") String displayPrompt, + /** Who created the schedule (`user` or `model`). Persisted so a resumed session keeps gating non-user schedules from firing skills that opted out of model invocation. Absent on entries created before this field existed; a missing origin fails closed (treated the same as a non-user origin), so such a schedule may not resolve a `disable-model-invocation` skill. */ + @JsonProperty("origin") ScheduleOrigin origin ) { } } diff --git a/java/src/generated/java/com/github/copilot/generated/SessionTaskCompleteEvent.java b/java/src/generated/java/com/github/copilot/generated/SessionTaskCompleteEvent.java index 8933662bab..c44c682b1c 100644 --- a/java/src/generated/java/com/github/copilot/generated/SessionTaskCompleteEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SessionTaskCompleteEvent.java @@ -36,8 +36,14 @@ public final class SessionTaskCompleteEvent extends SessionEvent { public record SessionTaskCompleteEventData( /** Summary of the completed task, provided by the agent */ @JsonProperty("summary") String summary, - /** Whether the tool call succeeded. False when validation failed (e.g., invalid arguments) */ - @JsonProperty("success") Boolean success + /** Whether the task was accepted as complete. False when validation failed or completion was rejected or blocked by the reviewer */ + @JsonProperty("success") Boolean success, + /** Semantic completion decision. Absent on legacy events and invalid tool calls */ + @JsonProperty("outcome") TaskCompletionOutcome outcome, + /** Label-safe runtime rationale for the completion decision (e.g. a cancellation or pause/resume downgrade), when one applies. Reviewer-authored rationale is intentionally omitted here because this event has no IFC label channel; the reviewer's findings remain available through its own labeled sub-agent events */ + @JsonProperty("reason") String reason, + /** Active autopilot objective ID evaluated by the completion reviewer */ + @JsonProperty("objectiveId") Long objectiveId ) { } } diff --git a/java/src/generated/java/com/github/copilot/generated/SystemMessageEvent.java b/java/src/generated/java/com/github/copilot/generated/SystemMessageEvent.java index a6248a7fee..315e9e8bb6 100644 --- a/java/src/generated/java/com/github/copilot/generated/SystemMessageEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/SystemMessageEvent.java @@ -36,6 +36,8 @@ public final class SystemMessageEvent extends SessionEvent { public record SystemMessageEventData( /** The system or developer prompt text sent as model input */ @JsonProperty("content") String content, + /** Logical interaction identifier for the model run receiving this prompt */ + @JsonProperty("interactionId") String interactionId, /** Message role: "system" for system prompts, "developer" for developer-injected instructions */ @JsonProperty("role") SystemMessageRole role, /** Optional name identifier for the message source */ diff --git a/java/src/generated/java/com/github/copilot/generated/TaskCompletionOutcome.java b/java/src/generated/java/com/github/copilot/generated/TaskCompletionOutcome.java new file mode 100644 index 0000000000..827cf2b77b --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/TaskCompletionOutcome.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: session-events.schema.json + +package com.github.copilot.generated; + +import javax.annotation.processing.Generated; + +/** + * Semantic result of evaluating a task completion request + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum TaskCompletionOutcome { + /** The {@code completed} variant. */ + COMPLETED("completed"), + /** The {@code continue} variant. */ + CONTINUE("continue"), + /** The {@code blocked} variant. */ + BLOCKED("blocked"); + + private final String value; + TaskCompletionOutcome(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static TaskCompletionOutcome fromValue(String value) { + for (TaskCompletionOutcome v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown TaskCompletionOutcome value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteEvent.java b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteEvent.java index 99d138b1e6..a265b5305e 100644 --- a/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/ToolExecutionCompleteEvent.java @@ -45,6 +45,7 @@ public record ToolExecutionCompleteEventData( @JsonProperty("mcpMeta") Object mcpMeta, /** CAPI interaction ID for correlating this tool execution with upstream telemetry */ @JsonProperty("interactionId") String interactionId, + @JsonProperty("rte") Boolean rte, /** Whether this tool call was explicitly requested by the user rather than the assistant */ @JsonProperty("isUserRequested") Boolean isUserRequested, /** Tool execution result on success */ diff --git a/java/src/generated/java/com/github/copilot/generated/ToolExecutionStartEvent.java b/java/src/generated/java/com/github/copilot/generated/ToolExecutionStartEvent.java index b119a3eb0e..782e93931f 100644 --- a/java/src/generated/java/com/github/copilot/generated/ToolExecutionStartEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/ToolExecutionStartEvent.java @@ -44,6 +44,7 @@ public record ToolExecutionStartEventData( @JsonProperty("shellToolInfo") ToolExecutionStartShellToolInfo shellToolInfo, /** Model identifier that generated this tool call */ @JsonProperty("model") String model, + @JsonProperty("rte") Boolean rte, /** Name of the MCP server hosting this tool, when the tool is an MCP tool */ @JsonProperty("mcpServerName") String mcpServerName, /** Original tool name on the MCP server, when the tool is an MCP tool */ diff --git a/java/src/generated/java/com/github/copilot/generated/UserMessageEvent.java b/java/src/generated/java/com/github/copilot/generated/UserMessageEvent.java index 5af4842430..bc579968b3 100644 --- a/java/src/generated/java/com/github/copilot/generated/UserMessageEvent.java +++ b/java/src/generated/java/com/github/copilot/generated/UserMessageEvent.java @@ -45,7 +45,7 @@ public record UserMessageEventData( @JsonProperty("supportedNativeDocumentMimeTypes") List supportedNativeDocumentMimeTypes, /** Path-backed native document attachments that stayed on the tagged_files path flow because native upload could not read them or would exceed the request size limit */ @JsonProperty("nativeDocumentPathFallbackPaths") List nativeDocumentPathFallbackPaths, - /** Origin of this message, used for timeline filtering (e.g., "skill-pdf" for skill-injected messages that should be hidden from the user) */ + /** Origin of this message, used for timeline filtering and attribution (e.g., `skill-pdf` for hidden skill injection or `agent-` for an inter-agent prompt) */ @JsonProperty("source") String source, /** How this message was delivered to the agentic loop relative to loop state (idle-start vs. steering/queued while busy). The timing axis; combine with `source` (origin) for the full picture. Used for telemetry attribution. */ @JsonProperty("delivery") UserMessageDelivery delivery, diff --git a/java/src/generated/java/com/github/copilot/generated/WorkingDirectoryContext.java b/java/src/generated/java/com/github/copilot/generated/WorkingDirectoryContext.java index 813cd5e02f..e22fc461d6 100644 --- a/java/src/generated/java/com/github/copilot/generated/WorkingDirectoryContext.java +++ b/java/src/generated/java/com/github/copilot/generated/WorkingDirectoryContext.java @@ -36,6 +36,8 @@ public record WorkingDirectoryContext( /** Head commit of current git branch at session start time */ @JsonProperty("headCommit") String headCommit, /** Base commit of current git branch at session start time */ - @JsonProperty("baseCommit") String baseCommit + @JsonProperty("baseCommit") String baseCommit, + /** Set on the immediate preliminary event of a working-directory change, before the git context is resolved. A settled follow-up event (enriched with git context, or cwd-only for a non-repository) is always emitted afterward, so observers may defer to it. Absent on standalone/final events (e.g. relay context changes). */ + @JsonProperty("pendingGitContext") Boolean pendingGitContext ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/AgentInfo.java b/java/src/generated/java/com/github/copilot/generated/rpc/AgentInfo.java index 29813e30a0..f239c82e61 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/AgentInfo.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/AgentInfo.java @@ -15,7 +15,7 @@ import javax.annotation.processing.Generated; /** - * Custom agent metadata, including identifiers, display details, source, tools, model, MCP servers, skills, and file path. + * Agent metadata, including identifiers, display details, source, tools, model, MCP servers, skills, and file path. * * @since 1.0.0 */ @@ -23,7 +23,7 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public record AgentInfo( - /** Unique identifier of the custom agent */ + /** Name of the agent. Use `id` as the stable selection identifier. */ @JsonProperty("name") String name, /** Human-readable display name */ @JsonProperty("displayName") String displayName, @@ -39,11 +39,13 @@ public record AgentInfo( @JsonProperty("userInvocable") Boolean userInvocable, /** Allowed tool names for this agent. Empty array means none; omitted means inherit defaults. */ @JsonProperty("tools") List tools, - /** Preferred model id for this agent. When omitted, inherits the outer agent's model. */ + /** Authored preferred model id for this agent. Runtime model selection may choose a different model; omitted means no authored preference. */ @JsonProperty("model") String model, /** MCP server configurations attached to this agent, keyed by server name. Server config shape mirrors the MCP `mcpServers` schema. */ @JsonProperty("mcpServers") Map mcpServers, /** Skill names preloaded into this agent's context. Omitted means none. */ - @JsonProperty("skills") List skills + @JsonProperty("skills") List skills, + /** Authored base prompt for the agent. Runtime prompt assembly may add dynamic context at invocation time. Omitted from `session.agent.list` unless `includePrompt` is true. */ + @JsonProperty("prompt") String prompt ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/BuiltInModelCatalogEntry.java b/java/src/generated/java/com/github/copilot/generated/rpc/BuiltInModelCatalogEntry.java new file mode 100644 index 0000000000..679278356e --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/BuiltInModelCatalogEntry.java @@ -0,0 +1,27 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * A well-known model in the runtime's built-in catalog. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record BuiltInModelCatalogEntry( + /** Well-known runtime model ID suitable for `ProviderConfig.modelId` or `ProviderModelConfig.modelId`. This is not necessarily the provider-facing deployment or model name and does not indicate CAPI entitlement or provider availability. */ + @JsonProperty("id") String id +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ConnectParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/ConnectParams.java index 491dadad37..19172cb1b4 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ConnectParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ConnectParams.java @@ -26,7 +26,7 @@ public record ConnectParams( /** Connection token; required when the server was started with COPILOT_CONNECTION_TOKEN */ @JsonProperty("token") String token, - /** Opt this connection in to GitHub telemetry forwarding for its lifetime. When set, the runtime forwards every internal telemetry event it emits — across all sessions, plus sessionless events — to this connection over the `gitHubTelemetry.event` notification, in addition to the runtime's normal GitHub/CTS emission (dual-write). Intended for first-party hosts that re-emit the events into their own telemetry stores. Both unrestricted and restricted events are forwarded, each tagged with a `restricted` discriminator; a backstop drops restricted events when restricted telemetry is disabled. */ + /** Opt this connection in to GitHub telemetry forwarding for its lifetime. When set, the runtime forwards every internal telemetry event it emits — across all sessions, plus sessionless events — to this connection over the `gitHubTelemetry.event` notification. Regular events are also written to the runtime's normal GitHub/CTS path (dual-write); host-only compatibility events are forward-only and intentionally skip that path. Intended for first-party hosts that re-emit the events into their own telemetry stores. Both unrestricted and restricted events are forwarded, each tagged with a `restricted` discriminator; a backstop drops restricted events when restricted telemetry is disabled — using the process-global gate for ordinary events and an explicit session-scoped decision for host-only events. */ @JsonProperty("enableGitHubTelemetryForwarding") Boolean enableGitHubTelemetryForwarding ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ContentExclusionPathCheck.java b/java/src/generated/java/com/github/copilot/generated/rpc/ContentExclusionPathCheck.java new file mode 100644 index 0000000000..ba48326c2e --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ContentExclusionPathCheck.java @@ -0,0 +1,29 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Content-exclusion decision for one requested path. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record ContentExclusionPathCheck( + /** The path supplied by the caller. */ + @JsonProperty("path") String path, + /** Whether the session's complete content-exclusion policy excludes the path. */ + @JsonProperty("excluded") Boolean excluded +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/FactoryAgentSummary.java b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryAgentSummary.java new file mode 100644 index 0000000000..af20d8e810 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryAgentSummary.java @@ -0,0 +1,38 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Prompt-safe durable identity and live status for a direct factory agent. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record FactoryAgentSummary( + @JsonProperty("agentId") String agentId, + @JsonProperty("toolCallId") String toolCallId, + @JsonProperty("runId") String runId, + @JsonProperty("phaseId") String phaseId, + @JsonProperty("label") String label, + @JsonProperty("agentType") String agentType, + @JsonProperty("status") String status, + @JsonProperty("requestedModel") String requestedModel, + @JsonProperty("resolvedModel") String resolvedModel, + @JsonProperty("startedAt") Long startedAt, + @JsonProperty("completedAt") Long completedAt, + @JsonProperty("activeMs") Long activeMs, + @JsonProperty("activity") String activity +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/FactoryCurrentPhase.java b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryCurrentPhase.java new file mode 100644 index 0000000000..6a8de8e82c --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryCurrentPhase.java @@ -0,0 +1,27 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Current factory phase identity. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record FactoryCurrentPhase( + @JsonProperty("id") String id, + @JsonProperty("ordinal") Long ordinal +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/FactoryDeclaredLimits.java b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryDeclaredLimits.java new file mode 100644 index 0000000000..21f74646fb --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryDeclaredLimits.java @@ -0,0 +1,29 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Declared or approved factory resource ceilings. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record FactoryDeclaredLimits( + @JsonProperty("maxConcurrentSubagents") Long maxConcurrentSubagents, + @JsonProperty("maxTotalSubagents") Long maxTotalSubagents, + @JsonProperty("timeoutSeconds") Double timeoutSeconds, + @JsonProperty("maxAiCredits") Double maxAiCredits +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/FactoryExecuteParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryExecuteParams.java index e6f4538146..6834dd4b12 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/FactoryExecuteParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryExecuteParams.java @@ -30,6 +30,8 @@ public record FactoryExecuteParams( @JsonProperty("name") String name, /** Factory run identifier. */ @JsonProperty("runId") String runId, + /** Opaque token identifying this factory execution attempt. */ + @JsonProperty("executionToken") String executionToken, /** Factory input value. */ @JsonProperty("args") Object args ) { diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/FactoryPhaseObservation.java b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryPhaseObservation.java new file mode 100644 index 0000000000..aa04ef5ba8 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryPhaseObservation.java @@ -0,0 +1,38 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Durable lifecycle and timing for one factory phase. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record FactoryPhaseObservation( + @JsonProperty("id") String id, + @JsonProperty("ordinal") Long ordinal, + @JsonProperty("title") String title, + @JsonProperty("detail") String detail, + @JsonProperty("status") FactoryPhaseStatus status, + @JsonProperty("lastEnteredRunAttempt") Long lastEnteredRunAttempt, + @JsonProperty("entryCount") Long entryCount, + @JsonProperty("startedAt") Long startedAt, + @JsonProperty("completedAt") Long completedAt, + @JsonProperty("accumulatedActiveMs") Long accumulatedActiveMs, + @JsonProperty("currentActiveMs") Long currentActiveMs, + @JsonProperty("totalAgentCount") Long totalAgentCount, + @JsonProperty("liveAgentCount") Long liveAgentCount +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/FactoryPhaseStatus.java b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryPhaseStatus.java new file mode 100644 index 0000000000..d9fea0bc36 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryPhaseStatus.java @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Derived lifecycle state of a factory phase. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum FactoryPhaseStatus { + /** The {@code pending} variant. */ + PENDING("pending"), + /** The {@code active} variant. */ + ACTIVE("active"), + /** The {@code completed} variant. */ + COMPLETED("completed"), + /** The {@code skipped} variant. */ + SKIPPED("skipped"); + + private final String value; + FactoryPhaseStatus(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static FactoryPhaseStatus fromValue(String value) { + for (FactoryPhaseStatus v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown FactoryPhaseStatus value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/FactoryProgressLine.java b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryProgressLine.java new file mode 100644 index 0000000000..3a26b67d79 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryProgressLine.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * One durable factory progress record. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record FactoryProgressLine( + /** Global monotonic sequence number within the run. */ + @JsonProperty("seq") Long seq, + /** Resume attempt that emitted this record. */ + @JsonProperty("attempt") Long attempt, + /** Phase active when the record was emitted, or null before any phase. */ + @JsonProperty("phaseId") String phaseId, + /** Epoch milliseconds when the record was persisted. */ + @JsonProperty("recordedAt") Long recordedAt, + /** Progress record kind. */ + @JsonProperty("kind") FactoryLogLineKind kind, + /** Prompt-safe progress text. */ + @JsonProperty("text") String text +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/FactoryProgressPage.java b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryProgressPage.java new file mode 100644 index 0000000000..56732d8f47 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryProgressPage.java @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * A bidirectional page of factory progress. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record FactoryProgressPage( + @JsonProperty("records") List records, + @JsonProperty("oldestSeq") Long oldestSeq, + @JsonProperty("newestSeq") Long newestSeq, + @JsonProperty("hasMoreOlder") Boolean hasMoreOlder, + @JsonProperty("hasMoreNewer") Boolean hasMoreNewer, + /** Run revision reflected by this page. */ + @JsonProperty("revision") Long revision +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/FactoryRunConsumed.java b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryRunConsumed.java new file mode 100644 index 0000000000..62cec5f730 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryRunConsumed.java @@ -0,0 +1,28 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Durable factory resource consumption. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record FactoryRunConsumed( + @JsonProperty("activeMs") Long activeMs, + @JsonProperty("subagents") Long subagents, + @JsonProperty("nanoAiu") Long nanoAiu +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/FactoryRunLimits.java b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryRunLimits.java index ede598b806..79304772a0 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/FactoryRunLimits.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryRunLimits.java @@ -25,7 +25,9 @@ public record FactoryRunLimits( @JsonProperty("maxConcurrentSubagents") Long maxConcurrentSubagents, /** Maximum total number of factory subagents that may be admitted. */ @JsonProperty("maxTotalSubagents") Long maxTotalSubagents, - /** Factory active-run timeout in milliseconds. */ - @JsonProperty("timeout") Double timeout + /** Maximum accumulated active-execution time in seconds. Active execution includes the entire extension body, subprocess waits, queued-agent waits, and sleeps; time between resumed attempts is not counted. */ + @JsonProperty("timeoutSeconds") Double timeoutSeconds, + /** Maximum AI credits consumed by factory subagents and their descendants. The post-paid ceiling is soft: parallel turns can settle beyond it before the run stops. */ + @JsonProperty("maxAiCredits") Double maxAiCredits ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/FactoryRunResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryRunResult.java new file mode 100644 index 0000000000..bb28f40887 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryRunResult.java @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Complete current or terminal factory run envelope. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record FactoryRunResult( + /** Factory run identifier. */ + @JsonProperty("runId") String runId, + /** Current or terminal factory run status. */ + @JsonProperty("status") FactoryRunStatus status, + /** Completed factory result. */ + @JsonProperty("result") Object result, + /** Error message for an errored run. */ + @JsonProperty("error") String error, + /** Machine-readable failure details for an errored run. */ + @JsonProperty("failure") Object failure, + /** Reason for a halted or cancelled run. */ + @JsonProperty("reason") String reason, + /** Partial journal and progress snapshot for a halted, cancelled, or errored run. */ + @JsonProperty("snapshot") Object snapshot +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/FactoryRunSummary.java b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryRunSummary.java new file mode 100644 index 0000000000..fb90885ee4 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryRunSummary.java @@ -0,0 +1,44 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Durable factory run summary with read-time live overlays. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record FactoryRunSummary( + @JsonProperty("runId") String runId, + @JsonProperty("factoryName") String factoryName, + @JsonProperty("description") String description, + @JsonProperty("status") FactoryRunStatus status, + @JsonProperty("revision") Long revision, + @JsonProperty("createdAt") Long createdAt, + @JsonProperty("startedAt") Long startedAt, + @JsonProperty("updatedAt") Long updatedAt, + @JsonProperty("completedAt") Long completedAt, + @JsonProperty("currentPhase") FactoryCurrentPhase currentPhase, + @JsonProperty("declaredPhaseCount") Long declaredPhaseCount, + @JsonProperty("liveAgentCount") Long liveAgentCount, + @JsonProperty("totalSpawnedAgentCount") Long totalSpawnedAgentCount, + @JsonProperty("consumed") FactoryRunConsumed consumed, + @JsonProperty("declaredLimits") FactoryDeclaredLimits declaredLimits, + @JsonProperty("approved") FactoryDeclaredLimits approved, + @JsonProperty("observedAt") Long observedAt, + @JsonProperty("activeSegmentStartedAt") Long activeSegmentStartedAt, + @JsonProperty("terminal") FactoryRunTerminal terminal +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/FactoryRunTerminal.java b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryRunTerminal.java new file mode 100644 index 0000000000..231c1b8a11 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/FactoryRunTerminal.java @@ -0,0 +1,29 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Prompt-safe terminal factory outcome. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record FactoryRunTerminal( + @JsonProperty("reason") String reason, + @JsonProperty("failure") Object failure, + @JsonProperty("error") String error, + @JsonProperty("resultPreview") String resultPreview +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/HistoryFileRestoreSkipReason.java b/java/src/generated/java/com/github/copilot/generated/rpc/HistoryFileRestoreSkipReason.java new file mode 100644 index 0000000000..46e943e016 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/HistoryFileRestoreSkipReason.java @@ -0,0 +1,35 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Reason a captured file was not restored. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum HistoryFileRestoreSkipReason { + /** The {@code user-modified} variant. */ + USER_MODIFIED("user-modified"), + /** The {@code skipped-capture} variant. */ + SKIPPED_CAPTURE("skipped-capture"); + + private final String value; + HistoryFileRestoreSkipReason(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static HistoryFileRestoreSkipReason fromValue(String value) { + for (HistoryFileRestoreSkipReason v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown HistoryFileRestoreSkipReason value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindChangeType.java b/java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindChangeType.java new file mode 100644 index 0000000000..85b12b873f --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindChangeType.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Aggregate file change represented by a rewind preview. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum HistoryRewindChangeType { + /** The {@code created} variant. */ + CREATED("created"), + /** The {@code deleted} variant. */ + DELETED("deleted"), + /** The {@code modified} variant. */ + MODIFIED("modified"); + + private final String value; + HistoryRewindChangeType(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static HistoryRewindChangeType fromValue(String value) { + for (HistoryRewindChangeType v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown HistoryRewindChangeType value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindFilePreview.java b/java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindFilePreview.java new file mode 100644 index 0000000000..7733246dd0 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindFilePreview.java @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * A file that a conversation-and-files rewind would restore. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record HistoryRewindFilePreview( + /** Absolute path of the captured file. */ + @JsonProperty("path") String path, + /** Aggregate change made across the discarded turns. */ + @JsonProperty("changeType") HistoryRewindChangeType changeType, + /** Lines added across the discarded turns. */ + @JsonProperty("linesAdded") Long linesAdded, + /** Lines removed across the discarded turns. */ + @JsonProperty("linesRemoved") Long linesRemoved +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindMode.java b/java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindMode.java new file mode 100644 index 0000000000..f72ded947a --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindMode.java @@ -0,0 +1,35 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Scope of a rewind operation. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum HistoryRewindMode { + /** The {@code conversation} variant. */ + CONVERSATION("conversation"), + /** The {@code conversation-and-files} variant. */ + CONVERSATION_AND_FILES("conversation-and-files"); + + private final String value; + HistoryRewindMode(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static HistoryRewindMode fromValue(String value) { + for (HistoryRewindMode v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown HistoryRewindMode value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindOutcome.java b/java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindOutcome.java new file mode 100644 index 0000000000..624795ee4e --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindOutcome.java @@ -0,0 +1,49 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Outcome of a rewind request. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum HistoryRewindOutcome { + /** The {@code success} variant. */ + SUCCESS("success"), + /** The {@code session-busy} variant. */ + SESSION_BUSY("session-busy"), + /** The {@code file-change-tracking-disabled} variant. */ + FILE_CHANGE_TRACKING_DISABLED("file-change-tracking-disabled"), + /** The {@code unsupported-remote-session} variant. */ + UNSUPPORTED_REMOTE_SESSION("unsupported-remote-session"), + /** The {@code files-rolled-back} variant. */ + FILES_ROLLED_BACK("files-rolled-back"), + /** The {@code rollback-incomplete} variant. */ + ROLLBACK_INCOMPLETE("rollback-incomplete"), + /** The {@code truncation-failed} variant. */ + TRUNCATION_FAILED("truncation-failed"), + /** The {@code checkpoint-cleanup-failed} variant. */ + CHECKPOINT_CLEANUP_FAILED("checkpoint-cleanup-failed"), + /** The {@code snapshot-prune-failed} variant. */ + SNAPSHOT_PRUNE_FAILED("snapshot-prune-failed"); + + private final String value; + HistoryRewindOutcome(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static HistoryRewindOutcome fromValue(String value) { + for (HistoryRewindOutcome v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown HistoryRewindOutcome value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindPoint.java b/java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindPoint.java new file mode 100644 index 0000000000..84926c74e0 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindPoint.java @@ -0,0 +1,43 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * A root user turn that the session can rewind to. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record HistoryRewindPoint( + /** ID of the user.message event that begins the discarded suffix. */ + @JsonProperty("eventId") String eventId, + /** User-visible message text for the turn. */ + @JsonProperty("userMessage") String userMessage, + /** ISO timestamp of the user turn. */ + @JsonProperty("timestamp") String timestamp, + /** Whether at least one file in this turn or a later turn can be restored. */ + @JsonProperty("canRestoreFiles") Boolean canRestoreFiles, + /** Number of unique files in this turn and all later turns that have captured changes. */ + @JsonProperty("fileCount") Long fileCount, + /** Whether this turn itself captured any file changes. */ + @JsonProperty("turnChangedFiles") Boolean turnChangedFiles, + /** Lines added by this turn's captured file changes. */ + @JsonProperty("linesAdded") Long linesAdded, + /** Lines removed by this turn's captured file changes. */ + @JsonProperty("linesRemoved") Long linesRemoved, + /** Whether this turn was an automatically injected autopilot continuation. */ + @JsonProperty("isAutopilotContinuation") Boolean isAutopilotContinuation +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindUnavailableReason.java b/java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindUnavailableReason.java new file mode 100644 index 0000000000..ae6b029ac4 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/HistoryRewindUnavailableReason.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Reason a rewind read (rewind points, file-restore preview, or session diff) could not be answered from the session's file-change captures. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum HistoryRewindUnavailableReason { + /** The {@code file-change-tracking-disabled} variant. */ + FILE_CHANGE_TRACKING_DISABLED("file-change-tracking-disabled"), + /** The {@code session-busy} variant. */ + SESSION_BUSY("session-busy"), + /** The {@code unsupported-remote-session} variant. */ + UNSUPPORTED_REMOTE_SESSION("unsupported-remote-session"); + + private final String value; + HistoryRewindUnavailableReason(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static HistoryRewindUnavailableReason fromValue(String value) { + for (HistoryRewindUnavailableReason v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown HistoryRewindUnavailableReason value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/HistorySkippedFileRestore.java b/java/src/generated/java/com/github/copilot/generated/rpc/HistorySkippedFileRestore.java new file mode 100644 index 0000000000..60c8c2d40c --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/HistorySkippedFileRestore.java @@ -0,0 +1,29 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * A captured file that rewind intentionally left unchanged. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record HistorySkippedFileRestore( + /** Absolute path of the skipped file. */ + @JsonProperty("path") String path, + /** Reason the file was not restored. */ + @JsonProperty("reason") HistoryFileRestoreSkipReason reason +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/InstructionSource.java b/java/src/generated/java/com/github/copilot/generated/rpc/InstructionSource.java index 2581375b33..496e1eadc1 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/InstructionSource.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/InstructionSource.java @@ -40,7 +40,7 @@ public record InstructionSource( @JsonProperty("description") String description, /** When true, this source starts disabled and must be toggled on by the user */ @JsonProperty("defaultDisabled") Boolean defaultDisabled, - /** The project path this source was discovered from. Only set by sessionless discovery for repository/working-directory sources, where it disambiguates same-named files (e.g. .github/copilot-instructions.md) across multiple workspace roots. The session-scoped getSources leaves it unset. */ + /** The project path this source was discovered from. Only set by sessionless discovery for repository, working-directory, and project-scoped plugin sources, where it disambiguates sources across multiple workspace roots. The session-scoped getSources leaves it unset. */ @JsonProperty("projectPath") String projectPath ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/McpFilteredServer.java b/java/src/generated/java/com/github/copilot/generated/rpc/McpFilteredServer.java index 51dbd2bd14..e0ecefae76 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/McpFilteredServer.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/McpFilteredServer.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * MCP server filtered by policy, with name, reason, optional redacted reason, and enterprise login. + * MCP server filtered by policy, with name, reason, and optional redacted reason. * * @since 1.0.0 */ @@ -27,7 +27,7 @@ public record McpFilteredServer( @JsonProperty("reason") String reason, /** PII-free filter reason */ @JsonProperty("redactedReason") String redactedReason, - /** Enterprise login associated with an allowlist policy */ + /** Deprecated. This field is no longer populated. */ @JsonProperty("enterpriseName") String enterpriseName ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/McpHostState.java b/java/src/generated/java/com/github/copilot/generated/rpc/McpHostState.java index 0326a120e1..152bd8556e 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/McpHostState.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/McpHostState.java @@ -27,7 +27,7 @@ public record McpHostState( @JsonProperty("mcp3pEnabled") Boolean mcp3pEnabled, /** Configured servers that are explicitly disabled. */ @JsonProperty("disabledServers") List disabledServers, - /** Configured servers filtered out by enterprise allowlist policy. */ + /** Configured servers filtered out by MCP server policy. */ @JsonProperty("filteredServers") List filteredServers, /** Names of currently-connected MCP clients. */ @JsonProperty("clients") List clients, diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ModelBilling.java b/java/src/generated/java/com/github/copilot/generated/rpc/ModelBilling.java index f8298dd624..f72f4b5cf5 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ModelBilling.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ModelBilling.java @@ -27,7 +27,7 @@ public record ModelBilling( @JsonProperty("tokenPrices") ModelBillingTokenPrices tokenPrices, /** Whole-number percentage discount (0-100) applied to usage billed through this model. Populated for the synthetic `auto` model, where requests routed by auto-mode are billed at a reduced rate; absent for concrete models. */ @JsonProperty("discountPercent") Long discountPercent, - /** Active server-driven promotion for this model, if any. Present when the model is being promoted with a time-boxed discount. */ + /** Active server-driven promotion for this model, if any. Present when the model is being promoted with a discount, which may be time-boxed or open-ended. */ @JsonProperty("promo") ModelBillingPromo promo ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ModelBillingPromo.java b/java/src/generated/java/com/github/copilot/generated/rpc/ModelBillingPromo.java index 731e298355..087ca1c15a 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ModelBillingPromo.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ModelBillingPromo.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Active server-driven promotion for a model, including its discount and expiry. + * Active server-driven promotion for a model, including its discount and optional expiry. * * @since 1.0.0 */ @@ -25,9 +25,9 @@ public record ModelBillingPromo( @JsonProperty("id") String id, /** Percentage discount (0-100) applied while the promotion is active. May be fractional. */ @JsonProperty("discountPercent") Double discountPercent, - /** UTC ISO 8601 timestamp marking when the promotion ends. Always present: the API only surfaces a promo whose expiry parses and is in the future. Consumers should treat a past value as expired. */ + /** UTC ISO 8601 timestamp marking when the promotion ends. Optional: an open-ended promotion omits this field. When present, the API only surfaces a promo whose expiry parses and is in the future, so consumers should treat a past value as expired. */ @JsonProperty("endsAt") String endsAt, - /** Human-readable promotion message. Does not include the expiry timestamp; consumers may format endsAt and append it. */ + /** Human-readable promotion message. Does not include the expiry timestamp; consumers may format endsAt and append it when present. */ @JsonProperty("message") String message ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ModelsGetBuiltInCatalogResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/ModelsGetBuiltInCatalogResult.java new file mode 100644 index 0000000000..9797a2d67f --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ModelsGetBuiltInCatalogResult.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * The running runtime's complete catalog of well-known built-in model IDs, including supported models and additional IDs with built-in metadata. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record ModelsGetBuiltInCatalogResult( + /** Built-in model entries. */ + @JsonProperty("models") List models +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/QueueInsertMessage.java b/java/src/generated/java/com/github/copilot/generated/rpc/QueueInsertMessage.java new file mode 100644 index 0000000000..d1056f8721 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/QueueInsertMessage.java @@ -0,0 +1,51 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import java.util.Map; +import javax.annotation.processing.Generated; + +/** + * Serializable message fields accepted by queue.insertAt. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record QueueInsertMessage( + /** The user message text. */ + @JsonProperty("prompt") String prompt, + /** Optional user-facing display text. */ + @JsonProperty("displayPrompt") String displayPrompt, + /** Optional attachments for the message. */ + @JsonProperty("attachments") List attachments, + /** Optional explicit agent mode. When omitted, the session's current mode is assigned. */ + @JsonProperty("agentMode") SendAgentMode agentMode, + /** Optional provenance source. `system` is rejected: it would hide the inserted row from `pendingItems` and make it unaddressable while still executing, so inserted items must stay visible. */ + @JsonProperty("source") String source, + /** Whether the message is billable. */ + @JsonProperty("billable") Boolean billable, + /** Required tool name for the turn, when any. */ + @JsonProperty("requiredTool") String requiredTool, + /** Per-turn request headers. */ + @JsonProperty("requestHeaders") Map requestHeaders, + /** Accepted for SendOptions compatibility but ignored; inserted items always use queued delivery semantics. */ + @JsonProperty("mode") SendMode mode, + /** Accepted for SendOptions compatibility but ignored; the requested public position controls placement. */ + @JsonProperty("prepend") Boolean prepend, + /** Accepted for SendOptions compatibility but ignored; insertion scheduling is controlled by the queue drain state. */ + @JsonProperty("wait") Boolean wait_, + /** Accepted for internal SendOptions compatibility but ignored; delivery is derived from current session activity. */ + @JsonProperty("delivery") String delivery +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/QueuePendingItems.java b/java/src/generated/java/com/github/copilot/generated/rpc/QueuePendingItems.java index 8767e91d0d..f3b2f99188 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/QueuePendingItems.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/QueuePendingItems.java @@ -21,9 +21,13 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public record QueuePendingItems( + /** Stable opaque id for the canonical queued item. Batch rows share one id. */ + @JsonProperty("id") String id, /** Whether this item is a queued user message or a queued slash command / model change */ @JsonProperty("kind") QueuePendingItemsKind kind, /** Human-readable text to display for this queue entry in the UI */ - @JsonProperty("displayText") String displayText + @JsonProperty("displayText") String displayText, + /** Agent mode stored on this queued entry, as stamped when it was enqueued. Items without an explicit mode report interactive. This is not necessarily the mode that will constrain the turn: a plan or autopilot session applies its own write gate, continuation loop and permission posture to every drained item regardless of the mode stored here. */ + @JsonProperty("agentMode") SendAgentMode agentMode ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SandboxConfigUserPolicyNetwork.java b/java/src/generated/java/com/github/copilot/generated/rpc/SandboxConfigUserPolicyNetwork.java index 9b8b53c816..1e56acb53f 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SandboxConfigUserPolicyNetwork.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SandboxConfigUserPolicyNetwork.java @@ -24,6 +24,8 @@ public record SandboxConfigUserPolicyNetwork( /** Whether outbound network traffic is allowed at all. */ @JsonProperty("allowOutbound") Boolean allowOutbound, /** Whether traffic to local/loopback addresses is allowed. */ - @JsonProperty("allowLocalNetwork") Boolean allowLocalNetwork + @JsonProperty("allowLocalNetwork") Boolean allowLocalNetwork, + /** HTTP proxy the sandboxed process routes traffic through. Enforced on Windows and cooperative (honored by well-behaved tools, not strictly enforced) on Linux and macOS. Credentials go in the separate `username`/`password` fields. A credential-free http:// loopback proxy URL is routed through the localhost proxy automatically; an https:// or authenticated loopback URL is used as-is. */ + @JsonProperty("proxy") SandboxConfigUserPolicyNetworkProxy proxy ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SandboxConfigUserPolicyNetworkProxy.java b/java/src/generated/java/com/github/copilot/generated/rpc/SandboxConfigUserPolicyNetworkProxy.java new file mode 100644 index 0000000000..74ff86919e --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SandboxConfigUserPolicyNetworkProxy.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * HTTP proxy configuration for sandboxed traffic. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SandboxConfigUserPolicyNetworkProxy( + /** Proxy URL (e.g. http://proxy.example.com:8080). The port is optional and defaults to the scheme's standard port when omitted. Credentials must not be embedded here — a `user:pass@` authority is rejected; put them in the separate `username`/`password` fields. A credential-free http:// loopback URL is routed through the localhost proxy automatically; loopback covers localhost and any *.localhost subdomain, the whole 127.0.0.0/8 range, ::1, and IPv4-mapped loopback (::ffff:127.0.0.1). An https:// URL, or one with a username/password set, is used as-is. */ + @JsonProperty("url") String url, + /** Optional username for proxy authentication. Combined with the URL (and `password`) into `user:pass@host` when the sandboxed process routes through the proxy. */ + @JsonProperty("username") String username, + /** Optional password for proxy authentication, combined with the URL at spawn time. The persisted value may be a literal password, a `${secret:…}` reference resolved from the OS keychain, or a `${VAR}`/`$VAR` environment reference; it is resolved just before the sandboxed process routes through the proxy. The /sandbox dialog stores a real password in the OS keychain and persists only a `${secret:…}` placeholder (never plaintext in settings.json); the field is masked in the dialog and redacted by /settings show. */ + @JsonProperty("password") String password +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SendMessageItem.java b/java/src/generated/java/com/github/copilot/generated/rpc/SendMessageItem.java index bdb37cd9fd..4a6696c01d 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SendMessageItem.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SendMessageItem.java @@ -32,7 +32,7 @@ public record SendMessageItem( @JsonProperty("billable") Boolean billable, /** If set, the request will fail if the named tool is not available when this message is among the user messages at the start of the current exchange */ @JsonProperty("requiredTool") String requiredTool, - /** Optional provenance tag copied to the resulting user.message event. Must match one of three forms: the literal `system`, `command-` for messages originating from a command (e.g. slash command, Mission Control command), or `schedule-` for messages originating from a scheduled job. */ + /** Optional provenance tag copied to the resulting user.message event. Must be `user`, `system`, `command-` for command-originated messages, `schedule-` for scheduled prompts, or `agent-` for prompts sent by another agent. */ @JsonProperty("source") String source ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerModelsApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerModelsApi.java index 64ccc62cde..ad3d04ce9f 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ServerModelsApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerModelsApi.java @@ -37,4 +37,15 @@ public CompletableFuture list() { return caller.invoke("models.list", java.util.Map.of(), ModelsListResult.class); } + /** + * The running runtime's complete catalog of well-known built-in model IDs, including supported models and additional IDs with built-in metadata. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture getBuiltInCatalog() { + return caller.invoke("models.getBuiltInCatalog", java.util.Map.of(), ModelsGetBuiltInCatalogResult.class); + } + } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerSessionsApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerSessionsApi.java index 7e3b4d90d8..1288cfb94e 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ServerSessionsApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerSessionsApi.java @@ -70,6 +70,28 @@ public CompletableFuture list() { return caller.invoke("sessions.list", java.util.Map.of(), SessionsListResult.class); } + /** + * Session ID whose persisted metadata should be read. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture getMetadata(SessionsGetMetadataParams params) { + return caller.invoke("sessions.getMetadata", params, SessionsGetMetadataResult.class); + } + + /** + * Limit for non-empty local session IDs. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture listNonEmptySessionIds(SessionsListNonEmptySessionIdsParams params) { + return caller.invoke("sessions.listNonEmptySessionIds", params, SessionsListNonEmptySessionIdsResult.class); + } + /** * GitHub task ID to look up. * @@ -169,6 +191,17 @@ public CompletableFuture bulkDelete(SessionsBulkDelete return caller.invoke("sessions.bulkDelete", params, SessionsBulkDeleteResult.class); } + /** + * Session ID to delete from disk. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture delete(SessionsDeleteParams params) { + return caller.invoke("sessions.delete", params, Void.class); + } + /** * Age threshold and optional flags controlling which old sessions are pruned (or simulated when dryRun is true). * diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionAgentApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionAgentApi.java index 37d6dafce9..69ce7cf43a 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionAgentApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionAgentApi.java @@ -31,14 +31,14 @@ public final class SessionAgentApi { } /** - * Identifies the target session. + * Controls whether built-in agents and authored prompt text are included. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ @CopilotExperimental public CompletableFuture list() { - return caller.invoke("session.agent.list", java.util.Map.of("sessionId", this.sessionId), SessionAgentListResult.class); + return caller.invoke("session.agent.list", java.util.Map.of(), SessionAgentListResult.class); } /** diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionAgentListResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionAgentListResult.java index acd240285d..3eefc2fd88 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionAgentListResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionAgentListResult.java @@ -15,7 +15,7 @@ import javax.annotation.processing.Generated; /** - * Custom agents available to the session. + * Agents available to the session. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 @@ -25,7 +25,7 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public record SessionAgentListResult( - /** Available custom agents */ + /** Available agents */ @JsonProperty("agents") List agents ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionPluginsReloadParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionCancelAllBackgroundAgentsParams.java similarity index 89% rename from java/src/generated/java/com/github/copilot/generated/rpc/SessionPluginsReloadParams.java rename to java/src/generated/java/com/github/copilot/generated/rpc/SessionCancelAllBackgroundAgentsParams.java index f48c7ee88f..0851f331ee 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionPluginsReloadParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionCancelAllBackgroundAgentsParams.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Optional flags controlling which side effects the reload performs. + * Identifies the target session. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 @@ -23,7 +23,7 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record SessionPluginsReloadParams( +public record SessionCancelAllBackgroundAgentsParams( /** Target session identifier */ @JsonProperty("sessionId") String sessionId ) { diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionCommandsApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionCommandsApi.java index 0cb7bb5517..e2e770ed72 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionCommandsApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionCommandsApi.java @@ -38,7 +38,7 @@ public final class SessionCommandsApi { */ @CopilotExperimental public CompletableFuture list() { - return caller.invoke("session.commands.list", java.util.Map.of("sessionId", this.sessionId), SessionCommandsListResult.class); + return caller.invoke("session.commands.list", java.util.Map.of(), SessionCommandsListResult.class); } /** diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionContentExclusionApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionContentExclusionApi.java new file mode 100644 index 0000000000..eb621e6b49 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionContentExclusionApi.java @@ -0,0 +1,49 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.github.copilot.CopilotExperimental; +import java.util.concurrent.CompletableFuture; +import javax.annotation.processing.Generated; + +/** + * API methods for the {@code contentExclusion} namespace. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionContentExclusionApi { + + private static final com.fasterxml.jackson.databind.ObjectMapper MAPPER = RpcMapper.INSTANCE; + + private final RpcCaller caller; + private final String sessionId; + + /** @param caller the RPC transport function */ + SessionContentExclusionApi(RpcCaller caller, String sessionId) { + this.caller = caller; + this.sessionId = sessionId; + } + + /** + * Local file system absolute paths within the session working directory to check against its content-exclusion policy. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture checkPaths(SessionContentExclusionCheckPathsParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.contentExclusion.checkPaths", _p, SessionContentExclusionCheckPathsResult.class); + } + +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionContentExclusionCheckPathsParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionContentExclusionCheckPathsParams.java new file mode 100644 index 0000000000..0c61f6c910 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionContentExclusionCheckPathsParams.java @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Local file system absolute paths within the session working directory to check against its content-exclusion policy. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionContentExclusionCheckPathsParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Local file system absolute paths within the session working directory to check. Results are returned in the same order, including duplicates. */ + @JsonProperty("paths") List paths +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionContentExclusionCheckPathsResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionContentExclusionCheckPathsResult.java new file mode 100644 index 0000000000..956ffc44d3 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionContentExclusionCheckPathsResult.java @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Batch content-exclusion result. Callers must fail closed when policy evaluation is unavailable. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionContentExclusionCheckPathsResult( + /** Whether the session's policy service was available for the complete batch. When false, checks is empty and callers must treat every requested path as excluded. */ + @JsonProperty("available") Boolean available, + /** Per-path decisions in request order. Empty when available is false. */ + @JsonProperty("checks") List checks +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionEventLogReadParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionEventLogReadParams.java index d330d616d1..ad16d802b6 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionEventLogReadParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionEventLogReadParams.java @@ -35,6 +35,8 @@ public record SessionEventLogReadParams( /** Either '*' to receive all event types, or a non-empty list of event types to receive */ @JsonProperty("types") Object 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. */ - @JsonProperty("agentScope") EventsAgentScope agentScope + @JsonProperty("agentScope") EventsAgentScope agentScope, + /** When false, skip ephemeral events entirely and return only durable (persisted) events. History-backfill callers that discard ephemerals anyway should set this so the read is bounded by the durable log length instead of racing the ephemeral ring on a busy session. Defaults to true (ephemerals are interleaved with durable events in creation order). */ + @JsonProperty("includeEphemeral") Boolean includeEphemeral ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionEventLogReadResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionEventLogReadResult.java index 7383e05003..240c385c0c 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionEventLogReadResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionEventLogReadResult.java @@ -25,7 +25,7 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public record SessionEventLogReadResult( - /** Events are delivered in two batches per read: persisted events first (in append order), then ephemeral events (in seq order). When `waitMs > 0` and the catch-up batches were empty, post-wait events follow the same two-batch ordering. Persisted and ephemeral events do not interleave within a single read. */ + /** Session events for this batch, merged into a single stream in creation order: durable (persisted) events and ephemeral events interleave exactly as they were emitted. Set `includeEphemeral: false` to receive only durable events. Ephemeral events are never replayable once pruned from the in-memory ring, so a consumer that needs them should keep reading with a non-zero `waitMs`. */ @JsonProperty("events") List events, /** Opaque cursor for the next read. Pass back unchanged in the next read.cursor to continue from where this read left off. Always present, even when no events were returned. */ @JsonProperty("cursor") String cursor, diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryAgentParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryAgentParams.java index 7f31066fc4..6ab02c27eb 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryAgentParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryAgentParams.java @@ -28,6 +28,8 @@ public record SessionFactoryAgentParams( @JsonProperty("sessionId") String sessionId, /** Factory run identifier that owns the subagent. */ @JsonProperty("factoryRunId") String factoryRunId, + /** Opaque token identifying the current factory execution attempt. */ + @JsonProperty("executionToken") String executionToken, /** Prompt to send to the subagent. */ @JsonProperty("prompt") String prompt, /** Subagent execution options. */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryApi.java index 703a2e711e..6d15ac17c3 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryApi.java @@ -50,6 +50,22 @@ public CompletableFuture run(SessionFactoryRunParams pa return caller.invoke("session.factory.run", _p, SessionFactoryRunResult.class); } + /** + * Parameters for resuming a factory run from its persisted identity. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture resume(SessionFactoryResumeParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.factory.resume", _p, SessionFactoryResumeResult.class); + } + /** * Parameters for retrieving a factory run. *

@@ -66,6 +82,49 @@ public CompletableFuture getRun(SessionFactoryGetRun return caller.invoke("session.factory.getRun", _p, SessionFactoryGetRunResult.class); } + /** + * Empty parameters for listing factory runs. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture listRuns() { + return caller.invoke("session.factory.listRuns", java.util.Map.of("sessionId", this.sessionId), SessionFactoryListRunsResult.class); + } + + /** + * Parameters for retrieving a factory run. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture getRunDetail(SessionFactoryGetRunDetailParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.factory.getRunDetail", _p, SessionFactoryGetRunDetailResult.class); + } + + /** + * Parameters for paging factory progress. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture getRunProgress(SessionFactoryGetRunProgressParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.factory.getRunProgress", _p, SessionFactoryGetRunProgressResult.class); + } + /** * Parameters for cancelling a factory run. *

diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunDetailParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunDetailParams.java new file mode 100644 index 0000000000..b4563d4b35 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunDetailParams.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Parameters for retrieving a factory run. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionFactoryGetRunDetailParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Factory run identifier. */ + @JsonProperty("runId") String runId +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunDetailResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunDetailResult.java new file mode 100644 index 0000000000..5da6f4979c --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunDetailResult.java @@ -0,0 +1,51 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Full factory run observability detail. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionFactoryGetRunDetailResult( + @JsonProperty("runId") String runId, + @JsonProperty("factoryName") String factoryName, + @JsonProperty("description") String description, + @JsonProperty("status") FactoryRunStatus status, + @JsonProperty("revision") Long revision, + @JsonProperty("createdAt") Long createdAt, + @JsonProperty("startedAt") Long startedAt, + @JsonProperty("updatedAt") Long updatedAt, + @JsonProperty("completedAt") Long completedAt, + @JsonProperty("currentPhase") FactoryCurrentPhase currentPhase, + @JsonProperty("declaredPhaseCount") Long declaredPhaseCount, + @JsonProperty("liveAgentCount") Long liveAgentCount, + @JsonProperty("totalSpawnedAgentCount") Long totalSpawnedAgentCount, + @JsonProperty("consumed") FactoryRunConsumed consumed, + @JsonProperty("declaredLimits") FactoryDeclaredLimits declaredLimits, + @JsonProperty("approved") FactoryDeclaredLimits approved, + @JsonProperty("observedAt") Long observedAt, + @JsonProperty("activeSegmentStartedAt") Long activeSegmentStartedAt, + @JsonProperty("terminal") FactoryRunTerminal terminal, + @JsonProperty("phases") List phases, + @JsonProperty("agents") List agents, + @JsonProperty("progress") FactoryProgressPage progress +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunProgressParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunProgressParams.java new file mode 100644 index 0000000000..8445943cba --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunProgressParams.java @@ -0,0 +1,40 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Parameters for paging factory progress. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionFactoryGetRunProgressParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Factory run identifier. */ + @JsonProperty("runId") String runId, + /** Optional phase identifier used to scope records and cursors. */ + @JsonProperty("phaseId") String phaseId, + /** Exclusive forward cursor. */ + @JsonProperty("afterSeq") Long afterSeq, + /** Exclusive backward cursor. */ + @JsonProperty("beforeSeq") Long beforeSeq, + /** Maximum records to return. Defaults to 200 and is capped at 500. */ + @JsonProperty("limit") Long limit +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunProgressResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunProgressResult.java new file mode 100644 index 0000000000..369fa07c22 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunProgressResult.java @@ -0,0 +1,36 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * A bidirectional page of factory progress. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionFactoryGetRunProgressResult( + @JsonProperty("records") List records, + @JsonProperty("oldestSeq") Long oldestSeq, + @JsonProperty("newestSeq") Long newestSeq, + @JsonProperty("hasMoreOlder") Boolean hasMoreOlder, + @JsonProperty("hasMoreNewer") Boolean hasMoreNewer, + /** Run revision reflected by this page. */ + @JsonProperty("revision") Long revision +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalGetParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalGetParams.java index a9b0acc7c1..251ca946cb 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalGetParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalGetParams.java @@ -28,6 +28,8 @@ public record SessionFactoryJournalGetParams( @JsonProperty("sessionId") String sessionId, /** Factory run identifier. */ @JsonProperty("runId") String runId, + /** Opaque token identifying the current factory execution attempt. */ + @JsonProperty("executionToken") String executionToken, /** Namespaced journal key. */ @JsonProperty("key") String key ) { diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalPutParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalPutParams.java index 84478dbb7d..06467b2657 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalPutParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalPutParams.java @@ -28,6 +28,8 @@ public record SessionFactoryJournalPutParams( @JsonProperty("sessionId") String sessionId, /** Factory run identifier. */ @JsonProperty("runId") String runId, + /** Opaque token identifying the current factory execution attempt. */ + @JsonProperty("executionToken") String executionToken, /** Namespaced journal key. */ @JsonProperty("key") String key, /** JSON result to memoize. */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryListRunsParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryListRunsParams.java new file mode 100644 index 0000000000..e3b90f07f7 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryListRunsParams.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Empty parameters for listing factory runs. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionFactoryListRunsParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryListRunsResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryListRunsResult.java new file mode 100644 index 0000000000..7d1ac45a9e --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryListRunsResult.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Factory runs in durable creation order. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionFactoryListRunsResult( + @JsonProperty("runs") List runs +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryLogParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryLogParams.java index 7618869e33..b4f52617f1 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryLogParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryLogParams.java @@ -29,6 +29,8 @@ public record SessionFactoryLogParams( @JsonProperty("sessionId") String sessionId, /** Factory run identifier. */ @JsonProperty("runId") String runId, + /** Opaque token identifying the current factory execution attempt. */ + @JsonProperty("executionToken") String executionToken, /** Ordered progress lines to append. */ @JsonProperty("lines") List lines ) { diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryResumeParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryResumeParams.java new file mode 100644 index 0000000000..9c264284fc --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryResumeParams.java @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Parameters for resuming a factory run from its persisted identity. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionFactoryResumeParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Factory run identifier. */ + @JsonProperty("runId") String runId, + /** Optional per-invocation resource ceiling overrides. */ + @JsonProperty("limits") FactoryRunLimits limits +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryResumeResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryResumeResult.java new file mode 100644 index 0000000000..b4cfcae116 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryResumeResult.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Resolved persisted factory identity and resumed run envelope. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionFactoryResumeResult( + /** Persisted factory name resolved for the resumed run. */ + @JsonProperty("factoryName") String factoryName, + /** Terminal resumed run envelope. */ + @JsonProperty("run") FactoryRunResult run +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteQueryParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteQueryParams.java index 47e30ebca5..9258635886 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteQueryParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteQueryParams.java @@ -15,7 +15,7 @@ import javax.annotation.processing.Generated; /** - * SQL query, query type, and optional bind parameters for executing a SQLite query against the per-session database. + * SQL query, query type, and optional bind parameters for executing a SQLite query against the per-session database. The provider applies its SQLite busy timeout for every call. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteQueryResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteQueryResult.java index 53370c0984..ff14d3ec1b 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteQueryResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteQueryResult.java @@ -10,7 +10,6 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; import java.util.List; import java.util.Map; import javax.annotation.processing.Generated; @@ -18,10 +17,8 @@ /** * Query results including rows, columns, and rows affected, or a filesystem error if execution failed. * - * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ -@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteTransactionError.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteTransactionError.java new file mode 100644 index 0000000000..cbe170a298 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteTransactionError.java @@ -0,0 +1,27 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Classified SQLite transaction failure. busyOrLocked guarantees rollback; postCommitAmbiguous must never be retried. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionFsSqliteTransactionError( + @JsonProperty("errorClass") SessionFsSqliteTransactionErrorClass errorClass, + @JsonProperty("message") String message +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteTransactionErrorClass.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteTransactionErrorClass.java new file mode 100644 index 0000000000..4e184a19a4 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteTransactionErrorClass.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * SQLite transaction failure classification. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum SessionFsSqliteTransactionErrorClass { + /** The {@code busyOrLocked} variant. */ + BUSYORLOCKED("busyOrLocked"), + /** The {@code fatal} variant. */ + FATAL("fatal"), + /** The {@code postCommitAmbiguous} variant. */ + POSTCOMMITAMBIGUOUS("postCommitAmbiguous"); + + private final String value; + SessionFsSqliteTransactionErrorClass(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static SessionFsSqliteTransactionErrorClass fromValue(String value) { + for (SessionFsSqliteTransactionErrorClass v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown SessionFsSqliteTransactionErrorClass value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteTransactionParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteTransactionParams.java new file mode 100644 index 0000000000..f834d55957 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteTransactionParams.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Statements to execute atomically. Providers apply busy handling for every call. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionFsSqliteTransactionParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + @JsonProperty("statements") List statements +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteTransactionResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteTransactionResult.java new file mode 100644 index 0000000000..f9c799b9b2 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteTransactionResult.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Per-statement results, or a classified transaction error. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionFsSqliteTransactionResult( + @JsonProperty("results") List results, + @JsonProperty("error") SessionFsSqliteTransactionError error +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteTransactionStatement.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteTransactionStatement.java new file mode 100644 index 0000000000..f56f268ba1 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionFsSqliteTransactionStatement.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Map; +import javax.annotation.processing.Generated; + +/** + * One statement in an atomic SQLite transaction. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionFsSqliteTransactionStatement( + /** SQL statement to execute. */ + @JsonProperty("query") String query, + /** How to execute the statement. */ + @JsonProperty("queryType") SessionFsSqliteQueryType queryType, + /** Optional named bind parameters. */ + @JsonProperty("params") Map params +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryApi.java index fa2f47b38b..ef9464ae4f 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryApi.java @@ -38,7 +38,7 @@ public final class SessionHistoryApi { */ @CopilotExperimental public CompletableFuture compact() { - return caller.invoke("session.history.compact", java.util.Map.of("sessionId", this.sessionId), SessionHistoryCompactResult.class); + return caller.invoke("session.history.compact", java.util.Map.of(), SessionHistoryCompactResult.class); } /** @@ -57,6 +57,49 @@ public CompletableFuture truncate(SessionHistoryTr return caller.invoke("session.history.truncate", _p, SessionHistoryTruncateResult.class); } + /** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture listRewindPoints() { + return caller.invoke("session.history.listRewindPoints", java.util.Map.of("sessionId", this.sessionId), SessionHistoryListRewindPointsResult.class); + } + + /** + * Event boundary to preview for conversation-and-files rewind. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture previewRewind(SessionHistoryPreviewRewindParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.history.previewRewind", _p, SessionHistoryPreviewRewindResult.class); + } + + /** + * Boundary and mode for rewinding session history. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture rewind(SessionHistoryRewindParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.history.rewind", _p, SessionHistoryRewindResult.class); + } + /** * Identifies the target session. * diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryListRewindPointsParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryListRewindPointsParams.java new file mode 100644 index 0000000000..d780d76b38 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryListRewindPointsParams.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionHistoryListRewindPointsParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryListRewindPointsResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryListRewindPointsResult.java new file mode 100644 index 0000000000..99dcc0fabf --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryListRewindPointsResult.java @@ -0,0 +1,35 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Rewind points and file-change-tracking availability for the session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionHistoryListRewindPointsResult( + /** Whether this session captured file changes from its first turn. */ + @JsonProperty("fileChangeTrackingEnabled") Boolean fileChangeTrackingEnabled, + /** Why the listed points could not be produced, when applicable; the points list is empty whenever it is set. `unsupported-remote-session` is permanent for the session and comes with `fileChangeTrackingEnabled: false`. `session-busy` is transient and only ever reported by a session that *is* tracking (`fileChangeTrackingEnabled: true`), because the file-change captures cannot be read while work that may still mutate them is in flight; the same request succeeds once the session settles, so a client that wants points should retry rather than treat it as a failure. It is never `file-change-tracking-disabled`: an untracked local session still lists conversation-only points and reports that through `fileChangeTrackingEnabled: false`. */ + @JsonProperty("unavailableReason") HistoryRewindUnavailableReason unavailableReason, + /** Root user turns in chronological order. Empty when `unavailableReason` is set. */ + @JsonProperty("points") List points +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryPreviewRewindParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryPreviewRewindParams.java new file mode 100644 index 0000000000..dd92709e2b --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryPreviewRewindParams.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Event boundary to preview for conversation-and-files rewind. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionHistoryPreviewRewindParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** ID of the user.message event that begins the discarded suffix. */ + @JsonProperty("eventId") String eventId +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryPreviewRewindResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryPreviewRewindResult.java new file mode 100644 index 0000000000..976597c4fa --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryPreviewRewindResult.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Files and aggregate changes for a prospective rewind. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionHistoryPreviewRewindResult( + /** Whether file restore is available for this session. This is authoritative: switch on it and read `reason` only when it is false. */ + @JsonProperty("available") Boolean available, + /** Why file restore is unavailable, when applicable. Populated only when `available` is false and never set when `available` is true. */ + @JsonProperty("reason") HistoryRewindUnavailableReason reason, + /** Number of unique files in the preview. */ + @JsonProperty("fileCount") Long fileCount, + /** Files ordered by path. */ + @JsonProperty("files") List files +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryRewindParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryRewindParams.java new file mode 100644 index 0000000000..bf93f3e245 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryRewindParams.java @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Boundary and mode for rewinding session history. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionHistoryRewindParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** ID of the user.message event that begins the discarded suffix. */ + @JsonProperty("eventId") String eventId, + /** Whether to rewind only conversation history or also restore captured files. */ + @JsonProperty("mode") HistoryRewindMode mode +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryRewindResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryRewindResult.java new file mode 100644 index 0000000000..d069ca9928 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryRewindResult.java @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Structured outcome of a rewind request. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionHistoryRewindResult( + /** Overall rewind outcome. This discriminates the result: it governs which of the remaining fields are populated, so consumers must switch on it before reading `eventsRemoved`, `restoredFiles`, `skippedFiles`, or `error`. See each field for the outcomes that populate it. */ + @JsonProperty("outcome") HistoryRewindOutcome outcome, + /** Number of persisted events removed by conversation truncation. Present only when truncation succeeded (outcomes `success`, `checkpoint-cleanup-failed`, and `snapshot-prune-failed`); omitted for every unavailable outcome (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`) and for `truncation-failed`, `files-rolled-back`, and `rollback-incomplete`. */ + @JsonProperty("eventsRemoved") Long eventsRemoved, + /** Absolute paths restored to their captured preimages. Always empty for conversation-only rewinds and for the unavailable outcomes (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`); only conversation-and-files outcomes that reached the file-restore stage populate it. */ + @JsonProperty("restoredFiles") List restoredFiles, + /** Captured files intentionally left unchanged. Always empty for conversation-only rewinds and for the unavailable outcomes (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`); only conversation-and-files outcomes that reached the file-restore stage populate it. */ + @JsonProperty("skippedFiles") List skippedFiles, + /** Failure detail. Set only for the failure and partial-failure outcomes (`files-rolled-back`, `rollback-incomplete`, `truncation-failed`, `checkpoint-cleanup-failed`, `snapshot-prune-failed`); omitted for `success` and for the unavailable outcomes (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`). */ + @JsonProperty("error") String error +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryTruncateResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryTruncateResult.java index 5b5043b609..f5ae17d622 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryTruncateResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryTruncateResult.java @@ -25,6 +25,10 @@ @JsonIgnoreProperties(ignoreUnknown = true) public record SessionHistoryTruncateResult( /** Number of events that were removed */ - @JsonProperty("eventsRemoved") Long eventsRemoved + @JsonProperty("eventsRemoved") Long eventsRemoved, + /** True when conversation truncation succeeded but post-truncation workspace checkpoint cleanup failed. History is already truncated; callers may still prune snapshots but should report a checkpoint-cleanup rather than a truncation failure. */ + @JsonProperty("checkpointCleanupFailed") Boolean checkpointCleanupFailed, + /** Failure detail when checkpointCleanupFailed is true. */ + @JsonProperty("checkpointCleanupError") String checkpointCleanupError ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionInterruptMainTurnParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionInterruptMainTurnParams.java new file mode 100644 index 0000000000..6e16ad1dd8 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionInterruptMainTurnParams.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Parameters for interrupting the main agent turn. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionInterruptMainTurnParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** When true, the user's queued prompts are preserved and run as the next turn once the interrupted turn unwinds; when false (the default), the queue is cleared like a plain abort. */ + @JsonProperty("flushQueued") Boolean flushQueued +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionInterruptMainTurnResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionInterruptMainTurnResult.java new file mode 100644 index 0000000000..a57804cf82 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionInterruptMainTurnResult.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Result of interrupting the main agent turn. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionInterruptMainTurnResult( + /** Whether an in-flight main agent turn was interrupted. False when the main loop was not processing. */ + @JsonProperty("interrupted") Boolean interrupted +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionApi.java new file mode 100644 index 0000000000..830132938a --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionApi.java @@ -0,0 +1,42 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.github.copilot.CopilotExperimental; +import java.util.concurrent.CompletableFuture; +import javax.annotation.processing.Generated; + +/** + * API methods for the {@code limitPrediction} namespace. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionLimitPredictionApi { + + private final RpcCaller caller; + private final String sessionId; + + /** @param caller the RPC transport function */ + SessionLimitPredictionApi(RpcCaller caller, String sessionId) { + this.caller = caller; + this.sessionId = sessionId; + } + + /** + * Parameters for predicting an AI-credit session limit. Omitting `modelId` uses the session's currently selected model. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture predict() { + return caller.invoke("session.limitPrediction.predict", java.util.Map.of(), SessionLimitPredictionResult.class); + } + +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionBaselineData.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionBaselineData.java new file mode 100644 index 0000000000..2387c5498c --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionBaselineData.java @@ -0,0 +1,29 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Baseline data provenance for a prediction. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionLimitPredictionBaselineData( + /** Start of the baseline data slice. */ + @JsonProperty("windowStart") String windowStart, + /** End of the baseline data slice. */ + @JsonProperty("windowEnd") String windowEnd +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionClientType.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionClientType.java new file mode 100644 index 0000000000..539602931d --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionClientType.java @@ -0,0 +1,35 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Client population used for the prediction baseline. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum SessionLimitPredictionClientType { + /** The {@code cli-interactive} variant. */ + CLI_INTERACTIVE("cli-interactive"), + /** The {@code cli-prompt} variant. */ + CLI_PROMPT("cli-prompt"); + + private final String value; + SessionLimitPredictionClientType(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static SessionLimitPredictionClientType fromValue(String value) { + for (SessionLimitPredictionClientType v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown SessionLimitPredictionClientType value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionDetails.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionDetails.java new file mode 100644 index 0000000000..f4329bb71b --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionDetails.java @@ -0,0 +1,44 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Explainable AI-credit session-limit prediction. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionLimitPredictionDetails( + /** Client population used for the prediction. */ + @JsonProperty("clientType") SessionLimitPredictionClientType clientType, + /** Model identifier used for lookup. */ + @JsonProperty("modelId") String modelId, + /** Baseline fallback level used to create the prediction. */ + @JsonProperty("source") SessionLimitPredictionSource source, + /** Key matched at the source level, such as a model id, family id, or `global`. */ + @JsonProperty("sourceKey") String sourceKey, + /** Resolved model family when known. */ + @JsonProperty("family") String family, + /** Ordered usage tiers and their AI-credit caps. */ + @JsonProperty("tiers") List tiers, + /** Baseline data provenance. */ + @JsonProperty("baselineData") SessionLimitPredictionBaselineData baselineData, + /** Tier chosen as the recommended cap. */ + @JsonProperty("recommendedTier") SessionLimitPredictionTier recommendedTier, + /** Recommended maximum AI credits for this session. */ + @JsonProperty("recommendedCap") Double recommendedCap +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionResult.java new file mode 100644 index 0000000000..0c2f489d9f --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionResult.java @@ -0,0 +1,35 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import javax.annotation.processing.Generated; + +/** + * Prediction result. Available results include prediction details; unavailable results include an explicit reason. + * + * @since 1.0.0 + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "kind", visible = true) +@JsonSubTypes({ + @JsonSubTypes.Type(value = SessionLimitPredictionResultAvailable.class, name = "available"), + @JsonSubTypes.Type(value = SessionLimitPredictionResultUnavailable.class, name = "unavailable") +}) +@JsonIgnoreProperties(ignoreUnknown = true) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public abstract class SessionLimitPredictionResult { + + /** + * Returns the discriminator value for this variant. + * + * @return the kind discriminator + */ + public abstract String getKind(); +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionResultAvailable.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionResultAvailable.java new file mode 100644 index 0000000000..632018f4d0 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionResultAvailable.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Variant {@code available} of {@link SessionLimitPredictionResult}. + * + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionLimitPredictionResultAvailable extends SessionLimitPredictionResult { + + @JsonProperty("kind") + private final String kind = "available"; + + @Override + public String getKind() { return kind; } + + /** Predicted session limit details. */ + @JsonProperty("prediction") + private SessionLimitPredictionDetails prediction; + + public SessionLimitPredictionDetails getPrediction() { return prediction; } + public void setPrediction(SessionLimitPredictionDetails prediction) { this.prediction = prediction; } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionResultUnavailable.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionResultUnavailable.java new file mode 100644 index 0000000000..3f4b3ebe2e --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionResultUnavailable.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Variant {@code unavailable} of {@link SessionLimitPredictionResult}. + * + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionLimitPredictionResultUnavailable extends SessionLimitPredictionResult { + + @JsonProperty("kind") + private final String kind = "unavailable"; + + @Override + public String getKind() { return kind; } + + /** Reason no prediction is available. */ + @JsonProperty("reason") + private SessionLimitPredictionUnavailableReason reason; + + public SessionLimitPredictionUnavailableReason getReason() { return reason; } + public void setReason(SessionLimitPredictionUnavailableReason reason) { this.reason = reason; } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionSource.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionSource.java new file mode 100644 index 0000000000..c22baa1183 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionSource.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Baseline fallback level used to create the prediction. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum SessionLimitPredictionSource { + /** The {@code model} variant. */ + MODEL("model"), + /** The {@code family} variant. */ + FAMILY("family"), + /** The {@code global} variant. */ + GLOBAL("global"); + + private final String value; + SessionLimitPredictionSource(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static SessionLimitPredictionSource fromValue(String value) { + for (SessionLimitPredictionSource v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown SessionLimitPredictionSource value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionTier.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionTier.java new file mode 100644 index 0000000000..21d3de43c4 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionTier.java @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Semantic usage tier used for a recommended cap or additional headroom. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum SessionLimitPredictionTier { + /** The {@code recommended} variant. */ + RECOMMENDED("recommended"), + /** The {@code additional_headroom} variant. */ + ADDITIONAL_HEADROOM("additional_headroom"), + /** The {@code generous_headroom} variant. */ + GENEROUS_HEADROOM("generous_headroom"), + /** The {@code maximum_headroom} variant. */ + MAXIMUM_HEADROOM("maximum_headroom"); + + private final String value; + SessionLimitPredictionTier(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static SessionLimitPredictionTier fromValue(String value) { + for (SessionLimitPredictionTier v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown SessionLimitPredictionTier value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionTierOption.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionTierOption.java new file mode 100644 index 0000000000..f468e53e04 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionTierOption.java @@ -0,0 +1,28 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Semantic usage tier and its AI-credit cap. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionLimitPredictionTierOption( + @JsonProperty("tier") SessionLimitPredictionTier tier, + /** AI-credit cap for this tier. */ + @JsonProperty("cap") Double cap +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionUnavailableReason.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionUnavailableReason.java new file mode 100644 index 0000000000..76ee7c8820 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionUnavailableReason.java @@ -0,0 +1,35 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Reason a prediction could not be computed. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum SessionLimitPredictionUnavailableReason { + /** The {@code auto_unresolved} variant. */ + AUTO_UNRESOLVED("auto_unresolved"), + /** The {@code no_model} variant. */ + NO_MODEL("no_model"); + + private final String value; + SessionLimitPredictionUnavailableReason(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static SessionLimitPredictionUnavailableReason fromValue(String value) { + for (SessionLimitPredictionUnavailableReason v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown SessionLimitPredictionUnavailableReason value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpApi.java index 172f6e5075..1a75b92c1b 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpApi.java @@ -205,7 +205,7 @@ public CompletableFuture configureGitHub(Sessio } /** - * Server name and configuration for an individual MCP server start. + * Server name and optional configuration for an individual MCP server start. Omit `config` for a config-free start-by-name of an already-configured server. *

* Note: the {@code sessionId} field in the params record is overridden * by the session-scoped wrapper; any value provided is ignored. diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpOauthApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpOauthApi.java index 7b7f7b82bd..4fb92cf145 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpOauthApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpOauthApi.java @@ -62,4 +62,20 @@ public CompletableFuture login(SessionMcpOauthLoginP return caller.invoke("session.mcp.oauth.login", _p, SessionMcpOauthLoginResult.class); } + /** + * Pending MCP OAuth request id to respond to. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture respond(SessionMcpOauthRespondParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.mcp.oauth.respond", _p, SessionMcpOauthRespondResult.class); + } + } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpOauthRespondParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpOauthRespondParams.java new file mode 100644 index 0000000000..ca79468c15 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpOauthRespondParams.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Pending MCP OAuth request id to respond to. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionMcpOauthRespondParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** OAuth request identifier from the mcp.oauth_required event */ + @JsonProperty("requestId") String requestId +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpOauthRespondResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpOauthRespondResult.java new file mode 100644 index 0000000000..1b1267cb57 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpOauthRespondResult.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Indicates whether the pending MCP OAuth response was accepted. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionMcpOauthRespondResult( + /** Whether the response was accepted. False if the request was unknown, timed out, or already resolved. */ + @JsonProperty("success") Boolean success +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpStartServerParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpStartServerParams.java index e4c14e30e4..9f6d5d73e4 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpStartServerParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionMcpStartServerParams.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Server name and configuration for an individual MCP server start. + * Server name and optional configuration for an individual MCP server start. Omit `config` for a config-free start-by-name of an already-configured server. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 @@ -28,7 +28,7 @@ public record SessionMcpStartServerParams( @JsonProperty("sessionId") String sessionId, /** Name of the MCP server to start */ @JsonProperty("serverName") String serverName, - /** MCP server configuration (stdio process or remote HTTP/SSE) */ + /** MCP server configuration (stdio process or remote HTTP/SSE). Omit to start the server with its already-registered configuration (config-free start-by-name). */ @JsonProperty("config") Object config ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelApi.java index 34be1729de..4e6ce5dbc5 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelApi.java @@ -81,7 +81,7 @@ public CompletableFuture setReasoningEffor */ @CopilotExperimental public CompletableFuture list() { - return caller.invoke("session.model.list", java.util.Map.of("sessionId", this.sessionId), SessionModelListResult.class); + return caller.invoke("session.model.list", java.util.Map.of(), SessionModelListResult.class); } } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelSwitchToParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelSwitchToParams.java index 580ab3bab2..a46e989bd9 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelSwitchToParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelSwitchToParams.java @@ -37,6 +37,8 @@ public record SessionModelSwitchToParams( /** Override individual model capabilities resolved by the runtime */ @JsonProperty("modelCapabilities") ModelCapabilitiesOverride modelCapabilities, /** Explicit context tier for the selected model. `"default"` / `"long_context"` apply the requested tier; omit this field to use normal model behavior with no explicit tier. */ - @JsonProperty("contextTier") ContextTier contextTier + @JsonProperty("contextTier") ContextTier contextTier, + /** When true, defer this switch (enqueue it) if another model change is already queued, even when no turn is active — so it drains last (FIFO) and wins over the already-queued change. Intended for genuine user-initiated model selections; internal restore/reapply switches omit it and apply immediately when no turn is active. When no other model change is queued this has no effect (a switch still applies immediately unless a turn is active). */ + @JsonProperty("deferIfModelChangeQueued") Boolean deferIfModelChangeQueued ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelSwitchToResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelSwitchToResult.java index 89584bc29c..030324a94b 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelSwitchToResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelSwitchToResult.java @@ -25,6 +25,8 @@ @JsonIgnoreProperties(ignoreUnknown = true) public record SessionModelSwitchToResult( /** Currently active model identifier after the switch */ - @JsonProperty("modelId") String modelId + @JsonProperty("modelId") String modelId, + /** True when the switch was deferred (enqueued as a cancellable `/model` command) because a turn was active or another model change was already queued, rather than applied immediately. When true, the session's live model is unchanged until the queued change drains. */ + @JsonProperty("deferred") Boolean deferred ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionOptionsUpdateParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionOptionsUpdateParams.java index fb8c25b3da..34ab8c2721 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionOptionsUpdateParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionOptionsUpdateParams.java @@ -66,9 +66,11 @@ public record SessionOptionsUpdateParams( @JsonProperty("toolFilterPrecedence") OptionsUpdateToolFilterPrecedence toolFilterPrecedence, /** Whether shell-script safety heuristics are enabled. */ @JsonProperty("enableScriptSafety") Boolean enableScriptSafety, - /** Shell init profile (`None` or `NonInteractive`). */ + /** Per-session settings for built-in shell tools. */ + @JsonProperty("shell") ShellOptions shell, + /** Use shell.initProfile instead. Shell init profile (`None` or `NonInteractive`). */ @JsonProperty("shellInitProfile") String shellInitProfile, - /** Per-shell process flags (e.g., `pwsh` arguments). */ + /** PowerShell process flags applied to built-in and user-requested shell commands. */ @JsonProperty("shellProcessFlags") List shellProcessFlags, /** Resolved sandbox configuration. */ @JsonProperty("sandboxConfig") SandboxConfig sandboxConfig, @@ -82,7 +84,7 @@ public record SessionOptionsUpdateParams( @JsonProperty("skillDirectories") List skillDirectories, /** Skill IDs that should be excluded from this session. */ @JsonProperty("disabledSkills") List disabledSkills, - /** Whether to discover custom instructions on demand after successful file views (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md surfacing). Combined with `skipCustomInstructions` and the runtime-side `ON_DEMAND_INSTRUCTIONS` feature flag. */ + /** Whether to discover custom instructions on demand after successful file views (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md surfacing). Combined with `skipCustomInstructions`. */ @JsonProperty("enableOnDemandInstructionDiscovery") Boolean enableOnDemandInstructionDiscovery, /** Maximum decoded byte size of a single model-facing binary tool result (e.g. an image) persisted inline in session events and re-presented to the model on later turns / resume. Larger results are persisted as a metadata-only marker and shown to the model as a short text note. Defaults to 10 MB. */ @JsonProperty("maxInlineBinaryBytes") Long maxInlineBinaryBytes, @@ -116,6 +118,8 @@ public record SessionOptionsUpdateParams( @JsonProperty("agentContext") String agentContext, /** Override directory for the session-events log. When unset, the runtime's default events log directory is used. */ @JsonProperty("eventsLogDirectory") String eventsLogDirectory, + /** Whether subagent callback events should be forwarded into the session event log sink. */ + @JsonProperty("eventsLogIncludesSubagents") Boolean eventsLogIncludesSubagents, /** Additional content-exclusion policies to merge into the session's policy set. */ @JsonProperty("additionalContentExclusionPolicies") List additionalContentExclusionPolicies, /** 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). */ diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsApi.java index aba3177083..25d2e36666 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsApi.java @@ -162,14 +162,19 @@ public CompletableFuture setRequired(Sessio } /** - * No parameters; clears all session-scoped tool permission approvals. + * Clears session-scoped tool permission approvals, and optionally the location-scoped ones. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ @CopilotExperimental - public CompletableFuture resetSessionApprovals() { - return caller.invoke("session.permissions.resetSessionApprovals", java.util.Map.of("sessionId", this.sessionId), SessionPermissionsResetSessionApprovalsResult.class); + public CompletableFuture resetSessionApprovals(SessionPermissionsResetSessionApprovalsParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.permissions.resetSessionApprovals", _p, SessionPermissionsResetSessionApprovalsResult.class); } /** diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsResetSessionApprovalsParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsResetSessionApprovalsParams.java index 881c081ab0..68ef9814d6 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsResetSessionApprovalsParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionPermissionsResetSessionApprovalsParams.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * No parameters; clears all session-scoped tool permission approvals. + * Clears session-scoped tool permission approvals, and optionally the location-scoped ones. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 @@ -25,6 +25,8 @@ @JsonIgnoreProperties(ignoreUnknown = true) public record SessionPermissionsResetSessionApprovalsParams( /** Target session identifier */ - @JsonProperty("sessionId") String sessionId + @JsonProperty("sessionId") String sessionId, + /** Whether location-scoped approvals are cleared too. Defaults to `true`. */ + @JsonProperty("includeLocation") Boolean includeLocation ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionPluginsApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionPluginsApi.java index 0b1e4dfef6..1d3e5dea9d 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionPluginsApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionPluginsApi.java @@ -47,7 +47,7 @@ public CompletableFuture list() { */ @CopilotExperimental public CompletableFuture reload() { - return caller.invoke("session.plugins.reload", java.util.Map.of("sessionId", this.sessionId), Void.class); + return caller.invoke("session.plugins.reload", java.util.Map.of(), Void.class); } } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionProviderApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionProviderApi.java index 4a6fdc1861..5abded471b 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionProviderApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionProviderApi.java @@ -38,7 +38,7 @@ public final class SessionProviderApi { */ @CopilotExperimental public CompletableFuture getEndpoint() { - return caller.invoke("session.provider.getEndpoint", java.util.Map.of("sessionId", this.sessionId), SessionProviderGetEndpointResult.class); + return caller.invoke("session.provider.getEndpoint", java.util.Map.of(), SessionProviderGetEndpointResult.class); } /** diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionProviderGetEndpointParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionProviderGetEndpointParams.java deleted file mode 100644 index 09e992a784..0000000000 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionProviderGetEndpointParams.java +++ /dev/null @@ -1,30 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Optional model identifier to scope the endpoint snapshot to. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record SessionProviderGetEndpointParams( - /** Target session identifier */ - @JsonProperty("sessionId") String sessionId -) { -} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueApi.java index 9b880e134f..6e40bdfeba 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueApi.java @@ -19,6 +19,8 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") public final class SessionQueueApi { + private static final com.fasterxml.jackson.databind.ObjectMapper MAPPER = RpcMapper.INSTANCE; + private final RpcCaller caller; private final String sessionId; @@ -39,6 +41,188 @@ public CompletableFuture pendingItems() { return caller.invoke("session.queue.pendingItems", java.util.Map.of("sessionId", this.sessionId), SessionQueuePendingItemsResult.class); } + /** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture snapshot() { + return caller.invoke("session.queue.snapshot", java.util.Map.of("sessionId", this.sessionId), SessionQueueSnapshotResult.class); + } + + /** + * Parameters for moving a queued item by stable id. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture moveItem(SessionQueueMoveItemParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.queue.moveItem", _p, SessionQueueMoveItemResult.class); + } + + /** + * Parameters for inserting a queued message at a public visible position. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture insertAt(SessionQueueInsertAtParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.queue.insertAt", _p, SessionQueueInsertAtResult.class); + } + + /** + * Parameters for removing a queued item by stable id. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture removeAt(SessionQueueRemoveAtParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.queue.removeAt", _p, SessionQueueRemoveAtResult.class); + } + + /** + * Parameters for editing a single queued message. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture updateText(SessionQueueUpdateTextParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.queue.updateText", _p, SessionQueueUpdateTextResult.class); + } + + /** + * Parameters for duplicating a queued item. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture duplicateAt(SessionQueueDuplicateAtParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.queue.duplicateAt", _p, SessionQueueDuplicateAtResult.class); + } + + /** + * Parameters for acquiring or releasing the queued-lane drain pause. Acquisition is exclusive and non-idempotent: `paused: true` against an already-paused session fails with `queue_already_paused`. The pause is never released automatically — it is not tied to the caller's lifetime, so a client that exits without sending `paused: false` leaves the lane frozen. Release is unowned: `paused: false` clears the pause for any caller, including one that never acquired it. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture setDrainPaused(SessionQueueSetDrainPausedParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.queue.setDrainPaused", _p, Void.class); + } + + /** + * Parameters for steering a queued message into a live turn. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture sendNow(SessionQueueSendNowParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.queue.sendNow", _p, SessionQueueSendNowResult.class); + } + + /** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture hasPending() { + return caller.invoke("session.queue.hasPending", java.util.Map.of("sessionId", this.sessionId), SessionQueueHasPendingResult.class); + } + + /** + * Inputs for starting a deferred-idle drain. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture beginDeferredIdleDrain(SessionQueueBeginDeferredIdleDrainParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.queue.beginDeferredIdleDrain", _p, SessionQueueBeginDeferredIdleDrainResult.class); + } + + /** + * Inputs for completing a deferred-idle drain. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture finishDeferredIdleDrain(SessionQueueFinishDeferredIdleDrainParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.queue.finishDeferredIdleDrain", _p, SessionQueueFinishDeferredIdleDrainResult.class); + } + + /** + * Inputs for marking session.idle deferred in native state. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture deferSessionIdle(SessionQueueDeferSessionIdleParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.queue.deferSessionIdle", _p, Void.class); + } + /** * Identifies the target session. * @@ -61,4 +245,42 @@ public CompletableFuture clear() { return caller.invoke("session.queue.clear", java.util.Map.of("sessionId", this.sessionId), Void.class); } + /** + * Internal filter for consuming queued system notifications. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture consumeSystemNotifications(SessionQueueConsumeSystemNotificationsParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.queue.consumeSystemNotifications", _p, SessionQueueConsumeSystemNotificationsResult.class); + } + + /** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture enqueueResumePending() { + return caller.invoke("session.queue.enqueueResumePending", java.util.Map.of("sessionId", this.sessionId), SessionQueueEnqueueResumePendingResult.class); + } + + /** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture process() { + return caller.invoke("session.queue.process", java.util.Map.of("sessionId", this.sessionId), Void.class); + } + } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueBeginDeferredIdleDrainParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueBeginDeferredIdleDrainParams.java new file mode 100644 index 0000000000..4973e31075 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueBeginDeferredIdleDrainParams.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Inputs for starting a deferred-idle drain. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueBeginDeferredIdleDrainParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Whether the host still has active background work. */ + @JsonProperty("activeBackgroundWork") Boolean activeBackgroundWork +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueBeginDeferredIdleDrainResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueBeginDeferredIdleDrainResult.java new file mode 100644 index 0000000000..77e6decb9b --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueBeginDeferredIdleDrainResult.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Whether a deferred-idle drain should run. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueBeginDeferredIdleDrainResult( + /** True when the host should run finishDeferredIdleDrain asynchronously. */ + @JsonProperty("shouldDrain") Boolean shouldDrain +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueConsumeSystemNotificationsParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueConsumeSystemNotificationsParams.java new file mode 100644 index 0000000000..6449ce7666 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueConsumeSystemNotificationsParams.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Internal filter for consuming queued system notifications. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueConsumeSystemNotificationsParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Opaque runtime-owned filter object. */ + @JsonProperty("filter") Object filter +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueConsumeSystemNotificationsResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueConsumeSystemNotificationsResult.java new file mode 100644 index 0000000000..bbc3715880 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueConsumeSystemNotificationsResult.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Indicates whether a user-facing pending item was removed. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueConsumeSystemNotificationsResult( + /** True if a user-facing pending item was removed (LIFO across both queues); false when no removable items remained. */ + @JsonProperty("removed") Boolean removed +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueDeferSessionIdleParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueDeferSessionIdleParams.java new file mode 100644 index 0000000000..7b3dff9ef5 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueDeferSessionIdleParams.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Inputs for marking session.idle deferred in native state. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueDeferSessionIdleParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Whether the deferred idle was caused by an aborted foreground turn. */ + @JsonProperty("aborted") Boolean aborted +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionCommandsListParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueDuplicateAtParams.java similarity index 84% rename from java/src/generated/java/com/github/copilot/generated/rpc/SessionCommandsListParams.java rename to java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueDuplicateAtParams.java index 6cd085b38e..bf16f9d35f 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionCommandsListParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueDuplicateAtParams.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Optional filters controlling which command sources to include in the listing. + * Parameters for duplicating a queued item. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 @@ -23,8 +23,9 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record SessionCommandsListParams( +public record SessionQueueDuplicateAtParams( /** Target session identifier */ - @JsonProperty("sessionId") String sessionId + @JsonProperty("sessionId") String sessionId, + @JsonProperty("id") String id ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueDuplicateAtResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueDuplicateAtResult.java new file mode 100644 index 0000000000..0be932f95e --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueDuplicateAtResult.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Result of duplicating a queued item. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueDuplicateAtResult( + /** Fresh stable opaque id assigned to the duplicate. */ + @JsonProperty("id") String id +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueEnqueueResumePendingParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueEnqueueResumePendingParams.java new file mode 100644 index 0000000000..1a0ec546ae --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueEnqueueResumePendingParams.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueEnqueueResumePendingParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueEnqueueResumePendingResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueEnqueueResumePendingResult.java new file mode 100644 index 0000000000..324765b4a2 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueEnqueueResumePendingResult.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Result of enqueueing the resume-pending wake item. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueEnqueueResumePendingResult( + /** True when a wake item was newly queued. */ + @JsonProperty("queued") Boolean queued +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueFinishDeferredIdleDrainParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueFinishDeferredIdleDrainParams.java new file mode 100644 index 0000000000..b6b29057d8 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueFinishDeferredIdleDrainParams.java @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Inputs for completing a deferred-idle drain. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueFinishDeferredIdleDrainParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Whether the host still has active background work. */ + @JsonProperty("activeBackgroundWork") Boolean activeBackgroundWork, + /** Whether native queued work remains. */ + @JsonProperty("hasPending") Boolean hasPending +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueFinishDeferredIdleDrainResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueFinishDeferredIdleDrainResult.java new file mode 100644 index 0000000000..1e6cc52577 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueFinishDeferredIdleDrainResult.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Action selected by the native deferred-idle drain. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueFinishDeferredIdleDrainResult( + /** One of none, processQueue, or emitSessionIdle. */ + @JsonProperty("action") String action, + /** Whether the deferred idle was caused by an aborted foreground turn. */ + @JsonProperty("aborted") Boolean aborted +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryCompactParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueHasPendingParams.java similarity index 92% rename from java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryCompactParams.java rename to java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueHasPendingParams.java index 9dc6a0ee94..e587fec4cb 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryCompactParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueHasPendingParams.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Optional compaction parameters. + * Identifies the target session. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 @@ -23,7 +23,7 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record SessionHistoryCompactParams( +public record SessionQueueHasPendingParams( /** Target session identifier */ @JsonProperty("sessionId") String sessionId ) { diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueHasPendingResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueHasPendingResult.java new file mode 100644 index 0000000000..5373856a45 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueHasPendingResult.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Whether the native queue has pending work. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueHasPendingResult( + /** True when queued or immediate native work is pending. */ + @JsonProperty("hasPending") Boolean hasPending +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueInsertAtParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueInsertAtParams.java new file mode 100644 index 0000000000..981aefb5fd --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueInsertAtParams.java @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Parameters for inserting a queued message at a public visible position. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueInsertAtParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Zero-based position in the public visible queue. Values outside the queue clamp to an end. */ + @JsonProperty("position") Long position, + @JsonProperty("message") QueueInsertMessage message +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueInsertAtResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueInsertAtResult.java new file mode 100644 index 0000000000..1d4805e8cc --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueInsertAtResult.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Result of inserting a queued message. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueInsertAtResult( + /** Fresh stable opaque id assigned to the inserted item. */ + @JsonProperty("id") String id +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueMoveItemParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueMoveItemParams.java new file mode 100644 index 0000000000..0a584f50c8 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueMoveItemParams.java @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Parameters for moving a queued item by stable id. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueMoveItemParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Stable opaque queued-item id. */ + @JsonProperty("id") String id, + /** Zero-based target position in the public visible queue. Values outside the queue clamp to an end. */ + @JsonProperty("toPosition") Long toPosition +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueMoveItemResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueMoveItemResult.java new file mode 100644 index 0000000000..431a081754 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueMoveItemResult.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Result of moving a queued item. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueMoveItemResult( + /** True when the item changed position; false when it was already at the requested position. */ + @JsonProperty("changed") Boolean changed +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionAgentListParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueProcessParams.java similarity index 96% rename from java/src/generated/java/com/github/copilot/generated/rpc/SessionAgentListParams.java rename to java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueProcessParams.java index 44636f59d2..8c8edfe554 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionAgentListParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueProcessParams.java @@ -23,7 +23,7 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record SessionAgentListParams( +public record SessionQueueProcessParams( /** Target session identifier */ @JsonProperty("sessionId") String sessionId ) { diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueRemoveAtParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueRemoveAtParams.java new file mode 100644 index 0000000000..bc7cd3e124 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueRemoveAtParams.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Parameters for removing a queued item by stable id. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueRemoveAtParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + @JsonProperty("id") String id +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueRemoveAtResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueRemoveAtResult.java new file mode 100644 index 0000000000..0f5d95487d --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueRemoveAtResult.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Result of removing a queued item. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueRemoveAtResult( + /** True when the addressed item was removed. */ + @JsonProperty("removed") Boolean removed +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueSendNowParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueSendNowParams.java new file mode 100644 index 0000000000..6381636a89 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueSendNowParams.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Parameters for steering a queued message into a live turn. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueSendNowParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + @JsonProperty("id") String id +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueSendNowResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueSendNowResult.java new file mode 100644 index 0000000000..584bd59d18 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueSendNowResult.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Result of trying to steer a queued message into a live turn. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueSendNowResult( + /** True when the item was accepted into the steering lane; false when no main turn was live. */ + @JsonProperty("steered") Boolean steered +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueSetDrainPausedParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueSetDrainPausedParams.java new file mode 100644 index 0000000000..f51e33ea16 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueSetDrainPausedParams.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Parameters for acquiring or releasing the queued-lane drain pause. Acquisition is exclusive and non-idempotent: `paused: true` against an already-paused session fails with `queue_already_paused`. The pause is never released automatically — it is not tied to the caller's lifetime, so a client that exits without sending `paused: false` leaves the lane frozen. Release is unowned: `paused: false` clears the pause for any caller, including one that never acquired it. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueSetDrainPausedParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + @JsonProperty("paused") Boolean paused +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelListParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueSnapshotParams.java similarity index 92% rename from java/src/generated/java/com/github/copilot/generated/rpc/SessionModelListParams.java rename to java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueSnapshotParams.java index 154ca5c22c..dff5db8a8d 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelListParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueSnapshotParams.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Optional listing options. + * Identifies the target session. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 @@ -23,7 +23,7 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record SessionModelListParams( +public record SessionQueueSnapshotParams( /** Target session identifier */ @JsonProperty("sessionId") String sessionId ) { diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueSnapshotResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueSnapshotResult.java new file mode 100644 index 0000000000..7ae1076d63 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueSnapshotResult.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Internal snapshot of native queue state for local session orchestration. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueSnapshotResult( + /** User-facing pending items in FIFO order. */ + @JsonProperty("items") List items, + /** Immediate steering messages waiting for an active turn. */ + @JsonProperty("steeringMessages") List steeringMessages, + /** Insertion orders for queued items, aligned with `items`. */ + @JsonProperty("itemOrders") List itemOrders, + /** Insertion orders for immediate steering messages, aligned with `steeringMessages`. */ + @JsonProperty("steeringMessageOrders") List steeringMessageOrders +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueUpdateTextParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueUpdateTextParams.java new file mode 100644 index 0000000000..139a5ba2a4 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueUpdateTextParams.java @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Parameters for editing a single queued message. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueUpdateTextParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + @JsonProperty("id") String id, + @JsonProperty("prompt") String prompt, + @JsonProperty("displayPrompt") String displayPrompt +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueUpdateTextResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueUpdateTextResult.java new file mode 100644 index 0000000000..3809f5bd68 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionQueueUpdateTextResult.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Result of editing a queued message. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionQueueUpdateTextResult( + /** True when the stored text changed. */ + @JsonProperty("updated") Boolean updated +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionRpc.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionRpc.java index 3ec3464d05..05cfd396d4 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionRpc.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionRpc.java @@ -85,6 +85,8 @@ public final class SessionRpc { public final SessionMetadataApi metadata; /** API methods for the {@code settings} namespace. */ public final SessionSettingsApi settings; + /** API methods for the {@code contentExclusion} namespace. */ + public final SessionContentExclusionApi contentExclusion; /** API methods for the {@code shell} namespace. */ public final SessionShellApi shell; /** API methods for the {@code history} namespace. */ @@ -95,6 +97,8 @@ public final class SessionRpc { public final SessionEventLogApi eventLog; /** API methods for the {@code usage} namespace. */ public final SessionUsageApi usage; + /** API methods for the {@code limitPrediction} namespace. */ + public final SessionLimitPredictionApi limitPrediction; /** API methods for the {@code remote} namespace. */ public final SessionRemoteApi remote; /** API methods for the {@code visibility} namespace. */ @@ -139,11 +143,13 @@ public SessionRpc(RpcCaller caller, String sessionId) { this.permissions = new SessionPermissionsApi(caller, sessionId); this.metadata = new SessionMetadataApi(caller, sessionId); this.settings = new SessionSettingsApi(caller, sessionId); + this.contentExclusion = new SessionContentExclusionApi(caller, sessionId); this.shell = new SessionShellApi(caller, sessionId); this.history = new SessionHistoryApi(caller, sessionId); this.queue = new SessionQueueApi(caller, sessionId); this.eventLog = new SessionEventLogApi(caller, sessionId); this.usage = new SessionUsageApi(caller, sessionId); + this.limitPrediction = new SessionLimitPredictionApi(caller, sessionId); this.remote = new SessionRemoteApi(caller, sessionId); this.visibility = new SessionVisibilityApi(caller, sessionId); this.schedule = new SessionScheduleApi(caller, sessionId); @@ -192,6 +198,22 @@ public CompletableFuture sendMessages(SessionSendMess return caller.invoke("session.sendMessages", _p, SessionSendMessagesResult.class); } + /** + * Internal request for sending a system notification. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture sendSystemNotification(SessionSendSystemNotificationParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.sendSystemNotification", _p, Void.class); + } + /** * Parameters for aborting the current turn *

@@ -208,6 +230,33 @@ public CompletableFuture abort(SessionAbortParams params) { return caller.invoke("session.abort", _p, SessionAbortResult.class); } + /** + * Parameters for interrupting the main agent turn. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture interruptMainTurn(SessionInterruptMainTurnParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.interruptMainTurn", _p, SessionInterruptMainTurnResult.class); + } + + /** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture cancelAllBackgroundAgents() { + return caller.invoke("session.cancelAllBackgroundAgents", java.util.Map.of("sessionId", this.sessionId), Void.class); + } + /** * Parameters for shutting down the session *

diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddAtParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddAtParams.java new file mode 100644 index 0000000000..0a099bdf4a --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddAtParams.java @@ -0,0 +1,38 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Register an absolute-time scheduled prompt. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionScheduleAddAtParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Epoch milliseconds when the prompt should fire. */ + @JsonProperty("at") Long at, + /** Prompt text to enqueue when the schedule fires. */ + @JsonProperty("prompt") String prompt, + /** Whether the schedule should re-arm after each tick. Defaults to false. */ + @JsonProperty("recurring") Boolean recurring, + /** Optional display-only prompt label. */ + @JsonProperty("displayPrompt") String displayPrompt +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddAtResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddAtResult.java new file mode 100644 index 0000000000..7952fdc88b --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddAtResult.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Result of registering or re-arming a scheduled prompt. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionScheduleAddAtResult( + /** The registered or updated schedule entry. */ + @JsonProperty("entry") ScheduleEntry entry, + /** User-facing validation error, when registration failed. */ + @JsonProperty("error") String error +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddCronParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddCronParams.java new file mode 100644 index 0000000000..08a9cd33bb --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddCronParams.java @@ -0,0 +1,40 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Register a cron scheduled prompt. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionScheduleAddCronParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** 5-field cron expression. */ + @JsonProperty("cron") String cron, + /** Prompt text to enqueue when the schedule fires. */ + @JsonProperty("prompt") String prompt, + /** Whether the schedule should re-arm after each tick. Defaults to true. */ + @JsonProperty("recurring") Boolean recurring, + /** Optional display-only prompt label. */ + @JsonProperty("displayPrompt") String displayPrompt, + /** IANA timezone for evaluating the cron expression. */ + @JsonProperty("tz") String tz +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddCronResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddCronResult.java new file mode 100644 index 0000000000..193dea1b4c --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddCronResult.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Result of registering or re-arming a scheduled prompt. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionScheduleAddCronResult( + /** The registered or updated schedule entry. */ + @JsonProperty("entry") ScheduleEntry entry, + /** User-facing validation error, when registration failed. */ + @JsonProperty("error") String error +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddParams.java new file mode 100644 index 0000000000..31580758cb --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddParams.java @@ -0,0 +1,38 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Register a relative-interval scheduled prompt. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionScheduleAddParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Human-readable interval such as `30s`, `5m`, or `2h`. */ + @JsonProperty("interval") String interval, + /** Prompt text to enqueue when the schedule fires. */ + @JsonProperty("prompt") String prompt, + /** Whether the schedule should re-arm after each tick. Defaults to true. */ + @JsonProperty("recurring") Boolean recurring, + /** Optional display-only prompt label. */ + @JsonProperty("displayPrompt") String displayPrompt +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddResult.java new file mode 100644 index 0000000000..021c784c37 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddResult.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Result of registering or re-arming a scheduled prompt. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionScheduleAddResult( + /** The registered or updated schedule entry. */ + @JsonProperty("entry") ScheduleEntry entry, + /** User-facing validation error, when registration failed. */ + @JsonProperty("error") String error +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddSelfPacedParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddSelfPacedParams.java new file mode 100644 index 0000000000..17a89c1b2d --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddSelfPacedParams.java @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Register a self-paced scheduled prompt. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionScheduleAddSelfPacedParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Prompt text to enqueue when the schedule fires. */ + @JsonProperty("prompt") String prompt, + /** Optional display-only prompt label. */ + @JsonProperty("displayPrompt") String displayPrompt +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddSelfPacedResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddSelfPacedResult.java new file mode 100644 index 0000000000..65f8745baf --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleAddSelfPacedResult.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Result of registering or re-arming a scheduled prompt. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionScheduleAddSelfPacedResult( + /** The registered or updated schedule entry. */ + @JsonProperty("entry") ScheduleEntry entry, + /** User-facing validation error, when registration failed. */ + @JsonProperty("error") String error +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleApi.java index 2e42c1bc30..f983f84f71 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleApi.java @@ -41,6 +41,108 @@ public CompletableFuture list() { return caller.invoke("session.schedule.list", java.util.Map.of("sessionId", this.sessionId), SessionScheduleListResult.class); } + /** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture hydrate() { + return caller.invoke("session.schedule.hydrate", java.util.Map.of("sessionId", this.sessionId), Void.class); + } + + /** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture hasSelfPaced() { + return caller.invoke("session.schedule.hasSelfPaced", java.util.Map.of("sessionId", this.sessionId), SessionScheduleHasSelfPacedResult.class); + } + + /** + * Register a relative-interval scheduled prompt. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture add(SessionScheduleAddParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.schedule.add", _p, SessionScheduleAddResult.class); + } + + /** + * Register a cron scheduled prompt. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture addCron(SessionScheduleAddCronParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.schedule.addCron", _p, SessionScheduleAddCronResult.class); + } + + /** + * Register an absolute-time scheduled prompt. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture addAt(SessionScheduleAddAtParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.schedule.addAt", _p, SessionScheduleAddAtResult.class); + } + + /** + * Register a self-paced scheduled prompt. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture addSelfPaced(SessionScheduleAddSelfPacedParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.schedule.addSelfPaced", _p, SessionScheduleAddSelfPacedResult.class); + } + + /** + * Re-arm a self-paced scheduled prompt. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture rearmSelfPaced(SessionScheduleRearmSelfPacedParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.schedule.rearmSelfPaced", _p, SessionScheduleRearmSelfPacedResult.class); + } + /** * Identifier of the scheduled prompt to remove. *

diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleHasSelfPacedParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleHasSelfPacedParams.java new file mode 100644 index 0000000000..7eb31df7f6 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleHasSelfPacedParams.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionScheduleHasSelfPacedParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleHasSelfPacedResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleHasSelfPacedResult.java new file mode 100644 index 0000000000..84c8e7a501 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleHasSelfPacedResult.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Whether the session currently has an active self-paced schedule. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionScheduleHasSelfPacedResult( + /** True when at least one active schedule is self-paced. */ + @JsonProperty("hasSelfPaced") Boolean hasSelfPaced +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleHydrateParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleHydrateParams.java new file mode 100644 index 0000000000..32ec85c7d4 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleHydrateParams.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionScheduleHydrateParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleRearmSelfPacedParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleRearmSelfPacedParams.java new file mode 100644 index 0000000000..d1999311c2 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleRearmSelfPacedParams.java @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Re-arm a self-paced scheduled prompt. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionScheduleRearmSelfPacedParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Id of the self-paced scheduled prompt. */ + @JsonProperty("id") Long id, + /** Epoch milliseconds when the prompt should next fire. */ + @JsonProperty("at") Long at +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleRearmSelfPacedResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleRearmSelfPacedResult.java new file mode 100644 index 0000000000..0280fbaccb --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionScheduleRearmSelfPacedResult.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Result of registering or re-arming a scheduled prompt. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionScheduleRearmSelfPacedResult( + /** The registered or updated schedule entry. */ + @JsonProperty("entry") ScheduleEntry entry, + /** User-facing validation error, when registration failed. */ + @JsonProperty("error") String error +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionSendMessagesParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSendMessagesParams.java index 2d66b4fe16..2943192041 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionSendMessagesParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSendMessagesParams.java @@ -42,7 +42,7 @@ public record SessionSendMessagesParams( @JsonProperty("traceparent") String traceparent, /** W3C Trace Context tracestate header for distributed tracing */ @JsonProperty("tracestate") String tracestate, - /** If true, await completion of the agentic loop for this turn before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageIds`; the caller can rely on the agent having processed the messages before the call resolves. */ + /** If true, await completion of the agentic loop for this turn before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageIds`; the caller can rely on the agent having processed the messages before the call resolves. Transport-dependent tail semantics: on a LOCAL (in-process) session the wait additionally blocks until the completed turn's event tail has been dispatched to this session's in-process subscribers, so a subsequent read of subscriber state already reflects the turn; on a REMOTE session the wait resolves once the loop completes and mirrored delivery follows over the wire. Callers that need the stronger local guarantee on remote sessions should await the event stream explicitly. */ @JsonProperty("wait") Boolean wait_ ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionSendParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSendParams.java index 7762c56831..f19c85ebe2 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionSendParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSendParams.java @@ -42,7 +42,7 @@ public record SessionSendParams( @JsonProperty("billable") Boolean billable, /** If set, the request will fail if the named tool is not available when this message is among the user messages at the start of the current exchange */ @JsonProperty("requiredTool") String requiredTool, - /** Optional provenance tag copied to the resulting user.message event. Must match one of three forms: the literal `system`, `command-` for messages originating from a command (e.g. slash command, Mission Control command), or `schedule-` for messages originating from a scheduled job. */ + /** Optional provenance tag copied to the resulting user.message event. Must be `user`, `system`, `command-` for command-originated messages, `schedule-` for scheduled prompts, or `agent-` for prompts sent by another agent. */ @JsonProperty("source") String source, /** The UI mode the agent was in when this message was sent. Defaults to the session's current mode. */ @JsonProperty("agentMode") SendAgentMode agentMode, @@ -52,7 +52,7 @@ public record SessionSendParams( @JsonProperty("traceparent") String traceparent, /** W3C Trace Context tracestate header for distributed tracing */ @JsonProperty("tracestate") String tracestate, - /** If true, await completion of the agentic loop for this message before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageId`; the caller can rely on the agent having processed the message before the call resolves. */ + /** If true, await completion of the agentic loop for this message before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageId`; the caller can rely on the agent having processed the message before the call resolves. Transport-dependent tail semantics: on a LOCAL (in-process) session the wait additionally blocks until the completed turn's event tail has been dispatched to this session's in-process subscribers, so a subsequent read of subscriber state already reflects the turn; on a REMOTE session the wait resolves once the loop completes and mirrored delivery follows over the wire. Callers that need the stronger local guarantee on remote sessions should await the event stream explicitly. */ @JsonProperty("wait") Boolean wait_ ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionSendSystemNotificationParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSendSystemNotificationParams.java new file mode 100644 index 0000000000..762fe6ef39 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSendSystemNotificationParams.java @@ -0,0 +1,36 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Internal request for sending a system notification. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionSendSystemNotificationParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Notification text to deliver to the model. */ + @JsonProperty("message") String message, + /** Optional structured notification kind. */ + @JsonProperty("kind") Object kind, + /** Internal delivery options, including passive policy. */ + @JsonProperty("options") Object options +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesAddSummaryParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesAddSummaryParams.java new file mode 100644 index 0000000000..2a1c247bf5 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesAddSummaryParams.java @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Compaction summary checkpoint to persist. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionWorkspacesAddSummaryParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Summary title shown in checkpoint listings. */ + @JsonProperty("title") String title, + /** Markdown summary content to persist. */ + @JsonProperty("content") String content +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesAddSummaryResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesAddSummaryResult.java new file mode 100644 index 0000000000..a50a0b5f53 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesAddSummaryResult.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.Map; +import javax.annotation.processing.Generated; + +/** + * Persisted summary metadata and refreshed workspace metadata. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionWorkspacesAddSummaryResult( + @JsonProperty("summary") Map summary, + @JsonProperty("workspace") Map workspace +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesApi.java index 690328176b..aaacb046f0 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesApi.java @@ -41,6 +41,38 @@ public CompletableFuture getWorkspace() { return caller.invoke("session.workspaces.getWorkspace", java.util.Map.of("sessionId", this.sessionId), SessionWorkspacesGetWorkspaceResult.class); } + /** + * Workspace metadata fields to update. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture updateMetadata(SessionWorkspacesUpdateMetadataParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.workspaces.updateMetadata", _p, SessionWorkspacesUpdateMetadataResult.class); + } + + /** + * Optional session context used when creating a local workspace. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture ensure(SessionWorkspacesEnsureParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.workspaces.ensure", _p, SessionWorkspacesEnsureResult.class); + } + /** * Identifies the target session. * @@ -111,6 +143,87 @@ public CompletableFuture readCheckpoint(S return caller.invoke("session.workspaces.readCheckpoint", _p, SessionWorkspacesReadCheckpointResult.class); } + /** + * Compaction summary checkpoint to persist. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture addSummary(SessionWorkspacesAddSummaryParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.workspaces.addSummary", _p, SessionWorkspacesAddSummaryResult.class); + } + + /** + * Rollback point for local workspace summaries. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture truncateSummaries(SessionWorkspacesTruncateSummariesParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.workspaces.truncateSummaries", _p, SessionWorkspacesTruncateSummariesResult.class); + } + + /** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture readAutopilotObjective() { + return caller.invoke("session.workspaces.readAutopilotObjective", java.util.Map.of("sessionId", this.sessionId), SessionWorkspacesReadAutopilotObjectiveResult.class); + } + + /** + * Autopilot objective file content to persist. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture writeAutopilotObjective(SessionWorkspacesWriteAutopilotObjectiveParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.workspaces.writeAutopilotObjective", _p, SessionWorkspacesWriteAutopilotObjectiveResult.class); + } + + /** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture deleteAutopilotObjective() { + return caller.invoke("session.workspaces.deleteAutopilotObjective", java.util.Map.of("sessionId", this.sessionId), SessionWorkspacesDeleteAutopilotObjectiveResult.class); + } + + /** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture autopilotObjectiveExists() { + return caller.invoke("session.workspaces.autopilotObjectiveExists", java.util.Map.of("sessionId", this.sessionId), SessionWorkspacesAutopilotObjectiveExistsResult.class); + } + /** * Pasted content to save as a UTF-8 file in the session workspace. *

diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesAutopilotObjectiveExistsParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesAutopilotObjectiveExistsParams.java new file mode 100644 index 0000000000..fc4b25c9dc --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesAutopilotObjectiveExistsParams.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionWorkspacesAutopilotObjectiveExistsParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesAutopilotObjectiveExistsResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesAutopilotObjectiveExistsResult.java new file mode 100644 index 0000000000..8fe0a849dd --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesAutopilotObjectiveExistsResult.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Whether the autopilot objective file exists. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionWorkspacesAutopilotObjectiveExistsResult( + /** True when the objective file exists. */ + @JsonProperty("exists") Boolean exists +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesDeleteAutopilotObjectiveParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesDeleteAutopilotObjectiveParams.java new file mode 100644 index 0000000000..81f59d7a0a --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesDeleteAutopilotObjectiveParams.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionWorkspacesDeleteAutopilotObjectiveParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesDeleteAutopilotObjectiveResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesDeleteAutopilotObjectiveResult.java new file mode 100644 index 0000000000..3fa3f35f26 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesDeleteAutopilotObjectiveResult.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Result of deleting the autopilot objective file. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionWorkspacesDeleteAutopilotObjectiveResult( + /** True when a file was deleted. */ + @JsonProperty("deleted") Boolean deleted +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesDiffResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesDiffResult.java index a3c8ce96e6..21beab3ead 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesDiffResult.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesDiffResult.java @@ -33,7 +33,9 @@ public record SessionWorkspacesDiffResult( @JsonProperty("changes") List changes, /** Default branch used for a branch diff, when branch mode was requested. */ @JsonProperty("baseBranch") String baseBranch, - /** Whether a requested branch diff fell back to unstaged changes because branch diff failed. */ - @JsonProperty("isFallback") Boolean isFallback + /** Whether the requested diff fell back to unstaged changes, either because branch diff failed or session diff was unavailable. */ + @JsonProperty("isFallback") Boolean isFallback, + /** Why the session diff could not be produced, when applicable. Set only when `session` mode was requested and `isFallback` is true, so a client can tell the permanent `file-change-tracking-disabled` apart from the transient `session-busy`, which the same request answers once the session settles. Never set for `unstaged` or `branch` mode, and never `unsupported-remote-session`: a remote session's captures live on its own host, so a `session`-mode diff is rejected for one rather than answered with a controller-side fallback. */ + @JsonProperty("unavailableReason") HistoryRewindUnavailableReason unavailableReason ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesEnsureParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesEnsureParams.java new file mode 100644 index 0000000000..aaa71621ff --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesEnsureParams.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Optional session context used when creating a local workspace. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionWorkspacesEnsureParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Opaque workspace context supplied by the session host. */ + @JsonProperty("context") Object context +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesEnsureResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesEnsureResult.java new file mode 100644 index 0000000000..4a810fe121 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesEnsureResult.java @@ -0,0 +1,57 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.time.OffsetDateTime; +import javax.annotation.processing.Generated; + +/** + * Current workspace metadata for the session, including its absolute filesystem path when available. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionWorkspacesEnsureResult( + /** Current workspace metadata, or null if not available */ + @JsonProperty("workspace") SessionWorkspacesEnsureResultWorkspace workspace, + /** Absolute filesystem path to the workspace directory. Omitted when the session has no workspace (e.g. remote sessions). */ + @JsonProperty("path") String path +) { + + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public record SessionWorkspacesEnsureResultWorkspace( + @JsonProperty("id") String id, + @JsonProperty("cwd") String cwd, + @JsonProperty("git_root") String gitRoot, + @JsonProperty("repository") String repository, + /** Allowed values for the `WorkspacesWorkspaceDetailsHostType` enumeration. */ + @JsonProperty("host_type") WorkspacesWorkspaceDetailsHostType hostType, + @JsonProperty("branch") String branch, + @JsonProperty("name") String name, + @JsonProperty("client_name") String clientName, + @JsonProperty("user_named") Boolean userNamed, + @JsonProperty("summary_count") Long summaryCount, + @JsonProperty("created_at") OffsetDateTime createdAt, + @JsonProperty("updated_at") OffsetDateTime updatedAt, + @JsonProperty("remote_steerable") Boolean remoteSteerable, + @JsonProperty("mc_task_id") String mcTaskId, + @JsonProperty("mc_session_id") String mcSessionId, + @JsonProperty("mc_last_event_id") String mcLastEventId, + @JsonProperty("chronicle_sync_dismissed") Boolean chronicleSyncDismissed + ) { + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesReadAutopilotObjectiveParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesReadAutopilotObjectiveParams.java new file mode 100644 index 0000000000..67d03a9549 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesReadAutopilotObjectiveParams.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Identifies the target session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionWorkspacesReadAutopilotObjectiveParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesReadAutopilotObjectiveResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesReadAutopilotObjectiveResult.java new file mode 100644 index 0000000000..7b2e157b56 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesReadAutopilotObjectiveResult.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Autopilot objective file content, or null when missing. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionWorkspacesReadAutopilotObjectiveResult( + /** Autopilot objective file content, or null when missing. */ + @JsonProperty("content") String content +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesTruncateSummariesParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesTruncateSummariesParams.java new file mode 100644 index 0000000000..43d392e48c --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesTruncateSummariesParams.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Rollback point for local workspace summaries. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionWorkspacesTruncateSummariesParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Number of newest summaries to keep. */ + @JsonProperty("keepCount") Long keepCount +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesTruncateSummariesResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesTruncateSummariesResult.java new file mode 100644 index 0000000000..caa44d0b7a --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesTruncateSummariesResult.java @@ -0,0 +1,57 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.time.OffsetDateTime; +import javax.annotation.processing.Generated; + +/** + * Current workspace metadata for the session, including its absolute filesystem path when available. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionWorkspacesTruncateSummariesResult( + /** Current workspace metadata, or null if not available */ + @JsonProperty("workspace") SessionWorkspacesTruncateSummariesResultWorkspace workspace, + /** Absolute filesystem path to the workspace directory. Omitted when the session has no workspace (e.g. remote sessions). */ + @JsonProperty("path") String path +) { + + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public record SessionWorkspacesTruncateSummariesResultWorkspace( + @JsonProperty("id") String id, + @JsonProperty("cwd") String cwd, + @JsonProperty("git_root") String gitRoot, + @JsonProperty("repository") String repository, + /** Allowed values for the `WorkspacesWorkspaceDetailsHostType` enumeration. */ + @JsonProperty("host_type") WorkspacesWorkspaceDetailsHostType hostType, + @JsonProperty("branch") String branch, + @JsonProperty("name") String name, + @JsonProperty("client_name") String clientName, + @JsonProperty("user_named") Boolean userNamed, + @JsonProperty("summary_count") Long summaryCount, + @JsonProperty("created_at") OffsetDateTime createdAt, + @JsonProperty("updated_at") OffsetDateTime updatedAt, + @JsonProperty("remote_steerable") Boolean remoteSteerable, + @JsonProperty("mc_task_id") String mcTaskId, + @JsonProperty("mc_session_id") String mcSessionId, + @JsonProperty("mc_last_event_id") String mcLastEventId, + @JsonProperty("chronicle_sync_dismissed") Boolean chronicleSyncDismissed + ) { + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesUpdateMetadataParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesUpdateMetadataParams.java new file mode 100644 index 0000000000..af45fead51 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesUpdateMetadataParams.java @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Workspace metadata fields to update. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionWorkspacesUpdateMetadataParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Opaque workspace context supplied by the session host. */ + @JsonProperty("context") Object context, + /** Optional workspace display name override. */ + @JsonProperty("name") String name +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesUpdateMetadataResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesUpdateMetadataResult.java new file mode 100644 index 0000000000..84ec136616 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesUpdateMetadataResult.java @@ -0,0 +1,57 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.time.OffsetDateTime; +import javax.annotation.processing.Generated; + +/** + * Current workspace metadata for the session, including its absolute filesystem path when available. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionWorkspacesUpdateMetadataResult( + /** Current workspace metadata, or null if not available */ + @JsonProperty("workspace") SessionWorkspacesUpdateMetadataResultWorkspace workspace, + /** Absolute filesystem path to the workspace directory. Omitted when the session has no workspace (e.g. remote sessions). */ + @JsonProperty("path") String path +) { + + @JsonIgnoreProperties(ignoreUnknown = true) + @JsonInclude(JsonInclude.Include.NON_NULL) + public record SessionWorkspacesUpdateMetadataResultWorkspace( + @JsonProperty("id") String id, + @JsonProperty("cwd") String cwd, + @JsonProperty("git_root") String gitRoot, + @JsonProperty("repository") String repository, + /** Allowed values for the `WorkspacesWorkspaceDetailsHostType` enumeration. */ + @JsonProperty("host_type") WorkspacesWorkspaceDetailsHostType hostType, + @JsonProperty("branch") String branch, + @JsonProperty("name") String name, + @JsonProperty("client_name") String clientName, + @JsonProperty("user_named") Boolean userNamed, + @JsonProperty("summary_count") Long summaryCount, + @JsonProperty("created_at") OffsetDateTime createdAt, + @JsonProperty("updated_at") OffsetDateTime updatedAt, + @JsonProperty("remote_steerable") Boolean remoteSteerable, + @JsonProperty("mc_task_id") String mcTaskId, + @JsonProperty("mc_session_id") String mcSessionId, + @JsonProperty("mc_last_event_id") String mcLastEventId, + @JsonProperty("chronicle_sync_dismissed") Boolean chronicleSyncDismissed + ) { + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesWriteAutopilotObjectiveParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesWriteAutopilotObjectiveParams.java new file mode 100644 index 0000000000..fb116ed307 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesWriteAutopilotObjectiveParams.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Autopilot objective file content to persist. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionWorkspacesWriteAutopilotObjectiveParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Autopilot objective file content. */ + @JsonProperty("content") String content +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesWriteAutopilotObjectiveResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesWriteAutopilotObjectiveResult.java new file mode 100644 index 0000000000..9b69713e97 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionWorkspacesWriteAutopilotObjectiveResult.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Result of writing the autopilot objective file. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionWorkspacesWriteAutopilotObjectiveResult( + /** Filesystem operation performed. */ + @JsonProperty("operation") String operation +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsDeleteParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsDeleteParams.java new file mode 100644 index 0000000000..788811e348 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsDeleteParams.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Session ID to delete from disk. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionsDeleteParams( + /** Session ID to delete */ + @JsonProperty("sessionId") String sessionId, + /** Internal resolved session directory path to delete */ + @JsonProperty("sessionPath") String sessionPath +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsGetMetadataParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsGetMetadataParams.java new file mode 100644 index 0000000000..cfa2e6326e --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsGetMetadataParams.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Session ID whose persisted metadata should be read. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionsGetMetadataParams( + /** Session ID to inspect */ + @JsonProperty("sessionId") String sessionId +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsGetMetadataResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsGetMetadataResult.java new file mode 100644 index 0000000000..6546b00fe0 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsGetMetadataResult.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Persisted local session metadata when the session exists. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionsGetMetadataResult( + /** Local session metadata, omitted when the session does not exist. */ + @JsonProperty("session") LocalSessionMetadataValue session +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsListNonEmptySessionIdsParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsListNonEmptySessionIdsParams.java new file mode 100644 index 0000000000..4e453121bc --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsListNonEmptySessionIdsParams.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Limit for non-empty local session IDs. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionsListNonEmptySessionIdsParams( + /** Maximum number of session IDs to return. */ + @JsonProperty("limit") Long limit +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsListNonEmptySessionIdsResult.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsListNonEmptySessionIdsResult.java new file mode 100644 index 0000000000..51cc266e63 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsListNonEmptySessionIdsResult.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Recent local session IDs that contain user-visible history. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionsListNonEmptySessionIdsResult( + /** Session IDs ordered newest-first. */ + @JsonProperty("sessionIds") List sessionIds +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ShellInitProfile.java b/java/src/generated/java/com/github/copilot/generated/rpc/ShellInitProfile.java new file mode 100644 index 0000000000..7d27a55b5d --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ShellInitProfile.java @@ -0,0 +1,35 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Controls automatic non-interactive profile loading where supported. Explicit initScripts are unaffected. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum ShellInitProfile { + /** The {@code none} variant. */ + NONE("none"), + /** The {@code non-interactive} variant. */ + NON_INTERACTIVE("non-interactive"); + + private final String value; + ShellInitProfile(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static ShellInitProfile fromValue(String value) { + for (ShellInitProfile v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown ShellInitProfile value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ShellInitScript.java b/java/src/generated/java/com/github/copilot/generated/rpc/ShellInitScript.java new file mode 100644 index 0000000000..31789619e8 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ShellInitScript.java @@ -0,0 +1,29 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * A host-provided script sourced before each built-in shell command when its shell target matches the active shell. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record ShellInitScript( + /** Path to the script to source. */ + @JsonProperty("path") String path, + /** Built-in shell that may source this script. */ + @JsonProperty("shell") ShellInitScriptShell shell +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ShellInitScriptShell.java b/java/src/generated/java/com/github/copilot/generated/rpc/ShellInitScriptShell.java new file mode 100644 index 0000000000..63d7ba7dc2 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ShellInitScriptShell.java @@ -0,0 +1,35 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Supported built-in shells for initialization scripts. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum ShellInitScriptShell { + /** The {@code bash} variant. */ + BASH("bash"), + /** The {@code powershell} variant. */ + POWERSHELL("powershell"); + + private final String value; + ShellInitScriptShell(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static ShellInitScriptShell fromValue(String value) { + for (ShellInitScriptShell v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown ShellInitScriptShell value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ShellOptions.java b/java/src/generated/java/com/github/copilot/generated/rpc/ShellOptions.java new file mode 100644 index 0000000000..596de0ef98 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ShellOptions.java @@ -0,0 +1,42 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Per-session settings for built-in shell tools. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record ShellOptions( + /** Controls automatic non-interactive profile loading where supported. Explicit initScripts are unaffected. */ + @JsonProperty("initProfile") ShellInitProfile initProfile, + /** Ordered host-provided script paths sourced before each built-in shell command when the +entry's shell target matches the active shell. Use these for rc files, environment setup scripts, +or other custom scripts. A script that returns a nonzero status is reported, and later scripts +and the user command continue while the shell remains running. Because scripts are sourced into +the command shell, `exit`, `exec`, failures under `set -e`, or other shell-terminating behavior +can prevent continuation. Script standard output is preserved; Bash script stderr is discarded, +PowerShell exception messages are replaced, and runtime-generated failure notices omit +configured script paths. When sandboxing is enabled, each script must already be readable under +the active sandbox filesystem policy. Pass an empty array to clear the list. */ + @JsonProperty("initScripts") List initScripts, + /** Flags passed to the active built-in shell process on startup, replacing its default flags. +When omitted, the built-in Bash shell uses `--norc --noprofile`, +and the built-in PowerShell shell uses `-NoProfile -NoLogo`. */ + @JsonProperty("processFlags") List processFlags +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/UIExitPlanModeResponse.java b/java/src/generated/java/com/github/copilot/generated/rpc/UIExitPlanModeResponse.java index d74d1b5042..b65b28fc10 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/UIExitPlanModeResponse.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/UIExitPlanModeResponse.java @@ -28,6 +28,8 @@ public record UIExitPlanModeResponse( /** Whether subsequent edits should be auto-approved without confirmation. */ @JsonProperty("autoApproveEdits") Boolean autoApproveEdits, /** Feedback from the user when they declined the plan or requested changes. */ - @JsonProperty("feedback") String feedback + @JsonProperty("feedback") String feedback, + /** When true, the agent is instructed to end its turn without starting implementation so the client can restore the session model and auto-submit a fresh implementation turn on it. Set only when a distinct plan configuration (a different model, reasoning effort, or context tier) actually ran the planning turn. */ + @JsonProperty("deferImplementation") Boolean deferImplementation ) { } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/WorkspaceDiffFileChange.java b/java/src/generated/java/com/github/copilot/generated/rpc/WorkspaceDiffFileChange.java index f091bc2799..e63b92b569 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/WorkspaceDiffFileChange.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/WorkspaceDiffFileChange.java @@ -21,7 +21,7 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) public record WorkspaceDiffFileChange( - /** Path to the changed file, relative to the workspace root. */ + /** Path to the changed file, relative to the workspace root when the file lives under it. A file changed outside the workspace root keeps a `../`-relative path, or an absolute path when no relative path exists (for example a different Windows drive). */ @JsonProperty("path") String path, /** Unified diff content for the file. Empty when the diff was truncated. */ @JsonProperty("diff") String diff, diff --git a/nodejs/package-lock.json b/nodejs/package-lock.json index 45837520bf..8554f085e6 100644 --- a/nodejs/package-lock.json +++ b/nodejs/package-lock.json @@ -9,7 +9,7 @@ "version": "0.0.0-dev", "license": "MIT", "dependencies": { - "@github/copilot": "^1.0.73", + "@github/copilot": "^1.0.76-5", "koffi": "^3.1.0", "vscode-jsonrpc": "^8.2.1", "zod": "^4.3.6" @@ -700,9 +700,9 @@ } }, "node_modules/@github/copilot": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot/-/copilot-1.0.73.tgz", - "integrity": "sha512-8I2Ejg2CX/PQA3c2H8W1zuqhniCeR1q1/bD8CrV53/ZLw8GF7DAV0xQpwa8ELYvFgjXb6AADojafCKwdbVef+A==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot/-/copilot-1.0.76-5.tgz", + "integrity": "sha512-hbE+dgYeR59lEGTNFgBi7G2xbMNetzq2G9FFrLVD1k0Z1ZavSeZAfrfAuBbVCXvYjr2cfKE6oSeMYUB0fArFjw==", "license": "SEE LICENSE IN LICENSE.md", "dependencies": { "detect-libc": "^2.1.2" @@ -711,20 +711,20 @@ "copilot": "npm-loader.js" }, "optionalDependencies": { - "@github/copilot-darwin-arm64": "1.0.73", - "@github/copilot-darwin-x64": "1.0.73", - "@github/copilot-linux-arm64": "1.0.73", - "@github/copilot-linux-x64": "1.0.73", - "@github/copilot-linuxmusl-arm64": "1.0.73", - "@github/copilot-linuxmusl-x64": "1.0.73", - "@github/copilot-win32-arm64": "1.0.73", - "@github/copilot-win32-x64": "1.0.73" + "@github/copilot-darwin-arm64": "1.0.76-5", + "@github/copilot-darwin-x64": "1.0.76-5", + "@github/copilot-linux-arm64": "1.0.76-5", + "@github/copilot-linux-x64": "1.0.76-5", + "@github/copilot-linuxmusl-arm64": "1.0.76-5", + "@github/copilot-linuxmusl-x64": "1.0.76-5", + "@github/copilot-win32-arm64": "1.0.76-5", + "@github/copilot-win32-x64": "1.0.76-5" } }, "node_modules/@github/copilot-darwin-arm64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-darwin-arm64/-/copilot-darwin-arm64-1.0.73.tgz", - "integrity": "sha512-5jv7t2sw35/zI0cPze38hG6239NT5/q/Emjx6gLibYkolDqMDJjpm17Ps7tc8oafUEOiMQMb+ar7+qi6rSiGJA==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-darwin-arm64/-/copilot-darwin-arm64-1.0.76-5.tgz", + "integrity": "sha512-kHg7wUP1RJoNHAd520I1g+nE0kHl4bxQtufg7CE18Xa0aNgC10PcSe9BwqcFEe8RiGdMCUMtohGMKJIqKdyv8Q==", "cpu": [ "arm64" ], @@ -738,9 +738,9 @@ } }, "node_modules/@github/copilot-darwin-x64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-darwin-x64/-/copilot-darwin-x64-1.0.73.tgz", - "integrity": "sha512-l794k6Ahb11AG2FQT/P4TEWxWblzM1h8aQQCzG8jBWp8dfwjhyYjJ+d+0CWQzM3Fc1ddNUZRjKXCUsfvFjiZhQ==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-darwin-x64/-/copilot-darwin-x64-1.0.76-5.tgz", + "integrity": "sha512-B01l/9qLn+BI3yjsTn7tPHJaCA+2hM6KrqSF7NR5HgQ+AtwRriC+ufwlbWPUatrwtXneQZIRgaSKCNUwLsBrBw==", "cpu": [ "x64" ], @@ -754,9 +754,9 @@ } }, "node_modules/@github/copilot-linux-arm64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-linux-arm64/-/copilot-linux-arm64-1.0.73.tgz", - "integrity": "sha512-Zu0W5nupJjNeem0brqU/pG+VY0IWr6EWr/FsC90g5SEDiaM4VhVNVWcz8t0E3DQCSYetV6IBaNMtjs/3uIIiDQ==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-linux-arm64/-/copilot-linux-arm64-1.0.76-5.tgz", + "integrity": "sha512-QvZSCcIA5cxOhWtviLAMHHn8em7PNSTM9DMujfgAAGKl9w1AFhbN+hsTOtvOojdZYXVMZuiQlYmtZ8EemyiZOg==", "cpu": [ "arm64" ], @@ -770,9 +770,9 @@ } }, "node_modules/@github/copilot-linux-x64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-linux-x64/-/copilot-linux-x64-1.0.73.tgz", - "integrity": "sha512-k33XIr6/PVp+K+5F/zv3No4PPaNImvHz73mcbIw63oxh5iiacXjgr0WqbBIS5s/rkhOWjNPIkbof/TTPZ7mQjA==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-linux-x64/-/copilot-linux-x64-1.0.76-5.tgz", + "integrity": "sha512-61wmKXleon7KGv7e2WtbUC6oYH/QkpjowTI3YvgriNaey8/SaZo4ODt59D/L47s8PqqpvPCbe/f6zmjGLNNWEw==", "cpu": [ "x64" ], @@ -786,9 +786,9 @@ } }, "node_modules/@github/copilot-linuxmusl-arm64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-arm64/-/copilot-linuxmusl-arm64-1.0.73.tgz", - "integrity": "sha512-HJWzhfD3oaiIgfRAHkNWzp17fELtshqM9HVN5n+lFEmSO2EETCEh0P1lhJc4m+FYfXSJnL0raAqVuyaNMuPoPw==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-arm64/-/copilot-linuxmusl-arm64-1.0.76-5.tgz", + "integrity": "sha512-WUD8c5YFEL3LecdocT+VIj83EqnNKrb3YL7Wqk+FtFzzjNmF3UGrVo1CbMerTuQzWU65QhgIt1mEBKN1bMSJqQ==", "cpu": [ "arm64" ], @@ -802,9 +802,9 @@ } }, "node_modules/@github/copilot-linuxmusl-x64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-x64/-/copilot-linuxmusl-x64-1.0.73.tgz", - "integrity": "sha512-/BpOXSb16wHEu8I1SaKiLszQ4Kvu4+Z4uCn7W0bv4xI4fPZwTEG0u3zgaI2W9Ao3+aBl0XRpPmpWzE9ziYEq+w==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-x64/-/copilot-linuxmusl-x64-1.0.76-5.tgz", + "integrity": "sha512-HM44XEx1TcZfpLDcFPf0ya0Bi/0wxJzrrR7FRhRG6C2VYBr/mfUsXBUF9V7vZZMv7yKDPro27PLjpsuMDJyYsQ==", "cpu": [ "x64" ], @@ -818,9 +818,9 @@ } }, "node_modules/@github/copilot-win32-arm64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-win32-arm64/-/copilot-win32-arm64-1.0.73.tgz", - "integrity": "sha512-DbPeXiYzQjpOy9oboaBvuCzjRwfcL987c3bG09cK1crdCDrKfkTJ7NXpcp1KWRPIRFO1FQm1qToNE89J+L3uvg==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-win32-arm64/-/copilot-win32-arm64-1.0.76-5.tgz", + "integrity": "sha512-cbrnDRo7cYAbJuCt4f+1Cw8SiFfNOkCBg3RR/jAcV7Y5ED3QEEoad3WN8avFaiAOGHyTJYqBRTQJNBkyRTmrEw==", "cpu": [ "arm64" ], @@ -834,9 +834,9 @@ } }, "node_modules/@github/copilot-win32-x64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-win32-x64/-/copilot-win32-x64-1.0.73.tgz", - "integrity": "sha512-8D3E1l5i+N5Eq8HIOQpx+Zbcb3MXdFxszksM2gqq175Z1S7Zna67oY4GoR3psxlbIpSyHKiLEBWYiaps6ayHWw==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-win32-x64/-/copilot-win32-x64-1.0.76-5.tgz", + "integrity": "sha512-ShgpTm07YqQQuRLgJ5BqVzKfSlZ4YMmlz7rl/Br5Ifkz57+/HUF2EJBX2LDt05ha1isOaN1ekZQmWvdzWrVCoQ==", "cpu": [ "x64" ], diff --git a/nodejs/package.json b/nodejs/package.json index aadba0ecee..56524ef57c 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -56,7 +56,7 @@ "author": "GitHub", "license": "MIT", "dependencies": { - "@github/copilot": "^1.0.73", + "@github/copilot": "^1.0.76-5", "koffi": "^3.1.0", "vscode-jsonrpc": "^8.2.1", "zod": "^4.3.6" diff --git a/nodejs/samples/package-lock.json b/nodejs/samples/package-lock.json index a12f7eedd4..38feed71f7 100644 --- a/nodejs/samples/package-lock.json +++ b/nodejs/samples/package-lock.json @@ -18,7 +18,7 @@ "version": "0.0.0-dev", "license": "MIT", "dependencies": { - "@github/copilot": "^1.0.73", + "@github/copilot": "^1.0.76-5", "koffi": "^3.1.0", "vscode-jsonrpc": "^8.2.1", "zod": "^4.3.6" diff --git a/nodejs/src/generated/rpc.ts b/nodejs/src/generated/rpc.ts index cf009115e1..db9039238e 100644 --- a/nodejs/src/generated/rpc.ts +++ b/nodejs/src/generated/rpc.ts @@ -68,6 +68,27 @@ export type AgentInfoSource = | "plugin" /** Agent built into the Copilot runtime. */ | "builtin"; +/** + * Controls whether built-in agents and authored prompt text are included. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "AgentListRequest". + */ +/** @experimental */ +export type AgentListRequest = + | { + [k: string]: unknown | undefined; + } + | { + /** + * When true, request the session's configured built-in agents alongside custom agents. Listing applies feature, context, inclusion, exclusion, and user-disabled-agent policy, but does not evaluate transient invocation requirements such as model availability. Built-in metadata may be omitted when the session cannot project it, such as a relay session. + */ + includeBuiltInAgents?: boolean; + /** + * When true, request authored base prompt text on each AgentInfo. Prompt text may be omitted when unavailable, such as for agents projected through a relay session. + */ + includePrompt?: boolean; + }; /** * Process kind tag for the registry entry * @@ -260,6 +281,31 @@ export type SlashCommandKind = */ /** @experimental */ export type SlashCommandInputCompletion = /** Input should complete filesystem directories. */ "directory"; +/** + * Optional filters controlling which command sources to include in the listing. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "CommandsListRequest". + */ +/** @experimental */ +export type CommandsListRequest = + | { + [k: string]: unknown | undefined; + } + | { + /** + * Include runtime built-in commands + */ + includeBuiltins?: boolean; + /** + * Include enabled user-invocable skills and commands + */ + includeSkills?: boolean; + /** + * Include commands registered by protocol clients, including SDK clients and extensions + */ + includeClientCommands?: boolean; + }; /** * Result of the queued command execution. * @@ -510,17 +556,53 @@ export type ExternalToolTextResultForLlmContentResourceDetails = | EmbeddedTextResourceContents | EmbeddedBlobResourceContents; /** - * Kind of factory progress line. + * Execution-critical factory storage operation. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "FactoryDurableOperation". + */ +/** @experimental */ +export type FactoryDurableOperation = + /** Creating the durable run and declared phases. */ + | "createRun" + /** Persisting the transition to running. */ + | "markRunStarted" + /** Persisting the terminal run envelope. */ + | "finishRun" + /** Persisting subagent admission accounting. */ + | "reserveAgent" + /** Rolling back an uncommitted subagent admission. */ + | "releaseAgent" + /** Persisting an idempotent model-usage charge. */ + | "chargeCredit" + /** Persisting active execution time. */ + | "addElapsed" + /** Reading the authoritative AI-credit total. */ + | "reconcileCreditTotal" + /** Reading a journal entry without treating storage failure as a cache miss. */ + | "journalGet" + /** Persisting a journal entry before reporting success. */ + | "journalPut"; +/** + * Current or terminal state of a factory run. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryLogLineKind". + * via the `definition` "FactoryRunStatus". */ /** @experimental */ -export type FactoryLogLineKind = - /** A narrator log line. */ - | "log" - /** A named factory phase marker. */ - | "phase"; +export type FactoryRunStatus = + /** The run was minted and is awaiting approval. */ + | "pending" + /** The run is executing. */ + | "running" + /** The run completed successfully. */ + | "completed" + /** The run was interrupted while resource budget remained. */ + | "halted" + /** The run was cancelled before completion. */ + | "cancelled" + /** The factory body failed or reached a cumulative resource ceiling. */ + | "error"; /** * Machine-readable factory run failure. * @@ -551,6 +633,18 @@ export type FactoryRunFailure = */ reason: string; type: "factory_resume_declined"; + } + | { + /** + * Stable failure code. + */ + code: string; + operation: FactoryDurableOperation; + /** + * Factory run identifier. + */ + runId: string; + type: "factory_durable_failure"; }; /** * Cumulative resource ceiling that stopped a factory run. @@ -562,28 +656,38 @@ export type FactoryRunFailure = export type FactoryRunFailureKind = /** The run admitted the approved maximum total number of subagents. */ | "maxTotalSubagents" - /** The run reached the approved timeout deadline. */ - | "timeout"; + /** The run reached the approved accumulated active-execution time in seconds. */ + | "timeoutSeconds" + /** The run's settled subagent model usage exceeded the approved AI-credit ceiling, or no headroom remained for another subagent. */ + | "maxAiCredits"; /** - * Current or terminal state of a factory run. + * Kind of factory progress line. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryRunStatus". + * via the `definition` "FactoryLogLineKind". */ /** @experimental */ -export type FactoryRunStatus = - /** The run was minted and is awaiting approval. */ +export type FactoryLogLineKind = + /** A narrator log line. */ + | "log" + /** A named factory phase marker. */ + | "phase"; +/** + * Derived lifecycle state of a factory phase. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "FactoryPhaseStatus". + */ +/** @experimental */ +export type FactoryPhaseStatus = + /** The phase has not been entered yet. */ | "pending" - /** The run is executing. */ - | "running" - /** The run completed successfully. */ + /** The phase is currently entered and accumulating active time. */ + | "active" + /** The phase was entered and has since been closed. */ | "completed" - /** The run was interrupted while resource budget remained. */ - | "halted" - /** The run was cancelled before completion. */ - | "cancelled" - /** The factory body failed or reached a cumulative resource ceiling. */ - | "error"; + /** The phase was never entered because a later phase was entered or the run reached a terminal state. */ + | "skipped"; /** * Content filtering mode to apply to all tools, or a map of tool name to content filtering mode. * @@ -596,6 +700,112 @@ export type FilterMapping = [k: string]: ContentFilterMode; } | ContentFilterMode; +/** + * Optional compaction parameters. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HistoryCompactRequest". + */ +/** @experimental */ +export type HistoryCompactRequest = + | { + [k: string]: unknown | undefined; + } + | { + /** + * Optional user-provided instructions to focus the compaction summary + */ + customInstructions?: string; + /** + * What initiated this compaction request, recorded as the `trigger` on the persisted `session.compaction_start` / `session.compaction_complete` events. When absent, the compaction is persisted without trigger attribution (initiator unknown). + */ + trigger?: /** User-requested compaction, e.g. the /compact command or a direct history.compact call. */ + | "manual" + /** Compaction requested while switching to a model with a smaller context window. */ + | "model_switch"; + /** + * Context window token limit this compaction is targeting, recorded as the `tokenLimit` on the persisted `session.compaction_start` / `session.compaction_complete` events. Set it when the compaction targets a window other than the compacting model's own, e.g. switching to a model with a smaller context window: the compaction still runs on the current model, so the limit that motivated it would otherwise be lost. When absent, the events record the compacting model's own resolved limit. Attribution metadata only - it does not change how much the compaction removes. + */ + tokenLimit?: number; + }; +/** + * Reason a captured file was not restored. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HistoryFileRestoreSkipReason". + */ +/** @experimental */ +export type HistoryFileRestoreSkipReason = + /** The file changed after Copilot's last captured write. */ + | "user-modified" + /** A faithful preimage was not captured. */ + | "skipped-capture"; +/** + * Reason a rewind read (rewind points, file-restore preview, or session diff) could not be answered from the session's file-change captures. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HistoryRewindUnavailableReason". + */ +/** @experimental */ +export type HistoryRewindUnavailableReason = + /** The session did not opt into file-change tracking before its first turn. */ + | "file-change-tracking-disabled" + /** The session still has work that may mutate files or history. Transient: the same request succeeds once the session settles, so callers should retry rather than treat it as a failure. */ + | "session-busy" + /** Remote-backed rewind routing is not supported. */ + | "unsupported-remote-session"; +/** + * Aggregate file change represented by a rewind preview. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HistoryRewindChangeType". + */ +/** @experimental */ +export type HistoryRewindChangeType = + /** The discarded turns created the file. */ + | "created" + /** The discarded turns deleted the file. */ + | "deleted" + /** The discarded turns modified the file. */ + | "modified"; +/** + * Scope of a rewind operation. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HistoryRewindMode". + */ +/** @experimental */ +export type HistoryRewindMode = + /** Discard conversation events while leaving files unchanged. */ + | "conversation" + /** Discard conversation events and restore captured files changed by those turns. */ + | "conversation-and-files"; +/** + * Outcome of a rewind request. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HistoryRewindOutcome". + */ +/** @experimental */ +export type HistoryRewindOutcome = + /** The requested rewind completed; reachable in either mode. */ + | "success" + /** The session still has work that may mutate files or history; reachable in either mode. */ + | "session-busy" + /** A conversation-and-files rewind was requested for a session that did not enable capture; conversation-only rewinds never produce this. */ + | "file-change-tracking-disabled" + /** Remote-backed rewind routing is not supported; reachable in either mode. */ + | "unsupported-remote-session" + /** File restore failed and all applied file changes were rolled back; only conversation-and-files rewinds produce this. */ + | "files-rolled-back" + /** File restore failed and its rollback could not fully restore the pre-rewind state; only conversation-and-files rewinds produce this. */ + | "rollback-incomplete" + /** Conversation truncation failed. In conversation-and-files mode any files that were restored are left in place because conversation history cannot be un-truncated; in conversation-only mode no files are restored. Consult restoredFiles for what, if anything, was applied. */ + | "truncation-failed" + /** The conversation was rewound (and, in conversation-and-files mode, captured files were restored), but persisted checkpoints could not be cleaned up; reachable in either mode. */ + | "checkpoint-cleanup-failed" + /** Files and conversation were rewound, but obsolete file snapshots could not be removed; only conversation-and-files rewinds produce this. */ + | "snapshot-prune-failed"; /** * Hook event name dispatched through the SDK callback transport. * @@ -1195,6 +1405,23 @@ export type ModelPickerPriceCategory = | "high" /** Highest relative token cost tier. */ | "very_high"; +/** + * Optional listing options. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "ModelListRequest". + */ +/** @experimental */ +export type ModelListRequest = + | { + [k: string]: unknown | undefined; + } + | { + /** + * If true, bypasses the per-session model list cache and re-fetches from CAPI. + */ + skipCache?: boolean; + }; /** * Provider type. Defaults to "openai" for generic OpenAI-compatible APIs. * @@ -1437,6 +1664,39 @@ export type PermissionsSetApproveAllSource = | "autopilot_confirmation" /** Allow-all was enabled through an RPC caller. */ | "rpc"; +/** + * Optional flags controlling which side effects the reload performs. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "PluginsReloadRequest". + */ +/** @experimental */ +export type PluginsReloadRequest = + | { + [k: string]: unknown | undefined; + } + | { + /** + * Reload MCP server connections after refreshing plugins. Defaults to true. + */ + reloadMcp?: boolean; + /** + * Re-run custom-agent discovery after refreshing plugins. Defaults to true. + */ + reloadCustomAgents?: boolean; + /** + * Re-load user, plugin, and (subject to `deferRepoHooks`) repo hooks. Defaults to true. Has no effect when the host has not registered a hook reloader (e.g. remote sessions). + */ + reloadHooks?: boolean; + /** + * Re-discover and relaunch subprocess extensions (including plugin-shipped extensions) after refreshing plugins. Defaults to true. Has no effect when the session has no active extension controller (e.g. extensions were not requested for the session). + */ + reloadExtensions?: boolean; + /** + * When true, skip repo-level hooks during the hook reload. Use before folder trust is confirmed; load them post-trust via `sessions.loadDeferredRepoHooks`. + */ + deferRepoHooks?: boolean; + }; /** * Provider family. Matches the `type` field of a BYOK provider config. * @@ -1475,6 +1735,23 @@ export type ProviderEndpointTransport = | "http" /** WebSocket transport. */ | "websockets"; +/** + * Optional model identifier to scope the endpoint snapshot to. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "ProviderGetEndpointRequest". + */ +/** @experimental */ +export type ProviderGetEndpointRequest = + | { + [k: string]: unknown | undefined; + } + | { + /** + * Model identifier the caller intends to use against the returned endpoint. Used to pick the correct wire shape. Omit to use whichever model the session is currently using. + */ + modelId?: string; + }; /** * Attachment union accepted by push input, covering files, directories, GitHub objects, blobs, snippets, and extension context. * @@ -1512,6 +1789,34 @@ export type PushAttachmentGitHubReferenceType = | "pr" /** GitHub discussion reference. */ | "discussion"; +/** + * The UI mode the agent was in when this message was sent. Defaults to the session's current mode. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SendAgentMode". + */ +/** @experimental */ +export type SendAgentMode = + /** The agent is responding interactively to the user. */ + | "interactive" + /** The agent is preparing a plan before making changes. */ + | "plan" + /** The agent is working autonomously toward task completion. */ + | "autopilot" + /** The agent is in shell-focused UI mode. */ + | "shell"; +/** + * How to deliver the message. `enqueue` (default) appends to the message queue. `immediate` interjects during an in-progress turn. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SendMode". + */ +/** @experimental */ +export type SendMode = + /** Append the message to the normal session queue. */ + | "enqueue" + /** Interject the message during the in-progress turn. */ + | "immediate"; /** * Whether this item is a queued user message or a queued slash command / model change * @@ -1562,34 +1867,6 @@ export type RemoteSessionMetadataTaskType = | "cca" /** CLI remote task. */ | "cli"; -/** - * The UI mode the agent was in when this message was sent. Defaults to the session's current mode. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "SendAgentMode". - */ -/** @experimental */ -export type SendAgentMode = - /** The agent is responding interactively to the user. */ - | "interactive" - /** The agent is preparing a plan before making changes. */ - | "plan" - /** The agent is working autonomously toward task completion. */ - | "autopilot" - /** The agent is in shell-focused UI mode. */ - | "shell"; -/** - * How to deliver the message. `enqueue` (default) appends to the message queue. `immediate` interjects during an in-progress turn. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "SendMode". - */ -/** @experimental */ -export type SendMode = - /** Append the message to the normal session queue. */ - | "enqueue" - /** Interject the message during the in-progress turn. */ - | "immediate"; /** * Session capability enabled for this session * @@ -1670,6 +1947,20 @@ export type SessionFsSqliteQueryType = | "query" /** Execute INSERT, UPDATE, or DELETE SQL and return affected-row metadata. */ | "run"; +/** + * SQLite transaction failure classification. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionFsSqliteTransactionErrorClass". + */ +/** @experimental */ +export type SessionFsSqliteTransactionErrorClass = + /** SQLite reported BUSY or LOCKED before commit; the transaction was rolled back and may be retried. */ + | "busyOrLocked" + /** The statement, database, or provider failed definitively and must not be retried automatically. */ + | "fatal" + /** The transport failed after the provider may have committed; retrying could duplicate effects. */ + | "postCommitAmbiguous"; /** * Source descriptor for direct repo installs (when marketplace is empty) * @@ -1683,32 +1974,120 @@ export type SessionInstalledPluginSource = | SessionInstalledPluginSourceUrl | SessionInstalledPluginSourceLocal; /** - * Local or remote session metadata entry. Narrow on `isRemote` to access source-specific fields. + * Client population used for the prediction baseline. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "SessionListEntry". + * via the `definition` "SessionLimitPredictionClientType". */ /** @experimental */ -export type SessionListEntry = LocalSessionMetadataValue | RemoteSessionMetadataValue; +export type SessionLimitPredictionClientType = + /** Interactive CLI sessions where a user can accept, edit, or top up the limit. */ + | "cli-interactive" + /** Prompt/non-interactive CLI sessions where the initial limit must cover more of the run. */ + | "cli-prompt"; /** - * 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). + * Baseline fallback level used to create the prediction. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "WorkspaceSummary". + * via the `definition` "SessionLimitPredictionSource". */ /** @experimental */ -export type WorkspaceSummary = { - /** - * Workspace identifier (1:1 with sessionId) - */ - id: string; - /** - * Current working directory at session start - */ - cwd?: string; - /** - * Resolved git root for cwd, if any - */ +export type SessionLimitPredictionSource = + /** The prediction used the exact resolved model's baseline cell. */ + | "model" + /** The exact model was unavailable, so the prediction used the model family's baseline cell. */ + | "family" + /** No model or family cell was available, so the prediction used the global client-type baseline cell. */ + | "global"; +/** + * Semantic usage tier used for a recommended cap or additional headroom. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionLimitPredictionTier". + */ +/** @experimental */ +export type SessionLimitPredictionTier = + /** Recommended starting tier. */ + | "recommended" + /** Additional headroom for longer-running sessions. */ + | "additional_headroom" + /** Generous headroom for unusually high usage. */ + | "generous_headroom" + /** Maximum available headroom tier. */ + | "maximum_headroom"; +/** + * Parameters for predicting an AI-credit session limit. Omitting `modelId` uses the session's currently selected model. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionLimitPredictionRequest". + */ +/** @experimental */ +export type SessionLimitPredictionRequest = + | { + [k: string]: unknown | undefined; + } + | { + /** + * Optional model identifier override. If omitted, the session's current model is used. + */ + modelId?: string; + clientType?: SessionLimitPredictionClientType; + }; +/** + * Prediction result. Available results include prediction details; unavailable results include an explicit reason. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionLimitPredictionResult". + */ +/** @experimental */ +export type SessionLimitPredictionResult = + | { + prediction: SessionLimitPredictionDetails; + kind: "available"; + } + | { + reason: SessionLimitPredictionUnavailableReason; + kind: "unavailable"; + }; +/** + * Reason a prediction could not be computed. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionLimitPredictionUnavailableReason". + */ +/** @experimental */ +export type SessionLimitPredictionUnavailableReason = + /** The current model is auto and has not resolved to a concrete model yet. */ + | "auto_unresolved" + /** No model was provided and the session does not currently have a selected model. */ + | "no_model"; +/** + * Local or remote session metadata entry. Narrow on `isRemote` to access source-specific fields. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionListEntry". + */ +/** @experimental */ +export type SessionListEntry = LocalSessionMetadataValue | RemoteSessionMetadataValue; +/** + * 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). + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "WorkspaceSummary". + */ +/** @experimental */ +export type WorkspaceSummary = { + /** + * Workspace identifier (1:1 with sessionId) + */ + id: string; + /** + * Current working directory at session start + */ + cwd?: string; + /** + * Resolved git root for cwd, if any + */ git_root?: string; /** * Repository identifier in 'owner/repo' or 'org/project/repo' format, if any @@ -1762,6 +2141,30 @@ export type SessionOpenOptionsReasoningSummary = | "concise" /** Request a detailed summary of model reasoning. */ | "detailed"; +/** + * Controls automatic non-interactive profile loading where supported. Explicit initScripts are unaffected. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "ShellInitProfile". + */ +/** @experimental */ +export type ShellInitProfile = + /** Disable automatic non-interactive profile loading. Explicit initScripts still run. */ + | "none" + /** Allow automatic non-interactive profile loading when supported. Explicit initScripts still run. */ + | "non-interactive"; +/** + * Supported built-in shells for initialization scripts. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "ShellInitScriptShell". + */ +/** @experimental */ +export type ShellInitScriptShell = + /** Source the script in the built-in Bash shell on macOS and Linux. */ + | "bash" + /** Source the script in the built-in PowerShell shell on Windows. */ + | "powershell"; /** * How MCP server environment values are interpreted. * @@ -2240,6 +2643,14 @@ export type WorkspacesWorkspaceDetailsHostType = */ /** @experimental */ export type AccountGetAllUsersResult = AccountAllUsers[]; +/** + * The number of running background agents (task-registry agents) that were cancelled. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionCancelAllBackgroundAgentsResult". + */ +/** @experimental */ +export type SessionCancelAllBackgroundAgentsResult = number; /** * Parameters for aborting the current turn @@ -2989,7 +3400,7 @@ export interface AgentGetCurrentResult { agent?: AgentInfo | null; } /** - * Custom agent metadata, including identifiers, display details, source, tools, model, MCP servers, skills, and file path. + * Agent metadata, including identifiers, display details, source, tools, model, MCP servers, skills, and file path. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "AgentInfo". @@ -2997,7 +3408,7 @@ export interface AgentGetCurrentResult { /** @experimental */ export interface AgentInfo { /** - * Unique identifier of the custom agent + * Name of the agent. Use `id` as the stable selection identifier. */ name: string; /** @@ -3026,7 +3437,7 @@ export interface AgentInfo { */ tools?: string[]; /** - * Preferred model id for this agent. When omitted, inherits the outer agent's model. + * Authored preferred model id for this agent. Runtime model selection may choose a different model; omitted means no authored preference. */ model?: string; /** @@ -3041,9 +3452,13 @@ export interface AgentInfo { * Skill names preloaded into this agent's context. Omitted means none. */ skills?: string[]; + /** + * Authored base prompt for the agent. Runtime prompt assembly may add dynamic context at invocation time. Omitted from `session.agent.list` unless `includePrompt` is true. + */ + prompt?: string; } /** - * Custom agents available to the session. + * Agents available to the session. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "AgentList". @@ -3051,7 +3466,7 @@ export interface AgentInfo { /** @experimental */ export interface AgentList { /** - * Available custom agents + * Available agents */ agents: AgentInfo[]; } @@ -3361,6 +3776,32 @@ export interface AllowAllPermissionState { enabled: boolean; mode?: PermissionsAllowAllMode; } +/** + * The running runtime's complete catalog of well-known built-in model IDs, including supported models and additional IDs with built-in metadata. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "BuiltInModelCatalog". + */ +/** @experimental */ +export interface BuiltInModelCatalog { + /** + * Built-in model entries. + */ + models: BuiltInModelCatalogEntry[]; +} +/** + * A well-known model in the runtime's built-in catalog. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "BuiltInModelCatalogEntry". + */ +/** @experimental */ +export interface BuiltInModelCatalogEntry { + /** + * Well-known runtime model ID suitable for `ProviderConfig.modelId` or `ProviderModelConfig.modelId`. This is not necessarily the provider-facing deployment or model name and does not indicate CAPI entitlement or provider availability. + */ + id: string; +} /** * Cancellation result for a user-requested shell command. * @@ -3891,27 +4332,6 @@ export interface CommandsInvokeRequest { */ input?: string; } -/** - * Optional filters controlling which command sources to include in the listing. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "CommandsListRequest". - */ -/** @experimental */ -export interface CommandsListRequest { - /** - * Include runtime built-in commands - */ - includeBuiltins?: boolean; - /** - * Include enabled user-invocable skills and commands - */ - includeSkills?: boolean; - /** - * Include commands registered by protocol clients, including SDK clients and extensions - */ - includeClientCommands?: boolean; -} /** * Queued-command request ID and the result indicating whether the host executed it (and whether to stop processing further queued commands). * @@ -4160,7 +4580,7 @@ export interface ConnectRequest { */ token?: string; /** - * Opt this connection in to GitHub telemetry forwarding for its lifetime. When set, the runtime forwards every internal telemetry event it emits — across all sessions, plus sessionless events — to this connection over the `gitHubTelemetry.event` notification, in addition to the runtime's normal GitHub/CTS emission (dual-write). Intended for first-party hosts that re-emit the events into their own telemetry stores. Both unrestricted and restricted events are forwarded, each tagged with a `restricted` discriminator; a backstop drops restricted events when restricted telemetry is disabled. + * Opt this connection in to GitHub telemetry forwarding for its lifetime. When set, the runtime forwards every internal telemetry event it emits — across all sessions, plus sessionless events — to this connection over the `gitHubTelemetry.event` notification. Regular events are also written to the runtime's normal GitHub/CTS path (dual-write); host-only compatibility events are forward-only and intentionally skip that path. Intended for first-party hosts that re-emit the events into their own telemetry stores. Both unrestricted and restricted events are forwarded, each tagged with a `restricted` discriminator; a backstop drops restricted events when restricted telemetry is disabled — using the process-global gate for ordinary events and an explicit session-scoped decision for host-only events. */ enableGitHubTelemetryForwarding?: boolean; } @@ -4186,6 +4606,53 @@ export interface ConnectResult { */ version: string; } +/** + * Local file system absolute paths within the session working directory to check against its content-exclusion policy. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "ContentExclusionCheckPathsRequest". + */ +/** @experimental */ +export interface ContentExclusionCheckPathsRequest { + /** + * Local file system absolute paths within the session working directory to check. Results are returned in the same order, including duplicates. + */ + paths: string[]; +} +/** + * Batch content-exclusion result. Callers must fail closed when policy evaluation is unavailable. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "ContentExclusionCheckPathsResult". + */ +/** @experimental */ +export interface ContentExclusionCheckPathsResult { + /** + * Whether the session's policy service was available for the complete batch. When false, checks is empty and callers must treat every requested path as excluded. + */ + available: boolean; + /** + * Per-path decisions in request order. Empty when available is false. + */ + checks: ContentExclusionPathCheck[]; +} +/** + * Content-exclusion decision for one requested path. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "ContentExclusionPathCheck". + */ +/** @experimental */ +export interface ContentExclusionPathCheck { + /** + * The path supplied by the caller. + */ + path: string; + /** + * Whether the session's complete content-exclusion policy excludes the path. + */ + excluded: boolean; +} /** * A single large message currently in context. * @@ -4479,6 +4946,10 @@ export interface EventLogReadRequest { waitMs?: number; types?: EventLogTypes; agentScope?: EventsAgentScope; + /** + * When false, skip ephemeral events entirely and return only durable (persisted) events. History-backfill callers that discard ephemerals anyway should set this so the read is bounded by the durable log length instead of racing the ephemeral ring on a busy session. Defaults to true (ephemerals are interleaved with durable events in creation order). + */ + includeEphemeral?: boolean; } /** * Indicates whether the operation succeeded. @@ -4515,7 +4986,7 @@ export interface EventLogTailResult { /** @experimental */ export interface EventsReadResult { /** - * Events are delivered in two batches per read: persisted events first (in append order), then ephemeral events (in seq order). When `waitMs > 0` and the catch-up batches were empty, post-wait events follow the same two-batch ordering. Persisted and ephemeral events do not interleave within a single read. + * Session events for this batch, merged into a single stream in creation order: durable (persisted) events and ephemeral events interleave exactly as they were emitted. Set `includeEphemeral: false` to receive only durable events. Ephemeral events are never replayable once pruned from the in-memory ring, so a consumer that needs them should keep reading with a non-zero `waitMs`. */ events: SessionEvent[]; /** @@ -4968,6 +5439,10 @@ export interface FactoryAgentRequest { * Factory run identifier that owns the subagent. */ factoryRunId: string; + /** + * Opaque token identifying the current factory execution attempt. + */ + executionToken: string; /** * Prompt to send to the subagent. */ @@ -4989,6 +5464,28 @@ export interface FactoryAgentResult { [k: string]: unknown | undefined; }; } +/** + * Prompt-safe durable identity and live status for a direct factory agent. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "FactoryAgentSummary". + */ +/** @experimental */ +export interface FactoryAgentSummary { + agentId: string; + toolCallId: string; + runId: string; + phaseId: string | null; + label: string; + agentType: string; + status: string; + requestedModel?: string; + resolvedModel?: string; + startedAt?: number; + completedAt?: number; + activeMs: number; + activity?: string; +} /** * Parameters for cancelling a factory run. * @@ -5002,6 +5499,30 @@ export interface FactoryCancelRequest { */ runId: string; } +/** + * Current factory phase identity. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "FactoryCurrentPhase". + */ +/** @experimental */ +export interface FactoryCurrentPhase { + id: string; + ordinal: number | null; +} +/** + * Declared or approved factory resource ceilings. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "FactoryDeclaredLimits". + */ +/** @experimental */ +export interface FactoryDeclaredLimits { + maxConcurrentSubagents?: number; + maxTotalSubagents?: number; + timeoutSeconds?: number; + maxAiCredits?: number; +} /** * Parameters sent to the owning extension to execute a factory closure. * @@ -5022,6 +5543,10 @@ export interface FactoryExecuteRequest { * Factory run identifier. */ runId: string; + /** + * Opaque token identifying this factory execution attempt. + */ + executionToken: string; /** * Factory input value. */ @@ -5040,10 +5565,39 @@ export interface FactoryExecuteResult { /** * Factory result value. */ - result: { + result?: { [k: string]: unknown | undefined; }; } +/** + * Parameters for paging factory progress. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "FactoryGetRunProgressRequest". + */ +/** @experimental */ +export interface FactoryGetRunProgressRequest { + /** + * Factory run identifier. + */ + runId: string; + /** + * Optional phase identifier used to scope records and cursors. + */ + phaseId?: string; + /** + * Exclusive forward cursor. + */ + afterSeq?: number; + /** + * Exclusive backward cursor. + */ + beforeSeq?: number; + /** + * Maximum records to return. Defaults to 200 and is capped at 500. + */ + limit?: number; +} /** * Parameters for retrieving a factory run. * @@ -5069,6 +5623,10 @@ export interface FactoryJournalGetRequest { * Factory run identifier. */ runId: string; + /** + * Opaque token identifying the current factory execution attempt. + */ + executionToken: string; /** * Namespaced journal key. */ @@ -5105,6 +5663,10 @@ export interface FactoryJournalPutRequest { * Factory run identifier. */ runId: string; + /** + * Opaque token identifying the current factory execution attempt. + */ + executionToken: string; /** * Namespaced journal key. */ @@ -5116,6 +5678,77 @@ export interface FactoryJournalPutRequest { [k: string]: unknown | undefined; }; } +/** + * Empty parameters for listing factory runs. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "FactoryListRunsRequest". + */ +/** @experimental */ +export interface FactoryListRunsRequest {} +/** + * Factory runs in durable creation order. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "FactoryListRunsResult". + */ +/** @experimental */ +export interface FactoryListRunsResult { + runs: FactoryRunSummary[]; +} +/** + * Durable factory run summary with read-time live overlays. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "FactoryRunSummary". + */ +/** @experimental */ +export interface FactoryRunSummary { + runId: string; + factoryName: string; + description: string; + status: FactoryRunStatus; + revision: number; + createdAt: number; + startedAt: number | null; + updatedAt: number; + completedAt: number | null; + currentPhase: FactoryCurrentPhase | null; + declaredPhaseCount: number; + liveAgentCount: number; + totalSpawnedAgentCount: number; + consumed: FactoryRunConsumed; + declaredLimits: FactoryDeclaredLimits; + approved: FactoryDeclaredLimits | null; + observedAt: number; + activeSegmentStartedAt: number | null; + terminal: FactoryRunTerminal | null; +} +/** + * Durable factory resource consumption. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "FactoryRunConsumed". + */ +/** @experimental */ +export interface FactoryRunConsumed { + activeMs: number; + subagents: number; + nanoAiu: number; +} +/** + * Prompt-safe terminal factory outcome. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "FactoryRunTerminal". + */ +/** @experimental */ +export interface FactoryRunTerminal { + reason?: string; + failure?: FactoryRunFailure; + error?: string; + resultPreview?: string; +} /** * One ordered factory progress line. * @@ -5146,65 +5779,137 @@ export interface FactoryLogRequest { * Factory run identifier. */ runId: string; + /** + * Opaque token identifying the current factory execution attempt. + */ + executionToken: string; /** * Ordered progress lines to append. */ lines: FactoryLogLine[]; } /** - * Wire-only per-invocation factory resource ceiling overrides. + * Durable lifecycle and timing for one factory phase. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryRunLimits". + * via the `definition` "FactoryPhaseObservation". */ /** @experimental */ -export interface FactoryRunLimits { +export interface FactoryPhaseObservation { + id: string; + ordinal: number | null; + title: string; + detail?: string; + status: FactoryPhaseStatus; + lastEnteredRunAttempt: number; + entryCount: number; + startedAt?: number; + completedAt?: number; + accumulatedActiveMs: number; + currentActiveMs: number; + totalAgentCount: number; + liveAgentCount: number; +} +/** + * One durable factory progress record. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "FactoryProgressLine". + */ +/** @experimental */ +export interface FactoryProgressLine { /** - * Maximum number of factory subagents that may run concurrently. + * Global monotonic sequence number within the run. */ - maxConcurrentSubagents?: number; + seq: number; /** - * Maximum total number of factory subagents that may be admitted. + * Resume attempt that emitted this record. */ - maxTotalSubagents?: number; + attempt: number; /** - * Factory active-run timeout in milliseconds. + * Phase active when the record was emitted, or null before any phase. */ - timeout?: number; + phaseId: string | null; + /** + * Epoch milliseconds when the record was persisted. + */ + recordedAt: number; + kind: FactoryLogLineKind; + /** + * Prompt-safe progress text. + */ + text: string; } /** - * Parameters for invoking a registered factory. + * A bidirectional page of factory progress. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryRunRequest". + * via the `definition` "FactoryProgressPage". */ /** @experimental */ -export interface FactoryRunRequest { +export interface FactoryProgressPage { + records: FactoryProgressLine[]; + oldestSeq: number | null; + newestSeq: number | null; + hasMoreOlder: boolean; + hasMoreNewer: boolean; /** - * Registered factory name. + * Run revision reflected by this page. */ - name: string; + revision: number; +} +/** + * Parameters for resuming a factory run from its persisted identity. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "FactoryResumeRequest". + */ +/** @experimental */ +export interface FactoryResumeRequest { /** - * Factory input value. + * Factory run identifier. */ - args: { - [k: string]: unknown | undefined; - }; - options?: RunOptions; + runId: string; + limits?: FactoryRunLimits; } /** - * Options controlling factory invocation. + * Wire-only per-invocation factory resource ceiling overrides. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "RunOptions". + * via the `definition` "FactoryRunLimits". */ /** @experimental */ -export interface RunOptions { - limits?: FactoryRunLimits; +export interface FactoryRunLimits { /** - * Run identifier whose journal and progress should seed this resumed run. + * Maximum number of factory subagents that may run concurrently. */ - resumeFromRunId?: string; + maxConcurrentSubagents?: number; + /** + * Maximum total number of factory subagents that may be admitted. + */ + maxTotalSubagents?: number; + /** + * Maximum accumulated active-execution time in seconds. Active execution includes the entire extension body, subprocess waits, queued-agent waits, and sleeps; time between resumed attempts is not counted. + */ + timeoutSeconds?: number; + /** + * Maximum AI credits consumed by factory subagents and their descendants. The post-paid ceiling is soft: parallel turns can settle beyond it before the run stops. + */ + maxAiCredits?: number; +} +/** + * Resolved persisted factory identity and resumed run envelope. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "FactoryResumeResult". + */ +/** @experimental */ +export interface FactoryResumeResult { + /** + * Persisted factory name resolved for the resumed run. + */ + factoryName: string; + run: FactoryRunResult; } /** * Complete current or terminal factory run envelope. @@ -5241,6 +5946,71 @@ export interface FactoryRunResult { [k: string]: unknown | undefined; }; } +/** + * Full factory run observability detail. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "FactoryRunDetail". + */ +/** @experimental */ +export interface FactoryRunDetail { + runId: string; + factoryName: string; + description: string; + status: FactoryRunStatus; + revision: number; + createdAt: number; + startedAt: number | null; + updatedAt: number; + completedAt: number | null; + currentPhase: FactoryCurrentPhase | null; + declaredPhaseCount: number; + liveAgentCount: number; + totalSpawnedAgentCount: number; + consumed: FactoryRunConsumed; + declaredLimits: FactoryDeclaredLimits; + approved: FactoryDeclaredLimits | null; + observedAt: number; + activeSegmentStartedAt: number | null; + terminal: FactoryRunTerminal | null; + phases: FactoryPhaseObservation[]; + agents: FactoryAgentSummary[]; + progress: FactoryProgressPage; +} +/** + * Parameters for invoking a registered factory. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "FactoryRunRequest". + */ +/** @experimental */ +export interface FactoryRunRequest { + /** + * Registered factory name. + */ + name: string; + /** + * Factory input value. + */ + args: { + [k: string]: unknown | undefined; + }; + options?: RunOptions; +} +/** + * Options controlling factory invocation. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "RunOptions". + */ +/** @experimental */ +export interface RunOptions { + limits?: FactoryRunLimits; + /** + * Run identifier whose journal and progress should seed this resumed run. + */ + resumeFromRunId?: string; +} /** * Optional user prompt to combine with the fleet orchestration instructions. * @@ -5515,19 +6285,6 @@ 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. * @@ -5554,6 +6311,180 @@ export interface HistoryCompactResult { summaryContent?: string; contextWindow?: HistoryCompactContextWindow; } +/** + * Rewind points and file-change-tracking availability for the session. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HistoryListRewindPointsResult". + */ +/** @experimental */ +export interface HistoryListRewindPointsResult { + /** + * Whether this session captured file changes from its first turn. + */ + fileChangeTrackingEnabled: boolean; + unavailableReason?: HistoryRewindUnavailableReason; + /** + * Root user turns in chronological order. Empty when `unavailableReason` is set. + */ + points: HistoryRewindPoint[]; +} +/** + * A root user turn that the session can rewind to. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HistoryRewindPoint". + */ +/** @experimental */ +export interface HistoryRewindPoint { + /** + * ID of the user.message event that begins the discarded suffix. + */ + eventId: string; + /** + * User-visible message text for the turn. + */ + userMessage: string; + /** + * ISO timestamp of the user turn. + */ + timestamp: string; + /** + * Whether at least one file in this turn or a later turn can be restored. + */ + canRestoreFiles: boolean; + /** + * Number of unique files in this turn and all later turns that have captured changes. + */ + fileCount: number; + /** + * Whether this turn itself captured any file changes. + */ + turnChangedFiles: boolean; + /** + * Lines added by this turn's captured file changes. + */ + linesAdded: number; + /** + * Lines removed by this turn's captured file changes. + */ + linesRemoved: number; + /** + * Whether this turn was an automatically injected autopilot continuation. + */ + isAutopilotContinuation: boolean; +} +/** + * Event boundary to preview for conversation-and-files rewind. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HistoryPreviewRewindRequest". + */ +/** @experimental */ +export interface HistoryPreviewRewindRequest { + /** + * ID of the user.message event that begins the discarded suffix. + */ + eventId: string; +} +/** + * Files and aggregate changes for a prospective rewind. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HistoryPreviewRewindResult". + */ +/** @experimental */ +export interface HistoryPreviewRewindResult { + /** + * Whether file restore is available for this session. This is authoritative: switch on it and read `reason` only when it is false. + */ + available: boolean; + reason?: HistoryRewindUnavailableReason; + /** + * Number of unique files in the preview. + */ + fileCount: number; + /** + * Files ordered by path. + */ + files: HistoryRewindFilePreview[]; +} +/** + * A file that a conversation-and-files rewind would restore. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HistoryRewindFilePreview". + */ +/** @experimental */ +export interface HistoryRewindFilePreview { + /** + * Absolute path of the captured file. + */ + path: string; + changeType: HistoryRewindChangeType; + /** + * Lines added across the discarded turns. + */ + linesAdded: number; + /** + * Lines removed across the discarded turns. + */ + linesRemoved: number; +} +/** + * Boundary and mode for rewinding session history. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HistoryRewindRequest". + */ +/** @experimental */ +export interface HistoryRewindRequest { + /** + * ID of the user.message event that begins the discarded suffix. + */ + eventId: string; + mode: HistoryRewindMode; +} +/** + * Structured outcome of a rewind request. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HistoryRewindResult". + */ +/** @experimental */ +export interface HistoryRewindResult { + outcome: HistoryRewindOutcome; + /** + * Number of persisted events removed by conversation truncation. Present only when truncation succeeded (outcomes `success`, `checkpoint-cleanup-failed`, and `snapshot-prune-failed`); omitted for every unavailable outcome (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`) and for `truncation-failed`, `files-rolled-back`, and `rollback-incomplete`. + */ + eventsRemoved?: number; + /** + * Absolute paths restored to their captured preimages. Always empty for conversation-only rewinds and for the unavailable outcomes (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`); only conversation-and-files outcomes that reached the file-restore stage populate it. + */ + restoredFiles: string[]; + /** + * Captured files intentionally left unchanged. Always empty for conversation-only rewinds and for the unavailable outcomes (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`); only conversation-and-files outcomes that reached the file-restore stage populate it. + */ + skippedFiles: HistorySkippedFileRestore[]; + /** + * Failure detail. Set only for the failure and partial-failure outcomes (`files-rolled-back`, `rollback-incomplete`, `truncation-failed`, `checkpoint-cleanup-failed`, `snapshot-prune-failed`); omitted for `success` and for the unavailable outcomes (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`). + */ + error?: string; +} +/** + * A captured file that rewind intentionally left unchanged. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HistorySkippedFileRestore". + */ +/** @experimental */ +export interface HistorySkippedFileRestore { + /** + * Absolute path of the skipped file. + */ + path: string; + reason: HistoryFileRestoreSkipReason; +} /** * Markdown summary of the conversation context (empty when not available). * @@ -5592,6 +6523,14 @@ export interface HistoryTruncateResult { * Number of events that were removed */ eventsRemoved: number; + /** + * True when conversation truncation succeeded but post-truncation workspace checkpoint cleanup failed. History is already truncated; callers may still prune snapshots but should report a checkpoint-cleanup rather than a truncation failure. + */ + checkpointCleanupFailed?: boolean; + /** + * Failure detail when checkpointCleanupFailed is true. + */ + checkpointCleanupError?: string; } /** * Runtime-owned wire payload for a server-to-client hook callback invocation. @@ -5652,7 +6591,7 @@ export interface InstalledPlugin { source?: InstalledPluginSource; } /** - * Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref, and optional subpath. + * Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref or full commit SHA, and optional subpath. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "InstalledPluginSourceGitHub". @@ -5665,10 +6604,14 @@ export interface InstalledPluginSourceGitHub { source: "github"; repo: string; ref?: string; + /** + * Optional full 40-character hexadecimal commit SHA. + */ + sha?: string; path?: string; } /** - * Source descriptor for a direct URL plugin install, with URL, optional ref, and optional subpath. + * Source descriptor for a direct URL plugin install, with URL, optional ref or full commit SHA, and optional subpath. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "InstalledPluginSourceUrl". @@ -5681,6 +6624,10 @@ export interface InstalledPluginSourceUrl { source: "url"; url: string; ref?: string; + /** + * Optional full 40-character hexadecimal commit SHA. + */ + sha?: string; path?: string; } /** @@ -5848,10 +6795,36 @@ export interface InstructionSource { */ defaultDisabled?: boolean; /** - * The project path this source was discovered from. Only set by sessionless discovery for repository/working-directory sources, where it disambiguates same-named files (e.g. .github/copilot-instructions.md) across multiple workspace roots. The session-scoped getSources leaves it unset. + * The project path this source was discovered from. Only set by sessionless discovery for repository, working-directory, and project-scoped plugin sources, where it disambiguates sources across multiple workspace roots. The session-scoped getSources leaves it unset. */ projectPath?: string; } +/** + * Parameters for interrupting the main agent turn. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "InterruptMainTurnRequest". + */ +/** @experimental */ +export interface InterruptMainTurnRequest { + /** + * When true, the user's queued prompts are preserved and run as the next turn once the interrupted turn unwinds; when false (the default), the queue is cleared like a plain abort. + */ + flushQueued?: boolean; +} +/** + * Result of interrupting the main agent turn. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "InterruptMainTurnResult". + */ +/** @experimental */ +export interface InterruptMainTurnResult { + /** + * Whether an in-flight main agent turn was interrupted. False when the main loop was not processing. + */ + interrupted: boolean; +} /** * HTTP headers as a map from lowercased header name to a list of values. Multi-valued headers (e.g. Set-Cookie) preserve all values. * @@ -6675,6 +7648,10 @@ export interface McpServerConfigStdio { oidc?: McpServerAuthConfig; auth?: McpServerAuthConfig; deferTools?: McpServerConfigDeferTools; + /** + * Set to true to disable persisted MCP tool snapshots for this server. Live tool discovery is unaffected. + */ + disableToolCache?: boolean; /** * Executable command used to start the Stdio MCP server process. */ @@ -6732,6 +7709,10 @@ export interface McpServerConfigHttp { oidc?: McpServerAuthConfig; auth?: McpServerAuthConfig; deferTools?: McpServerConfigDeferTools; + /** + * Set to true to disable persisted MCP tool snapshots for this server. Live tool discovery is unaffected. + */ + disableToolCache?: boolean; /** * URL of the remote MCP server endpoint. */ @@ -6948,7 +7929,7 @@ export interface McpExecuteSamplingResult { [k: string]: unknown | undefined; } /** - * MCP server filtered by policy, with name, reason, optional redacted reason, and enterprise login. + * MCP server filtered by policy, with name, reason, and optional redacted reason. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpFilteredServer". @@ -6968,7 +7949,8 @@ export interface McpFilteredServer { */ redactedReason?: string; /** - * Enterprise login associated with an allowlist policy + * @deprecated + * Deprecated. This field is no longer populated. */ enterpriseName?: string; } @@ -7016,7 +7998,7 @@ export interface McpHostState { */ disabledServers: string[]; /** - * Configured servers filtered out by enterprise allowlist policy. + * Configured servers filtered out by MCP server policy. */ filteredServers: string[]; /** @@ -7236,22 +8218,48 @@ export interface McpOauthLoginResult { authorizationUrl?: string; } /** - * Registration parameters for an external MCP client. + * Pending MCP OAuth request id to respond to. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "McpRegisterExternalClientRequest". + * via the `definition` "McpOauthRespondRequest". */ /** @experimental */ -/** @internal */ -export interface McpRegisterExternalClientRequest { +export interface McpOauthRespondRequest { /** - * Logical server name for the external client - */ - serverName: string; - /** - * In-process MCP Client instance. Marked internal: cannot be serialized across the JSON-RPC boundary. - * - * @internal + * OAuth request identifier from the mcp.oauth_required event + */ + requestId: string; +} +/** + * Indicates whether the pending MCP OAuth response was accepted. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpOauthRespondResult". + */ +/** @experimental */ +export interface McpOauthRespondResult { + /** + * Whether the response was accepted. False if the request was unknown, timed out, or already resolved. + */ + success: boolean; +} +/** + * Registration parameters for an external MCP client. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "McpRegisterExternalClientRequest". + */ +/** @experimental */ +/** @internal */ +export interface McpRegisterExternalClientRequest { + /** + * Logical server name for the external client + */ + serverName: string; + /** + * In-process MCP Client instance. Marked internal: cannot be serialized across the JSON-RPC boundary. + * + * @internal */ client: { [k: string]: unknown | undefined; @@ -7678,7 +8686,7 @@ export interface McpSetEnvValueModeResult { mode: McpSetEnvValueModeDetails; } /** - * Server name and configuration for an individual MCP server start. + * Server name and optional configuration for an individual MCP server start. Omit `config` for a config-free start-by-name of an already-configured server. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "McpStartServerRequest". @@ -7689,7 +8697,7 @@ export interface McpStartServerRequest { * Name of the MCP server to start */ serverName: string; - config: McpServerConfig; + config?: McpServerConfig; } /** * MCP server startup filtering result. @@ -8213,7 +9221,7 @@ export interface ModelBillingTokenPricesLongContext { maxPromptTokens?: number; } /** - * Active server-driven promotion for a model, including its discount and expiry. + * Active server-driven promotion for a model, including its discount and optional expiry. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ModelBillingPromo". @@ -8229,11 +9237,11 @@ export interface ModelBillingPromo { */ discountPercent?: number; /** - * UTC ISO 8601 timestamp marking when the promotion ends. Always present: the API only surfaces a promo whose expiry parses and is in the future. Consumers should treat a past value as expired. + * UTC ISO 8601 timestamp marking when the promotion ends. Optional: an open-ended promotion omits this field. When present, the API only surfaces a promo whose expiry parses and is in the future, so consumers should treat a past value as expired. */ - endsAt: string; + endsAt?: string; /** - * Human-readable promotion message. Does not include the expiry timestamp; consumers may format endsAt and append it. + * Human-readable promotion message. Does not include the expiry timestamp; consumers may format endsAt and append it when present. */ message?: string; } @@ -8322,19 +9330,6 @@ export interface ModelList { */ models: Model[]; } -/** - * Optional listing options. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "ModelListRequest". - */ -/** @experimental */ -export interface ModelListRequest { - /** - * If true, bypasses the per-session model list cache and re-fetches from CAPI. - */ - skipCache?: boolean; -} /** * Reasoning effort level to apply to the currently selected model. * @@ -8389,6 +9384,10 @@ export interface ModelSwitchToRequest { verbosity?: Verbosity; modelCapabilities?: ModelCapabilitiesOverride; contextTier?: ContextTier; + /** + * When true, defer this switch (enqueue it) if another model change is already queued, even when no turn is active — so it drains last (FIFO) and wins over the already-queued change. Intended for genuine user-initiated model selections; internal restore/reapply switches omit it and apply immediately when no turn is active. When no other model change is queued this has no effect (a switch still applies immediately unless a turn is active). + */ + deferIfModelChangeQueued?: boolean; } /** * The model identifier active on the session after the switch. @@ -8402,6 +9401,10 @@ export interface ModelSwitchToResult { * Currently active model identifier after the switch */ modelId?: string; + /** + * True when the switch was deferred (enqueued as a cancellable `/model` command) because a turn was active or another model change was already queued, rather than applied immediately. When true, the session's live model is unchanged until the queued change drains. + */ + deferred?: boolean; } /** * Agent interaction mode to apply to the session. @@ -8592,6 +9595,10 @@ export interface PermissionDecisionApproveOnce { * Approve this single request only */ kind: "approve-once"; + /** + * True only when a host surfaced this request to a user who approved it. + */ + approvedInteractively?: boolean; } /** * Permission-decision request variant to approve for the rest of the session, with optional tool approval or URL domain. @@ -9742,13 +10749,18 @@ export interface PermissionsPathsUpdatePrimaryResult { /** @experimental */ export interface PermissionsPendingRequestsRequest {} /** - * No parameters; clears all session-scoped tool permission approvals. + * Clears session-scoped tool permission approvals, and optionally the location-scoped ones. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "PermissionsResetSessionApprovalsRequest". */ /** @experimental */ -export interface PermissionsResetSessionApprovalsRequest {} +export interface PermissionsResetSessionApprovalsRequest { + /** + * Whether location-scoped approvals are cleared too. Defaults to `true`. + */ + includeLocation?: boolean; +} /** * Indicates whether the operation succeeded. * @@ -10171,35 +11183,6 @@ export interface PluginsMarketplacesRemoveRequest { */ force?: boolean; } -/** - * Optional flags controlling which side effects the reload performs. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "PluginsReloadRequest". - */ -/** @experimental */ -export interface PluginsReloadRequest { - /** - * Reload MCP server connections after refreshing plugins. Defaults to true. - */ - reloadMcp?: boolean; - /** - * Re-run custom-agent discovery after refreshing plugins. Defaults to true. - */ - reloadCustomAgents?: boolean; - /** - * Re-load user, plugin, and (subject to `deferRepoHooks`) repo hooks. Defaults to true. Has no effect when the host has not registered a hook reloader (e.g. remote sessions). - */ - reloadHooks?: boolean; - /** - * Re-discover and relaunch subprocess extensions (including plugin-shipped extensions) after refreshing plugins. Defaults to true. Has no effect when the session has no active extension controller (e.g. extensions were not requested for the session). - */ - reloadExtensions?: boolean; - /** - * When true, skip repo-level hooks during the hook reload. Use before folder trust is confirmed; load them post-trust via `sessions.loadDeferredRepoHooks`. - */ - deferRepoHooks?: boolean; -} /** * Name (or spec) of the plugin to uninstall. * @@ -10480,19 +11463,6 @@ export interface ProviderSessionToken { */ expiresAt?: string; } -/** - * Optional model identifier to scope the endpoint snapshot to. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "ProviderGetEndpointRequest". - */ -/** @experimental */ -export interface ProviderGetEndpointRequest { - /** - * Model identifier the caller intends to use against the returned endpoint. Used to pick the correct wire shape. Omit to use whichever model the session is currently using. - */ - modelId?: string; -} /** * Asks the SDK client to acquire a bearer token for a BYOK provider whose config set `hasBearerTokenProvider: true`. Issued by the runtime before each outbound model request; the runtime does no caching, so this is sent once per request. * @@ -10978,53 +11948,411 @@ export interface PushAttachmentBlob { */ mimeType: string; /** - * User-facing display name for the attachment + * User-facing display name for the attachment + */ + displayName?: string; +} +/** + * Inputs for starting a deferred-idle drain. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueueBeginDeferredIdleDrainRequest". + */ +/** @experimental */ +export interface QueueBeginDeferredIdleDrainRequest { + /** + * Whether the host still has active background work. + */ + activeBackgroundWork: boolean; +} +/** + * Whether a deferred-idle drain should run. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueueBeginDeferredIdleDrainResult". + */ +/** @experimental */ +export interface QueueBeginDeferredIdleDrainResult { + /** + * True when the host should run finishDeferredIdleDrain asynchronously. + */ + shouldDrain: boolean; +} +/** + * Internal filter for consuming queued system notifications. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueueConsumeSystemNotificationsRequest". + */ +/** @experimental */ +export interface QueueConsumeSystemNotificationsRequest { + /** + * Opaque runtime-owned filter object. + */ + filter: { + [k: string]: unknown | undefined; + }; +} +/** + * Inputs for marking session.idle deferred in native state. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueueDeferSessionIdleRequest". + */ +/** @experimental */ +export interface QueueDeferSessionIdleRequest { + /** + * Whether the deferred idle was caused by an aborted foreground turn. + */ + aborted: boolean; +} +/** + * Parameters for duplicating a queued item. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueueDuplicateAtRequest". + */ +/** @experimental */ +export interface QueueDuplicateAtRequest { + id: string; +} +/** + * Result of duplicating a queued item. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueueDuplicateAtResult". + */ +/** @experimental */ +export interface QueueDuplicateAtResult { + /** + * Fresh stable opaque id assigned to the duplicate. + */ + id: string; +} +/** + * Result of enqueueing the resume-pending wake item. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueueEnqueueResumePendingResult". + */ +/** @experimental */ +export interface QueueEnqueueResumePendingResult { + /** + * True when a wake item was newly queued. + */ + queued: boolean; +} +/** + * Inputs for completing a deferred-idle drain. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueueFinishDeferredIdleDrainRequest". + */ +/** @experimental */ +export interface QueueFinishDeferredIdleDrainRequest { + /** + * Whether the host still has active background work. + */ + activeBackgroundWork: boolean; + /** + * Whether native queued work remains. + */ + hasPending: boolean; +} +/** + * Action selected by the native deferred-idle drain. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueueFinishDeferredIdleDrainResult". + */ +/** @experimental */ +export interface QueueFinishDeferredIdleDrainResult { + /** + * One of none, processQueue, or emitSessionIdle. + */ + action: string; + /** + * Whether the deferred idle was caused by an aborted foreground turn. + */ + aborted: boolean; +} +/** + * Whether the native queue has pending work. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueueHasPendingResult". + */ +/** @experimental */ +export interface QueueHasPendingResult { + /** + * True when queued or immediate native work is pending. + */ + hasPending: boolean; +} +/** + * Parameters for inserting a queued message at a public visible position. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueueInsertAtRequest". + */ +/** @experimental */ +export interface QueueInsertAtRequest { + /** + * Zero-based position in the public visible queue. Values outside the queue clamp to an end. + */ + position: number; + message: QueueInsertMessage; +} +/** + * Serializable message fields accepted by queue.insertAt. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueueInsertMessage". + */ +/** @experimental */ +export interface QueueInsertMessage { + /** + * The user message text. + */ + prompt: string; + /** + * Optional user-facing display text. + */ + displayPrompt?: string; + /** + * Optional attachments for the message. + */ + attachments?: Attachment[]; + agentMode?: SendAgentMode; + /** + * Optional provenance source. `system` is rejected: it would hide the inserted row from `pendingItems` and make it unaddressable while still executing, so inserted items must stay visible. + */ + source?: string; + /** + * Whether the message is billable. + */ + billable?: boolean; + /** + * Required tool name for the turn, when any. + */ + requiredTool?: string; + /** + * Per-turn request headers. + */ + requestHeaders?: { + [k: string]: string | undefined; + }; + mode?: SendMode; + /** + * Accepted for SendOptions compatibility but ignored; the requested public position controls placement. + */ + prepend?: boolean; + /** + * Accepted for SendOptions compatibility but ignored; insertion scheduling is controlled by the queue drain state. + */ + wait?: boolean; + /** + * Accepted for internal SendOptions compatibility but ignored; delivery is derived from current session activity. + */ + delivery?: string; +} +/** + * Result of inserting a queued message. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueueInsertAtResult". + */ +/** @experimental */ +export interface QueueInsertAtResult { + /** + * Fresh stable opaque id assigned to the inserted item. + */ + id: string; +} +/** + * Parameters for moving a queued item by stable id. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueueMoveItemRequest". + */ +/** @experimental */ +export interface QueueMoveItemRequest { + /** + * Stable opaque queued-item id. + */ + id: string; + /** + * Zero-based target position in the public visible queue. Values outside the queue clamp to an end. + */ + toPosition: number; +} +/** + * Result of moving a queued item. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueueMoveItemResult". + */ +/** @experimental */ +export interface QueueMoveItemResult { + /** + * True when the item changed position; false when it was already at the requested position. + */ + changed: boolean; +} +/** + * User-facing pending queue entry, with kind and display text for a queued message, slash command, or model change. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueuePendingItems". + */ +/** @experimental */ +export interface QueuePendingItems { + /** + * Stable opaque id for the canonical queued item. Batch rows share one id. + */ + id: string; + kind: QueuePendingItemsKind; + /** + * Human-readable text to display for this queue entry in the UI + */ + displayText: string; + agentMode: SendAgentMode; +} +/** + * Snapshot of the session's pending queued items and immediate-steering messages. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueuePendingItemsResult". + */ +/** @experimental */ +export interface QueuePendingItemsResult { + /** + * Pending queued items in submission order. Includes user messages, queued slash commands, and queued model changes; omits internal system items. + */ + items: QueuePendingItems[]; + /** + * Display text for messages currently in the immediate steering queue (interjections sent during a running turn). + */ + steeringMessages: string[]; +} +/** + * Parameters for removing a queued item by stable id. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueueRemoveAtRequest". + */ +/** @experimental */ +export interface QueueRemoveAtRequest { + id: string; +} +/** + * Result of removing a queued item. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueueRemoveAtResult". + */ +/** @experimental */ +export interface QueueRemoveAtResult { + /** + * True when the addressed item was removed. + */ + removed: boolean; +} +/** + * Indicates whether a user-facing pending item was removed. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueueRemoveMostRecentResult". + */ +/** @experimental */ +export interface QueueRemoveMostRecentResult { + /** + * True if a user-facing pending item was removed (LIFO across both queues); false when no removable items remained. + */ + removed: boolean; +} +/** + * Parameters for steering a queued message into a live turn. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueueSendNowRequest". + */ +/** @experimental */ +export interface QueueSendNowRequest { + id: string; +} +/** + * Result of trying to steer a queued message into a live turn. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueueSendNowResult". + */ +/** @experimental */ +export interface QueueSendNowResult { + /** + * True when the item was accepted into the steering lane; false when no main turn was live. */ - displayName?: string; + steered: boolean; } /** - * User-facing pending queue entry, with kind and display text for a queued message, slash command, or model change. + * Parameters for acquiring or releasing the queued-lane drain pause. Acquisition is exclusive and non-idempotent: `paused: true` against an already-paused session fails with `queue_already_paused`. The pause is never released automatically — it is not tied to the caller's lifetime, so a client that exits without sending `paused: false` leaves the lane frozen. Release is unowned: `paused: false` clears the pause for any caller, including one that never acquired it. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "QueuePendingItems". + * via the `definition` "QueueSetDrainPausedRequest". */ /** @experimental */ -export interface QueuePendingItems { - kind: QueuePendingItemsKind; - /** - * Human-readable text to display for this queue entry in the UI - */ - displayText: string; +export interface QueueSetDrainPausedRequest { + paused: boolean; } /** - * Snapshot of the session's pending queued items and immediate-steering messages. + * Internal snapshot of native queue state for local session orchestration. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "QueuePendingItemsResult". + * via the `definition` "QueueSnapshotResult". */ /** @experimental */ -export interface QueuePendingItemsResult { +export interface QueueSnapshotResult { /** - * Pending queued items in submission order. Includes user messages, queued slash commands, and queued model changes; omits internal system items. + * User-facing pending items in FIFO order. */ items: QueuePendingItems[]; /** - * Display text for messages currently in the immediate steering queue (interjections sent during a running turn). + * Immediate steering messages waiting for an active turn. */ steeringMessages: string[]; + /** + * Insertion orders for queued items, aligned with `items`. + */ + itemOrders?: number[]; + /** + * Insertion orders for immediate steering messages, aligned with `steeringMessages`. + */ + steeringMessageOrders?: number[]; } /** - * Indicates whether a user-facing pending item was removed. + * Parameters for editing a single queued message. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "QueueRemoveMostRecentResult". + * via the `definition` "QueueUpdateTextRequest". */ /** @experimental */ -export interface QueueRemoveMostRecentResult { +export interface QueueUpdateTextRequest { + id: string; + prompt: string; + displayPrompt?: string; +} +/** + * Result of editing a queued message. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "QueueUpdateTextResult". + */ +/** @experimental */ +export interface QueueUpdateTextResult { /** - * True if a user-facing pending item was removed (LIFO across both queues); false when no removable items remained. + * True when the stored text changed. */ - removed: boolean; + updated: boolean; } /** * Event type to register consumer interest for, used by runtime gating logic. @@ -11542,6 +12870,28 @@ export interface SandboxConfigUserPolicyNetwork { * Whether traffic to local/loopback addresses is allowed. */ allowLocalNetwork?: boolean; + proxy?: SandboxConfigUserPolicyNetworkProxy; +} +/** + * HTTP proxy configuration for sandboxed traffic. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SandboxConfigUserPolicyNetworkProxy". + */ +/** @experimental */ +export interface SandboxConfigUserPolicyNetworkProxy { + /** + * Proxy URL (e.g. http://proxy.example.com:8080). The port is optional and defaults to the scheme's standard port when omitted. Credentials must not be embedded here — a `user:pass@` authority is rejected; put them in the separate `username`/`password` fields. A credential-free http:// loopback URL is routed through the localhost proxy automatically; loopback covers localhost and any *.localhost subdomain, the whole 127.0.0.0/8 range, ::1, and IPv4-mapped loopback (::ffff:127.0.0.1). An https:// URL, or one with a username/password set, is used as-is. + */ + url: string; + /** + * Optional username for proxy authentication. Combined with the URL (and `password`) into `user:pass@host` when the sandboxed process routes through the proxy. + */ + username?: string; + /** + * Optional password for proxy authentication, combined with the URL at spawn time. The persisted value may be a literal password, a `${secret:…}` reference resolved from the OS keychain, or a `${VAR}`/`$VAR` environment reference; it is resolved just before the sandboxed process routes through the proxy. The /sandbox dialog stores a real password in the OS keychain and persists only a `${secret:…}` placeholder (never plaintext in settings.json); the field is masked in the dialog and redacted by /settings show. + */ + password?: string; } /** * macOS seatbelt-specific options. @@ -11579,6 +12929,99 @@ export interface SandboxConfigUserPolicyExperimentalSeatbelt { */ keychainAccess?: boolean; } +/** + * Register an absolute-time scheduled prompt. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "ScheduleAddAtRequest". + */ +/** @experimental */ +export interface ScheduleAddAtRequest { + /** + * Epoch milliseconds when the prompt should fire. + */ + at: number; + /** + * Prompt text to enqueue when the schedule fires. + */ + prompt: string; + /** + * Whether the schedule should re-arm after each tick. Defaults to false. + */ + recurring?: boolean; + /** + * Optional display-only prompt label. + */ + displayPrompt?: string; +} +/** + * Register a cron scheduled prompt. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "ScheduleAddCronRequest". + */ +/** @experimental */ +export interface ScheduleAddCronRequest { + /** + * 5-field cron expression. + */ + cron: string; + /** + * Prompt text to enqueue when the schedule fires. + */ + prompt: string; + /** + * Whether the schedule should re-arm after each tick. Defaults to true. + */ + recurring?: boolean; + /** + * Optional display-only prompt label. + */ + displayPrompt?: string; + /** + * IANA timezone for evaluating the cron expression. + */ + tz?: string; +} +/** + * Register a relative-interval scheduled prompt. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "ScheduleAddRequest". + */ +/** @experimental */ +export interface ScheduleAddRequest { + /** + * Human-readable interval such as `30s`, `5m`, or `2h`. + */ + interval: string; + /** + * Prompt text to enqueue when the schedule fires. + */ + prompt: string; + /** + * Whether the schedule should re-arm after each tick. Defaults to true. + */ + recurring?: boolean; + /** + * Optional display-only prompt label. + */ + displayPrompt?: string; +} +/** + * Result of registering or re-arming a scheduled prompt. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "ScheduleAddResult". + */ +/** @experimental */ +export interface ScheduleAddResult { + entry?: ScheduleEntry; + /** + * User-facing validation error, when registration failed. + */ + error?: string; +} /** * Scheduled prompt entry with ID, timing (`intervalMs`, `cron`, or `at`), prompt text, recurrence, and next run time. * @@ -11628,6 +13071,36 @@ export interface ScheduleEntry { */ nextRunAt: string; } +/** + * Register a self-paced scheduled prompt. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "ScheduleAddSelfPacedRequest". + */ +/** @experimental */ +export interface ScheduleAddSelfPacedRequest { + /** + * Prompt text to enqueue when the schedule fires. + */ + prompt: string; + /** + * Optional display-only prompt label. + */ + displayPrompt?: string; +} +/** + * Whether the session currently has an active self-paced schedule. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "ScheduleHasSelfPacedResult". + */ +/** @experimental */ +export interface ScheduleHasSelfPacedResult { + /** + * True when at least one active schedule is self-paced. + */ + hasSelfPaced: boolean; +} /** * Snapshot of the currently active recurring prompts for this session. * @@ -11641,6 +13114,23 @@ export interface ScheduleList { */ entries: ScheduleEntry[]; } +/** + * Re-arm a self-paced scheduled prompt. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "ScheduleRearmSelfPacedRequest". + */ +/** @experimental */ +export interface ScheduleRearmSelfPacedRequest { + /** + * Id of the self-paced scheduled prompt. + */ + id: number; + /** + * Epoch milliseconds when the prompt should next fire. + */ + at: number; +} /** * Identifier of the scheduled prompt to remove. * @@ -11738,7 +13228,7 @@ export interface SendMessageItem { */ requiredTool?: string; /** - * Optional provenance tag copied to the resulting user.message event. Must match one of three forms: the literal `system`, `command-` for messages originating from a command (e.g. slash command, Mission Control command), or `schedule-` for messages originating from a scheduled job. + * Optional provenance tag copied to the resulting user.message event. Must be `user`, `system`, `command-` for command-originated messages, `schedule-` for scheduled prompts, or `agent-` for prompts sent by another agent. * * @internal */ @@ -11777,7 +13267,7 @@ export interface SendMessagesRequest { */ tracestate?: string; /** - * If true, await completion of the agentic loop for this turn before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageIds`; the caller can rely on the agent having processed the messages before the call resolves. + * If true, await completion of the agentic loop for this turn before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageIds`; the caller can rely on the agent having processed the messages before the call resolves. Transport-dependent tail semantics: on a LOCAL (in-process) session the wait additionally blocks until the completed turn's event tail has been dispatched to this session's in-process subscribers, so a subsequent read of subscriber state already reflects the turn; on a REMOTE session the wait resolves once the loop completes and mirrored delivery follows over the wire. Callers that need the stronger local guarantee on remote sessions should await the event stream explicitly. */ wait?: boolean; } @@ -11828,7 +13318,7 @@ export interface SendRequest { */ requiredTool?: string; /** - * Optional provenance tag copied to the resulting user.message event. Must match one of three forms: the literal `system`, `command-` for messages originating from a command (e.g. slash command, Mission Control command), or `schedule-` for messages originating from a scheduled job. + * Optional provenance tag copied to the resulting user.message event. Must be `user`, `system`, `command-` for command-originated messages, `schedule-` for scheduled prompts, or `agent-` for prompts sent by another agent. * * @internal */ @@ -11849,7 +13339,7 @@ export interface SendRequest { */ tracestate?: string; /** - * If true, await completion of the agentic loop for this message before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageId`; the caller can rely on the agent having processed the message before the call resolves. + * If true, await completion of the agentic loop for this message before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageId`; the caller can rely on the agent having processed the message before the call resolves. Transport-dependent tail semantics: on a LOCAL (in-process) session the wait additionally blocks until the completed turn's event tail has been dispatched to this session's in-process subscribers, so a subsequent read of subscriber state already reflects the turn; on a REMOTE session the wait resolves once the loop completes and mirrored delivery follows over the wire. Callers that need the stronger local guarantee on remote sessions should await the event stream explicitly. */ wait?: boolean; } @@ -11866,6 +13356,31 @@ export interface SendResult { */ messageId: string; } +/** + * Internal request for sending a system notification. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SendSystemNotificationRequest". + */ +/** @experimental */ +export interface SendSystemNotificationRequest { + /** + * Notification text to deliver to the model. + */ + message: string; + /** + * Optional structured notification kind. + */ + kind?: { + [k: string]: unknown | undefined; + }; + /** + * Internal delivery options, including passive policy. + */ + options?: { + [k: string]: unknown | undefined; + }; +} /** * Agents discovered across user, project, plugin, and remote sources. * @@ -12328,7 +13843,7 @@ export interface SessionFsSqliteExistsResult { exists: boolean; } /** - * SQL query, query type, and optional bind parameters for executing a SQLite query against the per-session database. + * SQL query, query type, and optional bind parameters for executing a SQLite query against the per-session database. The provider applies its SQLite busy timeout for every call. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SessionFsSqliteQueryRequest". @@ -12379,6 +13894,62 @@ export interface SessionFsSqliteQueryResult { lastInsertRowid?: number; error?: SessionFsError; } +/** + * Classified SQLite transaction failure. busyOrLocked guarantees rollback; postCommitAmbiguous must never be retried. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionFsSqliteTransactionError". + */ +/** @experimental */ +export interface SessionFsSqliteTransactionError { + errorClass: SessionFsSqliteTransactionErrorClass; + message: string; +} +/** + * Statements to execute atomically. Providers apply busy handling for every call. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionFsSqliteTransactionRequest". + */ +/** @experimental */ +export interface SessionFsSqliteTransactionRequest { + /** + * Target session identifier + */ + sessionId: string; + statements: SessionFsSqliteTransactionStatement[]; +} +/** + * One statement in an atomic SQLite transaction. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionFsSqliteTransactionStatement". + */ +/** @experimental */ +export interface SessionFsSqliteTransactionStatement { + /** + * SQL statement to execute. + */ + query: string; + queryType: SessionFsSqliteQueryType; + /** + * Optional named bind parameters. + */ + params?: { + [k: string]: unknown | undefined; + }; +} +/** + * Per-statement results, or a classified transaction error. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionFsSqliteTransactionResult". + */ +/** @experimental */ +export interface SessionFsSqliteTransactionResult { + results: SessionFsSqliteQueryResult[]; + error?: SessionFsSqliteTransactionError; +} /** * Path whose metadata should be returned from the client-provided session filesystem. * @@ -12486,7 +14057,7 @@ export interface SessionInstalledPlugin { source?: SessionInstalledPluginSource; } /** - * Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref, and optional subpath. + * Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref or full commit SHA, and optional subpath. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SessionInstalledPluginSourceGitHub". @@ -12499,10 +14070,14 @@ export interface SessionInstalledPluginSourceGitHub { source: "github"; repo: string; ref?: string; + /** + * Optional full 40-character hexadecimal commit SHA. + */ + sha?: string; path?: string; } /** - * Source descriptor for a direct URL plugin install, with URL, optional ref, and optional subpath. + * Source descriptor for a direct URL plugin install, with URL, optional ref or full commit SHA, and optional subpath. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "SessionInstalledPluginSourceUrl". @@ -12515,6 +14090,10 @@ export interface SessionInstalledPluginSourceUrl { source: "url"; url: string; ref?: string; + /** + * Optional full 40-character hexadecimal commit SHA. + */ + sha?: string; path?: string; } /** @@ -12531,6 +14110,70 @@ export interface SessionInstalledPluginSourceLocal { source: "local"; path: string; } +/** + * Baseline data provenance for a prediction. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionLimitPredictionBaselineData". + */ +/** @experimental */ +export interface SessionLimitPredictionBaselineData { + /** + * Start of the baseline data slice. + */ + windowStart: string; + /** + * End of the baseline data slice. + */ + windowEnd: string; +} +/** + * Explainable AI-credit session-limit prediction. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionLimitPredictionDetails". + */ +/** @experimental */ +export interface SessionLimitPredictionDetails { + clientType: SessionLimitPredictionClientType; + /** + * Model identifier used for lookup. + */ + modelId: string; + source: SessionLimitPredictionSource; + /** + * Key matched at the source level, such as a model id, family id, or `global`. + */ + sourceKey: string; + /** + * Resolved model family when known. + */ + family?: string; + /** + * Ordered usage tiers and their AI-credit caps. + */ + tiers: SessionLimitPredictionTierOption[]; + baselineData: SessionLimitPredictionBaselineData; + recommendedTier: SessionLimitPredictionTier; + /** + * Recommended maximum AI credits for this session. + */ + recommendedCap: number; +} +/** + * Semantic usage tier and its AI-credit cap. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionLimitPredictionTierOption". + */ +/** @experimental */ +export interface SessionLimitPredictionTierOption { + tier: SessionLimitPredictionTier; + /** + * AI-credit cap for this tier. + */ + cap: number; +} /** * Sessions matching the filter, ordered most-recently-modified first. * @@ -12737,6 +14380,10 @@ export interface SessionOpenOptions { * Opt-in: self-fetch and enforce enterprise managed settings at session bootstrap. */ enableManagedSettings?: boolean; + /** + * Opt in to capturing file changes for session rewind and session diff. Capture cannot reconstruct changes made before it was enabled. On create it starts capture from the first turn. It is also honored on resume: for a session that already has tracked prior turns, tracking continues automatically even if this is omitted; passing it on resume additionally enables tracking for an eligible session that has no prior root turn yet. Resuming a session whose prior root turns were never tracked has no restorable baseline, so tracking stays disabled for it and rewind reports file change tracking as unavailable; the resume itself still succeeds, so sessions that predate tracking remain loadable. The opt-in is only rejected when the session can never track (a subagent session, or one without local session storage). It is intentionally absent from the mutable options update because enabling it after edits have occurred would create an incomplete, misleading baseline. Subagents share the parent session's capture store and are not tracked as separate rewind points: a file a subagent writes is attributed to whichever root user turn was open when the capture was staged, just before the tool body ran. A turn cannot open while a staged capture is still in flight, so a subagent tool that staged under the spawning turn stays attributed to it however late the write lands, while a capture it stages after the user's next message belongs to that later turn. Attribution decides which turn's rewind point counts and file preview include that write; it does not narrow which rewinds revert it, because a rewind restores every capture from the selected turn onward, so the earlier spawning turn reverts it as well. + */ + enableFileChangeTracking?: boolean; /** * Feature-flag values resolved by the host. */ @@ -12766,6 +14413,10 @@ export interface SessionOpenOptions { * Working directory to anchor the session. */ workingDirectory?: string; + /** + * Additional directories the agent may access beyond the working directory. Each entry is granted to the session's file-access allow-list and surfaced to the model (system prompt context and `@`-mention completion). Absolute paths are recommended; a relative path is resolved against the session's working directory. Nonexistent or unresolvable entries are skipped with a warning. This is applied on both session creation and resume, and is not persisted: a resumed session that omits this option does not retain previously supplied directories (re-supply them, exactly as the CLI re-passes `--add-dir`). + */ + additionalDirectories?: string[]; workingDirectoryContext?: SessionContext; /** * Whether this session supports remote steering. @@ -12807,12 +14458,14 @@ export interface SessionOpenOptions { * Whether shell-script safety heuristics are enabled. */ enableScriptSafety?: boolean; + shell?: ShellOptions; /** - * Shell init profile. + * @deprecated + * Use shell.initProfile instead. Shell init profile. */ shellInitProfile?: string; /** - * Per-shell process flags. + * PowerShell process flags applied to built-in and user-requested shell commands. */ shellProcessFlags?: string[]; sandboxConfig?: SandboxConfig; @@ -12901,6 +14554,10 @@ export interface SessionOpenOptions { * Override directory for session event logs. */ eventsLogDirectory?: string; + /** + * Whether subagent callback events should be forwarded into the session event log sink. + */ + eventsLogIncludesSubagents?: boolean; /** * Override Copilot configuration directory. */ @@ -12913,9 +14570,51 @@ export interface SessionOpenOptions { additionalContentExclusionPolicies?: SessionOpenOptionsAdditionalContentExclusionPolicy[]; memory?: MemoryConfiguration; /** - * Capabilities enabled for this session. + * Capabilities enabled for this session. + */ + sessionCapabilities?: SessionCapability[]; +} +/** + * Per-session settings for built-in shell tools. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "ShellOptions". + */ +/** @experimental */ +export interface ShellOptions { + initProfile?: ShellInitProfile; + /** + * Ordered host-provided script paths sourced before each built-in shell command when the + * entry's shell target matches the active shell. Use these for rc files, environment setup scripts, + * or other custom scripts. A script that returns a nonzero status is reported, and later scripts + * and the user command continue while the shell remains running. Because scripts are sourced into + * the command shell, `exit`, `exec`, failures under `set -e`, or other shell-terminating behavior + * can prevent continuation. Script standard output is preserved; Bash script stderr is discarded, + * PowerShell exception messages are replaced, and runtime-generated failure notices omit + * configured script paths. When sandboxing is enabled, each script must already be readable under + * the active sandbox filesystem policy. Pass an empty array to clear the list. + */ + initScripts?: ShellInitScript[]; + /** + * Flags passed to the active built-in shell process on startup, replacing its default flags. + * When omitted, the built-in Bash shell uses `--norc --noprofile`, + * and the built-in PowerShell shell uses `-NoProfile -NoLogo`. + */ + processFlags?: string[]; +} +/** + * A host-provided script sourced before each built-in shell command when its shell target matches the active shell. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "ShellInitScript". + */ +/** @experimental */ +export interface ShellInitScript { + /** + * Path to the script to source. */ - sessionCapabilities?: SessionCapability[]; + path: string; + shell: ShellInitScriptShell; } /** * Content-exclusion policy supplied to `sessions.open` options, with rules, last-updated data, and scope. @@ -13252,6 +14951,23 @@ export interface SessionsCloseRequest { */ /** @experimental */ export interface SessionsCloseResult {} +/** + * Session ID to delete from disk. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionsDeleteRequest". + */ +/** @experimental */ +export interface SessionsDeleteRequest { + /** + * Session ID to delete + */ + sessionId: string; + /** + * Internal resolved session directory path to delete + */ + sessionPath?: string | null; +} /** * Session metadata records to enrich with summary and context information. * @@ -13585,6 +15301,29 @@ export interface SessionsGetLastForContextResult { */ sessionId?: string; } +/** + * Session ID whose persisted metadata should be read. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionsGetMetadataRequest". + */ +/** @experimental */ +export interface SessionsGetMetadataRequest { + /** + * Session ID to inspect + */ + sessionId: string; +} +/** + * Persisted local session metadata when the session exists. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionsGetMetadataResult". + */ +/** @experimental */ +export interface SessionsGetMetadataResult { + session?: LocalSessionMetadataValue; +} /** * Session ID to look up the persisted remote-steerable flag for. * @@ -13626,6 +15365,32 @@ export interface SessionSizes { [k: string]: number | undefined; }; } +/** + * Limit for non-empty local session IDs. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionsListNonEmptySessionIdsRequest". + */ +/** @experimental */ +export interface SessionsListNonEmptySessionIdsRequest { + /** + * Maximum number of session IDs to return. + */ + limit?: number; +} +/** + * Recent local session IDs that contain user-visible history. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionsListNonEmptySessionIdsResult". + */ +/** @experimental */ +export interface SessionsListNonEmptySessionIdsResult { + /** + * Session IDs ordered newest-first. + */ + sessionIds: string[]; +} /** * Optional source filter, metadata-load limit, and context filter applied to the returned sessions. * @@ -13912,12 +15677,14 @@ export interface SessionUpdateOptionsParams { * Whether shell-script safety heuristics are enabled. */ enableScriptSafety?: boolean; + shell?: ShellOptions; /** - * Shell init profile (`None` or `NonInteractive`). + * @deprecated + * Use shell.initProfile instead. Shell init profile (`None` or `NonInteractive`). */ shellInitProfile?: string; /** - * Per-shell process flags (e.g., `pwsh` arguments). + * PowerShell process flags applied to built-in and user-requested shell commands. */ shellProcessFlags?: string[]; sandboxConfig?: SandboxConfig; @@ -13939,7 +15706,7 @@ export interface SessionUpdateOptionsParams { */ disabledSkills?: string[]; /** - * Whether to discover custom instructions on demand after successful file views (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md surfacing). Combined with `skipCustomInstructions` and the runtime-side `ON_DEMAND_INSTRUCTIONS` feature flag. + * Whether to discover custom instructions on demand after successful file views (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md surfacing). Combined with `skipCustomInstructions`. */ enableOnDemandInstructionDiscovery?: boolean; /** @@ -14006,6 +15773,10 @@ export interface SessionUpdateOptionsParams { * Override directory for the session-events log. When unset, the runtime's default events log directory is used. */ eventsLogDirectory?: string; + /** + * Whether subagent callback events should be forwarded into the session event log sink. + */ + eventsLogIncludesSubagents?: boolean; /** * Additional content-exclusion policies to merge into the session's policy set. * @@ -15479,6 +17250,10 @@ export interface UIExitPlanModeResponse { * Feedback from the user when they declined the plan or requested changes. */ feedback?: string; + /** + * When true, the agent is instructed to end its turn without starting implementation so the client can restore the session model and auto-submit a fresh implementation turn on it. Set only when a distinct plan configuration (a different model, reasoning effort, or context tier) actually ran the planning turn. + */ + deferImplementation?: boolean; } /** * Request ID of a pending `auto_mode_switch.requested` event and the user's response. @@ -16002,7 +17777,7 @@ export interface VisibilitySetResult { /** @experimental */ export interface WorkspaceDiffFileChange { /** - * Path to the changed file, relative to the workspace root. + * Path to the changed file, relative to the workspace root when the file lives under it. A file changed outside the workspace root keeps a `../`-relative path, or an absolute path when no relative path exists (for example a different Windows drive). */ path: string; /** @@ -16038,9 +17813,52 @@ export interface WorkspaceDiffResult { */ baseBranch?: string; /** - * Whether a requested branch diff fell back to unstaged changes because branch diff failed. + * Whether the requested diff fell back to unstaged changes, either because branch diff failed or session diff was unavailable. */ isFallback: boolean; + unavailableReason?: HistoryRewindUnavailableReason; +} +/** + * Compaction summary checkpoint to persist. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "WorkspacesAddSummaryRequest". + */ +/** @experimental */ +export interface WorkspacesAddSummaryRequest { + /** + * Summary title shown in checkpoint listings. + */ + title: string; + /** + * Markdown summary content to persist. + */ + content: string; +} +/** + * Persisted summary metadata and refreshed workspace metadata. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "WorkspacesAddSummaryResult". + */ +/** @experimental */ +export interface WorkspacesAddSummaryResult { + summary?: {}; + workspace?: {}; + [k: string]: unknown | undefined; +} +/** + * Whether the autopilot objective file exists. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "WorkspacesAutopilotObjectiveExistsResult". + */ +/** @experimental */ +export interface WorkspacesAutopilotObjectiveExistsResult { + /** + * True when the objective file exists. + */ + exists: boolean; } /** * Workspace checkpoint metadata with assigned number, human-readable title, and checkpoint filename. @@ -16080,6 +17898,19 @@ export interface WorkspacesCreateFileRequest { */ content: string; } +/** + * Result of deleting the autopilot objective file. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "WorkspacesDeleteAutopilotObjectiveResult". + */ +/** @experimental */ +export interface WorkspacesDeleteAutopilotObjectiveResult { + /** + * True when a file was deleted. + */ + deleted: boolean; +} /** * Parameters for computing a workspace diff. * @@ -16094,6 +17925,21 @@ export interface WorkspacesDiffRequest { */ ignoreWhitespace?: boolean; } +/** + * Optional session context used when creating a local workspace. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "WorkspacesEnsureRequest". + */ +/** @experimental */ +export interface WorkspacesEnsureRequest { + /** + * Opaque workspace context supplied by the session host. + */ + context?: { + [k: string]: unknown | undefined; + }; +} /** * Current workspace metadata for the session, including its absolute filesystem path when available. * @@ -16155,6 +18001,19 @@ export interface WorkspacesListFilesResult { */ files: string[]; } +/** + * Autopilot objective file content, or null when missing. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "WorkspacesReadAutopilotObjectiveResult". + */ +/** @experimental */ +export interface WorkspacesReadAutopilotObjectiveResult { + /** + * Autopilot objective file content, or null when missing. + */ + content: string | null; +} /** * Checkpoint number to read. * @@ -16203,58 +18062,212 @@ export interface WorkspacesReadFileRequest { /** @experimental */ export interface WorkspacesReadFileResult { /** - * File content as a UTF-8 string + * File content as a UTF-8 string + */ + content: string; +} +/** + * Pasted content to save as a UTF-8 file in the session workspace. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "WorkspacesSaveLargePasteRequest". + */ +/** @experimental */ +export interface WorkspacesSaveLargePasteRequest { + /** + * Pasted content to save as a UTF-8 file + */ + content: string; +} +/** + * Descriptor for the saved paste file, or null when the workspace is unavailable. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "WorkspacesSaveLargePasteResult". + */ +/** @experimental */ +export interface WorkspacesSaveLargePasteResult { + /** + * Saved-paste descriptor, or null when the workspace is unavailable (e.g. CCA runtime, non-infinite sessions, remote sessions) + */ + saved: { + /** + * Absolute filesystem path to the saved paste file + */ + filePath: string; + /** + * Filename within the workspace files directory + */ + filename: string; + /** + * Size of the saved file in bytes + */ + sizeBytes: number; + } | null; +} +/** + * Rollback point for local workspace summaries. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "WorkspacesTruncateSummariesRequest". + */ +/** @experimental */ +export interface WorkspacesTruncateSummariesRequest { + /** + * Number of newest summaries to keep. + */ + keepCount: number; +} +/** + * Workspace metadata fields to update. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "WorkspacesUpdateMetadataRequest". + */ +/** @experimental */ +export interface WorkspacesUpdateMetadataRequest { + /** + * Opaque workspace context supplied by the session host. + */ + context?: { + [k: string]: unknown | undefined; + }; + /** + * Optional workspace display name override. + */ + name?: string; +} +/** + * Autopilot objective file content to persist. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "WorkspacesWriteAutopilotObjectiveRequest". + */ +/** @experimental */ +export interface WorkspacesWriteAutopilotObjectiveRequest { + /** + * Autopilot objective file content. + */ + content: string; +} +/** + * Result of writing the autopilot objective file. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "WorkspacesWriteAutopilotObjectiveResult". + */ +/** @experimental */ +export interface WorkspacesWriteAutopilotObjectiveResult { + /** + * Filesystem operation performed. + */ + operation: string; +} + +/** @experimental */ +export interface SessionModelListRequest { + /** + * If true, bypasses the per-session model list cache and re-fetches from CAPI. + */ + skipCache?: boolean; +} + +/** @experimental */ +export interface SessionAgentListRequest { + /** + * When true, request the session's configured built-in agents alongside custom agents. Listing applies feature, context, inclusion, exclusion, and user-disabled-agent policy, but does not evaluate transient invocation requirements such as model availability. Built-in metadata may be omitted when the session cannot project it, such as a relay session. + */ + includeBuiltInAgents?: boolean; + /** + * When true, request authored base prompt text on each AgentInfo. Prompt text may be omitted when unavailable, such as for agents projected through a relay session. + */ + includePrompt?: boolean; +} +/** + * Standard MCP CallToolResult + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "SessionMcpAppsCallToolResult". + */ +/** @experimental */ +export interface SessionMcpAppsCallToolResult { + [k: string]: unknown | undefined; +} + +/** @experimental */ +export interface SessionPluginsReloadRequest { + /** + * Reload MCP server connections after refreshing plugins. Defaults to true. + */ + reloadMcp?: boolean; + /** + * Re-run custom-agent discovery after refreshing plugins. Defaults to true. + */ + reloadCustomAgents?: boolean; + /** + * Re-load user, plugin, and (subject to `deferRepoHooks`) repo hooks. Defaults to true. Has no effect when the host has not registered a hook reloader (e.g. remote sessions). + */ + reloadHooks?: boolean; + /** + * Re-discover and relaunch subprocess extensions (including plugin-shipped extensions) after refreshing plugins. Defaults to true. Has no effect when the session has no active extension controller (e.g. extensions were not requested for the session). + */ + reloadExtensions?: boolean; + /** + * When true, skip repo-level hooks during the hook reload. Use before folder trust is confirmed; load them post-trust via `sessions.loadDeferredRepoHooks`. + */ + deferRepoHooks?: boolean; +} + +/** @experimental */ +export interface SessionProviderGetEndpointRequest { + /** + * Model identifier the caller intends to use against the returned endpoint. Used to pick the correct wire shape. Omit to use whichever model the session is currently using. + */ + modelId?: string; +} + +/** @experimental */ +export interface SessionCommandsListRequest { + /** + * Include runtime built-in commands + */ + includeBuiltins?: boolean; + /** + * Include enabled user-invocable skills and commands + */ + includeSkills?: boolean; + /** + * Include commands registered by protocol clients, including SDK clients and extensions */ - content: string; + includeClientCommands?: boolean; } -/** - * Pasted content to save as a UTF-8 file in the session workspace. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "WorkspacesSaveLargePasteRequest". - */ + /** @experimental */ -export interface WorkspacesSaveLargePasteRequest { +export interface SessionHistoryCompactRequest { /** - * Pasted content to save as a UTF-8 file + * Optional user-provided instructions to focus the compaction summary */ - content: string; -} -/** - * Descriptor for the saved paste file, or null when the workspace is unavailable. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "WorkspacesSaveLargePasteResult". - */ -/** @experimental */ -export interface WorkspacesSaveLargePasteResult { + customInstructions?: string; /** - * Saved-paste descriptor, or null when the workspace is unavailable (e.g. CCA runtime, non-infinite sessions, remote sessions) + * What initiated this compaction request, recorded as the `trigger` on the persisted `session.compaction_start` / `session.compaction_complete` events. When absent, the compaction is persisted without trigger attribution (initiator unknown). */ - saved: { - /** - * Absolute filesystem path to the saved paste file - */ - filePath: string; - /** - * Filename within the workspace files directory - */ - filename: string; - /** - * Size of the saved file in bytes - */ - sizeBytes: number; - } | null; + trigger?: /** User-requested compaction, e.g. the /compact command or a direct history.compact call. */ + | "manual" + /** Compaction requested while switching to a model with a smaller context window. */ + | "model_switch"; + /** + * Context window token limit this compaction is targeting, recorded as the `tokenLimit` on the persisted `session.compaction_start` / `session.compaction_complete` events. Set it when the compaction targets a window other than the compacting model's own, e.g. switching to a model with a smaller context window: the compaction still runs on the current model, so the limit that motivated it would otherwise be lost. When absent, the events record the compacting model's own resolved limit. Attribution metadata only - it does not change how much the compaction removes. + */ + tokenLimit?: number; } -/** - * Standard MCP CallToolResult - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "SessionMcpAppsCallToolResult". - */ + /** @experimental */ -export interface SessionMcpAppsCallToolResult { - [k: string]: unknown | undefined; +export interface SessionLimitPredictionPredictRequest { + /** + * Optional model identifier override. If omitted, the session's current model is used. + */ + modelId?: string; + clientType?: SessionLimitPredictionClientType; } /** * Identifies the target session. @@ -16295,6 +18308,13 @@ export function createServerRpc(connection: MessageConnection) { */ list: async (params: ModelsListRequest): Promise => connection.sendRequest("models.list", params), + /** + * Returns the running runtime's complete catalog of well-known built-in model IDs without authentication or network access. + * + * @returns The running runtime's complete catalog of well-known built-in model IDs, including supported models and additional IDs with built-in metadata. + */ + getBuiltInCatalog: async (): Promise => + connection.sendRequest("models.getBuiltInCatalog", {}), }, /** @experimental */ tools: { @@ -16927,6 +18947,24 @@ export function createInternalServerRpc(connection: MessageConnection) { connection.sendRequest("connect", params), /** @experimental */ sessions: { + /** + * Reads lightweight persisted metadata for one local session without opening it. + * + * @param params Session ID whose persisted metadata should be read. + * + * @returns Persisted local session metadata when the session exists. + */ + getMetadata: async (params: SessionsGetMetadataRequest): Promise => + connection.sendRequest("sessions.getMetadata", params), + /** + * Lists recent local session IDs that contain user-visible history, omitting housekeeping-only sessions. + * + * @param params Limit for non-empty local session IDs. + * + * @returns Recent local session IDs that contain user-visible history. + */ + listNonEmptySessionIds: async (params: SessionsListNonEmptySessionIdsRequest): Promise => + connection.sendRequest("sessions.listNonEmptySessionIds", params), /** * Computes the absolute path to a session's persisted events.jsonl file. Internal: filesystem paths are only meaningful in-process (CLI and runtime share a filesystem). Currently used by the CLI's contribution-graph feature to read historical events directly. Remote SDK consumers must not depend on this; a proper event-query API would replace it if the contribution graph ever needed to work over the wire. * @@ -16945,6 +18983,13 @@ export function createInternalServerRpc(connection: MessageConnection) { */ getPersistedRemoteSteerable: async (params: SessionsGetPersistedRemoteSteerableRequest): Promise => connection.sendRequest("sessions.getPersistedRemoteSteerable", params), + /** + * Deletes one local session from disk after running the same lifecycle hooks as the session manager. + * + * @param params Session ID to delete from disk. + */ + delete: async (params: SessionsDeleteRequest): Promise => + connection.sendRequest("sessions.delete", params), /** * Gets the dynamic-context board entry count associated with a session, when available. Internal: this exists solely so CLI telemetry events (`rem_spawn_gate`, `rem_consolidation_complete`) can pair START / END board counts around the detached rem-agent spawn. "Dynamic context board" is a runtime-internal concept that is not part of the public SDK contract; the long-term plan is to relocate the telemetry emission into the runtime so this method can be deleted entirely. * @@ -17017,6 +19062,26 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin */ abort: async (params: AbortRequest): Promise => connection.sendRequest("session.abort", { sessionId, ...params }), + /** + * Interrupts the current main agent turn while leaving running background work (subagents, sidekicks, and promoted attached shells) alive. No-op when the main loop is not processing. + * + * @param params Parameters for interrupting the main agent turn. + * + * @returns Result of interrupting the main agent turn. + * + * @experimental + */ + interruptMainTurn: async (params: InterruptMainTurnRequest): Promise => + connection.sendRequest("session.interruptMainTurn", { sessionId, ...params }), + /** + * Cancels every running background agent (task-registry subagents plus sidekick agents) without interrupting the main agent loop. Promoted attached shells are left running. + * + * @returns The number of running background agents (task-registry agents) that were cancelled. + * + * @experimental + */ + cancelAllBackgroundAgents: async (): Promise => + connection.sendRequest("session.cancelAllBackgroundAgents", { sessionId }), /** * Shuts down the session and persists its final state. Awaits any deferred sessionEnd hooks before resolving so user-supplied hook scripts complete before the runtime tears down. * @@ -17113,6 +19178,15 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin */ run: async (params: FactoryRunRequest): Promise => connection.sendRequest("session.factory.run", { sessionId, ...params }), + /** + * Resumes a factory run using its persisted name, arguments, journal, and accounting. + * + * @param params Parameters for resuming a factory run from its persisted identity. + * + * @returns Resolved persisted factory identity and resumed run envelope. + */ + resume: async (params: FactoryResumeRequest): Promise => + connection.sendRequest("session.factory.resume", { sessionId, ...params }), /** * Gets the current or settled envelope for a factory run. * @@ -17122,6 +19196,31 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin */ getRun: async (params: FactoryGetRunRequest): Promise => connection.sendRequest("session.factory.getRun", { sessionId, ...params }), + /** + * Lists durable factory runs for this session in creation order. + * + * @returns Factory runs in durable creation order. + */ + listRuns: async (): Promise => + connection.sendRequest("session.factory.listRuns", { sessionId }), + /** + * Gets durable and live observability detail for one factory run. + * + * @param params Parameters for retrieving a factory run. + * + * @returns Full factory run observability detail. + */ + getRunDetail: async (params: FactoryGetRunRequest): Promise => + connection.sendRequest("session.factory.getRunDetail", { sessionId, ...params }), + /** + * Pages durable progress for one factory run. + * + * @param params Parameters for paging factory progress. + * + * @returns A bidirectional page of factory progress. + */ + getRunProgress: async (params: FactoryGetRunProgressRequest): Promise => + connection.sendRequest("session.factory.getRunProgress", { sessionId, ...params }), /** * Requests cancellation of a factory run and returns its run envelope. * @@ -17205,7 +19304,7 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin * * @returns The list of models available to this session. */ - list: async (params?: ModelListRequest): Promise => + list: async (params?: SessionModelListRequest): Promise => connection.sendRequest("session.model.list", { sessionId, ...params }), }, /** @experimental */ @@ -17296,6 +19395,24 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin */ getWorkspace: async (): Promise => connection.sendRequest("session.workspaces.getWorkspace", { sessionId }), + /** + * Updates workspace metadata for a local session and returns the refreshed workspace. + * + * @param params Workspace metadata fields to update. + * + * @returns Current workspace metadata for the session, including its absolute filesystem path when available. + */ + updateMetadata: async (params: WorkspacesUpdateMetadataRequest): Promise => + connection.sendRequest("session.workspaces.updateMetadata", { sessionId, ...params }), + /** + * Ensures a local session workspace exists and returns it. + * + * @param params Optional session context used when creating a local workspace. + * + * @returns Current workspace metadata for the session, including its absolute filesystem path when available. + */ + ensure: async (params: WorkspacesEnsureRequest): Promise => + connection.sendRequest("session.workspaces.ensure", { sessionId, ...params }), /** * Lists files stored in the session workspace files directory. * @@ -17335,6 +19452,54 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin */ readCheckpoint: async (params: WorkspacesReadCheckpointRequest): Promise => connection.sendRequest("session.workspaces.readCheckpoint", { sessionId, ...params }), + /** + * Adds a compaction summary checkpoint to the local session workspace. + * + * @param params Compaction summary checkpoint to persist. + * + * @returns Persisted summary metadata and refreshed workspace metadata. + */ + addSummary: async (params: WorkspacesAddSummaryRequest): Promise => + connection.sendRequest("session.workspaces.addSummary", { sessionId, ...params }), + /** + * Truncates local workspace compaction summaries after a rollback. + * + * @param params Rollback point for local workspace summaries. + * + * @returns Current workspace metadata for the session, including its absolute filesystem path when available. + */ + truncateSummaries: async (params: WorkspacesTruncateSummariesRequest): Promise => + connection.sendRequest("session.workspaces.truncateSummaries", { sessionId, ...params }), + /** + * Reads the autopilot objective state file from the local session workspace. + * + * @returns Autopilot objective file content, or null when missing. + */ + readAutopilotObjective: async (): Promise => + connection.sendRequest("session.workspaces.readAutopilotObjective", { sessionId }), + /** + * Writes the autopilot objective state file in the local session workspace. + * + * @param params Autopilot objective file content to persist. + * + * @returns Result of writing the autopilot objective file. + */ + writeAutopilotObjective: async (params: WorkspacesWriteAutopilotObjectiveRequest): Promise => + connection.sendRequest("session.workspaces.writeAutopilotObjective", { sessionId, ...params }), + /** + * Deletes the autopilot objective state file from the local session workspace. + * + * @returns Result of deleting the autopilot objective file. + */ + deleteAutopilotObjective: async (): Promise => + connection.sendRequest("session.workspaces.deleteAutopilotObjective", { sessionId }), + /** + * Checks whether the local session workspace has an autopilot objective state file. + * + * @returns Whether the autopilot objective file exists. + */ + autopilotObjectiveExists: async (): Promise => + connection.sendRequest("session.workspaces.autopilotObjectiveExists", { sessionId }), /** * Saves pasted content as a UTF-8 file in the session workspace. * @@ -17345,7 +19510,7 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin saveLargePaste: async (params: WorkspacesSaveLargePasteRequest): Promise => connection.sendRequest("session.workspaces.saveLargePaste", { sessionId, ...params }), /** - * Computes a diff for the session workspace. + * Computes a diff for the session workspace. Never rejects for a busy session: a `session`-mode diff that cannot read the session's file-change captures falls back to an unstaged git diff with `isFallback: true` and reports why in `unavailableReason`. * * @param params Parameters for computing a workspace diff. * @@ -17398,12 +19563,14 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin /** @experimental */ agent: { /** - * Lists custom agents available to the session. + * Lists agents available to the session. Defaults to custom agents only; pass includeBuiltInAgents to include the effective built-in agents. + * + * @param params Controls whether built-in agents and authored prompt text are included. * - * @returns Custom agents available to the session. + * @returns Agents available to the session. */ - list: async (): Promise => - connection.sendRequest("session.agent.list", { sessionId }), + list: async (params?: SessionAgentListRequest): Promise => + connection.sendRequest("session.agent.list", { sessionId, ...params }), /** * Gets the currently selected custom agent for the session. * @@ -17640,9 +19807,9 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin removeGitHub: async (): Promise => connection.sendRequest("session.mcp.removeGitHub", { sessionId }), /** - * Starts an individual MCP server on the live session from a caller-supplied config. Session-scoped and ephemeral: the server is added to this session's running set only and is reaped when the session ends. Does NOT modify persistent user configuration (`mcp.config.*`), so it does not affect future sessions. The server surfaces through `session.mcp.list` and the `session.mcp_servers_loaded` / `session.mcp_server_status_changed` events like any other server. + * Starts an individual MCP server on the live session. Omit `config` for a config-free start-by-name of an already-configured server (reuses the server's already-registered configuration); supply `config` to start from a caller-supplied configuration. Session-scoped and ephemeral: the server is added to this session's running set only and is reaped when the session ends. Does NOT modify persistent user configuration (`mcp.config.*`), so it does not affect future sessions. The server surfaces through `session.mcp.list` and the `session.mcp_servers_loaded` / `session.mcp_server_status_changed` events like any other server. * - * @param params Server name and configuration for an individual MCP server start. + * @param params Server name and optional configuration for an individual MCP server start. Omit `config` for a config-free start-by-name of an already-configured server. */ startServer: async (params: McpStartServerRequest): Promise => connection.sendRequest("session.mcp.startServer", { sessionId, ...params }), @@ -17689,6 +19856,15 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin */ login: async (params: McpOauthLoginRequest): Promise => connection.sendRequest("session.mcp.oauth.login", { sessionId, ...params }), + /** + * Responds to a pending MCP OAuth authorization request by its request id. + * + * @param params Pending MCP OAuth request id to respond to. + * + * @returns Indicates whether the pending MCP OAuth response was accepted. + */ + respond: async (params: McpOauthRespondRequest): Promise => + connection.sendRequest("session.mcp.oauth.respond", { sessionId, ...params }), }, /** @experimental */ headers: { @@ -17800,7 +19976,7 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin * * @param params Optional flags controlling which side effects the reload performs. */ - reload: async (params?: PluginsReloadRequest): Promise => + reload: async (params?: SessionPluginsReloadRequest): Promise => connection.sendRequest("session.plugins.reload", { sessionId, ...params }), }, /** @experimental */ @@ -17812,7 +19988,7 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin * * @returns A snapshot of the provider endpoint the session is currently configured to talk to. */ - getEndpoint: async (params?: ProviderGetEndpointRequest): Promise => + getEndpoint: async (params?: SessionProviderGetEndpointRequest): Promise => connection.sendRequest("session.provider.getEndpoint", { sessionId, ...params }), /** * Adds BYOK providers and/or models to the session's registry at runtime, extending the additive registry built from the session's `providers`/`models` options. Both fields are optional, so a call may add providers only, models only, or both. Within a single call providers are registered before models, so a model may reference a provider added in the same call; across calls a model may reference any provider already registered (from session creation or a prior add). A model whose referenced provider is not registered by the end of the call is rejected. Newly added models become selectable via `model.list` / `model.switchTo` and are inherited by sub-agents spawned afterwards. @@ -17926,7 +20102,7 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin * * @returns Slash commands available in the session, after applying any include/exclude filters. */ - list: async (params?: CommandsListRequest): Promise => + list: async (params?: SessionCommandsListRequest): Promise => connection.sendRequest("session.commands.list", { sessionId, ...params }), /** * Invokes a slash command in the session. @@ -18155,10 +20331,12 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin /** * Clears session-scoped tool permission approvals. * + * @param params Clears session-scoped tool permission approvals, and optionally the location-scoped ones. + * * @returns Indicates whether the operation succeeded. */ - resetSessionApprovals: async (): Promise => - connection.sendRequest("session.permissions.resetSessionApprovals", { sessionId }), + resetSessionApprovals: async (params: PermissionsResetSessionApprovalsRequest): Promise => + connection.sendRequest("session.permissions.resetSessionApprovals", { sessionId, ...params }), /** * Notifies the runtime that a permission prompt UI has been shown to the user. * @@ -18366,9 +20544,21 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin connection.sendRequest("session.metadata.recomputeContextTokens", { sessionId, ...params }), }, /** @experimental */ + contentExclusion: { + /** + * Checks local file system absolute paths within the session working directory against its content-exclusion policy. Results preserve input order. Unsupported paths/filesystems and unavailable policy evaluation return available false, and callers must treat every requested path as excluded. + * + * @param params Local file system absolute paths within the session working directory to check against its content-exclusion policy. + * + * @returns Batch content-exclusion result. Callers must fail closed when policy evaluation is unavailable. + */ + checkPaths: async (params: ContentExclusionCheckPathsRequest): Promise => + connection.sendRequest("session.contentExclusion.checkPaths", { sessionId, ...params }), + }, + /** @experimental */ shell: { /** - * Starts a shell command and streams output through session notifications. + * Starts a shell command and streams output through session notifications. The command runs as the leader of its own process group (POSIX) or in a dedicated job object (Windows), so a forced termination — via "shell.kill", the request timeout, or session disposal — signals that whole group/job rather than only the direct child. Two gaps are worth planning for: a command that exits on its own does not trigger that teardown, and on POSIX a descendant that moves itself into a new session or process group (for example via "setsid") leaves the signalled group, so either can leave a background process running. * * @param params Shell command to run, with optional working directory and timeout in milliseconds. * @@ -18377,7 +20567,7 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin exec: async (params: ShellExecRequest): Promise => connection.sendRequest("session.shell.exec", { sessionId, ...params }), /** - * Sends a signal to a shell process previously started via "shell.exec". + * Sends a signal to a shell process previously started via "shell.exec". The signal targets the command's whole process group (POSIX) or job object (Windows), so descendants still in that group are signalled too, not just the direct child. On POSIX a descendant that moved itself into a new session or process group (for example via "setsid") is no longer in the signalled group and survives. * * @param params Identifier of a process previously returned by "shell.exec" and the signal to send. * @@ -18413,7 +20603,7 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin * * @returns Compaction outcome with the number of tokens and messages removed, summary text, and the resulting context window breakdown. */ - compact: async (params?: HistoryCompactRequest): Promise => + compact: async (params?: SessionHistoryCompactRequest): Promise => connection.sendRequest("session.history.compact", { sessionId, ...params }), /** * Truncates persisted session history to a specific event. @@ -18424,6 +20614,31 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin */ truncate: async (params: HistoryTruncateRequest): Promise => connection.sendRequest("session.history.truncate", { sessionId, ...params }), + /** + * Lists the user turns that the session can rewind to. Never rejects for a busy session: rewind reads need the session's file-change captures to be settled, so a session that still holds active work answers with `unavailableReason: "session-busy"` and no points, which the caller can retry. + * + * @returns Rewind points and file-change-tracking availability for the session. + */ + listRewindPoints: async (): Promise => + connection.sendRequest("session.history.listRewindPoints", { sessionId }), + /** + * Previews the files that a conversation-and-files rewind would restore. + * + * @param params Event boundary to preview for conversation-and-files rewind. + * + * @returns Files and aggregate changes for a prospective rewind. + */ + previewRewind: async (params: HistoryPreviewRewindRequest): Promise => + connection.sendRequest("session.history.previewRewind", { sessionId, ...params }), + /** + * Rewinds the session conversation, optionally restoring files changed by the discarded turns. Not crash-atomic: file restore and conversation truncation are separate stores, applied in that order, so a process crash between them can leave the workspace rewound while the conversation still contains the discarded turns. There is no recovery journal; re-running the same rewind is the recovery path for a crash before truncation lands, since file restore is idempotent (already-restored files are reported as skipped) and truncation is re-derived from the still-retained boundary event. After truncation lands that boundary no longer exists, so the same request is rejected; the only stage that can still be outstanding is snapshot pruning, whose failure leaves orphan snapshots the capture store tolerates. The reverse inconsistency cannot occur, because truncation is never applied before file restore succeeds. + * + * @param params Boundary and mode for rewinding session history. + * + * @returns Structured outcome of a rewind request. + */ + rewind: async (params: HistoryRewindRequest): Promise => + connection.sendRequest("session.history.rewind", { sessionId, ...params }), /** * Cancels any in-progress background compaction on a local session. * @@ -18455,6 +20670,67 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin */ pendingItems: async (): Promise => connection.sendRequest("session.queue.pendingItems", { sessionId }), + /** + * Moves an addressable queued item to a public visible position. + * + * @param params Parameters for moving a queued item by stable id. + * + * @returns Result of moving a queued item. + */ + moveItem: async (params: QueueMoveItemRequest): Promise => + connection.sendRequest("session.queue.moveItem", { sessionId, ...params }), + /** + * Inserts a new queued message at a public visible position. + * + * @param params Parameters for inserting a queued message at a public visible position. + * + * @returns Result of inserting a queued message. + */ + insertAt: async (params: QueueInsertAtRequest): Promise => + connection.sendRequest("session.queue.insertAt", { sessionId, ...params }), + /** + * Removes an addressable queued item by its stable id. + * + * @param params Parameters for removing a queued item by stable id. + * + * @returns Result of removing a queued item. + */ + removeAt: async (params: QueueRemoveAtRequest): Promise => + connection.sendRequest("session.queue.removeAt", { sessionId, ...params }), + /** + * Updates the text of an addressable single-message queue item. + * + * @param params Parameters for editing a single queued message. + * + * @returns Result of editing a queued message. + */ + updateText: async (params: QueueUpdateTextRequest): Promise => + connection.sendRequest("session.queue.updateText", { sessionId, ...params }), + /** + * Duplicates an addressable queued item immediately after its source. + * + * @param params Parameters for duplicating a queued item. + * + * @returns Result of duplicating a queued item. + */ + duplicateAt: async (params: QueueDuplicateAtRequest): Promise => + connection.sendRequest("session.queue.duplicateAt", { sessionId, ...params }), + /** + * Acquires or releases the queued-lane drain pause. + * + * @param params Parameters for acquiring or releasing the queued-lane drain pause. Acquisition is exclusive and non-idempotent: `paused: true` against an already-paused session fails with `queue_already_paused`. The pause is never released automatically — it is not tied to the caller's lifetime, so a client that exits without sending `paused: false` leaves the lane frozen. Release is unowned: `paused: false` clears the pause for any caller, including one that never acquired it. + */ + setDrainPaused: async (params: QueueSetDrainPausedRequest): Promise => + connection.sendRequest("session.queue.setDrainPaused", { sessionId, ...params }), + /** + * Moves an addressable queued message into the live turn's steering lane. + * + * @param params Parameters for steering a queued message into a live turn. + * + * @returns Result of trying to steer a queued message into a live turn. + */ + sendNow: async (params: QueueSendNowRequest): Promise => + connection.sendRequest("session.queue.sendNow", { sessionId, ...params }), /** * Removes the most recently queued user-facing item (LIFO). * @@ -18516,6 +20792,18 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin connection.sendRequest("session.usage.getMetrics", { sessionId }), }, /** @experimental */ + limitPrediction: { + /** + * Predicts an AI-credit session limit for the session's resolved model. Returns an unavailable result instead of falling back when the current model is unresolved auto. + * + * @param params Parameters for predicting an AI-credit session limit. Omitting `modelId` uses the session's currently selected model. + * + * @returns Prediction result. Available results include prediction details; unavailable results include an explicit reason. + */ + predict: async (params?: SessionLimitPredictionPredictRequest): Promise => + connection.sendRequest("session.limitPrediction.predict", { sessionId, ...params }), + }, + /** @experimental */ remote: { /** * Enables remote session export or steering. @@ -18589,6 +20877,15 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin */ export function createInternalSessionRpc(connection: MessageConnection, sessionId: string) { return { + /** + * Queues or sends an internal system notification to the session according to its passive policy. + * + * @param params Internal request for sending a system notification. + * + * @experimental + */ + sendSystemNotification: async (params: SendSystemNotificationRequest): Promise => + connection.sendRequest("session.sendSystemNotification", { sessionId, ...params }), /** @experimental */ mcp: { /** @@ -18643,6 +20940,129 @@ export function createInternalSessionRpc(connection: MessageConnection, sessionI evaluatePredicate: async (params: SessionSettingsEvaluatePredicateRequest): Promise => connection.sendRequest("session.settings.evaluatePredicate", { sessionId, ...params }), }, + /** @experimental */ + queue: { + /** + * Returns the internal native queue snapshot for in-process session orchestration. + * + * @returns Internal snapshot of native queue state for local session orchestration. + */ + snapshot: async (): Promise => + connection.sendRequest("session.queue.snapshot", { sessionId }), + /** + * Reports whether the local session has native queued work pending. + * + * @returns Whether the native queue has pending work. + */ + hasPending: async (): Promise => + connection.sendRequest("session.queue.hasPending", { sessionId }), + /** + * Begins a native deferred-idle drain when background work has quiesced. + * + * @param params Inputs for starting a deferred-idle drain. + * + * @returns Whether a deferred-idle drain should run. + */ + beginDeferredIdleDrain: async (params: QueueBeginDeferredIdleDrainRequest): Promise => + connection.sendRequest("session.queue.beginDeferredIdleDrain", { sessionId, ...params }), + /** + * Finishes a native deferred-idle drain and reports whether to drain queue work or emit idle. + * + * @param params Inputs for completing a deferred-idle drain. + * + * @returns Action selected by the native deferred-idle drain. + */ + finishDeferredIdleDrain: async (params: QueueFinishDeferredIdleDrainRequest): Promise => + connection.sendRequest("session.queue.finishDeferredIdleDrain", { sessionId, ...params }), + /** + * Marks session.idle as deferred by native background work state. + * + * @param params Inputs for marking session.idle deferred in native state. + */ + deferSessionIdle: async (params: QueueDeferSessionIdleRequest): Promise => + connection.sendRequest("session.queue.deferSessionIdle", { sessionId, ...params }), + /** + * Consumes queued native system notifications matching an internal filter. + * + * @param params Internal filter for consuming queued system notifications. + * + * @returns Indicates whether a user-facing pending item was removed. + */ + consumeSystemNotifications: async (params: QueueConsumeSystemNotificationsRequest): Promise => + connection.sendRequest("session.queue.consumeSystemNotifications", { sessionId, ...params }), + /** + * Enqueues the internal resume-pending wake item when orphan handling needs a follow-up turn. + * + * @returns Result of enqueueing the resume-pending wake item. + */ + enqueueResumePending: async (): Promise => + connection.sendRequest("session.queue.enqueueResumePending", { sessionId }), + /** + * Drains the native local-session work queue for in-process session orchestration. + */ + process: async (): Promise => + connection.sendRequest("session.queue.process", { sessionId }), + }, + /** @experimental */ + schedule: { + /** + * Hydrates the native schedule registry from persisted session events. + */ + hydrate: async (): Promise => + connection.sendRequest("session.schedule.hydrate", { sessionId }), + /** + * Reports whether the session has an active self-paced scheduled prompt. + * + * @returns Whether the session currently has an active self-paced schedule. + */ + hasSelfPaced: async (): Promise => + connection.sendRequest("session.schedule.hasSelfPaced", { sessionId }), + /** + * Registers a relative-interval scheduled prompt. + * + * @param params Register a relative-interval scheduled prompt. + * + * @returns Result of registering or re-arming a scheduled prompt. + */ + add: async (params: ScheduleAddRequest): Promise => + connection.sendRequest("session.schedule.add", { sessionId, ...params }), + /** + * Registers a recurring cron scheduled prompt. + * + * @param params Register a cron scheduled prompt. + * + * @returns Result of registering or re-arming a scheduled prompt. + */ + addCron: async (params: ScheduleAddCronRequest): Promise => + connection.sendRequest("session.schedule.addCron", { sessionId, ...params }), + /** + * Registers an absolute-time scheduled prompt. + * + * @param params Register an absolute-time scheduled prompt. + * + * @returns Result of registering or re-arming a scheduled prompt. + */ + addAt: async (params: ScheduleAddAtRequest): Promise => + connection.sendRequest("session.schedule.addAt", { sessionId, ...params }), + /** + * Registers a self-paced scheduled prompt. + * + * @param params Register a self-paced scheduled prompt. + * + * @returns Result of registering or re-arming a scheduled prompt. + */ + addSelfPaced: async (params: ScheduleAddSelfPacedRequest): Promise => + connection.sendRequest("session.schedule.addSelfPaced", { sessionId, ...params }), + /** + * Re-arms an active self-paced scheduled prompt. + * + * @param params Re-arm a self-paced scheduled prompt. + * + * @returns Result of registering or re-arming a scheduled prompt. + */ + rearmSelfPaced: async (params: ScheduleRearmSelfPacedRequest): Promise => + connection.sendRequest("session.schedule.rearmSelfPaced", { sessionId, ...params }), + }, }; } @@ -18764,13 +21184,21 @@ export interface SessionFsHandler { */ rename(params: SessionFsRenameRequest): Promise; /** - * Executes a SQLite query against the per-session database. + * Executes a SQLite query against the per-session database. Providers apply busy handling for every call. * - * @param params SQL query, query type, and optional bind parameters for executing a SQLite query against the per-session database. + * @param params SQL query, query type, and optional bind parameters for executing a SQLite query against the per-session database. The provider applies its SQLite busy timeout for every call. * * @returns Query results including rows, columns, and rows affected, or a filesystem error if execution failed. */ sqliteQuery(params: SessionFsSqliteQueryRequest): Promise; + /** + * Executes SQLite statements atomically on the provider-owned connection. + * + * @param params Statements to execute atomically. Providers apply busy handling for every call. + * + * @returns Per-statement results, or a classified transaction error. + */ + sqliteTransaction(params: SessionFsSqliteTransactionRequest): Promise; /** * Checks whether the per-session SQLite database already exists, without creating it. * @@ -18896,6 +21324,11 @@ export function registerClientSessionApiHandlers( if (!handler) throw new Error(`No sessionFs handler registered for session: ${params.sessionId}`); return handler.sqliteQuery(params); }); + connection.onRequest("sessionFs.sqliteTransaction", async (params: SessionFsSqliteTransactionRequest) => { + const handler = getHandlers(params.sessionId).sessionFs; + if (!handler) throw new Error(`No sessionFs handler registered for session: ${params.sessionId}`); + return handler.sqliteTransaction(params); + }); connection.onRequest("sessionFs.sqliteExists", async (params: SessionFsSqliteExistsRequest) => { const handler = getHandlers(params.sessionId).sessionFs; if (!handler) throw new Error(`No sessionFs handler registered for session: ${params.sessionId}`); diff --git a/nodejs/src/generated/session-events.ts b/nodejs/src/generated/session-events.ts index b9c9612b8f..193dc0defb 100644 --- a/nodejs/src/generated/session-events.ts +++ b/nodejs/src/generated/session-events.ts @@ -104,6 +104,7 @@ export type SessionEvent = | ExitPlanModeCompletedEvent | ToolsUpdatedEvent | BackgroundTasksChangedEvent + | FactoryRunUpdatedEvent | SkillsLoadedEvent | CustomAgentsUpdatedEvent | McpServersLoadedEvent @@ -156,6 +157,14 @@ export type Verbosity = | "medium" /** A more detailed response was requested. */ | "high"; +/** + * Who created the schedule: `user` (an explicit user action such as `/every` or `/after`) or `model` (the agent via the `manage_schedule` tool). Gates whether a scheduled skill that opted out of model invocation may fire: only user-created schedules may. + */ +export type ScheduleOrigin = + /** The schedule was created by an explicit user action, such as `/every` or `/after`. */ + | "user" + /** The schedule was created by the agent via the `manage_schedule` tool. */ + | "model"; /** * The type of operation performed on the autopilot objective state file */ @@ -233,6 +242,30 @@ export type ShutdownType = | "routine" /** The session ended because of a crash or fatal error. */ | "error"; +/** + * What initiated a conversation compaction + */ +export type CompactionTrigger = + /** Background compaction started automatically because context utilization crossed the background threshold. */ + | "threshold" + /** Compaction forced by a context-limit model response (e.g. HTTP 413) before retrying the request. */ + | "context_limit_retry" + /** User-requested compaction, e.g. the /compact command or the history.compact API. */ + | "manual" + /** Emergency compaction triggered by high process memory usage. */ + | "memory_pressure" + /** Compaction requested while switching to a model with a smaller context window. */ + | "model_switch"; +/** + * Semantic result of evaluating a task completion request + */ +export type TaskCompletionOutcome = + /** The completion request was accepted and the objective is complete. */ + | "completed" + /** The completion request was rejected because more work or validation remains. */ + | "continue" + /** Completion cannot proceed without intervention; the active objective is paused when one is identified. */ + | "blocked"; /** * The agent mode that was active when this message was sent */ @@ -475,7 +508,8 @@ export type SystemNotification = | SystemNotificationNewInboxMessage | SystemNotificationShellCompleted | SystemNotificationShellDetachedCompleted - | SystemNotificationInstructionDiscovered; + | SystemNotificationInstructionDiscovered + | SystemNotificationUnclassified; /** * Whether the agent completed successfully or failed */ @@ -529,6 +563,21 @@ export type PermissionPromptRequest = | PermissionPromptRequestHook | PermissionPromptRequestExtensionManagement | PermissionPromptRequestExtensionPermissionAccess; +/** + * Why the auto-approval judge produced no usable recommendation. Present only alongside an `error` recommendation, where the human-readable reason is a fixed string and therefore cannot distinguish these cases. Intended to make a judge failure reportable by a consumer that has no access to the host's logs. + */ +/** @experimental */ +export type AutoApprovalJudgeFailureReason = + /** The judge model call exceeded its deadline. */ + | "timeout" + /** The judge model call was cancelled before it returned. */ + | "abort" + /** The judge model call completed but returned no content. */ + | "empty_response" + /** The judge model call failed (for example a transport, authentication, or rate-limit error). */ + | "model_error" + /** The judge model replied, but the reply carried no ALLOW/DENY verdict. */ + | "parse_error"; /** * Outcome of the auto-approval safety judge for a permission request. Present only when auto mode is enabled; its absence means the judge did not evaluate the request (auto mode was off). */ @@ -900,6 +949,10 @@ export interface WorkingDirectoryContext { */ headCommit?: string; hostType?: WorkingDirectoryContextHostType; + /** + * Set on the immediate preliminary event of a working-directory change, before the git context is resolved. A settled follow-up event (enriched with git context, or cwd-only for a non-repository) is always emitted afterward, so observers may defer to it. Absent on standalone/final events (e.g. relay context changes). + */ + pendingGitContext?: boolean; /** * Repository identifier derived from the git remote URL ("owner/name" for GitHub, "org/project/repo" for Azure DevOps) */ @@ -962,7 +1015,7 @@ export interface ResumeData { */ contextTier?: ContextTier | null; /** - * When true, tool calls and permission requests left in flight by the previous session lifetime remain pending after resume and the agentic loop awaits their results. User sends are queued behind the pending work until all such requests reach a terminal state. When false (the default), any such tool calls and permission requests are immediately marked as interrupted on resume. + * When true, tool calls and permission requests left in flight by the previous session lifetime remain pending after resume and the agentic loop awaits their results. User sends are queued behind the pending work until all such requests reach a terminal state. When false or omitted, pending work is normally marked as interrupted unless the resume passively joined live work owned by another client; sessionWasActive distinguishes that case. */ continuePendingWork?: boolean; /** @@ -995,7 +1048,7 @@ export interface ResumeData { */ sessionLimits?: SessionLimitsConfig | null; /** - * True when this resume attached to a session that the runtime already had running in-memory (for example, an extension joining a session another client was actively driving). False (or omitted) for cold resumes — the runtime had to reconstitute the session from its persisted event log. + * True when this resume passively joined a session that already had live work running in the runtime - an agent turn, a native queue run, a queued resume continuation, or an in-flight send (for example, an extension joining a session another client was actively driving). False (or omitted) when the session had no live work or when the resume explicitly abandoned pending work, including cold resumes and suspended sessions that remain resident in memory. */ sessionWasActive?: boolean; verbosity?: Verbosity; @@ -1242,6 +1295,7 @@ export interface ScheduleCreatedData { * Interval between ticks in milliseconds (relative-interval schedules) */ intervalMs?: number; + origin?: ScheduleOrigin; /** * Prompt text that gets enqueued on every tick */ @@ -2363,6 +2417,10 @@ export interface CompactionStartData { * Token count from non-system messages (user, assistant, tool) at compaction start */ conversationTokens?: number; + /** + * Total context tokens (system + conversation + tool definitions) at compaction start, when known + */ + currentTokens?: number; /** * Model identifier used for compaction, when known */ @@ -2371,10 +2429,15 @@ export interface CompactionStartData { * Token count from system message(s) at compaction start */ systemTokens?: number; + /** + * Model context window token limit the compaction is targeting, when known + */ + tokenLimit?: number; /** * Token count from tool definitions at compaction start */ toolDefinitionsTokens?: number; + trigger?: CompactionTrigger; } /** * Session event "session.compaction_complete". Conversation compaction results including success status, metrics, and optional error details @@ -2471,6 +2534,10 @@ export interface CompactionCompleteData { * Token count from system message(s) after compaction */ systemTokens?: number; + /** + * Model context window token limit the compaction was targeting, when known + */ + tokenLimit?: number; /** * Number of tokens removed during compaction */ @@ -2479,6 +2546,7 @@ export interface CompactionCompleteData { * Token count from tool definitions after compaction */ toolDefinitionsTokens?: number; + trigger?: CompactionTrigger; } /** * Token usage breakdown for the compaction LLM call (aligned with assistant.usage format) @@ -2587,7 +2655,16 @@ export interface TaskCompleteEvent { */ export interface TaskCompleteData { /** - * Whether the tool call succeeded. False when validation failed (e.g., invalid arguments) + * Active autopilot objective ID evaluated by the completion reviewer + */ + objectiveId?: number; + outcome?: TaskCompletionOutcome; + /** + * Label-safe runtime rationale for the completion decision (e.g. a cancellation or pause/resume downgrade), when one applies. Reviewer-authored rationale is intentionally omitted here because this event has no IFC label channel; the reviewer's findings remain available through its own labeled sub-agent events + */ + reason?: string; + /** + * Whether the task was accepted as complete. False when validation failed or completion was rejected or blocked by the reviewer */ success?: boolean; /** @@ -2656,7 +2733,7 @@ export interface UserMessageData { */ parentAgentTaskId?: string; /** - * Origin of this message, used for timeline filtering (e.g., "skill-pdf" for skill-injected messages that should be hidden from the user) + * Origin of this message, used for timeline filtering and attribution (e.g., `skill-pdf` for hidden skill injection or `agent-` for an inter-agent prompt) */ source?: string; /** @@ -3365,6 +3442,7 @@ export interface AssistantReasoningData { * Unique identifier for this reasoning block */ reasoningId: string; + rte?: boolean; } /** * Session event "assistant.reasoning_delta". Streaming reasoning delta for incremental extended thinking updates @@ -3593,6 +3671,7 @@ export interface AssistantMessageData { * GitHub request tracing ID (x-github-request-id header) for correlating with server-side logs */ requestId?: string; + rte?: boolean; serverTools?: AssistantMessageServerTools; /** * Copilot service request ID (x-copilot-service-request-id header) for CAPI log correlation @@ -4037,6 +4116,10 @@ export interface AssistantUsageData { * Number of input tokens consumed */ inputTokens?: number; + /** + * Coarse classification of the interaction that produced this call, mirroring the session's per-request agent context (e.g. `conversation-agent`, `conversation-subagent`, `conversation-sampling`, `conversation-background`, `conversation-compaction`, `conversation-user`). Non-billing; lets consumers attribute a model call to a call class (e.g. sub-agent/sidekick) independently of the billing initiator. Absent when the runtime did not classify the request. + */ + interactionType?: string; /** * Average inter-token latency in milliseconds. Only available for streaming requests */ @@ -4074,6 +4157,7 @@ export interface AssistantUsageData { * Number of output tokens used for reasoning (e.g., chain-of-thought) */ reasoningTokens?: number; + rte?: boolean; /** * Copilot service request ID (x-copilot-service-request-id header) for CAPI log correlation */ @@ -4289,6 +4373,7 @@ export interface ModelCallFailureData { */ reasoningEffort?: string; requestFingerprint?: ModelCallFailureRequestFingerprint; + rte?: boolean; /** * Copilot service request ID (x-copilot-service-request-id header) for CAPI log correlation */ @@ -4372,6 +4457,12 @@ export interface ModelCallStartData { * Model identifier used for this API call, when known */ model?: string; + /** + * Previous response or interaction identifier included in the model request, when present + * + * @internal + */ + previousResponseId?: string; /** * Identifier of the assistant turn that initiated the model call */ @@ -4523,6 +4614,7 @@ export interface ToolExecutionStartData { * Tool call ID of the parent tool invocation when this event originates from a sub-agent */ parentToolCallId?: string; + rte?: boolean; shellToolInfo?: ToolExecutionStartShellToolInfo; /** * Unique identifier for this tool call @@ -4731,6 +4823,7 @@ export interface ToolExecutionCompleteData { */ parentToolCallId?: string; result?: ToolExecutionCompleteResult; + rte?: boolean; /** * Whether this tool execution ran inside a sandbox container */ @@ -5863,6 +5956,10 @@ export interface SystemMessageData { * The system or developer prompt text sent as model input */ content: string; + /** + * Logical interaction identifier for the model run receiving this prompt + */ + interactionId?: string; metadata?: SystemMessageMetadata; /** * Optional name identifier for the message source @@ -6060,6 +6157,21 @@ export interface SystemNotificationInstructionDiscovered { */ type: "instruction_discovered"; } +/** + * System notification metadata from an external host that does not match a runtime-owned notification kind. + */ +export interface SystemNotificationUnclassified { + /** + * Opaque metadata supplied by the external host, when present. + */ + metadata?: { + [k: string]: unknown | undefined; + }; + /** + * Type discriminator. Always "unclassified". + */ + type: "unclassified"; +} /** * Session event "permission.requested". Permission request notification requiring client approval with request details */ @@ -6104,6 +6216,12 @@ export interface PermissionRequestedData { * When true, this permission was already resolved by a permissionRequest hook and requires no client action */ resolvedByHook?: boolean; + /** + * Neutral risk metadata supplied by the tool host. Consumers may display this value but must not use it to bypass the permission decision. + */ + riskAssessment?: { + [k: string]: unknown | undefined; + }; } /** * Shell command permission request @@ -6117,6 +6235,10 @@ export interface PermissionRequestShell { * Parsed command identifiers found in the command text */ commands: PermissionRequestShellCommand[]; + /** + * Parsed command segments, including arguments, used for managed policy matching + */ + commandSegments?: PermissionRequestShellCommandSegment[]; /** * The complete shell command text to be executed */ @@ -6133,6 +6255,10 @@ export interface PermissionRequestShell { * Permission kind discriminator */ kind: "shell"; + /** + * Whether managed policy requires a human response and forbids host auto-approval + */ + managedApprovalRequired?: boolean; /** * File paths that may be read or written by the command */ @@ -6171,6 +6297,19 @@ export interface PermissionRequestShellCommand { */ readOnly: boolean; } +/** + * A parsed shell command segment used for argument-aware managed policy matching. + */ +export interface PermissionRequestShellCommandSegment { + /** + * Full text of this command segment, including arguments + */ + fullCommandText: string; + /** + * Command identifier (e.g., executable name) + */ + identifier: string; +} /** * A URL that may be accessed by a command in a shell permission request. */ @@ -6204,6 +6343,10 @@ export interface PermissionRequestWrite { * Permission kind discriminator */ kind: "write"; + /** + * Whether managed policy requires a human response and forbids host auto-approval + */ + managedApprovalRequired?: boolean; /** * Complete new file contents for newly created files */ @@ -6233,6 +6376,10 @@ export interface PermissionRequestRead { * Permission kind discriminator */ kind: "read"; + /** + * Whether managed policy requires a human response and forbids host auto-approval + */ + managedApprovalRequired?: boolean; /** * Path of the file or directory being read */ @@ -6297,6 +6444,14 @@ export interface PermissionRequestUrl { * Permission kind discriminator */ kind: "url"; + /** + * Whether managed policy requires a human response and forbids host auto-approval + */ + managedApprovalRequired?: boolean; + /** + * Immediately preceding URL when this request is for a redirect target + */ + redirectedFrom?: string; /** * True when this URL fetch is requesting to bypass the sandbox network policy: either the model set requestSandboxBypass: true, or the tool re-issued the request as an interactive bypass after the network policy denied the approved URL (host opted in via sandbox.allowBypass). This is a request, not a grant: the fetch runs only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. */ @@ -6471,6 +6626,10 @@ export interface PermissionPromptRequestCommands { * Prompt kind discriminator */ kind: "commands"; + /** + * Whether managed policy requires a human response and forbids host auto-approval + */ + managedApprovalRequired?: boolean; /** * Tool call ID that triggered this permission request */ @@ -6485,6 +6644,11 @@ export interface PermissionPromptRequestCommands { */ /** @experimental */ export interface PermissionAutoApproval { + failureReason?: AutoApprovalJudgeFailureReason; + /** + * Model id that produced the recommendation, when the judge was consulted and reported one. Absent for `excluded` (the judge was not consulted) and for failures that occurred before a model was selected. + */ + model?: string; /** * Human-readable reason for the judge's recommendation, when available. */ @@ -6521,6 +6685,10 @@ export interface PermissionPromptRequestWrite { * Prompt kind discriminator */ kind: "write"; + /** + * Whether managed policy requires a human response and forbids host auto-approval + */ + managedApprovalRequired?: boolean; /** * Complete new file contents for newly created files */ @@ -6548,6 +6716,10 @@ export interface PermissionPromptRequestRead { * Prompt kind discriminator */ kind: "read"; + /** + * Whether managed policy requires a human response and forbids host auto-approval + */ + managedApprovalRequired?: boolean; /** * Path of the file or directory being read */ @@ -6612,6 +6784,14 @@ export interface PermissionPromptRequestUrl { * Prompt kind discriminator */ kind: "url"; + /** + * Whether managed policy requires a human response and forbids host auto-approval + */ + managedApprovalRequired?: boolean; + /** + * Immediately preceding URL when this prompt is for a redirect target + */ + redirectedFrom?: string; /** * True when this URL fetch is requesting to bypass the sandbox network policy: either the model set requestSandboxBypass: true, or the tool re-issued the request as an interactive bypass after the network policy denied the approved URL (host opted in via sandbox.allowBypass). This is a request, not a grant: the fetch runs only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. */ @@ -8177,6 +8357,10 @@ export interface AutoModeResolvedEvent { */ /** @experimental */ export interface AutoModeResolvedData { + /** + * Models offered to the router for this resolution + */ + availableModels?: string[]; /** * Ordered candidate model list the router returned, when not a fallback */ @@ -8191,15 +8375,47 @@ export interface AutoModeResolvedData { * The concrete model the session will use after any intent refinement */ chosenModel: string; + /** + * The chosen model's score shortfall relative to the top candidate + */ + chosenShortfall?: number; /** * Classifier confidence for the predicted label, when available */ confidence?: number; + /** + * End-to-end client wait time for the router request in milliseconds + */ + endToEndLatencyMs?: number; + /** + * Whether the router fell back to the standard Auto selection + */ + fallback?: boolean; + /** + * Server-provided reason for falling back, when available + */ + fallbackReason?: string; + /** + * Whether the routed prompt contained an image + */ + hasImage?: boolean; /** * The predicted classifier label (e.g. `needs_reasoning`), when available */ predictedLabel?: string; reasoningBucket?: AutoModeResolvedReasoningBucket; + /** + * Server-reported router processing time in milliseconds + */ + routerLatencyMs?: number; + /** + * The routing method the server applied, when Auto Intent ran + */ + routingMethod?: string; + /** + * Whether a sticky model choice overrode the router result + */ + stickyOverride?: boolean; } /** * Session event "session.managed_settings_resolved". Enterprise managed-settings resolution: the effective managed settings the session applied and where they came from, so SDK clients can show users what is enterprise-managed and by which authority. Fires whenever managed policy is (re)applied — at session start, on resume, and on account switch. This is an ephemeral live snapshot (delivered to subscribers but not persisted to the session event log), because at session start it resolves before `session.start` is emitted; for a session-independent pull, use the SDK `getManagedSettings()` API, which returns the identical payload. Managed settings have a single authoritative source, so the highest-authority present layer (server > device) wins wholesale; `bypassPermissionsDisabled` is deny-wins across layers. Marked experimental while the managed-settings surface stabilizes. @@ -8253,6 +8469,10 @@ export interface ManagedSettingsResolvedData { * The setting keys under enterprise management in the effective managed settings (e.g. `model`, `enabledPlugins`, `permissions`). Empty when no managed settings are in force. */ managedKeys: string[]; + /** + * Whether server and device each supplied a permission allowlist, so enforcement intersects them and the flattened settings payload omits `permissions.allow`. + */ + permissionsAllowIntersected?: boolean; /** * Whether the server (account/org) managed-settings layer was present */ @@ -8598,6 +8818,48 @@ export interface BackgroundTasksChangedEvent { * Empty payload for `session.background_tasks_changed`, indicating background task state changed. */ export interface BackgroundTasksChangedData {} +/** + * Session event "factory.run_updated". Ephemeral invalidation signal for a changed factory run. + */ +/** @experimental */ +export interface FactoryRunUpdatedEvent { + /** + * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. + */ + agentId?: string; + data: FactoryRunUpdatedData; + /** + * Always true for events that are transient and not persisted to the session event log on disk. + */ + ephemeral: true; + /** + * Unique event identifier (UUID v4), generated when the event is emitted + */ + id: string; + /** + * ID of the chronologically preceding event in the session, forming a linked chain. Null for the first event. + */ + parentId: string | null; + /** + * ISO 8601 timestamp when the event was created + */ + timestamp: string; + /** + * Type discriminator. Always "factory.run_updated". + */ + type: "factory.run_updated"; +} +/** + * Ephemeral invalidation signal for a changed factory run. + */ +/** @experimental */ +export interface FactoryRunUpdatedData { + /** + * Monotonic revision now available for the run. + */ + revision: number; + runId: string; +} /** * Session event "session.skills_loaded". Payload of `session.skills_loaded` listing resolved skill metadata. */ diff --git a/python/copilot/generated/rpc.py b/python/copilot/generated/rpc.py index 713e78cca0..500a16eb76 100644 --- a/python/copilot/generated/rpc.py +++ b/python/copilot/generated/rpc.py @@ -1015,38 +1015,6 @@ def to_dict(self) -> dict: result["input"] = from_union([from_str, from_none], self.input) return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class CommandsListRequest: - """Optional filters controlling which command sources to include in the listing.""" - - include_builtins: bool | None = None - """Include runtime built-in commands""" - - include_client_commands: bool | None = None - """Include commands registered by protocol clients, including SDK clients and extensions""" - - include_skills: bool | None = None - """Include enabled user-invocable skills and commands""" - - @staticmethod - def from_dict(obj: Any) -> 'CommandsListRequest': - assert isinstance(obj, dict) - include_builtins = from_union([from_bool, from_none], obj.get("includeBuiltins")) - include_client_commands = from_union([from_bool, from_none], obj.get("includeClientCommands")) - include_skills = from_union([from_bool, from_none], obj.get("includeSkills")) - return CommandsListRequest(include_builtins, include_client_commands, include_skills) - - def to_dict(self) -> dict: - result: dict = {} - if self.include_builtins is not None: - result["includeBuiltins"] = from_union([from_bool, from_none], self.include_builtins) - if self.include_client_commands is not None: - result["includeClientCommands"] = from_union([from_bool, from_none], self.include_client_commands) - if self.include_skills is not None: - result["includeSkills"] = from_union([from_bool, from_none], self.include_skills) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class CommandsRespondToQueuedCommandRequest: @@ -1093,29 +1061,6 @@ def to_dict(self) -> dict: result["success"] = from_bool(self.success) return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class CompletionsGetTriggerCharactersResult: - """Characters that, when typed in the composer, should trigger a `completions.request`. - Empty when the session has no host-driven completions (e.g. local sessions, or a relay - host that does not advertise `completionTriggerCharacters`). - """ - trigger_characters: list[str] - """Trigger characters advertised by the host (e.g. `["@", "#"]`). Empty disables host-driven - completions for the session. - """ - - @staticmethod - def from_dict(obj: Any) -> 'CompletionsGetTriggerCharactersResult': - assert isinstance(obj, dict) - trigger_characters = from_list(from_str, obj.get("triggerCharacters")) - return CompletionsGetTriggerCharactersResult(trigger_characters) - - def to_dict(self) -> dict: - result: dict = {} - result["triggerCharacters"] = from_list(from_str, self.trigger_characters) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class CompletionsRequestRequest: @@ -1244,11 +1189,14 @@ class _ConnectRequest: enable_git_hub_telemetry_forwarding: bool | None = None """Opt this connection in to GitHub telemetry forwarding for its lifetime. When set, the runtime forwards every internal telemetry event it emits — across all sessions, plus - sessionless events — to this connection over the `gitHubTelemetry.event` notification, in - addition to the runtime's normal GitHub/CTS emission (dual-write). Intended for - first-party hosts that re-emit the events into their own telemetry stores. Both - unrestricted and restricted events are forwarded, each tagged with a `restricted` - discriminator; a backstop drops restricted events when restricted telemetry is disabled. + sessionless events — to this connection over the `gitHubTelemetry.event` notification. + Regular events are also written to the runtime's normal GitHub/CTS path (dual-write); + host-only compatibility events are forward-only and intentionally skip that path. + Intended for first-party hosts that re-emit the events into their own telemetry stores. + Both unrestricted and restricted events are forwarded, each tagged with a `restricted` + discriminator; a backstop drops restricted events when restricted telemetry is disabled — + using the process-global gate for ordinary events and an explicit session-scoped decision + for host-only events. """ token: str | None = None """Connection token; required when the server was started with COPILOT_CONNECTION_TOKEN""" @@ -1334,6 +1282,52 @@ def to_dict(self) -> dict: result["owner"] = from_str(self.owner) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class ContentExclusionCheckPathsRequest: + """Local file system absolute paths within the session working directory to check against + its content-exclusion policy. + """ + paths: list[str] + """Local file system absolute paths within the session working directory to check. Results + are returned in the same order, including duplicates. + """ + + @staticmethod + def from_dict(obj: Any) -> 'ContentExclusionCheckPathsRequest': + assert isinstance(obj, dict) + paths = from_list(from_str, obj.get("paths")) + return ContentExclusionCheckPathsRequest(paths) + + def to_dict(self) -> dict: + result: dict = {} + result["paths"] = from_list(from_str, self.paths) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class ContentExclusionPathCheck: + """Content-exclusion decision for one requested path.""" + + excluded: bool + """Whether the session's complete content-exclusion policy excludes the path.""" + + path: str + """The path supplied by the caller.""" + + @staticmethod + def from_dict(obj: Any) -> 'ContentExclusionPathCheck': + assert isinstance(obj, dict) + excluded = from_bool(obj.get("excluded")) + path = from_str(obj.get("path")) + return ContentExclusionPathCheck(excluded, path) + + def to_dict(self) -> dict: + result: dict = {} + result["excluded"] = from_bool(self.excluded) + result["path"] = from_str(self.path) + return result + # Experimental: this type is part of an experimental API and may change or be removed. class ContentFilterMode(Enum): """Controls how MCP tool result content is filtered: none leaves content unchanged, markdown @@ -2177,6 +2171,65 @@ def to_dict(self) -> dict: result["result"] = self.result return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class FactoryAgentSummary: + """Prompt-safe durable identity and live status for a direct factory agent.""" + + active_ms: int + agent_id: str + agent_type: str + label: str + run_id: str + status: str + tool_call_id: str + activity: str | None = None + completed_at: int | None = None + phase_id: str | None = None + requested_model: str | None = None + resolved_model: str | None = None + started_at: int | None = None + + @staticmethod + def from_dict(obj: Any) -> 'FactoryAgentSummary': + assert isinstance(obj, dict) + active_ms = from_int(obj.get("activeMs")) + agent_id = from_str(obj.get("agentId")) + agent_type = from_str(obj.get("agentType")) + label = from_str(obj.get("label")) + run_id = from_str(obj.get("runId")) + status = from_str(obj.get("status")) + tool_call_id = from_str(obj.get("toolCallId")) + activity = from_union([from_str, from_none], obj.get("activity")) + completed_at = from_union([from_int, from_none], obj.get("completedAt")) + phase_id = from_union([from_none, from_str], obj.get("phaseId")) + requested_model = from_union([from_str, from_none], obj.get("requestedModel")) + resolved_model = from_union([from_str, from_none], obj.get("resolvedModel")) + started_at = from_union([from_int, from_none], obj.get("startedAt")) + return FactoryAgentSummary(active_ms, agent_id, agent_type, label, run_id, status, tool_call_id, activity, completed_at, phase_id, requested_model, resolved_model, started_at) + + def to_dict(self) -> dict: + result: dict = {} + result["activeMs"] = from_int(self.active_ms) + result["agentId"] = from_str(self.agent_id) + result["agentType"] = from_str(self.agent_type) + result["label"] = from_str(self.label) + result["runId"] = from_str(self.run_id) + result["status"] = from_str(self.status) + result["toolCallId"] = from_str(self.tool_call_id) + if self.activity is not None: + result["activity"] = from_union([from_str, from_none], self.activity) + if self.completed_at is not None: + result["completedAt"] = from_union([from_int, from_none], self.completed_at) + result["phaseId"] = from_union([from_none, from_str], self.phase_id) + if self.requested_model is not None: + result["requestedModel"] = from_union([from_str, from_none], self.requested_model) + if self.resolved_model is not None: + result["resolvedModel"] = from_union([from_str, from_none], self.resolved_model) + if self.started_at is not None: + result["startedAt"] = from_union([from_int, from_none], self.started_at) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class FactoryCancelRequest: @@ -2196,6 +2249,75 @@ def to_dict(self) -> dict: result["runId"] = from_str(self.run_id) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class FactoryCurrentPhase: + """Current factory phase identity.""" + + id: str + ordinal: int | None = None + + @staticmethod + def from_dict(obj: Any) -> 'FactoryCurrentPhase': + assert isinstance(obj, dict) + id = from_str(obj.get("id")) + ordinal = from_union([from_none, from_int], obj.get("ordinal")) + return FactoryCurrentPhase(id, ordinal) + + def to_dict(self) -> dict: + result: dict = {} + result["id"] = from_str(self.id) + result["ordinal"] = from_union([from_none, from_int], self.ordinal) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class FactoryDeclaredLimits: + """Declared or approved factory resource ceilings.""" + + max_ai_credits: float | None = None + max_concurrent_subagents: int | None = None + max_total_subagents: int | None = None + timeout_seconds: float | None = None + + @staticmethod + def from_dict(obj: Any) -> 'FactoryDeclaredLimits': + assert isinstance(obj, dict) + max_ai_credits = from_union([from_float, from_none], obj.get("maxAiCredits")) + max_concurrent_subagents = from_union([from_int, from_none], obj.get("maxConcurrentSubagents")) + max_total_subagents = from_union([from_int, from_none], obj.get("maxTotalSubagents")) + timeout_seconds = from_union([from_float, from_none], obj.get("timeoutSeconds")) + return FactoryDeclaredLimits(max_ai_credits, max_concurrent_subagents, max_total_subagents, timeout_seconds) + + def to_dict(self) -> dict: + result: dict = {} + if self.max_ai_credits is not None: + result["maxAiCredits"] = from_union([to_float, from_none], self.max_ai_credits) + if self.max_concurrent_subagents is not None: + result["maxConcurrentSubagents"] = from_union([from_int, from_none], self.max_concurrent_subagents) + if self.max_total_subagents is not None: + result["maxTotalSubagents"] = from_union([from_int, from_none], self.max_total_subagents) + if self.timeout_seconds is not None: + result["timeoutSeconds"] = from_union([to_float, from_none], self.timeout_seconds) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +class FactoryDurableOperation(Enum): + """Execution-critical factory storage operation. + + Execution-critical durable operation that failed. + """ + ADD_ELAPSED = "addElapsed" + CHARGE_CREDIT = "chargeCredit" + CREATE_RUN = "createRun" + FINISH_RUN = "finishRun" + JOURNAL_GET = "journalGet" + JOURNAL_PUT = "journalPut" + MARK_RUN_STARTED = "markRunStarted" + RECONCILE_CREDIT_TOTAL = "reconcileCreditTotal" + RELEASE_AGENT = "releaseAgent" + RESERVE_AGENT = "reserveAgent" + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class FactoryExecuteRequest: @@ -2204,6 +2326,9 @@ class FactoryExecuteRequest: args: Any """Factory input value.""" + execution_token: str + """Opaque token identifying this factory execution attempt.""" + name: str """Registered factory name.""" @@ -2217,14 +2342,16 @@ class FactoryExecuteRequest: def from_dict(obj: Any) -> 'FactoryExecuteRequest': assert isinstance(obj, dict) args = obj.get("args") + execution_token = from_str(obj.get("executionToken")) name = from_str(obj.get("name")) run_id = from_str(obj.get("runId")) session_id = from_str(obj.get("sessionId")) - return FactoryExecuteRequest(args, name, run_id, session_id) + return FactoryExecuteRequest(args, execution_token, name, run_id, session_id) def to_dict(self) -> dict: result: dict = {} result["args"] = self.args + result["executionToken"] = from_str(self.execution_token) result["name"] = from_str(self.name) result["runId"] = from_str(self.run_id) result["sessionId"] = from_str(self.session_id) @@ -2235,7 +2362,7 @@ def to_dict(self) -> dict: class FactoryExecuteResult: """Result returned by an extension factory closure.""" - result: Any + result: Any = None """Factory result value.""" @staticmethod @@ -2246,7 +2373,51 @@ def from_dict(obj: Any) -> 'FactoryExecuteResult': def to_dict(self) -> dict: result: dict = {} - result["result"] = self.result + if self.result is not None: + result["result"] = self.result + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class FactoryGetRunProgressRequest: + """Parameters for paging factory progress.""" + + run_id: str + """Factory run identifier.""" + + after_seq: int | None = None + """Exclusive forward cursor.""" + + before_seq: int | None = None + """Exclusive backward cursor.""" + + limit: int | None = None + """Maximum records to return. Defaults to 200 and is capped at 500.""" + + phase_id: str | None = None + """Optional phase identifier used to scope records and cursors.""" + + @staticmethod + def from_dict(obj: Any) -> 'FactoryGetRunProgressRequest': + assert isinstance(obj, dict) + run_id = from_str(obj.get("runId")) + after_seq = from_union([from_int, from_none], obj.get("afterSeq")) + before_seq = from_union([from_int, from_none], obj.get("beforeSeq")) + limit = from_union([from_int, from_none], obj.get("limit")) + phase_id = from_union([from_str, from_none], obj.get("phaseId")) + return FactoryGetRunProgressRequest(run_id, after_seq, before_seq, limit, phase_id) + + def to_dict(self) -> dict: + result: dict = {} + result["runId"] = from_str(self.run_id) + if self.after_seq is not None: + result["afterSeq"] = from_union([from_int, from_none], self.after_seq) + if self.before_seq is not None: + result["beforeSeq"] = from_union([from_int, from_none], self.before_seq) + if self.limit is not None: + result["limit"] = from_union([from_int, from_none], self.limit) + if self.phase_id is not None: + result["phaseId"] = from_union([from_str, from_none], self.phase_id) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -2273,6 +2444,9 @@ def to_dict(self) -> dict: class FactoryJournalGetRequest: """Parameters for reading a factory journal entry.""" + execution_token: str + """Opaque token identifying the current factory execution attempt.""" + key: str """Namespaced journal key.""" @@ -2282,12 +2456,14 @@ class FactoryJournalGetRequest: @staticmethod def from_dict(obj: Any) -> 'FactoryJournalGetRequest': assert isinstance(obj, dict) + execution_token = from_str(obj.get("executionToken")) key = from_str(obj.get("key")) run_id = from_str(obj.get("runId")) - return FactoryJournalGetRequest(key, run_id) + return FactoryJournalGetRequest(execution_token, key, run_id) def to_dict(self) -> dict: result: dict = {} + result["executionToken"] = from_str(self.execution_token) result["key"] = from_str(self.key) result["runId"] = from_str(self.run_id) return result @@ -2322,6 +2498,9 @@ def to_dict(self) -> dict: class FactoryJournalPutRequest: """Parameters for storing a factory journal entry.""" + execution_token: str + """Opaque token identifying the current factory execution attempt.""" + key: str """Namespaced journal key.""" @@ -2334,26 +2513,69 @@ class FactoryJournalPutRequest: @staticmethod def from_dict(obj: Any) -> 'FactoryJournalPutRequest': assert isinstance(obj, dict) + execution_token = from_str(obj.get("executionToken")) key = from_str(obj.get("key")) result_json = obj.get("resultJson") run_id = from_str(obj.get("runId")) - return FactoryJournalPutRequest(key, result_json, run_id) + return FactoryJournalPutRequest(execution_token, key, result_json, run_id) def to_dict(self) -> dict: result: dict = {} + result["executionToken"] = from_str(self.execution_token) result["key"] = from_str(self.key) result["resultJson"] = self.result_json result["runId"] = from_str(self.run_id) return result # Experimental: this type is part of an experimental API and may change or be removed. -class FactoryLogLineKind(Enum): - """Progress line kind. +@dataclass +class FactoryListRunsRequest: + """Empty parameters for listing factory runs.""" + @staticmethod + def from_dict(obj: Any) -> 'FactoryListRunsRequest': + assert isinstance(obj, dict) + return FactoryListRunsRequest() - Kind of factory progress line. + def to_dict(self) -> dict: + result: dict = {} + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class FactoryRunConsumed: + """Durable factory resource consumption.""" + + active_ms: int + nano_aiu: int + subagents: int + + @staticmethod + def from_dict(obj: Any) -> 'FactoryRunConsumed': + assert isinstance(obj, dict) + active_ms = from_int(obj.get("activeMs")) + nano_aiu = from_int(obj.get("nanoAiu")) + subagents = from_int(obj.get("subagents")) + return FactoryRunConsumed(active_ms, nano_aiu, subagents) + + def to_dict(self) -> dict: + result: dict = {} + result["activeMs"] = from_int(self.active_ms) + result["nanoAiu"] = from_int(self.nano_aiu) + result["subagents"] = from_int(self.subagents) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +class FactoryRunStatus(Enum): + """Current or terminal state of a factory run. + + Current or terminal factory run status. """ - LOG = "log" - PHASE = "phase" + CANCELLED = "cancelled" + COMPLETED = "completed" + ERROR = "error" + HALTED = "halted" + PENDING = "pending" + RUNNING = "running" # Experimental: this type is part of an experimental API and may change or be removed. class FactoryRunFailureKind(Enum): @@ -2361,60 +2583,81 @@ class FactoryRunFailureKind(Enum): Cumulative resource ceiling that stopped a factory run. """ + MAX_AI_CREDITS = "maxAiCredits" MAX_TOTAL_SUBAGENTS = "maxTotalSubagents" - TIMEOUT = "timeout" + TIMEOUT_SECONDS = "timeoutSeconds" class FactoryRunFailureType(Enum): + FACTORY_DURABLE_FAILURE = "factory_durable_failure" FACTORY_LIMIT_REACHED = "factory_limit_reached" FACTORY_RESUME_DECLINED = "factory_resume_declined" +# Experimental: this type is part of an experimental API and may change or be removed. +class FactoryLogLineKind(Enum): + """Progress line kind. + + Kind of factory progress line. + + Progress record kind. + """ + LOG = "log" + PHASE = "phase" + +# Experimental: this type is part of an experimental API and may change or be removed. +class FactoryPhaseStatus(Enum): + """Derived lifecycle state of a factory phase.""" + + ACTIVE = "active" + COMPLETED = "completed" + PENDING = "pending" + SKIPPED = "skipped" + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class FactoryRunLimits: - """Wire-only per-invocation factory resource ceiling overrides. + """Optional per-invocation resource ceiling overrides. + + Wire-only per-invocation factory resource ceiling overrides. Per-invocation resource ceiling overrides. """ + max_ai_credits: float | None = None + """Maximum AI credits consumed by factory subagents and their descendants. The post-paid + ceiling is soft: parallel turns can settle beyond it before the run stops. + """ max_concurrent_subagents: int | None = None """Maximum number of factory subagents that may run concurrently.""" max_total_subagents: int | None = None """Maximum total number of factory subagents that may be admitted.""" - timeout: float | None = None - """Factory active-run timeout in milliseconds.""" + timeout_seconds: float | None = None + """Maximum accumulated active-execution time in seconds. Active execution includes the + entire extension body, subprocess waits, queued-agent waits, and sleeps; time between + resumed attempts is not counted. + """ @staticmethod def from_dict(obj: Any) -> 'FactoryRunLimits': assert isinstance(obj, dict) + max_ai_credits = from_union([from_float, from_none], obj.get("maxAiCredits")) max_concurrent_subagents = from_union([from_int, from_none], obj.get("maxConcurrentSubagents")) max_total_subagents = from_union([from_int, from_none], obj.get("maxTotalSubagents")) - timeout = from_union([from_float, from_none], obj.get("timeout")) - return FactoryRunLimits(max_concurrent_subagents, max_total_subagents, timeout) + timeout_seconds = from_union([from_float, from_none], obj.get("timeoutSeconds")) + return FactoryRunLimits(max_ai_credits, max_concurrent_subagents, max_total_subagents, timeout_seconds) def to_dict(self) -> dict: result: dict = {} + if self.max_ai_credits is not None: + result["maxAiCredits"] = from_union([to_float, from_none], self.max_ai_credits) if self.max_concurrent_subagents is not None: result["maxConcurrentSubagents"] = from_union([from_int, from_none], self.max_concurrent_subagents) if self.max_total_subagents is not None: result["maxTotalSubagents"] = from_union([from_int, from_none], self.max_total_subagents) - if self.timeout is not None: - result["timeout"] = from_union([to_float, from_none], self.timeout) + if self.timeout_seconds is not None: + result["timeoutSeconds"] = from_union([to_float, from_none], self.timeout_seconds) return result -# Experimental: this type is part of an experimental API and may change or be removed. -class FactoryRunStatus(Enum): - """Current or terminal factory run status. - - Current or terminal state of a factory run. - """ - CANCELLED = "cancelled" - COMPLETED = "completed" - ERROR = "error" - HALTED = "halted" - PENDING = "pending" - RUNNING = "running" - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class FleetStartRequest: @@ -2694,25 +2937,160 @@ def to_dict(self) -> dict: return result # Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class HistoryCompactRequest: - """Optional compaction parameters.""" +class HistoryFileRestoreSkipReason(Enum): + """Reason a captured file was not restored. - custom_instructions: str | None = None - """Optional user-provided instructions to focus the compaction summary""" + Reason the file was not restored. + """ + SKIPPED_CAPTURE = "skipped-capture" + USER_MODIFIED = "user-modified" + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class HistoryRewindPoint: + """A root user turn that the session can rewind to.""" + + can_restore_files: bool + """Whether at least one file in this turn or a later turn can be restored.""" + + event_id: str + """ID of the user.message event that begins the discarded suffix.""" + + file_count: int + """Number of unique files in this turn and all later turns that have captured changes.""" + + is_autopilot_continuation: bool + """Whether this turn was an automatically injected autopilot continuation.""" + + lines_added: int + """Lines added by this turn's captured file changes.""" + + lines_removed: int + """Lines removed by this turn's captured file changes.""" + + timestamp: str + """ISO timestamp of the user turn.""" + + turn_changed_files: bool + """Whether this turn itself captured any file changes.""" + + user_message: str + """User-visible message text for the turn.""" @staticmethod - def from_dict(obj: Any) -> 'HistoryCompactRequest': + def from_dict(obj: Any) -> 'HistoryRewindPoint': assert isinstance(obj, dict) - custom_instructions = from_union([from_str, from_none], obj.get("customInstructions")) - return HistoryCompactRequest(custom_instructions) + can_restore_files = from_bool(obj.get("canRestoreFiles")) + event_id = from_str(obj.get("eventId")) + file_count = from_int(obj.get("fileCount")) + is_autopilot_continuation = from_bool(obj.get("isAutopilotContinuation")) + lines_added = from_int(obj.get("linesAdded")) + lines_removed = from_int(obj.get("linesRemoved")) + timestamp = from_str(obj.get("timestamp")) + turn_changed_files = from_bool(obj.get("turnChangedFiles")) + user_message = from_str(obj.get("userMessage")) + return HistoryRewindPoint(can_restore_files, event_id, file_count, is_autopilot_continuation, lines_added, lines_removed, timestamp, turn_changed_files, user_message) 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) + result["canRestoreFiles"] = from_bool(self.can_restore_files) + result["eventId"] = from_str(self.event_id) + result["fileCount"] = from_int(self.file_count) + result["isAutopilotContinuation"] = from_bool(self.is_autopilot_continuation) + result["linesAdded"] = from_int(self.lines_added) + result["linesRemoved"] = from_int(self.lines_removed) + result["timestamp"] = from_str(self.timestamp) + result["turnChangedFiles"] = from_bool(self.turn_changed_files) + result["userMessage"] = from_str(self.user_message) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +class HistoryRewindUnavailableReason(Enum): + """Why the listed points could not be produced, when applicable; the points list is empty + whenever it is set. `unsupported-remote-session` is permanent for the session and comes + with `fileChangeTrackingEnabled: false`. `session-busy` is transient and only ever + reported by a session that *is* tracking (`fileChangeTrackingEnabled: true`), because the + file-change captures cannot be read while work that may still mutate them is in flight; + the same request succeeds once the session settles, so a client that wants points should + retry rather than treat it as a failure. It is never `file-change-tracking-disabled`: an + untracked local session still lists conversation-only points and reports that through + `fileChangeTrackingEnabled: false`. + + Reason a rewind read (rewind points, file-restore preview, or session diff) could not be + answered from the session's file-change captures. + + Why file restore is unavailable, when applicable. Populated only when `available` is + false and never set when `available` is true. + + Why the session diff could not be produced, when applicable. Set only when `session` mode + was requested and `isFallback` is true, so a client can tell the permanent + `file-change-tracking-disabled` apart from the transient `session-busy`, which the same + request answers once the session settles. Never set for `unstaged` or `branch` mode, and + never `unsupported-remote-session`: a remote session's captures live on its own host, so + a `session`-mode diff is rejected for one rather than answered with a controller-side + fallback. + """ + FILE_CHANGE_TRACKING_DISABLED = "file-change-tracking-disabled" + SESSION_BUSY = "session-busy" + UNSUPPORTED_REMOTE_SESSION = "unsupported-remote-session" + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class HistoryPreviewRewindRequest: + """Event boundary to preview for conversation-and-files rewind.""" + + event_id: str + """ID of the user.message event that begins the discarded suffix.""" + + @staticmethod + def from_dict(obj: Any) -> 'HistoryPreviewRewindRequest': + assert isinstance(obj, dict) + event_id = from_str(obj.get("eventId")) + return HistoryPreviewRewindRequest(event_id) + + def to_dict(self) -> dict: + result: dict = {} + result["eventId"] = from_str(self.event_id) return result +# Experimental: this type is part of an experimental API and may change or be removed. +class HistoryRewindChangeType(Enum): + """Aggregate change made across the discarded turns. + + Aggregate file change represented by a rewind preview. + """ + CREATED = "created" + DELETED = "deleted" + MODIFIED = "modified" + +# Experimental: this type is part of an experimental API and may change or be removed. +class HistoryRewindMode(Enum): + """Scope of a rewind operation. + + Whether to rewind only conversation history or also restore captured files. + """ + CONVERSATION = "conversation" + CONVERSATION_AND_FILES = "conversation-and-files" + +# Experimental: this type is part of an experimental API and may change or be removed. +class HistoryRewindOutcome(Enum): + """Outcome of a rewind request. + + Overall rewind outcome. This discriminates the result: it governs which of the remaining + fields are populated, so consumers must switch on it before reading `eventsRemoved`, + `restoredFiles`, `skippedFiles`, or `error`. See each field for the outcomes that + populate it. + """ + CHECKPOINT_CLEANUP_FAILED = "checkpoint-cleanup-failed" + FILES_ROLLED_BACK = "files-rolled-back" + FILE_CHANGE_TRACKING_DISABLED = "file-change-tracking-disabled" + ROLLBACK_INCOMPLETE = "rollback-incomplete" + SESSION_BUSY = "session-busy" + SNAPSHOT_PRUNE_FAILED = "snapshot-prune-failed" + SUCCESS = "success" + TRUNCATION_FAILED = "truncation-failed" + UNSUPPORTED_REMOTE_SESSION = "unsupported-remote-session" + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class HistorySummarizeForHandoffResult: @@ -2761,15 +3139,30 @@ class HistoryTruncateResult: events_removed: int """Number of events that were removed""" + checkpoint_cleanup_error: str | None = None + """Failure detail when checkpointCleanupFailed is true.""" + + checkpoint_cleanup_failed: bool | None = None + """True when conversation truncation succeeded but post-truncation workspace checkpoint + cleanup failed. History is already truncated; callers may still prune snapshots but + should report a checkpoint-cleanup rather than a truncation failure. + """ + @staticmethod def from_dict(obj: Any) -> 'HistoryTruncateResult': assert isinstance(obj, dict) events_removed = from_int(obj.get("eventsRemoved")) - return HistoryTruncateResult(events_removed) + checkpoint_cleanup_error = from_union([from_str, from_none], obj.get("checkpointCleanupError")) + checkpoint_cleanup_failed = from_union([from_bool, from_none], obj.get("checkpointCleanupFailed")) + return HistoryTruncateResult(events_removed, checkpoint_cleanup_error, checkpoint_cleanup_failed) def to_dict(self) -> dict: result: dict = {} result["eventsRemoved"] = from_int(self.events_removed) + if self.checkpoint_cleanup_error is not None: + result["checkpointCleanupError"] = from_union([from_str, from_none], self.checkpoint_cleanup_error) + if self.checkpoint_cleanup_failed is not None: + result["checkpointCleanupFailed"] = from_union([from_bool, from_none], self.checkpoint_cleanup_failed) return result class HMACAuthInfoType(Enum): @@ -2912,6 +3305,50 @@ def to_dict(self) -> dict: result["projectPaths"] = from_union([lambda x: from_list(from_str, x), from_none], self.project_paths) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class InterruptMainTurnRequest: + """Parameters for interrupting the main agent turn.""" + + flush_queued: bool | None = None + """When true, the user's queued prompts are preserved and run as the next turn once the + interrupted turn unwinds; when false (the default), the queue is cleared like a plain + abort. + """ + + @staticmethod + def from_dict(obj: Any) -> 'InterruptMainTurnRequest': + assert isinstance(obj, dict) + flush_queued = from_union([from_bool, from_none], obj.get("flushQueued")) + return InterruptMainTurnRequest(flush_queued) + + def to_dict(self) -> dict: + result: dict = {} + if self.flush_queued is not None: + result["flushQueued"] = from_union([from_bool, from_none], self.flush_queued) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class InterruptMainTurnResult: + """Result of interrupting the main agent turn.""" + + interrupted: bool + """Whether an in-flight main agent turn was interrupted. False when the main loop was not + processing. + """ + + @staticmethod + def from_dict(obj: Any) -> 'InterruptMainTurnResult': + assert isinstance(obj, dict) + interrupted = from_bool(obj.get("interrupted")) + return InterruptMainTurnResult(interrupted) + + def to_dict(self) -> dict: + result: dict = {} + result["interrupted"] = from_bool(self.interrupted) + return result + @dataclass class LlmInferenceHTTPRequestChunkRequest: """A request body chunk or cancellation signal.""" @@ -3809,9 +4246,8 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPFilteredServer: - """MCP server filtered by policy, with name, reason, optional redacted reason, and - enterprise login. - """ + """MCP server filtered by policy, with name, reason, and optional redacted reason.""" + name: str """Filtered server name""" @@ -3819,7 +4255,7 @@ class MCPFilteredServer: """Human-readable filter reason""" enterprise_name: str | None = None - """Enterprise login associated with an allowlist policy""" + """Deprecated. This field is no longer populated.""" redacted_reason: str | None = None """PII-free filter reason""" @@ -4026,6 +4462,46 @@ def to_dict(self) -> dict: result["authorizationUrl"] = from_union([from_str, from_none], self.authorization_url) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class MCPOauthRespondRequest: + """Pending MCP OAuth request id to respond to.""" + + request_id: str + """OAuth request identifier from the mcp.oauth_required event""" + + @staticmethod + def from_dict(obj: Any) -> 'MCPOauthRespondRequest': + assert isinstance(obj, dict) + request_id = from_str(obj.get("requestId")) + return MCPOauthRespondRequest(request_id) + + def to_dict(self) -> dict: + result: dict = {} + result["requestId"] = from_str(self.request_id) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class MCPOauthRespondResult: + """Indicates whether the pending MCP OAuth response was accepted.""" + + success: bool + """Whether the response was accepted. False if the request was unknown, timed out, or + already resolved. + """ + + @staticmethod + def from_dict(obj: Any) -> 'MCPOauthRespondResult': + assert isinstance(obj, dict) + success = from_bool(obj.get("success")) + return MCPOauthRespondResult(success) + + def to_dict(self) -> dict: + result: dict = {} + result["success"] = from_bool(self.success) + return result + # Experimental: this type is part of an experimental API and may change or be removed. # Internal: this type is an internal SDK API and is not part of the public surface. @dataclass @@ -4633,40 +5109,41 @@ def to_dict(self) -> dict: @dataclass class ModelBillingPromo: """Active server-driven promotion for this model, if any. Present when the model is being - promoted with a time-boxed discount. + promoted with a discount, which may be time-boxed or open-ended. - Active server-driven promotion for a model, including its discount and expiry. - """ - ends_at: str - """UTC ISO 8601 timestamp marking when the promotion ends. Always present: the API only - surfaces a promo whose expiry parses and is in the future. Consumers should treat a past - value as expired. + Active server-driven promotion for a model, including its discount and optional expiry. """ discount_percent: float | None = None """Percentage discount (0-100) applied while the promotion is active. May be fractional.""" + ends_at: str | None = None + """UTC ISO 8601 timestamp marking when the promotion ends. Optional: an open-ended promotion + omits this field. When present, the API only surfaces a promo whose expiry parses and is + in the future, so consumers should treat a past value as expired. + """ id: str | None = None """Stable identifier for the promotion campaign.""" message: str | None = None """Human-readable promotion message. Does not include the expiry timestamp; consumers may - format endsAt and append it. + format endsAt and append it when present. """ @staticmethod def from_dict(obj: Any) -> 'ModelBillingPromo': assert isinstance(obj, dict) - ends_at = from_str(obj.get("endsAt")) discount_percent = from_union([from_float, from_none], obj.get("discountPercent")) + ends_at = from_union([from_str, from_none], obj.get("endsAt")) id = from_union([from_str, from_none], obj.get("id")) message = from_union([from_str, from_none], obj.get("message")) - return ModelBillingPromo(ends_at, discount_percent, id, message) + return ModelBillingPromo(discount_percent, ends_at, id, message) def to_dict(self) -> dict: result: dict = {} - result["endsAt"] = from_str(self.ends_at) if self.discount_percent is not None: result["discountPercent"] = from_union([to_float, from_none], self.discount_percent) + if self.ends_at is not None: + result["endsAt"] = from_union([from_str, from_none], self.ends_at) if self.id is not None: result["id"] = from_union([from_str, from_none], self.id) if self.message is not None: @@ -4809,26 +5286,6 @@ def to_dict(self) -> dict: result["supported_media_types"] = from_union([lambda x: from_list(from_str, x), from_none], self.supported_media_types) return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class ModelListRequest: - """Optional listing options.""" - - skip_cache: bool | None = None - """If true, bypasses the per-session model list cache and re-fetches from CAPI.""" - - @staticmethod - def from_dict(obj: Any) -> 'ModelListRequest': - assert isinstance(obj, dict) - skip_cache = from_union([from_bool, from_none], obj.get("skipCache")) - return ModelListRequest(skip_cache) - - def to_dict(self) -> dict: - result: dict = {} - if self.skip_cache is not None: - result["skipCache"] = from_union([from_bool, from_none], self.skip_cache) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ModelSetReasoningEffortRequest: @@ -4876,17 +5333,26 @@ def to_dict(self) -> dict: class ModelSwitchToResult: """The model identifier active on the session after the switch.""" + deferred: bool | None = None + """True when the switch was deferred (enqueued as a cancellable `/model` command) because a + turn was active or another model change was already queued, rather than applied + immediately. When true, the session's live model is unchanged until the queued change + drains. + """ model_id: str | None = None """Currently active model identifier after the switch""" @staticmethod def from_dict(obj: Any) -> 'ModelSwitchToResult': assert isinstance(obj, dict) + deferred = from_union([from_bool, from_none], obj.get("deferred")) model_id = from_union([from_str, from_none], obj.get("modelId")) - return ModelSwitchToResult(model_id) + return ModelSwitchToResult(deferred, model_id) def to_dict(self) -> dict: result: dict = {} + if self.deferred is not None: + result["deferred"] = from_union([from_bool, from_none], self.deferred) if self.model_id is not None: result["modelId"] = from_union([from_str, from_none], self.model_id) return result @@ -5753,14 +6219,21 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionsResetSessionApprovalsRequest: - """No parameters; clears all session-scoped tool permission approvals.""" + """Clears session-scoped tool permission approvals, and optionally the location-scoped ones.""" + + include_location: bool | None = None + """Whether location-scoped approvals are cleared too. Defaults to `true`.""" + @staticmethod def from_dict(obj: Any) -> 'PermissionsResetSessionApprovalsRequest': assert isinstance(obj, dict) - return PermissionsResetSessionApprovalsRequest() + include_location = from_union([from_bool, from_none], obj.get("includeLocation")) + return PermissionsResetSessionApprovalsRequest(include_location) def to_dict(self) -> dict: result: dict = {} + if self.include_location is not None: + result["includeLocation"] = from_union([from_bool, from_none], self.include_location) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -6184,54 +6657,6 @@ def to_dict(self) -> dict: result["force"] = from_union([from_bool, from_none], self.force) return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class PluginsReloadRequest: - """Optional flags controlling which side effects the reload performs.""" - - defer_repo_hooks: bool | None = None - """When true, skip repo-level hooks during the hook reload. Use before folder trust is - confirmed; load them post-trust via `sessions.loadDeferredRepoHooks`. - """ - reload_custom_agents: bool | None = None - """Re-run custom-agent discovery after refreshing plugins. Defaults to true.""" - - reload_extensions: bool | None = None - """Re-discover and relaunch subprocess extensions (including plugin-shipped extensions) - after refreshing plugins. Defaults to true. Has no effect when the session has no active - extension controller (e.g. extensions were not requested for the session). - """ - reload_hooks: bool | None = None - """Re-load user, plugin, and (subject to `deferRepoHooks`) repo hooks. Defaults to true. Has - no effect when the host has not registered a hook reloader (e.g. remote sessions). - """ - reload_mcp: bool | None = None - """Reload MCP server connections after refreshing plugins. Defaults to true.""" - - @staticmethod - def from_dict(obj: Any) -> 'PluginsReloadRequest': - assert isinstance(obj, dict) - defer_repo_hooks = from_union([from_bool, from_none], obj.get("deferRepoHooks")) - reload_custom_agents = from_union([from_bool, from_none], obj.get("reloadCustomAgents")) - reload_extensions = from_union([from_bool, from_none], obj.get("reloadExtensions")) - reload_hooks = from_union([from_bool, from_none], obj.get("reloadHooks")) - reload_mcp = from_union([from_bool, from_none], obj.get("reloadMcp")) - return PluginsReloadRequest(defer_repo_hooks, reload_custom_agents, reload_extensions, reload_hooks, reload_mcp) - - def to_dict(self) -> dict: - result: dict = {} - if self.defer_repo_hooks is not None: - result["deferRepoHooks"] = from_union([from_bool, from_none], self.defer_repo_hooks) - if self.reload_custom_agents is not None: - result["reloadCustomAgents"] = from_union([from_bool, from_none], self.reload_custom_agents) - if self.reload_extensions is not None: - result["reloadExtensions"] = from_union([from_bool, from_none], self.reload_extensions) - if self.reload_hooks is not None: - result["reloadHooks"] = from_union([from_bool, from_none], self.reload_hooks) - if self.reload_mcp is not None: - result["reloadMcp"] = from_union([from_bool, from_none], self.reload_mcp) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ProviderAddResult: @@ -6494,110 +6919,548 @@ class PushAttachmentGitHubURLType(Enum): class PushAttachmentSelectionType(Enum): SELECTION = "selection" -# Experimental: this type is part of an experimental API and may change or be removed. -class QueuePendingItemsKind(Enum): - """Whether this item is a queued user message or a queued slash command / model change""" - - COMMAND = "command" - MESSAGE = "message" - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class QueueRemoveMostRecentResult: - """Indicates whether a user-facing pending item was removed.""" +class QueueBeginDeferredIdleDrainRequest: + """Inputs for starting a deferred-idle drain.""" - removed: bool - """True if a user-facing pending item was removed (LIFO across both queues); false when no - removable items remained. - """ + active_background_work: bool + """Whether the host still has active background work.""" @staticmethod - def from_dict(obj: Any) -> 'QueueRemoveMostRecentResult': + def from_dict(obj: Any) -> 'QueueBeginDeferredIdleDrainRequest': assert isinstance(obj, dict) - removed = from_bool(obj.get("removed")) - return QueueRemoveMostRecentResult(removed) + active_background_work = from_bool(obj.get("activeBackgroundWork")) + return QueueBeginDeferredIdleDrainRequest(active_background_work) def to_dict(self) -> dict: result: dict = {} - result["removed"] = from_bool(self.removed) + result["activeBackgroundWork"] = from_bool(self.active_background_work) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class QueuedCommandHandled: - """Queued-command response indicating the host executed the command, with an optional flag - to stop queue processing. - """ - handled: ClassVar[str] = "true" - """The host actually executed the queued command.""" +class QueueBeginDeferredIdleDrainResult: + """Whether a deferred-idle drain should run.""" - stop_processing_queue: bool | None = None - """When true, the runtime will not process subsequent queued commands until a new request - comes in. - """ + should_drain: bool + """True when the host should run finishDeferredIdleDrain asynchronously.""" @staticmethod - def from_dict(obj: Any) -> 'QueuedCommandHandled': + def from_dict(obj: Any) -> 'QueueBeginDeferredIdleDrainResult': assert isinstance(obj, dict) - stop_processing_queue = from_union([from_bool, from_none], obj.get("stopProcessingQueue")) - return QueuedCommandHandled(stop_processing_queue) + should_drain = from_bool(obj.get("shouldDrain")) + return QueueBeginDeferredIdleDrainResult(should_drain) def to_dict(self) -> dict: result: dict = {} - result["handled"] = self.handled - if self.stop_processing_queue is not None: - result["stopProcessingQueue"] = from_union([from_bool, from_none], self.stop_processing_queue) + result["shouldDrain"] = from_bool(self.should_drain) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class QueuedCommandNotHandled: - """Queued-command response indicating the host did not execute the command and the queue may - continue. - """ - handled: ClassVar[str] = "false" - """The host did not execute the queued command. Unblocks the queue without claiming the - command was processed (e.g. when the handler threw before completing). - """ +class QueueConsumeSystemNotificationsRequest: + """Internal filter for consuming queued system notifications.""" + + filter: Any + """Opaque runtime-owned filter object.""" @staticmethod - def from_dict(obj: Any) -> 'QueuedCommandNotHandled': + def from_dict(obj: Any) -> 'QueueConsumeSystemNotificationsRequest': assert isinstance(obj, dict) - return QueuedCommandNotHandled() + filter = obj.get("filter") + return QueueConsumeSystemNotificationsRequest(filter) def to_dict(self) -> dict: result: dict = {} - result["handled"] = self.handled + result["filter"] = self.filter return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class RegisterEventInterestParams: - """Event type to register consumer interest for, used by runtime gating logic.""" +class QueueDeferSessionIdleRequest: + """Inputs for marking session.idle deferred in native state.""" - event_type: str - """The event type the consumer wants the runtime to treat as 'observed' for - behavior-switching gating. Some runtime code paths inspect whether any consumer is - interested in a specific event type and choose a different implementation accordingly - (e.g. `mcp.oauth_required`: when interest is registered the runtime delegates interactive - OAuth token acquisition to the consumer via `mcp.oauth_required` events; when no interest - is registered the runtime still attempts non-interactive reconnect from cached or - refreshable tokens, and only marks the server `needs-auth` if usable credentials are - unavailable — it does not open a browser or start interactive OAuth without a consumer). - SDK clients that long-poll events do NOT automatically appear as listeners to these - gating checks — they must explicitly call `registerInterest` for each event type they - want the runtime to count as having a consumer. Multiple registrations for the same event - type from the same or different consumers are tracked independently and must each be - released. See: `mcp.oauth_required`, `sampling.requested`, `auto_mode_switch.requested`, - `session_limits_exhausted.requested`, `user_input.requested`, `elicitation.requested`, - `command.queued`, `exit_plan_mode.requested`. - """ + aborted: bool + """Whether the deferred idle was caused by an aborted foreground turn.""" @staticmethod - def from_dict(obj: Any) -> 'RegisterEventInterestParams': + def from_dict(obj: Any) -> 'QueueDeferSessionIdleRequest': assert isinstance(obj, dict) - event_type = from_str(obj.get("eventType")) - return RegisterEventInterestParams(event_type) + aborted = from_bool(obj.get("aborted")) + return QueueDeferSessionIdleRequest(aborted) + + def to_dict(self) -> dict: + result: dict = {} + result["aborted"] = from_bool(self.aborted) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueueDuplicateAtRequest: + """Parameters for duplicating a queued item.""" + + id: str + + @staticmethod + def from_dict(obj: Any) -> 'QueueDuplicateAtRequest': + assert isinstance(obj, dict) + id = from_str(obj.get("id")) + return QueueDuplicateAtRequest(id) + + def to_dict(self) -> dict: + result: dict = {} + result["id"] = from_str(self.id) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueueDuplicateAtResult: + """Result of duplicating a queued item.""" + + id: str + """Fresh stable opaque id assigned to the duplicate.""" + + @staticmethod + def from_dict(obj: Any) -> 'QueueDuplicateAtResult': + assert isinstance(obj, dict) + id = from_str(obj.get("id")) + return QueueDuplicateAtResult(id) + + def to_dict(self) -> dict: + result: dict = {} + result["id"] = from_str(self.id) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueueEnqueueResumePendingResult: + """Result of enqueueing the resume-pending wake item.""" + + queued: bool + """True when a wake item was newly queued.""" + + @staticmethod + def from_dict(obj: Any) -> 'QueueEnqueueResumePendingResult': + assert isinstance(obj, dict) + queued = from_bool(obj.get("queued")) + return QueueEnqueueResumePendingResult(queued) + + def to_dict(self) -> dict: + result: dict = {} + result["queued"] = from_bool(self.queued) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueueFinishDeferredIdleDrainRequest: + """Inputs for completing a deferred-idle drain.""" + + active_background_work: bool + """Whether the host still has active background work.""" + + has_pending: bool + """Whether native queued work remains.""" + + @staticmethod + def from_dict(obj: Any) -> 'QueueFinishDeferredIdleDrainRequest': + assert isinstance(obj, dict) + active_background_work = from_bool(obj.get("activeBackgroundWork")) + has_pending = from_bool(obj.get("hasPending")) + return QueueFinishDeferredIdleDrainRequest(active_background_work, has_pending) + + def to_dict(self) -> dict: + result: dict = {} + result["activeBackgroundWork"] = from_bool(self.active_background_work) + result["hasPending"] = from_bool(self.has_pending) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueueFinishDeferredIdleDrainResult: + """Action selected by the native deferred-idle drain.""" + + aborted: bool + """Whether the deferred idle was caused by an aborted foreground turn.""" + + action: str + """One of none, processQueue, or emitSessionIdle.""" + + @staticmethod + def from_dict(obj: Any) -> 'QueueFinishDeferredIdleDrainResult': + assert isinstance(obj, dict) + aborted = from_bool(obj.get("aborted")) + action = from_str(obj.get("action")) + return QueueFinishDeferredIdleDrainResult(aborted, action) + + def to_dict(self) -> dict: + result: dict = {} + result["aborted"] = from_bool(self.aborted) + result["action"] = from_str(self.action) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueueHasPendingResult: + """Whether the native queue has pending work.""" + + has_pending: bool + """True when queued or immediate native work is pending.""" + + @staticmethod + def from_dict(obj: Any) -> 'QueueHasPendingResult': + assert isinstance(obj, dict) + has_pending = from_bool(obj.get("hasPending")) + return QueueHasPendingResult(has_pending) + + def to_dict(self) -> dict: + result: dict = {} + result["hasPending"] = from_bool(self.has_pending) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +class SendAgentMode(Enum): + """Optional explicit agent mode. When omitted, the session's current mode is assigned. + + The UI mode the agent was in when this message was sent. Defaults to the session's + current mode. + + Agent mode stored on this queued entry, as stamped when it was enqueued. Items without an + explicit mode report interactive. This is not necessarily the mode that will constrain + the turn: a plan or autopilot session applies its own write gate, continuation loop and + permission posture to every drained item regardless of the mode stored here. + + The UI mode the agent was in when these messages were sent. Defaults to the session's + current mode. + """ + AUTOPILOT = "autopilot" + INTERACTIVE = "interactive" + PLAN = "plan" + SHELL = "shell" + +# Experimental: this type is part of an experimental API and may change or be removed. +class SendMode(Enum): + """Accepted for SendOptions compatibility but ignored; inserted items always use queued + delivery semantics. + + How to deliver the message. `enqueue` (default) appends to the message queue. `immediate` + interjects during an in-progress turn. + + How to deliver the messages. `enqueue` (default) appends to the message queue. + `immediate` interjects during an in-progress turn. + """ + ENQUEUE = "enqueue" + IMMEDIATE = "immediate" + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueueInsertAtResult: + """Result of inserting a queued message.""" + + id: str + """Fresh stable opaque id assigned to the inserted item.""" + + @staticmethod + def from_dict(obj: Any) -> 'QueueInsertAtResult': + assert isinstance(obj, dict) + id = from_str(obj.get("id")) + return QueueInsertAtResult(id) + + def to_dict(self) -> dict: + result: dict = {} + result["id"] = from_str(self.id) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueueMoveItemRequest: + """Parameters for moving a queued item by stable id.""" + + id: str + """Stable opaque queued-item id.""" + + to_position: int + """Zero-based target position in the public visible queue. Values outside the queue clamp to + an end. + """ + + @staticmethod + def from_dict(obj: Any) -> 'QueueMoveItemRequest': + assert isinstance(obj, dict) + id = from_str(obj.get("id")) + to_position = from_int(obj.get("toPosition")) + return QueueMoveItemRequest(id, to_position) + + def to_dict(self) -> dict: + result: dict = {} + result["id"] = from_str(self.id) + result["toPosition"] = from_int(self.to_position) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueueMoveItemResult: + """Result of moving a queued item.""" + + changed: bool + """True when the item changed position; false when it was already at the requested position.""" + + @staticmethod + def from_dict(obj: Any) -> 'QueueMoveItemResult': + assert isinstance(obj, dict) + changed = from_bool(obj.get("changed")) + return QueueMoveItemResult(changed) + + def to_dict(self) -> dict: + result: dict = {} + result["changed"] = from_bool(self.changed) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +class QueuePendingItemsKind(Enum): + """Whether this item is a queued user message or a queued slash command / model change""" + + COMMAND = "command" + MESSAGE = "message" + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueueRemoveAtRequest: + """Parameters for removing a queued item by stable id.""" + + id: str + + @staticmethod + def from_dict(obj: Any) -> 'QueueRemoveAtRequest': + assert isinstance(obj, dict) + id = from_str(obj.get("id")) + return QueueRemoveAtRequest(id) + + def to_dict(self) -> dict: + result: dict = {} + result["id"] = from_str(self.id) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueueRemoveAtResult: + """Result of removing a queued item.""" + + removed: bool + """True when the addressed item was removed.""" + + @staticmethod + def from_dict(obj: Any) -> 'QueueRemoveAtResult': + assert isinstance(obj, dict) + removed = from_bool(obj.get("removed")) + return QueueRemoveAtResult(removed) + + def to_dict(self) -> dict: + result: dict = {} + result["removed"] = from_bool(self.removed) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueueRemoveMostRecentResult: + """Indicates whether a user-facing pending item was removed.""" + + removed: bool + """True if a user-facing pending item was removed (LIFO across both queues); false when no + removable items remained. + """ + + @staticmethod + def from_dict(obj: Any) -> 'QueueRemoveMostRecentResult': + assert isinstance(obj, dict) + removed = from_bool(obj.get("removed")) + return QueueRemoveMostRecentResult(removed) + + def to_dict(self) -> dict: + result: dict = {} + result["removed"] = from_bool(self.removed) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueueSendNowRequest: + """Parameters for steering a queued message into a live turn.""" + + id: str + + @staticmethod + def from_dict(obj: Any) -> 'QueueSendNowRequest': + assert isinstance(obj, dict) + id = from_str(obj.get("id")) + return QueueSendNowRequest(id) + + def to_dict(self) -> dict: + result: dict = {} + result["id"] = from_str(self.id) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueueSendNowResult: + """Result of trying to steer a queued message into a live turn.""" + + steered: bool + """True when the item was accepted into the steering lane; false when no main turn was live.""" + + @staticmethod + def from_dict(obj: Any) -> 'QueueSendNowResult': + assert isinstance(obj, dict) + steered = from_bool(obj.get("steered")) + return QueueSendNowResult(steered) + + def to_dict(self) -> dict: + result: dict = {} + result["steered"] = from_bool(self.steered) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueueSetDrainPausedRequest: + """Parameters for acquiring or releasing the queued-lane drain pause. Acquisition is + exclusive and non-idempotent: `paused: true` against an already-paused session fails with + `queue_already_paused`. The pause is never released automatically — it is not tied to the + caller's lifetime, so a client that exits without sending `paused: false` leaves the lane + frozen. Release is unowned: `paused: false` clears the pause for any caller, including + one that never acquired it. + """ + paused: bool + + @staticmethod + def from_dict(obj: Any) -> 'QueueSetDrainPausedRequest': + assert isinstance(obj, dict) + paused = from_bool(obj.get("paused")) + return QueueSetDrainPausedRequest(paused) + + def to_dict(self) -> dict: + result: dict = {} + result["paused"] = from_bool(self.paused) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueueUpdateTextRequest: + """Parameters for editing a single queued message.""" + + id: str + prompt: str + display_prompt: str | None = None + + @staticmethod + def from_dict(obj: Any) -> 'QueueUpdateTextRequest': + assert isinstance(obj, dict) + id = from_str(obj.get("id")) + prompt = from_str(obj.get("prompt")) + display_prompt = from_union([from_str, from_none], obj.get("displayPrompt")) + return QueueUpdateTextRequest(id, prompt, display_prompt) + + def to_dict(self) -> dict: + result: dict = {} + result["id"] = from_str(self.id) + result["prompt"] = from_str(self.prompt) + if self.display_prompt is not None: + result["displayPrompt"] = from_union([from_str, from_none], self.display_prompt) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueueUpdateTextResult: + """Result of editing a queued message.""" + + updated: bool + """True when the stored text changed.""" + + @staticmethod + def from_dict(obj: Any) -> 'QueueUpdateTextResult': + assert isinstance(obj, dict) + updated = from_bool(obj.get("updated")) + return QueueUpdateTextResult(updated) + + def to_dict(self) -> dict: + result: dict = {} + result["updated"] = from_bool(self.updated) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueuedCommandHandled: + """Queued-command response indicating the host executed the command, with an optional flag + to stop queue processing. + """ + handled: ClassVar[str] = "true" + """The host actually executed the queued command.""" + + stop_processing_queue: bool | None = None + """When true, the runtime will not process subsequent queued commands until a new request + comes in. + """ + + @staticmethod + def from_dict(obj: Any) -> 'QueuedCommandHandled': + assert isinstance(obj, dict) + stop_processing_queue = from_union([from_bool, from_none], obj.get("stopProcessingQueue")) + return QueuedCommandHandled(stop_processing_queue) + + def to_dict(self) -> dict: + result: dict = {} + result["handled"] = self.handled + if self.stop_processing_queue is not None: + result["stopProcessingQueue"] = from_union([from_bool, from_none], self.stop_processing_queue) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueuedCommandNotHandled: + """Queued-command response indicating the host did not execute the command and the queue may + continue. + """ + handled: ClassVar[str] = "false" + """The host did not execute the queued command. Unblocks the queue without claiming the + command was processed (e.g. when the handler threw before completing). + """ + + @staticmethod + def from_dict(obj: Any) -> 'QueuedCommandNotHandled': + assert isinstance(obj, dict) + return QueuedCommandNotHandled() + + def to_dict(self) -> dict: + result: dict = {} + result["handled"] = self.handled + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class RegisterEventInterestParams: + """Event type to register consumer interest for, used by runtime gating logic.""" + + event_type: str + """The event type the consumer wants the runtime to treat as 'observed' for + behavior-switching gating. Some runtime code paths inspect whether any consumer is + interested in a specific event type and choose a different implementation accordingly + (e.g. `mcp.oauth_required`: when interest is registered the runtime delegates interactive + OAuth token acquisition to the consumer via `mcp.oauth_required` events; when no interest + is registered the runtime still attempts non-interactive reconnect from cached or + refreshable tokens, and only marks the server `needs-auth` if usable credentials are + unavailable — it does not open a browser or start interactive OAuth without a consumer). + SDK clients that long-poll events do NOT automatically appear as listeners to these + gating checks — they must explicitly call `registerInterest` for each event type they + want the runtime to count as having a consumer. Multiple registrations for the same event + type from the same or different consumers are tracked independently and must each be + released. See: `mcp.oauth_required`, `sampling.requested`, `auto_mode_switch.requested`, + `session_limits_exhausted.requested`, `user_input.requested`, `elicitation.requested`, + `command.queued`, `exit_plan_mode.requested`. + """ + + @staticmethod + def from_dict(obj: Any) -> 'RegisterEventInterestParams': + assert isinstance(obj, dict) + event_type = from_str(obj.get("eventType")) + return RegisterEventInterestParams(event_type) def to_dict(self) -> dict: result: dict = {} @@ -6974,56 +7837,196 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class SandboxConfigUserPolicyNetwork: - """Network rules to merge into the base policy.""" +class SandboxConfigUserPolicyNetworkProxy: + """HTTP proxy the sandboxed process routes traffic through. Enforced on Windows and + cooperative (honored by well-behaved tools, not strictly enforced) on Linux and macOS. + Credentials go in the separate `username`/`password` fields. A credential-free http:// + loopback proxy URL is routed through the localhost proxy automatically; an https:// or + authenticated loopback URL is used as-is. + + HTTP proxy configuration for sandboxed traffic. + """ + url: str + """Proxy URL (e.g. http://proxy.example.com:8080). The port is optional and defaults to the + scheme's standard port when omitted. Credentials must not be embedded here — a + `user:pass@` authority is rejected; put them in the separate `username`/`password` + fields. A credential-free http:// loopback URL is routed through the localhost proxy + automatically; loopback covers localhost and any *.localhost subdomain, the whole + 127.0.0.0/8 range, ::1, and IPv4-mapped loopback (::ffff:127.0.0.1). An https:// URL, or + one with a username/password set, is used as-is. + """ + password: str | None = None + """Optional password for proxy authentication, combined with the URL at spawn time. The + persisted value may be a literal password, a `${secret:…}` reference resolved from the OS + keychain, or a `${VAR}`/`$VAR` environment reference; it is resolved just before the + sandboxed process routes through the proxy. The /sandbox dialog stores a real password in + the OS keychain and persists only a `${secret:…}` placeholder (never plaintext in + settings.json); the field is masked in the dialog and redacted by /settings show. + """ + username: str | None = None + """Optional username for proxy authentication. Combined with the URL (and `password`) into + `user:pass@host` when the sandboxed process routes through the proxy. + """ + + @staticmethod + def from_dict(obj: Any) -> 'SandboxConfigUserPolicyNetworkProxy': + assert isinstance(obj, dict) + url = from_str(obj.get("url")) + password = from_union([from_str, from_none], obj.get("password")) + username = from_union([from_str, from_none], obj.get("username")) + return SandboxConfigUserPolicyNetworkProxy(url, password, username) + + def to_dict(self) -> dict: + result: dict = {} + result["url"] = from_str(self.url) + if self.password is not None: + result["password"] = from_union([from_str, from_none], self.password) + if self.username is not None: + result["username"] = from_union([from_str, from_none], self.username) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SandboxConfigUserPolicySeatbelt: + """macOS seatbelt options to merge into the base policy. + + macOS seatbelt-specific options. + """ + keychain_access: bool | None = None + """Whether the macOS seatbelt profile may access the keychain.""" + + @staticmethod + def from_dict(obj: Any) -> 'SandboxConfigUserPolicySeatbelt': + assert isinstance(obj, dict) + keychain_access = from_union([from_bool, from_none], obj.get("keychainAccess")) + return SandboxConfigUserPolicySeatbelt(keychain_access) + + def to_dict(self) -> dict: + result: dict = {} + if self.keychain_access is not None: + result["keychainAccess"] = from_union([from_bool, from_none], self.keychain_access) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class ScheduleAddAtRequest: + """Register an absolute-time scheduled prompt.""" + + at: int + """Epoch milliseconds when the prompt should fire.""" + + prompt: str + """Prompt text to enqueue when the schedule fires.""" + + display_prompt: str | None = None + """Optional display-only prompt label.""" + + recurring: bool | None = None + """Whether the schedule should re-arm after each tick. Defaults to false.""" + + @staticmethod + def from_dict(obj: Any) -> 'ScheduleAddAtRequest': + assert isinstance(obj, dict) + at = from_int(obj.get("at")) + prompt = from_str(obj.get("prompt")) + display_prompt = from_union([from_str, from_none], obj.get("displayPrompt")) + recurring = from_union([from_bool, from_none], obj.get("recurring")) + return ScheduleAddAtRequest(at, prompt, display_prompt, recurring) + + def to_dict(self) -> dict: + result: dict = {} + result["at"] = from_int(self.at) + result["prompt"] = from_str(self.prompt) + if self.display_prompt is not None: + result["displayPrompt"] = from_union([from_str, from_none], self.display_prompt) + if self.recurring is not None: + result["recurring"] = from_union([from_bool, from_none], self.recurring) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class ScheduleAddCronRequest: + """Register a cron scheduled prompt.""" - allow_local_network: bool | None = None - """Whether traffic to local/loopback addresses is allowed.""" + cron: str + """5-field cron expression.""" - allow_outbound: bool | None = None - """Whether outbound network traffic is allowed at all.""" + prompt: str + """Prompt text to enqueue when the schedule fires.""" + + display_prompt: str | None = None + """Optional display-only prompt label.""" + + recurring: bool | None = None + """Whether the schedule should re-arm after each tick. Defaults to true.""" + + tz: str | None = None + """IANA timezone for evaluating the cron expression.""" @staticmethod - def from_dict(obj: Any) -> 'SandboxConfigUserPolicyNetwork': + def from_dict(obj: Any) -> 'ScheduleAddCronRequest': assert isinstance(obj, dict) - allow_local_network = from_union([from_bool, from_none], obj.get("allowLocalNetwork")) - allow_outbound = from_union([from_bool, from_none], obj.get("allowOutbound")) - return SandboxConfigUserPolicyNetwork(allow_local_network, allow_outbound) + cron = from_str(obj.get("cron")) + prompt = from_str(obj.get("prompt")) + display_prompt = from_union([from_str, from_none], obj.get("displayPrompt")) + recurring = from_union([from_bool, from_none], obj.get("recurring")) + tz = from_union([from_str, from_none], obj.get("tz")) + return ScheduleAddCronRequest(cron, prompt, display_prompt, recurring, tz) def to_dict(self) -> dict: result: dict = {} - if self.allow_local_network is not None: - result["allowLocalNetwork"] = from_union([from_bool, from_none], self.allow_local_network) - if self.allow_outbound is not None: - result["allowOutbound"] = from_union([from_bool, from_none], self.allow_outbound) + result["cron"] = from_str(self.cron) + result["prompt"] = from_str(self.prompt) + if self.display_prompt is not None: + result["displayPrompt"] = from_union([from_str, from_none], self.display_prompt) + if self.recurring is not None: + result["recurring"] = from_union([from_bool, from_none], self.recurring) + if self.tz is not None: + result["tz"] = from_union([from_str, from_none], self.tz) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class SandboxConfigUserPolicySeatbelt: - """macOS seatbelt options to merge into the base policy. +class ScheduleAddRequest: + """Register a relative-interval scheduled prompt.""" - macOS seatbelt-specific options. - """ - keychain_access: bool | None = None - """Whether the macOS seatbelt profile may access the keychain.""" + interval: str + """Human-readable interval such as `30s`, `5m`, or `2h`.""" + + prompt: str + """Prompt text to enqueue when the schedule fires.""" + + display_prompt: str | None = None + """Optional display-only prompt label.""" + + recurring: bool | None = None + """Whether the schedule should re-arm after each tick. Defaults to true.""" @staticmethod - def from_dict(obj: Any) -> 'SandboxConfigUserPolicySeatbelt': + def from_dict(obj: Any) -> 'ScheduleAddRequest': assert isinstance(obj, dict) - keychain_access = from_union([from_bool, from_none], obj.get("keychainAccess")) - return SandboxConfigUserPolicySeatbelt(keychain_access) + interval = from_str(obj.get("interval")) + prompt = from_str(obj.get("prompt")) + display_prompt = from_union([from_str, from_none], obj.get("displayPrompt")) + recurring = from_union([from_bool, from_none], obj.get("recurring")) + return ScheduleAddRequest(interval, prompt, display_prompt, recurring) def to_dict(self) -> dict: result: dict = {} - if self.keychain_access is not None: - result["keychainAccess"] = from_union([from_bool, from_none], self.keychain_access) + result["interval"] = from_str(self.interval) + result["prompt"] = from_str(self.prompt) + if self.display_prompt is not None: + result["displayPrompt"] = from_union([from_str, from_none], self.display_prompt) + if self.recurring is not None: + result["recurring"] = from_union([from_bool, from_none], self.recurring) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ScheduleEntry: - """Scheduled prompt entry with ID, timing (`intervalMs`, `cron`, or `at`), prompt text, + """The registered or updated schedule entry. + + Scheduled prompt entry with ID, timing (`intervalMs`, `cron`, or `at`), prompt text, recurrence, and next run time. The removed entry, or omitted if no entry matched. @@ -7096,6 +8099,74 @@ def to_dict(self) -> dict: result["tz"] = from_union([from_str, from_none], self.tz) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class ScheduleAddSelfPacedRequest: + """Register a self-paced scheduled prompt.""" + + prompt: str + """Prompt text to enqueue when the schedule fires.""" + + display_prompt: str | None = None + """Optional display-only prompt label.""" + + @staticmethod + def from_dict(obj: Any) -> 'ScheduleAddSelfPacedRequest': + assert isinstance(obj, dict) + prompt = from_str(obj.get("prompt")) + display_prompt = from_union([from_str, from_none], obj.get("displayPrompt")) + return ScheduleAddSelfPacedRequest(prompt, display_prompt) + + def to_dict(self) -> dict: + result: dict = {} + result["prompt"] = from_str(self.prompt) + if self.display_prompt is not None: + result["displayPrompt"] = from_union([from_str, from_none], self.display_prompt) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class ScheduleHasSelfPacedResult: + """Whether the session currently has an active self-paced schedule.""" + + has_self_paced: bool + """True when at least one active schedule is self-paced.""" + + @staticmethod + def from_dict(obj: Any) -> 'ScheduleHasSelfPacedResult': + assert isinstance(obj, dict) + has_self_paced = from_bool(obj.get("hasSelfPaced")) + return ScheduleHasSelfPacedResult(has_self_paced) + + def to_dict(self) -> dict: + result: dict = {} + result["hasSelfPaced"] = from_bool(self.has_self_paced) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class ScheduleRearmSelfPacedRequest: + """Re-arm a self-paced scheduled prompt.""" + + at: int + """Epoch milliseconds when the prompt should next fire.""" + + id: int + """Id of the self-paced scheduled prompt.""" + + @staticmethod + def from_dict(obj: Any) -> 'ScheduleRearmSelfPacedRequest': + assert isinstance(obj, dict) + at = from_int(obj.get("at")) + id = from_int(obj.get("id")) + return ScheduleRearmSelfPacedRequest(at, id) + + def to_dict(self) -> dict: + result: dict = {} + result["at"] = from_int(self.at) + result["id"] = from_int(self.id) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ScheduleStopRequest: @@ -7153,19 +8224,6 @@ def to_dict(self) -> dict: result["ok"] = from_bool(self.ok) return result -# Experimental: this type is part of an experimental API and may change or be removed. -class SendAgentMode(Enum): - """The UI mode the agent was in when this message was sent. Defaults to the session's - current mode. - - The UI mode the agent was in when these messages were sent. Defaults to the session's - current mode. - """ - AUTOPILOT = "autopilot" - INTERACTIVE = "interactive" - PLAN = "plan" - SHELL = "shell" - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SendAttachmentsToMessageParams: @@ -7222,10 +8280,9 @@ class SendMessageItem: """ # Internal: this field is an internal SDK API and is not part of the public surface. source: str | None = None - """Optional provenance tag copied to the resulting user.message event. Must match one of - three forms: the literal `system`, `command-` for messages originating from a - command (e.g. slash command, Mission Control command), or `schedule-` for - messages originating from a scheduled job. + """Optional provenance tag copied to the resulting user.message event. Must be `user`, + `system`, `command-` for command-originated messages, `schedule-` + for scheduled prompts, or `agent-` for prompts sent by another agent. """ @staticmethod @@ -7254,17 +8311,6 @@ def to_dict(self) -> dict: result["source"] = from_union([from_str, from_none], self.source) return result -# Experimental: this type is part of an experimental API and may change or be removed. -class SendMode(Enum): - """How to deliver the messages. `enqueue` (default) appends to the message queue. - `immediate` interjects during an in-progress turn. - - How to deliver the message. `enqueue` (default) appends to the message queue. `immediate` - interjects during an in-progress turn. - """ - ENQUEUE = "enqueue" - IMMEDIATE = "immediate" - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SendMessagesResult: @@ -7305,6 +8351,37 @@ def to_dict(self) -> dict: result["messageId"] = from_str(self.message_id) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SendSystemNotificationRequest: + """Internal request for sending a system notification.""" + + message: str + """Notification text to deliver to the model.""" + + kind: Any = None + """Optional structured notification kind.""" + + options: Any = None + """Internal delivery options, including passive policy.""" + + @staticmethod + def from_dict(obj: Any) -> 'SendSystemNotificationRequest': + assert isinstance(obj, dict) + message = from_str(obj.get("message")) + kind = obj.get("kind") + options = obj.get("options") + return SendSystemNotificationRequest(message, kind, options) + + def to_dict(self) -> dict: + result: dict = {} + result["message"] = from_str(self.message) + if self.kind is not None: + result["kind"] = self.kind + if self.options is not None: + result["options"] = self.options + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ServerSkill: @@ -7428,6 +8505,36 @@ class SessionCapability(Enum): SYSTEM_NOTIFICATIONS = "system-notifications" TUI_HINTS = "tui-hints" +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionCommandsListRequest: + include_builtins: bool | None = None + """Include runtime built-in commands""" + + include_client_commands: bool | None = None + """Include commands registered by protocol clients, including SDK clients and extensions""" + + include_skills: bool | None = None + """Include enabled user-invocable skills and commands""" + + @staticmethod + def from_dict(obj: Any) -> 'SessionCommandsListRequest': + assert isinstance(obj, dict) + include_builtins = from_union([from_bool, from_none], obj.get("includeBuiltins")) + include_client_commands = from_union([from_bool, from_none], obj.get("includeClientCommands")) + include_skills = from_union([from_bool, from_none], obj.get("includeSkills")) + return SessionCommandsListRequest(include_builtins, include_client_commands, include_skills) + + def to_dict(self) -> dict: + result: dict = {} + if self.include_builtins is not None: + result["includeBuiltins"] = from_union([from_bool, from_none], self.include_builtins) + if self.include_client_commands is not None: + result["includeClientCommands"] = from_union([from_bool, from_none], self.include_client_commands) + if self.include_skills is not None: + result["includeSkills"] = from_union([from_bool, from_none], self.include_skills) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionFSAppendFileRequest: @@ -7779,11 +8886,21 @@ def to_dict(self) -> dict: class SessionFSSqliteQueryType(Enum): """How to execute the query: 'exec' for DDL/multi-statement (no results), 'query' for SELECT (returns rows), 'run' for INSERT/UPDATE/DELETE (returns rowsAffected) + + How to execute the statement. """ EXEC = "exec" QUERY = "query" RUN = "run" +# Experimental: this type is part of an experimental API and may change or be removed. +class SessionFSSqliteTransactionErrorClass(Enum): + """SQLite transaction failure classification.""" + + BUSY_OR_LOCKED = "busyOrLocked" + FATAL = "fatal" + POST_COMMIT_AMBIGUOUS = "postCommitAmbiguous" + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionFSStatRequest: @@ -7843,6 +8960,83 @@ def to_dict(self) -> dict: result["mode"] = from_union([from_int, from_none], self.mode) return result +class Trigger(Enum): + """What initiated this compaction request, recorded as the `trigger` on the persisted + `session.compaction_start` / `session.compaction_complete` events. When absent, the + compaction is persisted without trigger attribution (initiator unknown). + """ + MANUAL = "manual" + MODEL_SWITCH = "model_switch" + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionLimitPredictionBaselineData: + """Baseline data provenance for a prediction. + + Baseline data provenance. + """ + window_end: str + """End of the baseline data slice.""" + + window_start: str + """Start of the baseline data slice.""" + + @staticmethod + def from_dict(obj: Any) -> 'SessionLimitPredictionBaselineData': + assert isinstance(obj, dict) + window_end = from_str(obj.get("windowEnd")) + window_start = from_str(obj.get("windowStart")) + return SessionLimitPredictionBaselineData(window_end, window_start) + + def to_dict(self) -> dict: + result: dict = {} + result["windowEnd"] = from_str(self.window_end) + result["windowStart"] = from_str(self.window_start) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +class SessionLimitPredictionClientType(Enum): + """Client population used for the prediction baseline. + + Client population used for the prediction. + + Client type to size for. Defaults to `cli-interactive`. + """ + CLI_INTERACTIVE = "cli-interactive" + CLI_PROMPT = "cli-prompt" + +# Experimental: this type is part of an experimental API and may change or be removed. +class SessionLimitPredictionTier(Enum): + """Tier chosen as the recommended cap. + + Semantic usage tier used for a recommended cap or additional headroom. + """ + ADDITIONAL_HEADROOM = "additional_headroom" + GENEROUS_HEADROOM = "generous_headroom" + MAXIMUM_HEADROOM = "maximum_headroom" + RECOMMENDED = "recommended" + +# Experimental: this type is part of an experimental API and may change or be removed. +class SessionLimitPredictionSource(Enum): + """Baseline fallback level used to create the prediction.""" + + FAMILY = "family" + GLOBAL = "global" + MODEL = "model" + +class SessionLimitPredictionResultKind(Enum): + AVAILABLE = "available" + UNAVAILABLE = "unavailable" + +# Experimental: this type is part of an experimental API and may change or be removed. +class SessionLimitPredictionUnavailableReason(Enum): + """Reason no prediction is available. + + Reason a prediction could not be computed. + """ + AUTO_UNRESOLVED = "auto_unresolved" + NO_MODEL = "no_model" + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionList: @@ -7927,6 +9121,24 @@ def to_dict(self) -> dict: result["startupPrompts"] = from_list(from_str, self.startup_prompts) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionModelListRequest: + skip_cache: bool | None = None + """If true, bypasses the per-session model list cache and re-fetches from CAPI.""" + + @staticmethod + def from_dict(obj: Any) -> 'SessionModelListRequest': + assert isinstance(obj, dict) + skip_cache = from_union([from_bool, from_none], obj.get("skipCache")) + return SessionModelListRequest(skip_cache) + + def to_dict(self) -> dict: + result: dict = {} + if self.skip_cache is not None: + result["skipCache"] = from_union([from_bool, from_none], self.skip_cache) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource: @@ -7948,6 +9160,23 @@ def to_dict(self) -> dict: result["type"] = from_str(self.type) return result +# Experimental: this type is part of an experimental API and may change or be removed. +class ShellInitProfile(Enum): + """Controls automatic non-interactive profile loading where supported. Explicit initScripts + are unaffected. + """ + NONE = "none" + NON_INTERACTIVE = "non-interactive" + +# Experimental: this type is part of an experimental API and may change or be removed. +class ShellInitScriptShell(Enum): + """Built-in shell that may source this script. + + Supported built-in shells for initialization scripts. + """ + BASH = "bash" + POWERSHELL = "powershell" + class SessionOpenParamsKind(Enum): ATTACH = "attach" CLOUD = "cloud" @@ -7975,15 +9204,61 @@ class SessionsOpenProgressStep(Enum): SAVE_SESSION = "save-session" VALIDATE_REPO = "validate-repo" -# Experimental: this type is part of an experimental API and may change or be removed. -class SessionsOpenStatus(Enum): - """Outcome of the open request.""" +# Experimental: this type is part of an experimental API and may change or be removed. +class SessionsOpenStatus(Enum): + """Outcome of the open request.""" + + CONNECTED = "connected" + CREATED = "created" + HANDED_OFF = "handed_off" + NOT_FOUND = "not_found" + RESUMED = "resumed" + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionPluginsReloadRequest: + defer_repo_hooks: bool | None = None + """When true, skip repo-level hooks during the hook reload. Use before folder trust is + confirmed; load them post-trust via `sessions.loadDeferredRepoHooks`. + """ + reload_custom_agents: bool | None = None + """Re-run custom-agent discovery after refreshing plugins. Defaults to true.""" + + reload_extensions: bool | None = None + """Re-discover and relaunch subprocess extensions (including plugin-shipped extensions) + after refreshing plugins. Defaults to true. Has no effect when the session has no active + extension controller (e.g. extensions were not requested for the session). + """ + reload_hooks: bool | None = None + """Re-load user, plugin, and (subject to `deferRepoHooks`) repo hooks. Defaults to true. Has + no effect when the host has not registered a hook reloader (e.g. remote sessions). + """ + reload_mcp: bool | None = None + """Reload MCP server connections after refreshing plugins. Defaults to true.""" + + @staticmethod + def from_dict(obj: Any) -> 'SessionPluginsReloadRequest': + assert isinstance(obj, dict) + defer_repo_hooks = from_union([from_bool, from_none], obj.get("deferRepoHooks")) + reload_custom_agents = from_union([from_bool, from_none], obj.get("reloadCustomAgents")) + reload_extensions = from_union([from_bool, from_none], obj.get("reloadExtensions")) + reload_hooks = from_union([from_bool, from_none], obj.get("reloadHooks")) + reload_mcp = from_union([from_bool, from_none], obj.get("reloadMcp")) + return SessionPluginsReloadRequest(defer_repo_hooks, reload_custom_agents, reload_extensions, reload_hooks, reload_mcp) - CONNECTED = "connected" - CREATED = "created" - HANDED_OFF = "handed_off" - NOT_FOUND = "not_found" - RESUMED = "resumed" + def to_dict(self) -> dict: + result: dict = {} + if self.defer_repo_hooks is not None: + result["deferRepoHooks"] = from_union([from_bool, from_none], self.defer_repo_hooks) + if self.reload_custom_agents is not None: + result["reloadCustomAgents"] = from_union([from_bool, from_none], self.reload_custom_agents) + if self.reload_extensions is not None: + result["reloadExtensions"] = from_union([from_bool, from_none], self.reload_extensions) + if self.reload_hooks is not None: + result["reloadHooks"] = from_union([from_bool, from_none], self.reload_hooks) + if self.reload_mcp is not None: + result["reloadMcp"] = from_union([from_bool, from_none], self.reload_mcp) + return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass @@ -8507,6 +9782,31 @@ def to_dict(self) -> dict: result: dict = {} return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionsDeleteRequest: + """Session ID to delete from disk.""" + + session_id: str + """Session ID to delete""" + + session_path: str | None = None + """Internal resolved session directory path to delete""" + + @staticmethod + def from_dict(obj: Any) -> 'SessionsDeleteRequest': + assert isinstance(obj, dict) + session_id = from_str(obj.get("sessionId")) + session_path = from_union([from_none, from_str], obj.get("sessionPath")) + return SessionsDeleteRequest(session_id, session_path) + + def to_dict(self) -> dict: + result: dict = {} + result["sessionId"] = from_str(self.session_id) + if self.session_path is not None: + result["sessionPath"] = from_union([from_none, from_str], self.session_path) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionsFindByPrefixRequest: @@ -8743,6 +10043,25 @@ def to_dict(self) -> dict: result["sessionId"] = from_union([from_str, from_none], self.session_id) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionsGetMetadataRequest: + """Session ID whose persisted metadata should be read.""" + + session_id: str + """Session ID to inspect""" + + @staticmethod + def from_dict(obj: Any) -> 'SessionsGetMetadataRequest': + assert isinstance(obj, dict) + session_id = from_str(obj.get("sessionId")) + return SessionsGetMetadataRequest(session_id) + + def to_dict(self) -> dict: + result: dict = {} + 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 SessionsGetPersistedRemoteSteerableRequest: @@ -8785,6 +10104,45 @@ def to_dict(self) -> dict: result["remoteSteerable"] = from_union([from_bool, from_none], self.remote_steerable) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionsListNonEmptySessionIDSRequest: + """Limit for non-empty local session IDs.""" + + limit: int | None = None + """Maximum number of session IDs to return.""" + + @staticmethod + def from_dict(obj: Any) -> 'SessionsListNonEmptySessionIDSRequest': + assert isinstance(obj, dict) + limit = from_union([from_int, from_none], obj.get("limit")) + return SessionsListNonEmptySessionIDSRequest(limit) + + def to_dict(self) -> dict: + result: dict = {} + if self.limit is not None: + result["limit"] = from_union([from_int, from_none], self.limit) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionsListNonEmptySessionIDSResult: + """Recent local session IDs that contain user-visible history.""" + + session_ids: list[str] + """Session IDs ordered newest-first.""" + + @staticmethod + def from_dict(obj: Any) -> 'SessionsListNonEmptySessionIDSResult': + assert isinstance(obj, dict) + session_ids = from_list(from_str, obj.get("sessionIds")) + return SessionsListNonEmptySessionIDSResult(session_ids) + + def to_dict(self) -> dict: + result: dict = {} + result["sessionIds"] = from_list(from_str, self.session_ids) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionsLoadDeferredRepoHooksRequest: @@ -10530,6 +11888,72 @@ class WorkspaceDiffMode(Enum): SESSION = "session" UNSTAGED = "unstaged" +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class WorkspacesAddSummaryRequest: + """Compaction summary checkpoint to persist.""" + + content: str + """Markdown summary content to persist.""" + + title: str + """Summary title shown in checkpoint listings.""" + + @staticmethod + def from_dict(obj: Any) -> 'WorkspacesAddSummaryRequest': + assert isinstance(obj, dict) + content = from_str(obj.get("content")) + title = from_str(obj.get("title")) + return WorkspacesAddSummaryRequest(content, title) + + def to_dict(self) -> dict: + result: dict = {} + result["content"] = from_str(self.content) + result["title"] = from_str(self.title) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class WorkspacesAddSummaryResult: + """Persisted summary metadata and refreshed workspace metadata.""" + + summary: dict[str, Any] | None = None + workspace: dict[str, Any] | None = None + + @staticmethod + def from_dict(obj: Any) -> 'WorkspacesAddSummaryResult': + assert isinstance(obj, dict) + summary = from_union([lambda x: from_dict(lambda x: x, x), from_none], obj.get("summary")) + workspace = from_union([lambda x: from_dict(lambda x: x, x), from_none], obj.get("workspace")) + return WorkspacesAddSummaryResult(summary, workspace) + + def to_dict(self) -> dict: + result: dict = {} + if self.summary is not None: + result["summary"] = from_union([lambda x: from_dict(lambda x: x, x), from_none], self.summary) + if self.workspace is not None: + result["workspace"] = from_union([lambda x: from_dict(lambda x: x, x), from_none], self.workspace) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class WorkspacesAutopilotObjectiveExistsResult: + """Whether the autopilot objective file exists.""" + + exists: bool + """True when the objective file exists.""" + + @staticmethod + def from_dict(obj: Any) -> 'WorkspacesAutopilotObjectiveExistsResult': + assert isinstance(obj, dict) + exists = from_bool(obj.get("exists")) + return WorkspacesAutopilotObjectiveExistsResult(exists) + + def to_dict(self) -> dict: + result: dict = {} + result["exists"] = from_bool(self.exists) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class WorkspacesCreateFileRequest: @@ -10554,6 +11978,45 @@ def to_dict(self) -> dict: result["path"] = from_str(self.path) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class WorkspacesDeleteAutopilotObjectiveResult: + """Result of deleting the autopilot objective file.""" + + deleted: bool + """True when a file was deleted.""" + + @staticmethod + def from_dict(obj: Any) -> 'WorkspacesDeleteAutopilotObjectiveResult': + assert isinstance(obj, dict) + deleted = from_bool(obj.get("deleted")) + return WorkspacesDeleteAutopilotObjectiveResult(deleted) + + def to_dict(self) -> dict: + result: dict = {} + result["deleted"] = from_bool(self.deleted) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class WorkspacesEnsureRequest: + """Optional session context used when creating a local workspace.""" + + context: Any = None + """Opaque workspace context supplied by the session host.""" + + @staticmethod + def from_dict(obj: Any) -> 'WorkspacesEnsureRequest': + assert isinstance(obj, dict) + context = obj.get("context") + return WorkspacesEnsureRequest(context) + + def to_dict(self) -> dict: + result: dict = {} + if self.context is not None: + result["context"] = self.context + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class WorkspacesListFilesResult: @@ -10573,6 +12036,25 @@ def to_dict(self) -> dict: result["files"] = from_list(from_str, self.files) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class WorkspacesReadAutopilotObjectiveResult: + """Autopilot objective file content, or null when missing.""" + + content: str | None = None + """Autopilot objective file content, or null when missing.""" + + @staticmethod + def from_dict(obj: Any) -> 'WorkspacesReadAutopilotObjectiveResult': + assert isinstance(obj, dict) + content = from_union([from_none, from_str], obj.get("content")) + return WorkspacesReadAutopilotObjectiveResult(content) + + def to_dict(self) -> dict: + result: dict = {} + result["content"] = from_union([from_none, from_str], self.content) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class WorkspacesReadCheckpointRequest: @@ -10694,6 +12176,63 @@ def to_dict(self) -> dict: result["sizeBytes"] = from_int(self.size_bytes) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class WorkspacesTruncateSummariesRequest: + """Rollback point for local workspace summaries.""" + + keep_count: int + """Number of newest summaries to keep.""" + + @staticmethod + def from_dict(obj: Any) -> 'WorkspacesTruncateSummariesRequest': + assert isinstance(obj, dict) + keep_count = from_int(obj.get("keepCount")) + return WorkspacesTruncateSummariesRequest(keep_count) + + def to_dict(self) -> dict: + result: dict = {} + result["keepCount"] = from_int(self.keep_count) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class WorkspacesWriteAutopilotObjectiveRequest: + """Autopilot objective file content to persist.""" + + content: str + """Autopilot objective file content.""" + + @staticmethod + def from_dict(obj: Any) -> 'WorkspacesWriteAutopilotObjectiveRequest': + assert isinstance(obj, dict) + content = from_str(obj.get("content")) + return WorkspacesWriteAutopilotObjectiveRequest(content) + + def to_dict(self) -> dict: + result: dict = {} + result["content"] = from_str(self.content) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class WorkspacesWriteAutopilotObjectiveResult: + """Result of writing the autopilot objective file.""" + + operation: str + """Filesystem operation performed.""" + + @staticmethod + def from_dict(obj: Any) -> 'WorkspacesWriteAutopilotObjectiveResult': + assert isinstance(obj, dict) + operation = from_str(obj.get("operation")) + return WorkspacesWriteAutopilotObjectiveResult(operation) + + def to_dict(self) -> dict: + result: dict = {} + result["operation"] = from_str(self.operation) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionAuthStatus: @@ -11173,6 +12712,32 @@ def to_dict(self) -> dict: result["summary"] = from_union([from_str, from_none], self.summary) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class ContentExclusionCheckPathsResult: + """Batch content-exclusion result. Callers must fail closed when policy evaluation is + unavailable. + """ + available: bool + """Whether the session's policy service was available for the complete batch. When false, + checks is empty and callers must treat every requested path as excluded. + """ + checks: list[ContentExclusionPathCheck] + """Per-path decisions in request order. Empty when available is false.""" + + @staticmethod + def from_dict(obj: Any) -> 'ContentExclusionCheckPathsResult': + assert isinstance(obj, dict) + available = from_bool(obj.get("available")) + checks = from_list(ContentExclusionPathCheck.from_dict, obj.get("checks")) + return ContentExclusionCheckPathsResult(available, checks) + + def to_dict(self) -> dict: + result: dict = {} + result["available"] = from_bool(self.available) + result["checks"] = from_list(lambda x: to_class(ContentExclusionPathCheck, x), self.checks) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MetadataContextHeaviestMessagesResult: @@ -11445,6 +13010,12 @@ class EventLogReadRequest: """Opaque cursor returned by a previous read. Omit on the first call to start from the beginning of the session's persisted history. """ + include_ephemeral: bool | None = None + """When false, skip ephemeral events entirely and return only durable (persisted) events. + History-backfill callers that discard ephemerals anyway should set this so the read is + bounded by the durable log length instead of racing the ephemeral ring on a busy session. + Defaults to true (ephemerals are interleaved with durable events in creation order). + """ max: int | None = None """Maximum number of events to return in this batch (1–1000, default 200).""" @@ -11464,10 +13035,11 @@ def from_dict(obj: Any) -> 'EventLogReadRequest': assert isinstance(obj, dict) agent_scope = from_union([EventsAgentScope, from_none], obj.get("agentScope")) cursor = from_union([from_str, from_none], obj.get("cursor")) + include_ephemeral = from_union([from_bool, from_none], obj.get("includeEphemeral")) 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")) wait_ms = from_union([from_int, from_none], obj.get("waitMs")) - return EventLogReadRequest(agent_scope, cursor, max, types, wait_ms) + return EventLogReadRequest(agent_scope, cursor, include_ephemeral, max, types, wait_ms) def to_dict(self) -> dict: result: dict = {} @@ -11475,6 +13047,8 @@ def to_dict(self) -> dict: result["agentScope"] = from_union([lambda x: to_enum(EventsAgentScope, x), from_none], self.agent_scope) if self.cursor is not None: result["cursor"] = from_union([from_str, from_none], self.cursor) + if self.include_ephemeral is not None: + result["includeEphemeral"] = from_union([from_bool, from_none], self.include_ephemeral) if self.max is not None: result["max"] = from_union([from_int, from_none], self.max) if self.types is not None: @@ -11498,10 +13072,11 @@ class EventsReadResult: and the read started from the beginning of the remaining history. """ events: list[SessionEvent] - """Events are delivered in two batches per read: persisted events first (in append order), - then ephemeral events (in seq order). When `waitMs > 0` and the catch-up batches were - empty, post-wait events follow the same two-batch ordering. Persisted and ephemeral - events do not interleave within a single read. + """Session events for this batch, merged into a single stream in creation order: durable + (persisted) events and ephemeral events interleave exactly as they were emitted. Set + `includeEphemeral: false` to receive only durable events. Ephemeral events are never + replayable once pruned from the in-memory ring, so a consumer that needs them should keep + reading with a non-zero `waitMs`. """ has_more: bool """True when the read returned `max` events and more events are available immediately. When @@ -11953,28 +13528,89 @@ def to_dict(self) -> dict: class FactoryAgentRequest: """Parameters for one factory-scoped subagent call.""" - factory_run_id: str - """Factory run identifier that owns the subagent.""" + execution_token: str + """Opaque token identifying the current factory execution attempt.""" + + factory_run_id: str + """Factory run identifier that owns the subagent.""" + + opts: FactoryAgentOptions + """Subagent execution options.""" + + prompt: str + """Prompt to send to the subagent.""" + + @staticmethod + def from_dict(obj: Any) -> 'FactoryAgentRequest': + assert isinstance(obj, dict) + execution_token = from_str(obj.get("executionToken")) + factory_run_id = from_str(obj.get("factoryRunId")) + opts = FactoryAgentOptions.from_dict(obj.get("opts")) + prompt = from_str(obj.get("prompt")) + return FactoryAgentRequest(execution_token, factory_run_id, opts, prompt) + + def to_dict(self) -> dict: + result: dict = {} + result["executionToken"] = from_str(self.execution_token) + result["factoryRunId"] = from_str(self.factory_run_id) + result["opts"] = to_class(FactoryAgentOptions, self.opts) + result["prompt"] = from_str(self.prompt) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class FactoryRunFailure: + """Machine-readable factory run failure. + + Machine-readable failure details for an errored run. + """ + run_id: str + """Factory run identifier. + + Factory run identifier whose changed limits were declined. + """ + type: FactoryRunFailureType + kind: FactoryRunFailureKind | None = None + """Resource ceiling that stopped the run.""" + + value: float | None = None + """Approved effective ceiling that was reached.""" - opts: FactoryAgentOptions - """Subagent execution options.""" + reason: str | None = None + """Human-readable reason the resume did not proceed.""" - prompt: str - """Prompt to send to the subagent.""" + code: str | None = None + """Stable failure code.""" + + operation: FactoryDurableOperation | None = None + """Execution-critical durable operation that failed.""" @staticmethod - def from_dict(obj: Any) -> 'FactoryAgentRequest': + def from_dict(obj: Any) -> 'FactoryRunFailure': assert isinstance(obj, dict) - factory_run_id = from_str(obj.get("factoryRunId")) - opts = FactoryAgentOptions.from_dict(obj.get("opts")) - prompt = from_str(obj.get("prompt")) - return FactoryAgentRequest(factory_run_id, opts, prompt) + run_id = from_str(obj.get("runId")) + type = FactoryRunFailureType(obj.get("type")) + kind = from_union([FactoryRunFailureKind, from_none], obj.get("kind")) + value = from_union([from_float, from_none], obj.get("value")) + reason = from_union([from_str, from_none], obj.get("reason")) + code = from_union([from_str, from_none], obj.get("code")) + operation = from_union([FactoryDurableOperation, from_none], obj.get("operation")) + return FactoryRunFailure(run_id, type, kind, value, reason, code, operation) def to_dict(self) -> dict: result: dict = {} - result["factoryRunId"] = from_str(self.factory_run_id) - result["opts"] = to_class(FactoryAgentOptions, self.opts) - result["prompt"] = from_str(self.prompt) + result["runId"] = from_str(self.run_id) + result["type"] = to_enum(FactoryRunFailureType, self.type) + if self.kind is not None: + result["kind"] = from_union([lambda x: to_enum(FactoryRunFailureKind, x), from_none], self.kind) + if self.value is not None: + result["value"] = from_union([to_float, from_none], self.value) + if self.reason is not None: + result["reason"] = from_union([from_str, from_none], self.reason) + if self.code is not None: + result["code"] = from_union([from_str, from_none], self.code) + if self.operation is not None: + result["operation"] = from_union([lambda x: to_enum(FactoryDurableOperation, x), from_none], self.operation) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -12008,46 +13644,128 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class FactoryRunFailure: - """Machine-readable factory run failure. +class FactoryProgressLine: + """One durable factory progress record.""" - Machine-readable failure details for an errored run. - """ - run_id: str - """Factory run identifier. + attempt: int + """Resume attempt that emitted this record.""" - Factory run identifier whose changed limits were declined. - """ - type: FactoryRunFailureType - kind: FactoryRunFailureKind | None = None - """Resource ceiling that stopped the run.""" + kind: FactoryLogLineKind + """Progress record kind.""" - value: float | None = None - """Approved effective ceiling that was reached.""" + recorded_at: int + """Epoch milliseconds when the record was persisted.""" - reason: str | None = None - """Human-readable reason the resume did not proceed.""" + seq: int + """Global monotonic sequence number within the run.""" + + text: str + """Prompt-safe progress text.""" + + phase_id: str | None = None + """Phase active when the record was emitted, or null before any phase.""" @staticmethod - def from_dict(obj: Any) -> 'FactoryRunFailure': + def from_dict(obj: Any) -> 'FactoryProgressLine': + assert isinstance(obj, dict) + attempt = from_int(obj.get("attempt")) + kind = FactoryLogLineKind(obj.get("kind")) + recorded_at = from_int(obj.get("recordedAt")) + seq = from_int(obj.get("seq")) + text = from_str(obj.get("text")) + phase_id = from_union([from_none, from_str], obj.get("phaseId")) + return FactoryProgressLine(attempt, kind, recorded_at, seq, text, phase_id) + + def to_dict(self) -> dict: + result: dict = {} + result["attempt"] = from_int(self.attempt) + result["kind"] = to_enum(FactoryLogLineKind, self.kind) + result["recordedAt"] = from_int(self.recorded_at) + result["seq"] = from_int(self.seq) + result["text"] = from_str(self.text) + result["phaseId"] = from_union([from_none, from_str], self.phase_id) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class FactoryPhaseObservation: + """Durable lifecycle and timing for one factory phase.""" + + accumulated_active_ms: int + current_active_ms: int + entry_count: int + id: str + last_entered_run_attempt: int + live_agent_count: int + status: FactoryPhaseStatus + title: str + total_agent_count: int + completed_at: int | None = None + detail: str | None = None + ordinal: int | None = None + started_at: int | None = None + + @staticmethod + def from_dict(obj: Any) -> 'FactoryPhaseObservation': + assert isinstance(obj, dict) + accumulated_active_ms = from_int(obj.get("accumulatedActiveMs")) + current_active_ms = from_int(obj.get("currentActiveMs")) + entry_count = from_int(obj.get("entryCount")) + id = from_str(obj.get("id")) + last_entered_run_attempt = from_int(obj.get("lastEnteredRunAttempt")) + live_agent_count = from_int(obj.get("liveAgentCount")) + status = FactoryPhaseStatus(obj.get("status")) + title = from_str(obj.get("title")) + total_agent_count = from_int(obj.get("totalAgentCount")) + completed_at = from_union([from_int, from_none], obj.get("completedAt")) + detail = from_union([from_str, from_none], obj.get("detail")) + ordinal = from_union([from_none, from_int], obj.get("ordinal")) + started_at = from_union([from_int, from_none], obj.get("startedAt")) + return FactoryPhaseObservation(accumulated_active_ms, current_active_ms, entry_count, id, last_entered_run_attempt, live_agent_count, status, title, total_agent_count, completed_at, detail, ordinal, started_at) + + def to_dict(self) -> dict: + result: dict = {} + result["accumulatedActiveMs"] = from_int(self.accumulated_active_ms) + result["currentActiveMs"] = from_int(self.current_active_ms) + result["entryCount"] = from_int(self.entry_count) + result["id"] = from_str(self.id) + result["lastEnteredRunAttempt"] = from_int(self.last_entered_run_attempt) + result["liveAgentCount"] = from_int(self.live_agent_count) + result["status"] = to_enum(FactoryPhaseStatus, self.status) + result["title"] = from_str(self.title) + result["totalAgentCount"] = from_int(self.total_agent_count) + if self.completed_at is not None: + result["completedAt"] = from_union([from_int, from_none], self.completed_at) + if self.detail is not None: + result["detail"] = from_union([from_str, from_none], self.detail) + result["ordinal"] = from_union([from_none, from_int], self.ordinal) + if self.started_at is not None: + result["startedAt"] = from_union([from_int, from_none], self.started_at) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class FactoryResumeRequest: + """Parameters for resuming a factory run from its persisted identity.""" + + run_id: str + """Factory run identifier.""" + + limits: FactoryRunLimits | None = None + """Optional per-invocation resource ceiling overrides.""" + + @staticmethod + def from_dict(obj: Any) -> 'FactoryResumeRequest': assert isinstance(obj, dict) run_id = from_str(obj.get("runId")) - type = FactoryRunFailureType(obj.get("type")) - kind = from_union([FactoryRunFailureKind, from_none], obj.get("kind")) - value = from_union([from_float, from_none], obj.get("value")) - reason = from_union([from_str, from_none], obj.get("reason")) - return FactoryRunFailure(run_id, type, kind, value, reason) + limits = from_union([FactoryRunLimits.from_dict, from_none], obj.get("limits")) + return FactoryResumeRequest(run_id, limits) def to_dict(self) -> dict: result: dict = {} result["runId"] = from_str(self.run_id) - result["type"] = to_enum(FactoryRunFailureType, self.type) - if self.kind is not None: - result["kind"] = from_union([lambda x: to_enum(FactoryRunFailureKind, x), from_none], self.kind) - if self.value is not None: - result["value"] = from_union([to_float, from_none], self.value) - if self.reason is not None: - result["reason"] = from_union([from_str, from_none], self.reason) + if self.limits is not None: + result["limits"] = from_union([lambda x: to_class(FactoryRunLimits, x), from_none], self.limits) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -12122,6 +13840,127 @@ def to_dict(self) -> dict: result["summaryContent"] = from_union([from_str, from_none], self.summary_content) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class HistorySkippedFileRestore: + """A captured file that rewind intentionally left unchanged.""" + + path: str + """Absolute path of the skipped file.""" + + reason: HistoryFileRestoreSkipReason + """Reason the file was not restored.""" + + @staticmethod + def from_dict(obj: Any) -> 'HistorySkippedFileRestore': + assert isinstance(obj, dict) + path = from_str(obj.get("path")) + reason = HistoryFileRestoreSkipReason(obj.get("reason")) + return HistorySkippedFileRestore(path, reason) + + def to_dict(self) -> dict: + result: dict = {} + result["path"] = from_str(self.path) + result["reason"] = to_enum(HistoryFileRestoreSkipReason, self.reason) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class HistoryListRewindPointsResult: + """Rewind points and file-change-tracking availability for the session.""" + + file_change_tracking_enabled: bool + """Whether this session captured file changes from its first turn.""" + + points: list[HistoryRewindPoint] + """Root user turns in chronological order. Empty when `unavailableReason` is set.""" + + unavailable_reason: HistoryRewindUnavailableReason | None = None + """Why the listed points could not be produced, when applicable; the points list is empty + whenever it is set. `unsupported-remote-session` is permanent for the session and comes + with `fileChangeTrackingEnabled: false`. `session-busy` is transient and only ever + reported by a session that *is* tracking (`fileChangeTrackingEnabled: true`), because the + file-change captures cannot be read while work that may still mutate them is in flight; + the same request succeeds once the session settles, so a client that wants points should + retry rather than treat it as a failure. It is never `file-change-tracking-disabled`: an + untracked local session still lists conversation-only points and reports that through + `fileChangeTrackingEnabled: false`. + """ + + @staticmethod + def from_dict(obj: Any) -> 'HistoryListRewindPointsResult': + assert isinstance(obj, dict) + file_change_tracking_enabled = from_bool(obj.get("fileChangeTrackingEnabled")) + points = from_list(HistoryRewindPoint.from_dict, obj.get("points")) + unavailable_reason = from_union([HistoryRewindUnavailableReason, from_none], obj.get("unavailableReason")) + return HistoryListRewindPointsResult(file_change_tracking_enabled, points, unavailable_reason) + + def to_dict(self) -> dict: + result: dict = {} + result["fileChangeTrackingEnabled"] = from_bool(self.file_change_tracking_enabled) + result["points"] = from_list(lambda x: to_class(HistoryRewindPoint, x), self.points) + if self.unavailable_reason is not None: + result["unavailableReason"] = from_union([lambda x: to_enum(HistoryRewindUnavailableReason, x), from_none], self.unavailable_reason) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class HistoryRewindFilePreview: + """A file that a conversation-and-files rewind would restore.""" + + change_type: HistoryRewindChangeType + """Aggregate change made across the discarded turns.""" + + lines_added: int + """Lines added across the discarded turns.""" + + lines_removed: int + """Lines removed across the discarded turns.""" + + path: str + """Absolute path of the captured file.""" + + @staticmethod + def from_dict(obj: Any) -> 'HistoryRewindFilePreview': + assert isinstance(obj, dict) + change_type = HistoryRewindChangeType(obj.get("changeType")) + lines_added = from_int(obj.get("linesAdded")) + lines_removed = from_int(obj.get("linesRemoved")) + path = from_str(obj.get("path")) + return HistoryRewindFilePreview(change_type, lines_added, lines_removed, path) + + def to_dict(self) -> dict: + result: dict = {} + result["changeType"] = to_enum(HistoryRewindChangeType, self.change_type) + result["linesAdded"] = from_int(self.lines_added) + result["linesRemoved"] = from_int(self.lines_removed) + result["path"] = from_str(self.path) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class HistoryRewindRequest: + """Boundary and mode for rewinding session history.""" + + event_id: str + """ID of the user.message event that begins the discarded suffix.""" + + mode: HistoryRewindMode + """Whether to rewind only conversation history or also restore captured files.""" + + @staticmethod + def from_dict(obj: Any) -> 'HistoryRewindRequest': + assert isinstance(obj, dict) + event_id = from_str(obj.get("eventId")) + mode = HistoryRewindMode(obj.get("mode")) + return HistoryRewindRequest(event_id, mode) + + def to_dict(self) -> dict: + result: dict = {} + result["eventId"] = from_str(self.event_id) + result["mode"] = to_enum(HistoryRewindMode, self.mode) + return result + # Internal: this type is an internal SDK API and is not part of the public surface. @dataclass class _HookInvokeRequest: @@ -12149,11 +13988,11 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class InstalledPluginSource: - """Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref, - and optional subpath. + """Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref or + full commit SHA, and optional subpath. - Source descriptor for a direct URL plugin install, with URL, optional ref, and optional - subpath. + Source descriptor for a direct URL plugin install, with URL, optional ref or full commit + SHA, and optional subpath. Source descriptor for a direct local plugin install, with a local filesystem path. """ @@ -12167,6 +14006,9 @@ class InstalledPluginSource: path: str | None = None ref: str | None = None repo: str | None = None + sha: str | None = None + """Optional full 40-character hexadecimal commit SHA.""" + url: str | None = None @staticmethod @@ -12176,8 +14018,9 @@ def from_dict(obj: Any) -> 'InstalledPluginSource': path = from_union([from_str, from_none], obj.get("path")) ref = from_union([from_str, from_none], obj.get("ref")) repo = from_union([from_str, from_none], obj.get("repo")) + sha = from_union([from_str, from_none], obj.get("sha")) url = from_union([from_str, from_none], obj.get("url")) - return InstalledPluginSource(source, path, ref, repo, url) + return InstalledPluginSource(source, path, ref, repo, sha, url) def to_dict(self) -> dict: result: dict = {} @@ -12188,6 +14031,8 @@ def to_dict(self) -> dict: result["ref"] = from_union([from_str, from_none], self.ref) if self.repo is not None: result["repo"] = from_union([from_str, from_none], self.repo) + if self.sha is not None: + result["sha"] = from_union([from_str, from_none], self.sha) if self.url is not None: result["url"] = from_union([from_str, from_none], self.url) return result @@ -12195,11 +14040,11 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionInstalledPluginSource: - """Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref, - and optional subpath. + """Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref or + full commit SHA, and optional subpath. - Source descriptor for a direct URL plugin install, with URL, optional ref, and optional - subpath. + Source descriptor for a direct URL plugin install, with URL, optional ref or full commit + SHA, and optional subpath. Source descriptor for a direct local plugin install, with a local filesystem path. """ @@ -12213,6 +14058,9 @@ class SessionInstalledPluginSource: path: str | None = None ref: str | None = None repo: str | None = None + sha: str | None = None + """Optional full 40-character hexadecimal commit SHA.""" + url: str | None = None @staticmethod @@ -12222,8 +14070,9 @@ def from_dict(obj: Any) -> 'SessionInstalledPluginSource': path = from_union([from_str, from_none], obj.get("path")) ref = from_union([from_str, from_none], obj.get("ref")) repo = from_union([from_str, from_none], obj.get("repo")) + sha = from_union([from_str, from_none], obj.get("sha")) url = from_union([from_str, from_none], obj.get("url")) - return SessionInstalledPluginSource(source, path, ref, repo, url) + return SessionInstalledPluginSource(source, path, ref, repo, sha, url) def to_dict(self) -> dict: result: dict = {} @@ -12234,6 +14083,8 @@ def to_dict(self) -> dict: result["ref"] = from_union([from_str, from_none], self.ref) if self.repo is not None: result["repo"] = from_union([from_str, from_none], self.repo) + if self.sha is not None: + result["sha"] = from_union([from_str, from_none], self.sha) if self.url is not None: result["url"] = from_union([from_str, from_none], self.url) return result @@ -12241,8 +14092,8 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class InstalledPluginSourceGitHub: - """Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref, - and optional subpath. + """Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref or + full commit SHA, and optional subpath. """ repo: str source: FluffySource @@ -12250,6 +14101,8 @@ class InstalledPluginSourceGitHub: path: str | None = None ref: str | None = None + sha: str | None = None + """Optional full 40-character hexadecimal commit SHA.""" @staticmethod def from_dict(obj: Any) -> 'InstalledPluginSourceGitHub': @@ -12258,7 +14111,8 @@ def from_dict(obj: Any) -> 'InstalledPluginSourceGitHub': source = FluffySource(obj.get("source")) path = from_union([from_str, from_none], obj.get("path")) ref = from_union([from_str, from_none], obj.get("ref")) - return InstalledPluginSourceGitHub(repo, source, path, ref) + sha = from_union([from_str, from_none], obj.get("sha")) + return InstalledPluginSourceGitHub(repo, source, path, ref, sha) def to_dict(self) -> dict: result: dict = {} @@ -12268,13 +14122,15 @@ def to_dict(self) -> dict: result["path"] = from_union([from_str, from_none], self.path) if self.ref is not None: result["ref"] = from_union([from_str, from_none], self.ref) + if self.sha is not None: + result["sha"] = from_union([from_str, from_none], self.sha) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionInstalledPluginSourceGitHub: - """Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref, - and optional subpath. + """Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref or + full commit SHA, and optional subpath. """ repo: str source: FluffySource @@ -12282,6 +14138,8 @@ class SessionInstalledPluginSourceGitHub: path: str | None = None ref: str | None = None + sha: str | None = None + """Optional full 40-character hexadecimal commit SHA.""" @staticmethod def from_dict(obj: Any) -> 'SessionInstalledPluginSourceGitHub': @@ -12290,7 +14148,8 @@ def from_dict(obj: Any) -> 'SessionInstalledPluginSourceGitHub': source = FluffySource(obj.get("source")) path = from_union([from_str, from_none], obj.get("path")) ref = from_union([from_str, from_none], obj.get("ref")) - return SessionInstalledPluginSourceGitHub(repo, source, path, ref) + sha = from_union([from_str, from_none], obj.get("sha")) + return SessionInstalledPluginSourceGitHub(repo, source, path, ref, sha) def to_dict(self) -> dict: result: dict = {} @@ -12300,6 +14159,8 @@ def to_dict(self) -> dict: result["path"] = from_union([from_str, from_none], self.path) if self.ref is not None: result["ref"] = from_union([from_str, from_none], self.ref) + if self.sha is not None: + result["sha"] = from_union([from_str, from_none], self.sha) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -12349,8 +14210,8 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class InstalledPluginSourceURL: - """Source descriptor for a direct URL plugin install, with URL, optional ref, and optional - subpath. + """Source descriptor for a direct URL plugin install, with URL, optional ref or full commit + SHA, and optional subpath. """ source: StickySource """Constant value. Always "url".""" @@ -12358,6 +14219,8 @@ class InstalledPluginSourceURL: url: str path: str | None = None ref: str | None = None + sha: str | None = None + """Optional full 40-character hexadecimal commit SHA.""" @staticmethod def from_dict(obj: Any) -> 'InstalledPluginSourceURL': @@ -12366,7 +14229,8 @@ def from_dict(obj: Any) -> 'InstalledPluginSourceURL': url = from_str(obj.get("url")) path = from_union([from_str, from_none], obj.get("path")) ref = from_union([from_str, from_none], obj.get("ref")) - return InstalledPluginSourceURL(source, url, path, ref) + sha = from_union([from_str, from_none], obj.get("sha")) + return InstalledPluginSourceURL(source, url, path, ref, sha) def to_dict(self) -> dict: result: dict = {} @@ -12376,13 +14240,15 @@ def to_dict(self) -> dict: result["path"] = from_union([from_str, from_none], self.path) if self.ref is not None: result["ref"] = from_union([from_str, from_none], self.ref) + if self.sha is not None: + result["sha"] = from_union([from_str, from_none], self.sha) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionInstalledPluginSourceURL: - """Source descriptor for a direct URL plugin install, with URL, optional ref, and optional - subpath. + """Source descriptor for a direct URL plugin install, with URL, optional ref or full commit + SHA, and optional subpath. """ source: StickySource """Constant value. Always "url".""" @@ -12390,6 +14256,8 @@ class SessionInstalledPluginSourceURL: url: str path: str | None = None ref: str | None = None + sha: str | None = None + """Optional full 40-character hexadecimal commit SHA.""" @staticmethod def from_dict(obj: Any) -> 'SessionInstalledPluginSourceURL': @@ -12398,7 +14266,8 @@ def from_dict(obj: Any) -> 'SessionInstalledPluginSourceURL': url = from_str(obj.get("url")) path = from_union([from_str, from_none], obj.get("path")) ref = from_union([from_str, from_none], obj.get("ref")) - return SessionInstalledPluginSourceURL(source, url, path, ref) + sha = from_union([from_str, from_none], obj.get("sha")) + return SessionInstalledPluginSourceURL(source, url, path, ref, sha) def to_dict(self) -> dict: result: dict = {} @@ -12408,6 +14277,8 @@ def to_dict(self) -> dict: result["path"] = from_union([from_str, from_none], self.path) if self.ref is not None: result["ref"] = from_union([from_str, from_none], self.ref) + if self.sha is not None: + result["sha"] = from_union([from_str, from_none], self.sha) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -12446,9 +14317,8 @@ class InstructionSource: project_path: str | None = None """The project path this source was discovered from. Only set by sessionless discovery for - repository/working-directory sources, where it disambiguates same-named files (e.g. - .github/copilot-instructions.md) across multiple workspace roots. The session-scoped - getSources leaves it unset. + repository, working-directory, and project-scoped plugin sources, where it disambiguates + sources across multiple workspace roots. The session-scoped getSources leaves it unset. """ @staticmethod @@ -13085,6 +14955,10 @@ class MCPServerConfigStdio: """Controls if tools provided by this server can be loaded on demand via tool search (auto) or always included in the initial tool list (never) """ + disable_tool_cache: bool | None = None + """Set to true to disable persisted MCP tool snapshots for this server. Live tool discovery + is unaffected. + """ env: dict[str, str] | None = None """Environment variables to pass to the Stdio MCP server process.""" @@ -13113,13 +14987,14 @@ def from_dict(obj: Any) -> 'MCPServerConfigStdio': auth = from_union([from_bool, MCPServerAuthConfigRedirectPort.from_dict, from_none], obj.get("auth")) cwd = from_union([from_str, from_none], obj.get("cwd")) defer_tools = from_union([MCPServerConfigDeferTools, from_none], obj.get("deferTools")) + disable_tool_cache = from_union([from_bool, from_none], obj.get("disableToolCache")) env = from_union([lambda x: from_dict(from_str, x), from_none], obj.get("env")) filter_mapping = from_union([lambda x: from_dict(ContentFilterMode, x), ContentFilterMode, from_none], obj.get("filterMapping")) is_default_server = from_union([from_bool, from_none], obj.get("isDefaultServer")) oidc = from_union([from_bool, MCPServerAuthConfigRedirectPort.from_dict, from_none], obj.get("oidc")) timeout = from_union([from_int, from_none], obj.get("timeout")) tools = from_union([lambda x: from_list(from_str, x), from_none], obj.get("tools")) - return MCPServerConfigStdio(command, args, auth, cwd, defer_tools, env, filter_mapping, is_default_server, oidc, timeout, tools) + return MCPServerConfigStdio(command, args, auth, cwd, defer_tools, disable_tool_cache, env, filter_mapping, is_default_server, oidc, timeout, tools) def to_dict(self) -> dict: result: dict = {} @@ -13132,6 +15007,8 @@ def to_dict(self) -> dict: result["cwd"] = from_union([from_str, from_none], self.cwd) if self.defer_tools is not None: result["deferTools"] = from_union([lambda x: to_enum(MCPServerConfigDeferTools, x), from_none], self.defer_tools) + if self.disable_tool_cache is not None: + result["disableToolCache"] = from_union([from_bool, from_none], self.disable_tool_cache) if self.env is not None: result["env"] = from_union([lambda x: from_dict(from_str, x), from_none], self.env) if self.filter_mapping is not None: @@ -13231,6 +15108,9 @@ class MCPServerConfig: Replacement MCP server configuration (stdio process or remote HTTP/SSE). Omit to restart the server with its already-registered configuration (config-free restart-by-name). + MCP server configuration (stdio process or remote HTTP/SSE). Omit to start the server + with its already-registered configuration (config-free start-by-name). + Stdio MCP server configuration launched as a child process. Remote MCP server configuration accessed over HTTP or SSE. @@ -13251,6 +15131,10 @@ class MCPServerConfig: """Controls if tools provided by this server can be loaded on demand via tool search (auto) or always included in the initial tool list (never) """ + disable_tool_cache: bool | None = None + """Set to true to disable persisted MCP tool snapshots for this server. Live tool discovery + is unaffected. + """ env: dict[str, str] | None = None """Environment variables to pass to the Stdio MCP server process.""" @@ -13297,6 +15181,7 @@ def from_dict(obj: Any) -> 'MCPServerConfig': command = from_union([from_str, from_none], obj.get("command")) cwd = from_union([from_str, from_none], obj.get("cwd")) defer_tools = from_union([MCPServerConfigDeferTools, from_none], obj.get("deferTools")) + disable_tool_cache = from_union([from_bool, from_none], obj.get("disableToolCache")) env = from_union([lambda x: from_dict(from_str, x), from_none], obj.get("env")) filter_mapping = from_union([lambda x: from_dict(ContentFilterMode, x), ContentFilterMode, from_none], obj.get("filterMapping")) is_default_server = from_union([from_bool, from_none], obj.get("isDefaultServer")) @@ -13309,7 +15194,7 @@ def from_dict(obj: Any) -> 'MCPServerConfig': oauth_public_client = from_union([from_bool, from_none], obj.get("oauthPublicClient")) type = from_union([MCPServerConfigHTTPType, from_none], obj.get("type")) url = from_union([from_str, from_none], obj.get("url")) - return MCPServerConfig(args, auth, command, cwd, defer_tools, env, filter_mapping, is_default_server, oidc, timeout, tools, headers, oauth_client_id, oauth_grant_type, oauth_public_client, type, url) + return MCPServerConfig(args, auth, command, cwd, defer_tools, disable_tool_cache, env, filter_mapping, is_default_server, oidc, timeout, tools, headers, oauth_client_id, oauth_grant_type, oauth_public_client, type, url) def to_dict(self) -> dict: result: dict = {} @@ -13323,6 +15208,8 @@ def to_dict(self) -> dict: result["cwd"] = from_union([from_str, from_none], self.cwd) if self.defer_tools is not None: result["deferTools"] = from_union([lambda x: to_enum(MCPServerConfigDeferTools, x), from_none], self.defer_tools) + if self.disable_tool_cache is not None: + result["disableToolCache"] = from_union([from_bool, from_none], self.disable_tool_cache) if self.env is not None: result["env"] = from_union([lambda x: from_dict(from_str, x), from_none], self.env) if self.filter_mapping is not None: @@ -13364,6 +15251,10 @@ class MCPServerConfigHTTP: """Controls if tools provided by this server can be loaded on demand via tool search (auto) or always included in the initial tool list (never) """ + disable_tool_cache: bool | None = None + """Set to true to disable persisted MCP tool snapshots for this server. Live tool discovery + is unaffected. + """ filter_mapping: dict[str, ContentFilterMode] | ContentFilterMode | None = None """Content filtering mode to apply to all tools, or a map of tool name to content filtering mode. @@ -13402,6 +15293,7 @@ def from_dict(obj: Any) -> 'MCPServerConfigHTTP': url = from_str(obj.get("url")) auth = from_union([from_bool, MCPServerAuthConfigRedirectPort.from_dict, from_none], obj.get("auth")) defer_tools = from_union([MCPServerConfigDeferTools, from_none], obj.get("deferTools")) + disable_tool_cache = from_union([from_bool, from_none], obj.get("disableToolCache")) filter_mapping = from_union([lambda x: from_dict(ContentFilterMode, x), ContentFilterMode, from_none], obj.get("filterMapping")) headers = from_union([lambda x: from_dict(from_str, x), from_none], obj.get("headers")) is_default_server = from_union([from_bool, from_none], obj.get("isDefaultServer")) @@ -13412,7 +15304,7 @@ def from_dict(obj: Any) -> 'MCPServerConfigHTTP': timeout = from_union([from_int, from_none], obj.get("timeout")) tools = from_union([lambda x: from_list(from_str, x), from_none], obj.get("tools")) type = from_union([MCPServerConfigHTTPType, from_none], obj.get("type")) - return MCPServerConfigHTTP(url, auth, defer_tools, filter_mapping, headers, is_default_server, oauth_client_id, oauth_grant_type, oauth_public_client, oidc, timeout, tools, type) + return MCPServerConfigHTTP(url, auth, defer_tools, disable_tool_cache, filter_mapping, headers, is_default_server, oauth_client_id, oauth_grant_type, oauth_public_client, oidc, timeout, tools, type) def to_dict(self) -> dict: result: dict = {} @@ -13421,6 +15313,8 @@ def to_dict(self) -> dict: result["auth"] = from_union([from_bool, lambda x: to_class(MCPServerAuthConfigRedirectPort, x), from_none], self.auth) if self.defer_tools is not None: result["deferTools"] = from_union([lambda x: to_enum(MCPServerConfigDeferTools, x), from_none], self.defer_tools) + if self.disable_tool_cache is not None: + result["disableToolCache"] = from_union([from_bool, from_none], self.disable_tool_cache) if self.filter_mapping is not None: result["filterMapping"] = from_union([lambda x: from_dict(lambda x: to_enum(ContentFilterMode, x), x), lambda x: to_enum(ContentFilterMode, x), from_none], self.filter_mapping) if self.headers is not None: @@ -13508,7 +15402,7 @@ class MCPHostState: """Map of server name to recorded connection failure.""" filtered_servers: list[str] - """Configured servers filtered out by enterprise allowlist policy.""" + """Configured servers filtered out by MCP server policy.""" mcp3_p_enabled: bool """Whether third-party MCP servers are policy-enabled for this session.""" @@ -14830,14 +16724,20 @@ class PermissionDecisionApproveOnce: kind: ClassVar[str] = "approve-once" """Approve this single request only""" + approved_interactively: bool | None = None + """True only when a host surfaced this request to a user who approved it.""" + @staticmethod def from_dict(obj: Any) -> 'PermissionDecisionApproveOnce': assert isinstance(obj, dict) - return PermissionDecisionApproveOnce() + approved_interactively = from_union([from_bool, from_none], obj.get("approvedInteractively")) + return PermissionDecisionApproveOnce(approved_interactively) def to_dict(self) -> dict: result: dict = {} result["kind"] = self.kind + if self.approved_interactively is not None: + result["approvedInteractively"] = from_union([from_bool, from_none], self.approved_interactively) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -16227,35 +18127,237 @@ def from_dict(obj: Any) -> 'PushAttachmentGitHubSnippet': def to_dict(self) -> dict: result: dict = {} - result["lineRange"] = to_class(PushAttachmentFileLineRange, self.line_range) - result["path"] = from_str(self.path) - result["ref"] = from_str(self.ref) - result["repo"] = to_class(PushGitHubRepoRef, self.repo) - result["type"] = self.type - result["url"] = from_str(self.url) + result["lineRange"] = to_class(PushAttachmentFileLineRange, self.line_range) + result["path"] = from_str(self.path) + result["ref"] = from_str(self.ref) + result["repo"] = to_class(PushGitHubRepoRef, self.repo) + result["type"] = self.type + result["url"] = from_str(self.url) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class PushAttachmentGitHubURL: + """Generic GitHub URL reference.""" + + type: ClassVar[str] = "github_url" + """Attachment type discriminator""" + + url: str + """URL to the GitHub resource""" + + @staticmethod + def from_dict(obj: Any) -> 'PushAttachmentGitHubURL': + assert isinstance(obj, dict) + url = from_str(obj.get("url")) + return PushAttachmentGitHubURL(url) + + def to_dict(self) -> dict: + result: dict = {} + result["type"] = self.type + result["url"] = from_str(self.url) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueueInsertMessage: + """Serializable message fields accepted by queue.insertAt.""" + + prompt: str + """The user message text.""" + + agent_mode: SendAgentMode | None = None + """Optional explicit agent mode. When omitted, the session's current mode is assigned.""" + + attachments: list[Attachment] | None = None + """Optional attachments for the message.""" + + billable: bool | None = None + """Whether the message is billable.""" + + delivery: str | None = None + """Accepted for internal SendOptions compatibility but ignored; delivery is derived from + current session activity. + """ + display_prompt: str | None = None + """Optional user-facing display text.""" + + mode: SendMode | None = None + """Accepted for SendOptions compatibility but ignored; inserted items always use queued + delivery semantics. + """ + prepend: bool | None = None + """Accepted for SendOptions compatibility but ignored; the requested public position + controls placement. + """ + request_headers: dict[str, str] | None = None + """Per-turn request headers.""" + + required_tool: str | None = None + """Required tool name for the turn, when any.""" + + source: str | None = None + """Optional provenance source. `system` is rejected: it would hide the inserted row from + `pendingItems` and make it unaddressable while still executing, so inserted items must + stay visible. + """ + wait: bool | None = None + """Accepted for SendOptions compatibility but ignored; insertion scheduling is controlled by + the queue drain state. + """ + + @staticmethod + def from_dict(obj: Any) -> 'QueueInsertMessage': + assert isinstance(obj, dict) + prompt = from_str(obj.get("prompt")) + agent_mode = from_union([SendAgentMode, from_none], obj.get("agentMode")) + attachments = from_union([lambda x: from_list(Attachment.from_dict, x), from_none], obj.get("attachments")) + billable = from_union([from_bool, from_none], obj.get("billable")) + delivery = from_union([from_str, from_none], obj.get("delivery")) + display_prompt = from_union([from_str, from_none], obj.get("displayPrompt")) + mode = from_union([SendMode, from_none], obj.get("mode")) + prepend = from_union([from_bool, from_none], obj.get("prepend")) + request_headers = from_union([lambda x: from_dict(from_str, x), from_none], obj.get("requestHeaders")) + required_tool = from_union([from_str, from_none], obj.get("requiredTool")) + source = from_union([from_str, from_none], obj.get("source")) + wait = from_union([from_bool, from_none], obj.get("wait")) + return QueueInsertMessage(prompt, agent_mode, attachments, billable, delivery, display_prompt, mode, prepend, request_headers, required_tool, source, wait) + + def to_dict(self) -> dict: + result: dict = {} + result["prompt"] = from_str(self.prompt) + if self.agent_mode is not None: + result["agentMode"] = from_union([lambda x: to_enum(SendAgentMode, x), from_none], self.agent_mode) + if self.attachments is not None: + result["attachments"] = from_union([lambda x: from_list(lambda x: to_class(Attachment, x), x), from_none], self.attachments) + if self.billable is not None: + result["billable"] = from_union([from_bool, from_none], self.billable) + if self.delivery is not None: + result["delivery"] = from_union([from_str, from_none], self.delivery) + if self.display_prompt is not None: + result["displayPrompt"] = from_union([from_str, from_none], self.display_prompt) + if self.mode is not None: + result["mode"] = from_union([lambda x: to_enum(SendMode, x), from_none], self.mode) + if self.prepend is not None: + result["prepend"] = from_union([from_bool, from_none], self.prepend) + if self.request_headers is not None: + result["requestHeaders"] = from_union([lambda x: from_dict(from_str, x), from_none], self.request_headers) + if self.required_tool is not None: + result["requiredTool"] = from_union([from_str, from_none], self.required_tool) + if self.source is not None: + result["source"] = from_union([from_str, from_none], self.source) + if self.wait is not None: + result["wait"] = from_union([from_bool, from_none], self.wait) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class PushAttachmentGitHubURL: - """Generic GitHub URL reference.""" +class SendRequest: + """Parameters for sending a user message to the session""" - type: ClassVar[str] = "github_url" - """Attachment type discriminator""" + prompt: str + """The user message text""" - url: str - """URL to the GitHub resource""" + agent_mode: SendAgentMode | None = None + """The UI mode the agent was in when this message was sent. Defaults to the session's + current mode. + """ + attachments: list[Attachment] | None = None + """Optional attachments (files, directories, selections, blobs, GitHub references) to + include with the message + """ + billable: bool | None = None + """If false, this message will not trigger a Premium Request Unit charge. User messages + default to billable. + """ + display_prompt: str | None = None + """If provided, this is shown in the timeline instead of `prompt`""" + + mode: SendMode | None = None + """How to deliver the message. `enqueue` (default) appends to the message queue. `immediate` + interjects during an in-progress turn. + """ + prepend: bool | None = None + """If true, adds the message to the front of the queue instead of the end""" + + request_headers: dict[str, str] | None = None + """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. + """ + required_tool: str | None = None + """If set, the request will fail if the named tool is not available when this message is + among the user messages at the start of the current exchange + """ + # Internal: this field is an internal SDK API and is not part of the public surface. + source: str | None = None + """Optional provenance tag copied to the resulting user.message event. Must be `user`, + `system`, `command-` for command-originated messages, `schedule-` + for scheduled prompts, or `agent-` for prompts sent by another agent. + """ + traceparent: str | None = None + """W3C Trace Context traceparent header for distributed tracing of this agent turn""" + + tracestate: str | None = None + """W3C Trace Context tracestate header for distributed tracing""" + + wait: bool | None = None + """If true, await completion of the agentic loop for this message before returning. Defaults + to false (fire-and-forget). When true, the result still contains the same `messageId`; + the caller can rely on the agent having processed the message before the call resolves. + Transport-dependent tail semantics: on a LOCAL (in-process) session the wait additionally + blocks until the completed turn's event tail has been dispatched to this session's + in-process subscribers, so a subsequent read of subscriber state already reflects the + turn; on a REMOTE session the wait resolves once the loop completes and mirrored delivery + follows over the wire. Callers that need the stronger local guarantee on remote sessions + should await the event stream explicitly. + """ @staticmethod - def from_dict(obj: Any) -> 'PushAttachmentGitHubURL': + def from_dict(obj: Any) -> 'SendRequest': assert isinstance(obj, dict) - url = from_str(obj.get("url")) - return PushAttachmentGitHubURL(url) + prompt = from_str(obj.get("prompt")) + agent_mode = from_union([SendAgentMode, from_none], obj.get("agentMode")) + attachments = from_union([lambda x: from_list(Attachment.from_dict, x), from_none], obj.get("attachments")) + billable = from_union([from_bool, from_none], obj.get("billable")) + display_prompt = from_union([from_str, from_none], obj.get("displayPrompt")) + mode = from_union([SendMode, from_none], obj.get("mode")) + prepend = from_union([from_bool, from_none], obj.get("prepend")) + request_headers = from_union([lambda x: from_dict(from_str, x), from_none], obj.get("requestHeaders")) + required_tool = from_union([from_str, from_none], obj.get("requiredTool")) + source = from_union([from_str, from_none], obj.get("source")) + traceparent = from_union([from_str, from_none], obj.get("traceparent")) + tracestate = from_union([from_str, from_none], obj.get("tracestate")) + wait = from_union([from_bool, from_none], obj.get("wait")) + return SendRequest(prompt, agent_mode, attachments, billable, display_prompt, mode, prepend, request_headers, required_tool, source, traceparent, tracestate, wait) def to_dict(self) -> dict: result: dict = {} - result["type"] = self.type - result["url"] = from_str(self.url) + result["prompt"] = from_str(self.prompt) + if self.agent_mode is not None: + result["agentMode"] = from_union([lambda x: to_enum(SendAgentMode, x), from_none], self.agent_mode) + if self.attachments is not None: + result["attachments"] = from_union([lambda x: from_list(lambda x: to_class(Attachment, x), x), from_none], self.attachments) + if self.billable is not None: + result["billable"] = from_union([from_bool, from_none], self.billable) + if self.display_prompt is not None: + result["displayPrompt"] = from_union([from_str, from_none], self.display_prompt) + if self.mode is not None: + result["mode"] = from_union([lambda x: to_enum(SendMode, x), from_none], self.mode) + if self.prepend is not None: + result["prepend"] = from_union([from_bool, from_none], self.prepend) + if self.request_headers is not None: + result["requestHeaders"] = from_union([lambda x: from_dict(from_str, x), from_none], self.request_headers) + if self.required_tool is not None: + result["requiredTool"] = from_union([from_str, from_none], self.required_tool) + if self.source is not None: + result["source"] = from_union([from_str, from_none], self.source) + if self.traceparent is not None: + result["traceparent"] = from_union([from_str, from_none], self.traceparent) + if self.tracestate is not None: + result["tracestate"] = from_union([from_str, from_none], self.tracestate) + if self.wait is not None: + result["wait"] = from_union([from_bool, from_none], self.wait) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -16264,22 +18366,35 @@ class QueuePendingItems: """User-facing pending queue entry, with kind and display text for a queued message, slash command, or model change. """ + agent_mode: SendAgentMode + """Agent mode stored on this queued entry, as stamped when it was enqueued. Items without an + explicit mode report interactive. This is not necessarily the mode that will constrain + the turn: a plan or autopilot session applies its own write gate, continuation loop and + permission posture to every drained item regardless of the mode stored here. + """ display_text: str """Human-readable text to display for this queue entry in the UI""" + id: str + """Stable opaque id for the canonical queued item. Batch rows share one id.""" + kind: QueuePendingItemsKind """Whether this item is a queued user message or a queued slash command / model change""" @staticmethod def from_dict(obj: Any) -> 'QueuePendingItems': assert isinstance(obj, dict) + agent_mode = SendAgentMode(obj.get("agentMode")) display_text = from_str(obj.get("displayText")) + id = from_str(obj.get("id")) kind = QueuePendingItemsKind(obj.get("kind")) - return QueuePendingItems(display_text, kind) + return QueuePendingItems(agent_mode, display_text, id, kind) def to_dict(self) -> dict: result: dict = {} + result["agentMode"] = to_enum(SendAgentMode, self.agent_mode) result["displayText"] = from_str(self.display_text) + result["id"] = from_str(self.id) result["kind"] = to_enum(QueuePendingItemsKind, self.kind) return result @@ -16536,160 +18651,133 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class ScheduleList: - """Snapshot of the currently active recurring prompts for this session.""" +class SandboxConfigUserPolicyNetwork: + """Network rules to merge into the base policy.""" - entries: list[ScheduleEntry] - """Active scheduled prompts, ordered by id.""" + allow_local_network: bool | None = None + """Whether traffic to local/loopback addresses is allowed.""" + + allow_outbound: bool | None = None + """Whether outbound network traffic is allowed at all.""" + + proxy: SandboxConfigUserPolicyNetworkProxy | None = None + """HTTP proxy the sandboxed process routes traffic through. Enforced on Windows and + cooperative (honored by well-behaved tools, not strictly enforced) on Linux and macOS. + Credentials go in the separate `username`/`password` fields. A credential-free http:// + loopback proxy URL is routed through the localhost proxy automatically; an https:// or + authenticated loopback URL is used as-is. + """ @staticmethod - def from_dict(obj: Any) -> 'ScheduleList': + def from_dict(obj: Any) -> 'SandboxConfigUserPolicyNetwork': assert isinstance(obj, dict) - entries = from_list(ScheduleEntry.from_dict, obj.get("entries")) - return ScheduleList(entries) + allow_local_network = from_union([from_bool, from_none], obj.get("allowLocalNetwork")) + allow_outbound = from_union([from_bool, from_none], obj.get("allowOutbound")) + proxy = from_union([SandboxConfigUserPolicyNetworkProxy.from_dict, from_none], obj.get("proxy")) + return SandboxConfigUserPolicyNetwork(allow_local_network, allow_outbound, proxy) def to_dict(self) -> dict: result: dict = {} - result["entries"] = from_list(lambda x: to_class(ScheduleEntry, x), self.entries) + if self.allow_local_network is not None: + result["allowLocalNetwork"] = from_union([from_bool, from_none], self.allow_local_network) + if self.allow_outbound is not None: + result["allowOutbound"] = from_union([from_bool, from_none], self.allow_outbound) + if self.proxy is not None: + result["proxy"] = from_union([lambda x: to_class(SandboxConfigUserPolicyNetworkProxy, x), from_none], self.proxy) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class ScheduleStopResult: - """Remove a scheduled prompt by id. The result entry is omitted if the id was unknown.""" +class ScheduleAddResult: + """Result of registering or re-arming a scheduled prompt.""" entry: ScheduleEntry | None = None - """The removed entry, or omitted if no entry matched.""" + """The registered or updated schedule entry.""" + + error: str | None = None + """User-facing validation error, when registration failed.""" @staticmethod - def from_dict(obj: Any) -> 'ScheduleStopResult': + def from_dict(obj: Any) -> 'ScheduleAddResult': assert isinstance(obj, dict) entry = from_union([ScheduleEntry.from_dict, from_none], obj.get("entry")) - return ScheduleStopResult(entry) + error = from_union([from_str, from_none], obj.get("error")) + return ScheduleAddResult(entry, error) def to_dict(self) -> dict: result: dict = {} if self.entry is not None: result["entry"] = from_union([lambda x: to_class(ScheduleEntry, x), from_none], self.entry) + if self.error is not None: + result["error"] = from_union([from_str, from_none], self.error) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class SendMessagesRequest: - """Parameters for sending zero or more user messages to the session in a single turn. - Remote-backed (Mission Control) sessions do not support this method and will return an - error. - """ - messages: list[SendMessageItem] - """The user messages to append to the conversation, in order. May be empty, in which case a - single turn runs over the existing history with no new user message. - """ - agent_mode: SendAgentMode | None = None - """The UI mode the agent was in when these messages were sent. Defaults to the session's - current mode. - """ - mode: SendMode | None = None - """How to deliver the messages. `enqueue` (default) appends to the message queue. - `immediate` interjects during an in-progress turn. - """ - prepend: bool | None = None - """If true, adds the messages to the front of the queue instead of the end""" +class ScheduleList: + """Snapshot of the currently active recurring prompts for this session.""" - request_headers: dict[str, str] | None = None - """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. - """ - traceparent: str | None = None - """W3C Trace Context traceparent header for distributed tracing of this agent turn""" + entries: list[ScheduleEntry] + """Active scheduled prompts, ordered by id.""" - tracestate: str | None = None - """W3C Trace Context tracestate header for distributed tracing""" + @staticmethod + def from_dict(obj: Any) -> 'ScheduleList': + assert isinstance(obj, dict) + entries = from_list(ScheduleEntry.from_dict, obj.get("entries")) + return ScheduleList(entries) - wait: bool | None = None - """If true, await completion of the agentic loop for this turn before returning. Defaults to - false (fire-and-forget). When true, the result still contains the same `messageIds`; the - caller can rely on the agent having processed the messages before the call resolves. - """ + def to_dict(self) -> dict: + result: dict = {} + result["entries"] = from_list(lambda x: to_class(ScheduleEntry, x), self.entries) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class ScheduleStopResult: + """Remove a scheduled prompt by id. The result entry is omitted if the id was unknown.""" + + entry: ScheduleEntry | None = None + """The removed entry, or omitted if no entry matched.""" @staticmethod - def from_dict(obj: Any) -> 'SendMessagesRequest': + def from_dict(obj: Any) -> 'ScheduleStopResult': assert isinstance(obj, dict) - messages = from_list(SendMessageItem.from_dict, obj.get("messages")) - agent_mode = from_union([SendAgentMode, from_none], obj.get("agentMode")) - mode = from_union([SendMode, from_none], obj.get("mode")) - prepend = from_union([from_bool, from_none], obj.get("prepend")) - request_headers = from_union([lambda x: from_dict(from_str, x), from_none], obj.get("requestHeaders")) - traceparent = from_union([from_str, from_none], obj.get("traceparent")) - tracestate = from_union([from_str, from_none], obj.get("tracestate")) - wait = from_union([from_bool, from_none], obj.get("wait")) - return SendMessagesRequest(messages, agent_mode, mode, prepend, request_headers, traceparent, tracestate, wait) + entry = from_union([ScheduleEntry.from_dict, from_none], obj.get("entry")) + return ScheduleStopResult(entry) def to_dict(self) -> dict: result: dict = {} - result["messages"] = from_list(lambda x: to_class(SendMessageItem, x), self.messages) - if self.agent_mode is not None: - result["agentMode"] = from_union([lambda x: to_enum(SendAgentMode, x), from_none], self.agent_mode) - if self.mode is not None: - result["mode"] = from_union([lambda x: to_enum(SendMode, x), from_none], self.mode) - if self.prepend is not None: - result["prepend"] = from_union([from_bool, from_none], self.prepend) - if self.request_headers is not None: - result["requestHeaders"] = from_union([lambda x: from_dict(from_str, x), from_none], self.request_headers) - if self.traceparent is not None: - result["traceparent"] = from_union([from_str, from_none], self.traceparent) - if self.tracestate is not None: - result["tracestate"] = from_union([from_str, from_none], self.tracestate) - if self.wait is not None: - result["wait"] = from_union([from_bool, from_none], self.wait) + if self.entry is not None: + result["entry"] = from_union([lambda x: to_class(ScheduleEntry, x), from_none], self.entry) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class SendRequest: - """Parameters for sending a user message to the session""" - - prompt: str - """The user message text""" - - agent_mode: SendAgentMode | None = None - """The UI mode the agent was in when this message was sent. Defaults to the session's - current mode. +class SendMessagesRequest: + """Parameters for sending zero or more user messages to the session in a single turn. + Remote-backed (Mission Control) sessions do not support this method and will return an + error. """ - attachments: list[Attachment] | None = None - """Optional attachments (files, directories, selections, blobs, GitHub references) to - include with the message + messages: list[SendMessageItem] + """The user messages to append to the conversation, in order. May be empty, in which case a + single turn runs over the existing history with no new user message. """ - billable: bool | None = None - """If false, this message will not trigger a Premium Request Unit charge. User messages - default to billable. + agent_mode: SendAgentMode | None = None + """The UI mode the agent was in when these messages were sent. Defaults to the session's + current mode. """ - display_prompt: str | None = None - """If provided, this is shown in the timeline instead of `prompt`""" - mode: SendMode | None = None - """How to deliver the message. `enqueue` (default) appends to the message queue. `immediate` - interjects during an in-progress turn. + """How to deliver the messages. `enqueue` (default) appends to the message queue. + `immediate` interjects during an in-progress turn. """ prepend: bool | None = None - """If true, adds the message to the front of the queue instead of the end""" + """If true, adds the messages to the front of the queue instead of the end""" request_headers: dict[str, str] | None = None """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. """ - required_tool: str | None = None - """If set, the request will fail if the named tool is not available when this message is - among the user messages at the start of the current exchange - """ - # Internal: this field is an internal SDK API and is not part of the public surface. - source: str | None = None - """Optional provenance tag copied to the resulting user.message event. Must match one of - three forms: the literal `system`, `command-` for messages originating from a - command (e.g. slash command, Mission Control command), or `schedule-` for - messages originating from a scheduled job. - """ traceparent: str | None = None """W3C Trace Context traceparent header for distributed tracing of this agent turn""" @@ -16697,50 +18785,41 @@ class SendRequest: """W3C Trace Context tracestate header for distributed tracing""" wait: bool | None = None - """If true, await completion of the agentic loop for this message before returning. Defaults - to false (fire-and-forget). When true, the result still contains the same `messageId`; - the caller can rely on the agent having processed the message before the call resolves. + """If true, await completion of the agentic loop for this turn before returning. Defaults to + false (fire-and-forget). When true, the result still contains the same `messageIds`; the + caller can rely on the agent having processed the messages before the call resolves. + Transport-dependent tail semantics: on a LOCAL (in-process) session the wait additionally + blocks until the completed turn's event tail has been dispatched to this session's + in-process subscribers, so a subsequent read of subscriber state already reflects the + turn; on a REMOTE session the wait resolves once the loop completes and mirrored delivery + follows over the wire. Callers that need the stronger local guarantee on remote sessions + should await the event stream explicitly. """ @staticmethod - def from_dict(obj: Any) -> 'SendRequest': + def from_dict(obj: Any) -> 'SendMessagesRequest': assert isinstance(obj, dict) - prompt = from_str(obj.get("prompt")) + messages = from_list(SendMessageItem.from_dict, obj.get("messages")) agent_mode = from_union([SendAgentMode, from_none], obj.get("agentMode")) - attachments = from_union([lambda x: from_list(Attachment.from_dict, x), from_none], obj.get("attachments")) - billable = from_union([from_bool, from_none], obj.get("billable")) - display_prompt = from_union([from_str, from_none], obj.get("displayPrompt")) mode = from_union([SendMode, from_none], obj.get("mode")) prepend = from_union([from_bool, from_none], obj.get("prepend")) request_headers = from_union([lambda x: from_dict(from_str, x), from_none], obj.get("requestHeaders")) - required_tool = from_union([from_str, from_none], obj.get("requiredTool")) - source = from_union([from_str, from_none], obj.get("source")) traceparent = from_union([from_str, from_none], obj.get("traceparent")) tracestate = from_union([from_str, from_none], obj.get("tracestate")) wait = from_union([from_bool, from_none], obj.get("wait")) - return SendRequest(prompt, agent_mode, attachments, billable, display_prompt, mode, prepend, request_headers, required_tool, source, traceparent, tracestate, wait) + return SendMessagesRequest(messages, agent_mode, mode, prepend, request_headers, traceparent, tracestate, wait) def to_dict(self) -> dict: result: dict = {} - result["prompt"] = from_str(self.prompt) + result["messages"] = from_list(lambda x: to_class(SendMessageItem, x), self.messages) if self.agent_mode is not None: result["agentMode"] = from_union([lambda x: to_enum(SendAgentMode, x), from_none], self.agent_mode) - if self.attachments is not None: - result["attachments"] = from_union([lambda x: from_list(lambda x: to_class(Attachment, x), x), from_none], self.attachments) - if self.billable is not None: - result["billable"] = from_union([from_bool, from_none], self.billable) - if self.display_prompt is not None: - result["displayPrompt"] = from_union([from_str, from_none], self.display_prompt) if self.mode is not None: result["mode"] = from_union([lambda x: to_enum(SendMode, x), from_none], self.mode) if self.prepend is not None: result["prepend"] = from_union([from_bool, from_none], self.prepend) if self.request_headers is not None: result["requestHeaders"] = from_union([lambda x: from_dict(from_str, x), from_none], self.request_headers) - if self.required_tool is not None: - result["requiredTool"] = from_union([from_str, from_none], self.required_tool) - if self.source is not None: - result["source"] = from_union([from_str, from_none], self.source) if self.traceparent is not None: result["traceparent"] = from_union([from_str, from_none], self.traceparent) if self.tracestate is not None: @@ -16841,7 +18920,7 @@ def to_dict(self) -> dict: @dataclass class SessionFSSqliteQueryRequest: """SQL query, query type, and optional bind parameters for executing a SQLite query against - the per-session database. + the per-session database. The provider applies its SQLite busy timeout for every call. """ query: str """SQL query to execute""" @@ -16874,6 +18953,167 @@ def to_dict(self) -> dict: result["params"] = from_union([lambda x: from_dict(lambda x: x, x), from_none], self.params) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionFSSqliteTransactionStatement: + """One statement in an atomic SQLite transaction.""" + + query: str + """SQL statement to execute.""" + + query_type: SessionFSSqliteQueryType + """How to execute the statement.""" + + params: dict[str, Any] | None = None + """Optional named bind parameters.""" + + @staticmethod + def from_dict(obj: Any) -> 'SessionFSSqliteTransactionStatement': + assert isinstance(obj, dict) + query = from_str(obj.get("query")) + query_type = SessionFSSqliteQueryType(obj.get("queryType")) + params = from_union([lambda x: from_dict(lambda x: x, x), from_none], obj.get("params")) + return SessionFSSqliteTransactionStatement(query, query_type, params) + + def to_dict(self) -> dict: + result: dict = {} + result["query"] = from_str(self.query) + result["queryType"] = to_enum(SessionFSSqliteQueryType, self.query_type) + if self.params is not None: + result["params"] = from_union([lambda x: from_dict(lambda x: x, x), from_none], self.params) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionFSSqliteTransactionError: + """Classified SQLite transaction failure. busyOrLocked guarantees rollback; + postCommitAmbiguous must never be retried. + """ + error_class: SessionFSSqliteTransactionErrorClass + message: str + + @staticmethod + def from_dict(obj: Any) -> 'SessionFSSqliteTransactionError': + assert isinstance(obj, dict) + error_class = SessionFSSqliteTransactionErrorClass(obj.get("errorClass")) + message = from_str(obj.get("message")) + return SessionFSSqliteTransactionError(error_class, message) + + def to_dict(self) -> dict: + result: dict = {} + result["errorClass"] = to_enum(SessionFSSqliteTransactionErrorClass, self.error_class) + result["message"] = from_str(self.message) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class CompletionsGetTriggerCharactersResult: + """Characters that, when typed in the composer, should trigger a `completions.request`. + Empty when the session has no host-driven completions (e.g. local sessions, or a relay + host that does not advertise `completionTriggerCharacters`). + """ + trigger_characters: list[str] + """Trigger characters advertised by the host (e.g. `["@", "#"]`). Empty disables host-driven + completions for the session. + """ + + @staticmethod + def from_dict(obj: Any) -> 'CompletionsGetTriggerCharactersResult': + assert isinstance(obj, dict) + trigger_characters = from_list(from_str, obj.get("triggerCharacters")) + return CompletionsGetTriggerCharactersResult(trigger_characters) + + def to_dict(self) -> dict: + result: dict = {} + result["triggerCharacters"] = from_list(from_str, self.trigger_characters) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionHistoryCompactRequest: + custom_instructions: str | None = None + """Optional user-provided instructions to focus the compaction summary""" + + token_limit: int | None = None + """Context window token limit this compaction is targeting, recorded as the `tokenLimit` on + the persisted `session.compaction_start` / `session.compaction_complete` events. Set it + when the compaction targets a window other than the compacting model's own, e.g. + switching to a model with a smaller context window: the compaction still runs on the + current model, so the limit that motivated it would otherwise be lost. When absent, the + events record the compacting model's own resolved limit. Attribution metadata only - it + does not change how much the compaction removes. + """ + trigger: Trigger | None = None + """What initiated this compaction request, recorded as the `trigger` on the persisted + `session.compaction_start` / `session.compaction_complete` events. When absent, the + compaction is persisted without trigger attribution (initiator unknown). + """ + + @staticmethod + def from_dict(obj: Any) -> 'SessionHistoryCompactRequest': + assert isinstance(obj, dict) + custom_instructions = from_union([from_str, from_none], obj.get("customInstructions")) + token_limit = from_union([from_int, from_none], obj.get("tokenLimit")) + trigger = from_union([Trigger, from_none], obj.get("trigger")) + return SessionHistoryCompactRequest(custom_instructions, token_limit, trigger) + + 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) + if self.token_limit is not None: + result["tokenLimit"] = from_union([from_int, from_none], self.token_limit) + if self.trigger is not None: + result["trigger"] = from_union([lambda x: to_enum(Trigger, x), from_none], self.trigger) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionLimitPredictionPredictRequest: + client_type: SessionLimitPredictionClientType | None = None + """Client type to size for. Defaults to `cli-interactive`.""" + + model_id: str | None = None + """Optional model identifier override. If omitted, the session's current model is used.""" + + @staticmethod + def from_dict(obj: Any) -> 'SessionLimitPredictionPredictRequest': + assert isinstance(obj, dict) + client_type = from_union([SessionLimitPredictionClientType, from_none], obj.get("clientType")) + model_id = from_union([from_str, from_none], obj.get("modelId")) + return SessionLimitPredictionPredictRequest(client_type, model_id) + + def to_dict(self) -> dict: + result: dict = {} + if self.client_type is not None: + result["clientType"] = from_union([lambda x: to_enum(SessionLimitPredictionClientType, x), from_none], self.client_type) + if self.model_id is not None: + result["modelId"] = from_union([from_str, from_none], self.model_id) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionLimitPredictionTierOption: + """Semantic usage tier and its AI-credit cap.""" + + cap: float + """AI-credit cap for this tier.""" + + tier: SessionLimitPredictionTier + + @staticmethod + def from_dict(obj: Any) -> 'SessionLimitPredictionTierOption': + assert isinstance(obj, dict) + cap = from_float(obj.get("cap")) + tier = SessionLimitPredictionTier(obj.get("tier")) + return SessionLimitPredictionTierOption(cap, tier) + + def to_dict(self) -> dict: + result: dict = {} + result["cap"] = to_float(self.cap) + result["tier"] = to_enum(SessionLimitPredictionTier, self.tier) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionOpenOptionsAdditionalContentExclusionPolicyRule: @@ -16906,6 +19146,31 @@ def to_dict(self) -> dict: result["ifNoneMatch"] = from_union([lambda x: from_list(from_str, x), from_none], self.if_none_match) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class ShellInitScript: + """A host-provided script sourced before each built-in shell command when its shell target + matches the active shell. + """ + path: str + """Path to the script to source.""" + + shell: ShellInitScriptShell + """Built-in shell that may source this script.""" + + @staticmethod + def from_dict(obj: Any) -> 'ShellInitScript': + assert isinstance(obj, dict) + path = from_str(obj.get("path")) + shell = ShellInitScriptShell(obj.get("shell")) + return ShellInitScript(path, shell) + + def to_dict(self) -> dict: + result: dict = {} + result["path"] = from_str(self.path) + result["shell"] = to_enum(ShellInitScriptShell, self.shell) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionsOpenProgress: @@ -17161,7 +19426,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class AgentInfo: - """Custom agent metadata, including identifiers, display details, source, tools, model, MCP + """Agent metadata, including identifiers, display details, source, tools, model, MCP servers, skills, and file path. The newly selected custom agent @@ -17178,19 +19443,24 @@ class AgentInfo: distinct id was assigned. """ name: str - """Unique identifier of the custom agent""" + """Name of the agent. Use `id` as the stable selection identifier.""" mcp_servers: dict[str, Any] | None = None """MCP server configurations attached to this agent, keyed by server name. Server config shape mirrors the MCP `mcpServers` schema. """ model: str | None = None - """Preferred model id for this agent. When omitted, inherits the outer agent's model.""" - + """Authored preferred model id for this agent. Runtime model selection may choose a + different model; omitted means no authored preference. + """ path: str | None = None """Absolute local file path of the agent definition. Only set for file-based agents loaded from disk; remote agents do not have a path. """ + prompt: str | None = None + """Authored base prompt for the agent. Runtime prompt assembly may add dynamic context at + invocation time. Omitted from `session.agent.list` unless `includePrompt` is true. + """ skills: list[str] | None = None """Skill names preloaded into this agent's context. Omitted means none.""" @@ -17215,11 +19485,12 @@ def from_dict(obj: Any) -> 'AgentInfo': mcp_servers = from_union([lambda x: from_dict(lambda x: x, x), from_none], obj.get("mcpServers")) model = from_union([from_str, from_none], obj.get("model")) path = from_union([from_str, from_none], obj.get("path")) + prompt = from_union([from_str, from_none], obj.get("prompt")) skills = from_union([lambda x: from_list(from_str, x), from_none], obj.get("skills")) source = from_union([AgentInfoSource, from_none], obj.get("source")) tools = from_union([lambda x: from_list(from_str, x), from_none], obj.get("tools")) user_invocable = from_union([from_bool, from_none], obj.get("userInvocable")) - return AgentInfo(description, display_name, id, name, mcp_servers, model, path, skills, source, tools, user_invocable) + return AgentInfo(description, display_name, id, name, mcp_servers, model, path, prompt, skills, source, tools, user_invocable) def to_dict(self) -> dict: result: dict = {} @@ -17233,6 +19504,8 @@ def to_dict(self) -> dict: result["model"] = from_union([from_str, from_none], self.model) if self.path is not None: result["path"] = from_union([from_str, from_none], self.path) + if self.prompt is not None: + result["prompt"] = from_union([from_str, from_none], self.prompt) if self.skills is not None: result["skills"] = from_union([lambda x: from_list(from_str, x), from_none], self.skills) if self.source is not None: @@ -18339,6 +20612,12 @@ class UIExitPlanModeResponse: auto_approve_edits: bool | None = None """Whether subsequent edits should be auto-approved without confirmation.""" + defer_implementation: bool | None = None + """When true, the agent is instructed to end its turn without starting implementation so the + client can restore the session model and auto-submit a fresh implementation turn on it. + Set only when a distinct plan configuration (a different model, reasoning effort, or + context tier) actually ran the planning turn. + """ feedback: str | None = None """Feedback from the user when they declined the plan or requested changes.""" @@ -18352,15 +20631,18 @@ def from_dict(obj: Any) -> 'UIExitPlanModeResponse': assert isinstance(obj, dict) approved = from_bool(obj.get("approved")) auto_approve_edits = from_union([from_bool, from_none], obj.get("autoApproveEdits")) + defer_implementation = from_union([from_bool, from_none], obj.get("deferImplementation")) feedback = from_union([from_str, from_none], obj.get("feedback")) selected_action = from_union([UIExitPlanModeAction, from_none], obj.get("selectedAction")) - return UIExitPlanModeResponse(approved, auto_approve_edits, feedback, selected_action) + return UIExitPlanModeResponse(approved, auto_approve_edits, defer_implementation, feedback, selected_action) def to_dict(self) -> dict: result: dict = {} result["approved"] = from_bool(self.approved) if self.auto_approve_edits is not None: result["autoApproveEdits"] = from_union([from_bool, from_none], self.auto_approve_edits) + if self.defer_implementation is not None: + result["deferImplementation"] = from_union([from_bool, from_none], self.defer_implementation) if self.feedback is not None: result["feedback"] = from_union([from_str, from_none], self.feedback) if self.selected_action is not None: @@ -18505,8 +20787,10 @@ class WorkspaceDiffFileChange: """Unified diff content for the file. Empty when the diff was truncated.""" path: str - """Path to the changed file, relative to the workspace root.""" - + """Path to the changed file, relative to the workspace root when the file lives under it. A + file changed outside the workspace root keeps a `../`-relative path, or an absolute path + when no relative path exists (for example a different Windows drive). + """ is_truncated: bool | None = None """Whether the diff content was omitted because it exceeded the per-file size limit.""" @@ -19146,33 +21430,42 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class FactoryLogRequest: - """Parameters for recording factory progress.""" - - lines: list[FactoryLogLine] - """Ordered progress lines to append.""" +class FactoryRunTerminal: + """Prompt-safe terminal factory outcome.""" - run_id: str - """Factory run identifier.""" + error: str | None = None + failure: FactoryRunFailure | None = None + reason: str | None = None + result_preview: str | None = None @staticmethod - def from_dict(obj: Any) -> 'FactoryLogRequest': + def from_dict(obj: Any) -> 'FactoryRunTerminal': assert isinstance(obj, dict) - lines = from_list(FactoryLogLine.from_dict, obj.get("lines")) - run_id = from_str(obj.get("runId")) - return FactoryLogRequest(lines, run_id) + error = from_union([from_str, from_none], obj.get("error")) + failure = from_union([FactoryRunFailure.from_dict, from_none], obj.get("failure")) + reason = from_union([from_str, from_none], obj.get("reason")) + result_preview = from_union([from_str, from_none], obj.get("resultPreview")) + return FactoryRunTerminal(error, failure, reason, result_preview) def to_dict(self) -> dict: result: dict = {} - result["lines"] = from_list(lambda x: to_class(FactoryLogLine, x), self.lines) - result["runId"] = from_str(self.run_id) + if self.error is not None: + result["error"] = from_union([from_str, from_none], self.error) + if self.failure is not None: + result["failure"] = from_union([lambda x: to_class(FactoryRunFailure, x), from_none], self.failure) + if self.reason is not None: + result["reason"] = from_union([from_str, from_none], self.reason) + if self.result_preview is not None: + result["resultPreview"] = from_union([from_str, from_none], self.result_preview) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class FactoryRunResult: - """Complete current or terminal factory run envelope.""" + """Terminal resumed run envelope. + Complete current or terminal factory run envelope. + """ run_id: str """Factory run identifier.""" @@ -19222,6 +21515,70 @@ def to_dict(self) -> dict: result["snapshot"] = self.snapshot return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class FactoryLogRequest: + """Parameters for recording factory progress.""" + + execution_token: str + """Opaque token identifying the current factory execution attempt.""" + + lines: list[FactoryLogLine] + """Ordered progress lines to append.""" + + run_id: str + """Factory run identifier.""" + + @staticmethod + def from_dict(obj: Any) -> 'FactoryLogRequest': + assert isinstance(obj, dict) + execution_token = from_str(obj.get("executionToken")) + lines = from_list(FactoryLogLine.from_dict, obj.get("lines")) + run_id = from_str(obj.get("runId")) + return FactoryLogRequest(execution_token, lines, run_id) + + def to_dict(self) -> dict: + result: dict = {} + result["executionToken"] = from_str(self.execution_token) + result["lines"] = from_list(lambda x: to_class(FactoryLogLine, x), self.lines) + result["runId"] = from_str(self.run_id) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class FactoryProgressPage: + """A bidirectional page of factory progress.""" + + has_more_newer: bool + has_more_older: bool + records: list[FactoryProgressLine] + revision: int + """Run revision reflected by this page.""" + + newest_seq: int | None = None + oldest_seq: int | None = None + + @staticmethod + def from_dict(obj: Any) -> 'FactoryProgressPage': + assert isinstance(obj, dict) + has_more_newer = from_bool(obj.get("hasMoreNewer")) + has_more_older = from_bool(obj.get("hasMoreOlder")) + records = from_list(FactoryProgressLine.from_dict, obj.get("records")) + revision = from_int(obj.get("revision")) + newest_seq = from_union([from_int, from_none], obj.get("newestSeq")) + oldest_seq = from_union([from_int, from_none], obj.get("oldestSeq")) + return FactoryProgressPage(has_more_newer, has_more_older, records, revision, newest_seq, oldest_seq) + + def to_dict(self) -> dict: + result: dict = {} + result["hasMoreNewer"] = from_bool(self.has_more_newer) + result["hasMoreOlder"] = from_bool(self.has_more_older) + result["records"] = from_list(lambda x: to_class(FactoryProgressLine, x), self.records) + result["revision"] = from_int(self.revision) + result["newestSeq"] = from_union([from_int, from_none], self.newest_seq) + result["oldestSeq"] = from_union([from_int, from_none], self.oldest_seq) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class FactoryRunRequest: @@ -19252,6 +21609,103 @@ def to_dict(self) -> dict: result["options"] = from_union([lambda x: to_class(RunOptions, x), from_none], self.options) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class HistoryRewindResult: + """Structured outcome of a rewind request.""" + + outcome: HistoryRewindOutcome + """Overall rewind outcome. This discriminates the result: it governs which of the remaining + fields are populated, so consumers must switch on it before reading `eventsRemoved`, + `restoredFiles`, `skippedFiles`, or `error`. See each field for the outcomes that + populate it. + """ + restored_files: list[str] + """Absolute paths restored to their captured preimages. Always empty for conversation-only + rewinds and for the unavailable outcomes (`session-busy`, + `file-change-tracking-disabled`, `unsupported-remote-session`); only + conversation-and-files outcomes that reached the file-restore stage populate it. + """ + skipped_files: list[HistorySkippedFileRestore] + """Captured files intentionally left unchanged. Always empty for conversation-only rewinds + and for the unavailable outcomes (`session-busy`, `file-change-tracking-disabled`, + `unsupported-remote-session`); only conversation-and-files outcomes that reached the + file-restore stage populate it. + """ + error: str | None = None + """Failure detail. Set only for the failure and partial-failure outcomes + (`files-rolled-back`, `rollback-incomplete`, `truncation-failed`, + `checkpoint-cleanup-failed`, `snapshot-prune-failed`); omitted for `success` and for the + unavailable outcomes (`session-busy`, `file-change-tracking-disabled`, + `unsupported-remote-session`). + """ + events_removed: int | None = None + """Number of persisted events removed by conversation truncation. Present only when + truncation succeeded (outcomes `success`, `checkpoint-cleanup-failed`, and + `snapshot-prune-failed`); omitted for every unavailable outcome (`session-busy`, + `file-change-tracking-disabled`, `unsupported-remote-session`) and for + `truncation-failed`, `files-rolled-back`, and `rollback-incomplete`. + """ + + @staticmethod + def from_dict(obj: Any) -> 'HistoryRewindResult': + assert isinstance(obj, dict) + outcome = HistoryRewindOutcome(obj.get("outcome")) + restored_files = from_list(from_str, obj.get("restoredFiles")) + skipped_files = from_list(HistorySkippedFileRestore.from_dict, obj.get("skippedFiles")) + error = from_union([from_str, from_none], obj.get("error")) + events_removed = from_union([from_int, from_none], obj.get("eventsRemoved")) + return HistoryRewindResult(outcome, restored_files, skipped_files, error, events_removed) + + def to_dict(self) -> dict: + result: dict = {} + result["outcome"] = to_enum(HistoryRewindOutcome, self.outcome) + result["restoredFiles"] = from_list(from_str, self.restored_files) + result["skippedFiles"] = from_list(lambda x: to_class(HistorySkippedFileRestore, x), self.skipped_files) + if self.error is not None: + result["error"] = from_union([from_str, from_none], self.error) + if self.events_removed is not None: + result["eventsRemoved"] = from_union([from_int, from_none], self.events_removed) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class HistoryPreviewRewindResult: + """Files and aggregate changes for a prospective rewind.""" + + available: bool + """Whether file restore is available for this session. This is authoritative: switch on it + and read `reason` only when it is false. + """ + file_count: int + """Number of unique files in the preview.""" + + files: list[HistoryRewindFilePreview] + """Files ordered by path.""" + + reason: HistoryRewindUnavailableReason | None = None + """Why file restore is unavailable, when applicable. Populated only when `available` is + false and never set when `available` is true. + """ + + @staticmethod + def from_dict(obj: Any) -> 'HistoryPreviewRewindResult': + assert isinstance(obj, dict) + available = from_bool(obj.get("available")) + file_count = from_int(obj.get("fileCount")) + files = from_list(HistoryRewindFilePreview.from_dict, obj.get("files")) + reason = from_union([HistoryRewindUnavailableReason, from_none], obj.get("reason")) + return HistoryPreviewRewindResult(available, file_count, files, reason) + + def to_dict(self) -> dict: + result: dict = {} + result["available"] = from_bool(self.available) + result["fileCount"] = from_int(self.file_count) + result["files"] = from_list(lambda x: to_class(HistoryRewindFilePreview, x), self.files) + if self.reason is not None: + result["reason"] = from_union([lambda x: to_enum(HistoryRewindUnavailableReason, x), from_none], self.reason) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class InstalledPlugin: @@ -19401,6 +21855,8 @@ def to_dict(self) -> dict: class LocalSessionMetadataValue: """Persisted local session metadata, including identifiers, timestamps, summary/name, client, context, detached state, and task ID. + + Local session metadata, omitted when the session does not exist. """ is_remote: bool """Always false for local sessions.""" @@ -19786,6 +22242,32 @@ def to_dict(self) -> dict: result["workspace"] = from_union([lambda x: to_class(Workspace, x), from_none], self.workspace) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class WorkspacesUpdateMetadataRequest: + """Workspace metadata fields to update.""" + + context: Any = None + """Opaque workspace context supplied by the session host.""" + + name: str | None = None + """Optional workspace display name override.""" + + @staticmethod + def from_dict(obj: Any) -> 'WorkspacesUpdateMetadataRequest': + assert isinstance(obj, dict) + context = obj.get("context") + name = from_union([from_str, from_none], obj.get("name")) + return WorkspacesUpdateMetadataRequest(context, name) + + def to_dict(self) -> dict: + result: dict = {} + if self.context is not None: + result["context"] = self.context + if self.name is not None: + result["name"] = from_union([from_str, from_none], self.name) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPAppsHostContext: @@ -19922,25 +22404,29 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPStartServerRequest: - """Server name and configuration for an individual MCP server start.""" - - config: MCPServerConfig - """MCP server configuration (stdio process or remote HTTP/SSE)""" - + """Server name and optional configuration for an individual MCP server start. Omit `config` + for a config-free start-by-name of an already-configured server. + """ server_name: str """Name of the MCP server to start""" + config: MCPServerConfig | None = None + """MCP server configuration (stdio process or remote HTTP/SSE). Omit to start the server + with its already-registered configuration (config-free start-by-name). + """ + @staticmethod def from_dict(obj: Any) -> 'MCPStartServerRequest': assert isinstance(obj, dict) - config = MCPServerConfig.from_dict(obj.get("config")) server_name = from_str(obj.get("serverName")) - return MCPStartServerRequest(config, server_name) + config = from_union([MCPServerConfig.from_dict, from_none], obj.get("config")) + return MCPStartServerRequest(server_name, config) def to_dict(self) -> dict: result: dict = {} - result["config"] = to_class(MCPServerConfig, self.config) result["serverName"] = from_str(self.server_name) + if self.config is not None: + result["config"] = from_union([lambda x: to_class(MCPServerConfig, x), from_none], self.config) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -20139,7 +22625,7 @@ class ModelBilling: promo: ModelBillingPromo | None = None """Active server-driven promotion for this model, if any. Present when the model is being - promoted with a time-boxed discount. + promoted with a discount, which may be time-boxed or open-ended. """ token_prices: ModelBillingTokenPrices | None = None """Token-level pricing information for this model""" @@ -20556,6 +23042,28 @@ def to_dict(self) -> dict: result["type"] = self.type return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueueInsertAtRequest: + """Parameters for inserting a queued message at a public visible position.""" + + message: QueueInsertMessage + position: int + """Zero-based position in the public visible queue. Values outside the queue clamp to an end.""" + + @staticmethod + def from_dict(obj: Any) -> 'QueueInsertAtRequest': + assert isinstance(obj, dict) + message = QueueInsertMessage.from_dict(obj.get("message")) + position = from_int(obj.get("position")) + return QueueInsertAtRequest(message, position) + + def to_dict(self) -> dict: + result: dict = {} + result["message"] = to_class(QueueInsertMessage, self.message) + result["position"] = from_int(self.position) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class QueuePendingItemsResult: @@ -20583,6 +23091,42 @@ def to_dict(self) -> dict: result["steeringMessages"] = from_list(from_str, self.steering_messages) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class QueueSnapshotResult: + """Internal snapshot of native queue state for local session orchestration.""" + + items: list[QueuePendingItems] + """User-facing pending items in FIFO order.""" + + steering_messages: list[str] + """Immediate steering messages waiting for an active turn.""" + + item_orders: list[int] | None = None + """Insertion orders for queued items, aligned with `items`.""" + + steering_message_orders: list[int] | None = None + """Insertion orders for immediate steering messages, aligned with `steeringMessages`.""" + + @staticmethod + def from_dict(obj: Any) -> 'QueueSnapshotResult': + assert isinstance(obj, dict) + items = from_list(QueuePendingItems.from_dict, obj.get("items")) + steering_messages = from_list(from_str, obj.get("steeringMessages")) + item_orders = from_union([lambda x: from_list(from_int, x), from_none], obj.get("itemOrders")) + steering_message_orders = from_union([lambda x: from_list(from_int, x), from_none], obj.get("steeringMessageOrders")) + return QueueSnapshotResult(items, steering_messages, item_orders, steering_message_orders) + + def to_dict(self) -> dict: + result: dict = {} + result["items"] = from_list(lambda x: to_class(QueuePendingItems, x), self.items) + result["steeringMessages"] = from_list(from_str, self.steering_messages) + if self.item_orders is not None: + result["itemOrders"] = from_union([lambda x: from_list(from_int, x), from_none], self.item_orders) + if self.steering_message_orders is not None: + result["steeringMessageOrders"] = from_union([lambda x: from_list(from_int, x), from_none], self.steering_message_orders) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionsStartRemoteControlRequest: @@ -20783,6 +23327,29 @@ def to_dict(self) -> dict: result["error"] = from_union([lambda x: to_class(SessionFSError, x), from_none], self.error) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionFSSqliteTransactionRequest: + """Statements to execute atomically. Providers apply busy handling for every call.""" + + session_id: str + """Target session identifier""" + + statements: list[SessionFSSqliteTransactionStatement] + + @staticmethod + def from_dict(obj: Any) -> 'SessionFSSqliteTransactionRequest': + assert isinstance(obj, dict) + session_id = from_str(obj.get("sessionId")) + statements = from_list(SessionFSSqliteTransactionStatement.from_dict, obj.get("statements")) + return SessionFSSqliteTransactionRequest(session_id, statements) + + def to_dict(self) -> dict: + result: dict = {} + result["sessionId"] = from_str(self.session_id) + result["statements"] = from_list(lambda x: to_class(SessionFSSqliteTransactionStatement, x), self.statements) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionOpenOptionsAdditionalContentExclusionPolicy: @@ -20811,6 +23378,57 @@ def to_dict(self) -> dict: result["scope"] = to_enum(AdditionalContentExclusionPolicyScope, self.scope) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class ShellOptions: + """Per-session settings for built-in shell tools.""" + + init_profile: ShellInitProfile | None = None + """Controls automatic non-interactive profile loading where supported. Explicit initScripts + are unaffected. + """ + init_scripts: list[ShellInitScript] | None = None + """Ordered host-provided script paths sourced before each built-in shell command when the + entry's shell target matches the active shell. Use these for rc files, environment setup + scripts, + or other custom scripts. A script that returns a nonzero status is reported, and later + scripts + and the user command continue while the shell remains running. Because scripts are + sourced into + the command shell, `exit`, `exec`, failures under `set -e`, or other shell-terminating + behavior + can prevent continuation. Script standard output is preserved; Bash script stderr is + discarded, + PowerShell exception messages are replaced, and runtime-generated failure notices omit + configured script paths. When sandboxing is enabled, each script must already be readable + under + the active sandbox filesystem policy. Pass an empty array to clear the list. + """ + process_flags: list[str] | None = None + """Flags passed to the active built-in shell process on startup, replacing its default + flags. + When omitted, the built-in Bash shell uses `--norc --noprofile`, + and the built-in PowerShell shell uses `-NoProfile -NoLogo`. + """ + + @staticmethod + def from_dict(obj: Any) -> 'ShellOptions': + assert isinstance(obj, dict) + init_profile = from_union([ShellInitProfile, from_none], obj.get("initProfile")) + init_scripts = from_union([lambda x: from_list(ShellInitScript.from_dict, x), from_none], obj.get("initScripts")) + process_flags = from_union([lambda x: from_list(from_str, x), from_none], obj.get("processFlags")) + return ShellOptions(init_profile, init_scripts, process_flags) + + def to_dict(self) -> dict: + result: dict = {} + if self.init_profile is not None: + result["initProfile"] = from_union([lambda x: to_enum(ShellInitProfile, x), from_none], self.init_profile) + if self.init_scripts is not None: + result["initScripts"] = from_union([lambda x: from_list(lambda x: to_class(ShellInitScript, x), x), from_none], self.init_scripts) + if self.process_flags is not None: + result["processFlags"] = from_union([lambda x: from_list(from_str, x), from_none], self.process_flags) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionSettingsSnapshot: @@ -20881,10 +23499,10 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class AgentList: - """Custom agents available to the session.""" + """Agents available to the session.""" agents: list[AgentInfo] - """Available custom agents""" + """Available agents""" @staticmethod def from_dict(obj: Any) -> 'AgentList': @@ -20954,6 +23572,36 @@ def to_dict(self) -> dict: result["agents"] = from_list(lambda x: to_class(AgentInfo, x), self.agents) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionAgentListRequest: + include_built_in_agents: bool | None = None + """When true, request the session's configured built-in agents alongside custom agents. + Listing applies feature, context, inclusion, exclusion, and user-disabled-agent policy, + but does not evaluate transient invocation requirements such as model availability. + Built-in metadata may be omitted when the session cannot project it, such as a relay + session. + """ + include_prompt: bool | None = None + """When true, request authored base prompt text on each AgentInfo. Prompt text may be + omitted when unavailable, such as for agents projected through a relay session. + """ + + @staticmethod + def from_dict(obj: Any) -> 'SessionAgentListRequest': + assert isinstance(obj, dict) + include_built_in_agents = from_union([from_bool, from_none], obj.get("includeBuiltInAgents")) + include_prompt = from_union([from_bool, from_none], obj.get("includePrompt")) + return SessionAgentListRequest(include_built_in_agents, include_prompt) + + def to_dict(self) -> dict: + result: dict = {} + if self.include_built_in_agents is not None: + result["includeBuiltInAgents"] = from_union([from_bool, from_none], self.include_built_in_agents) + if self.include_prompt is not None: + result["includePrompt"] = from_union([from_bool, from_none], self.include_prompt) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SkillsGetInvokedResult: @@ -21442,8 +24090,9 @@ class WorkspaceDiffResult: """Changed files and their unified diffs.""" is_fallback: bool - """Whether a requested branch diff fell back to unstaged changes because branch diff failed.""" - + """Whether the requested diff fell back to unstaged changes, either because branch diff + failed or session diff was unavailable. + """ mode: WorkspaceDiffMode """Effective mode used for the returned changes.""" @@ -21453,6 +24102,16 @@ class WorkspaceDiffResult: base_branch: str | None = None """Default branch used for a branch diff, when branch mode was requested.""" + unavailable_reason: HistoryRewindUnavailableReason | None = None + """Why the session diff could not be produced, when applicable. Set only when `session` mode + was requested and `isFallback` is true, so a client can tell the permanent + `file-change-tracking-disabled` apart from the transient `session-busy`, which the same + request answers once the session settles. Never set for `unstaged` or `branch` mode, and + never `unsupported-remote-session`: a remote session's captures live on its own host, so + a `session`-mode diff is rejected for one rather than answered with a controller-side + fallback. + """ + @staticmethod def from_dict(obj: Any) -> 'WorkspaceDiffResult': assert isinstance(obj, dict) @@ -21461,7 +24120,8 @@ def from_dict(obj: Any) -> 'WorkspaceDiffResult': mode = WorkspaceDiffMode(obj.get("mode")) requested_mode = WorkspaceDiffMode(obj.get("requestedMode")) base_branch = from_union([from_str, from_none], obj.get("baseBranch")) - return WorkspaceDiffResult(changes, is_fallback, mode, requested_mode, base_branch) + unavailable_reason = from_union([HistoryRewindUnavailableReason, from_none], obj.get("unavailableReason")) + return WorkspaceDiffResult(changes, is_fallback, mode, requested_mode, base_branch, unavailable_reason) def to_dict(self) -> dict: result: dict = {} @@ -21471,6 +24131,8 @@ def to_dict(self) -> dict: result["requestedMode"] = to_enum(WorkspaceDiffMode, self.requested_mode) if self.base_branch is not None: result["baseBranch"] = from_union([from_str, from_none], self.base_branch) + if self.unavailable_reason is not None: + result["unavailableReason"] = from_union([lambda x: to_enum(HistoryRewindUnavailableReason, x), from_none], self.unavailable_reason) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -21679,6 +24341,183 @@ def to_dict(self) -> dict: result["result"] = from_union([lambda x: to_class(ExternalToolTextResultForLlm, x), from_str, from_none], self.result) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class FactoryRunSummary: + """Durable factory run summary with read-time live overlays.""" + + consumed: FactoryRunConsumed + created_at: int + declared_limits: FactoryDeclaredLimits + declared_phase_count: int + description: str + factory_name: str + live_agent_count: int + observed_at: int + revision: int + run_id: str + status: FactoryRunStatus + total_spawned_agent_count: int + updated_at: int + active_segment_started_at: int | None = None + approved: FactoryDeclaredLimits | None = None + completed_at: int | None = None + current_phase: FactoryCurrentPhase | None = None + started_at: int | None = None + terminal: FactoryRunTerminal | None = None + + @staticmethod + def from_dict(obj: Any) -> 'FactoryRunSummary': + assert isinstance(obj, dict) + consumed = FactoryRunConsumed.from_dict(obj.get("consumed")) + created_at = from_int(obj.get("createdAt")) + declared_limits = FactoryDeclaredLimits.from_dict(obj.get("declaredLimits")) + declared_phase_count = from_int(obj.get("declaredPhaseCount")) + description = from_str(obj.get("description")) + factory_name = from_str(obj.get("factoryName")) + live_agent_count = from_int(obj.get("liveAgentCount")) + observed_at = from_int(obj.get("observedAt")) + revision = from_int(obj.get("revision")) + run_id = from_str(obj.get("runId")) + status = FactoryRunStatus(obj.get("status")) + total_spawned_agent_count = from_int(obj.get("totalSpawnedAgentCount")) + updated_at = from_int(obj.get("updatedAt")) + active_segment_started_at = from_union([from_int, from_none], obj.get("activeSegmentStartedAt")) + approved = from_union([FactoryDeclaredLimits.from_dict, from_none], obj.get("approved")) + completed_at = from_union([from_int, from_none], obj.get("completedAt")) + current_phase = from_union([FactoryCurrentPhase.from_dict, from_none], obj.get("currentPhase")) + started_at = from_union([from_int, from_none], obj.get("startedAt")) + terminal = from_union([FactoryRunTerminal.from_dict, from_none], obj.get("terminal")) + return FactoryRunSummary(consumed, created_at, declared_limits, declared_phase_count, description, factory_name, live_agent_count, observed_at, revision, run_id, status, total_spawned_agent_count, updated_at, active_segment_started_at, approved, completed_at, current_phase, started_at, terminal) + + def to_dict(self) -> dict: + result: dict = {} + result["consumed"] = to_class(FactoryRunConsumed, self.consumed) + result["createdAt"] = from_int(self.created_at) + result["declaredLimits"] = to_class(FactoryDeclaredLimits, self.declared_limits) + result["declaredPhaseCount"] = from_int(self.declared_phase_count) + result["description"] = from_str(self.description) + result["factoryName"] = from_str(self.factory_name) + result["liveAgentCount"] = from_int(self.live_agent_count) + result["observedAt"] = from_int(self.observed_at) + result["revision"] = from_int(self.revision) + result["runId"] = from_str(self.run_id) + result["status"] = to_enum(FactoryRunStatus, self.status) + result["totalSpawnedAgentCount"] = from_int(self.total_spawned_agent_count) + result["updatedAt"] = from_int(self.updated_at) + result["activeSegmentStartedAt"] = from_union([from_int, from_none], self.active_segment_started_at) + result["approved"] = from_union([lambda x: to_class(FactoryDeclaredLimits, x), from_none], self.approved) + result["completedAt"] = from_union([from_int, from_none], self.completed_at) + result["currentPhase"] = from_union([lambda x: to_class(FactoryCurrentPhase, x), from_none], self.current_phase) + result["startedAt"] = from_union([from_int, from_none], self.started_at) + result["terminal"] = from_union([lambda x: to_class(FactoryRunTerminal, x), from_none], self.terminal) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class FactoryResumeResult: + """Resolved persisted factory identity and resumed run envelope.""" + + factory_name: str + """Persisted factory name resolved for the resumed run.""" + + run: FactoryRunResult + """Terminal resumed run envelope.""" + + @staticmethod + def from_dict(obj: Any) -> 'FactoryResumeResult': + assert isinstance(obj, dict) + factory_name = from_str(obj.get("factoryName")) + run = FactoryRunResult.from_dict(obj.get("run")) + return FactoryResumeResult(factory_name, run) + + def to_dict(self) -> dict: + result: dict = {} + result["factoryName"] = from_str(self.factory_name) + result["run"] = to_class(FactoryRunResult, self.run) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class FactoryRunDetail: + """Full factory run observability detail.""" + + agents: list[FactoryAgentSummary] + consumed: FactoryRunConsumed + created_at: int + declared_limits: FactoryDeclaredLimits + declared_phase_count: int + description: str + factory_name: str + live_agent_count: int + observed_at: int + phases: list[FactoryPhaseObservation] + progress: FactoryProgressPage + revision: int + run_id: str + status: FactoryRunStatus + total_spawned_agent_count: int + updated_at: int + active_segment_started_at: int | None = None + approved: FactoryDeclaredLimits | None = None + completed_at: int | None = None + current_phase: FactoryCurrentPhase | None = None + started_at: int | None = None + terminal: FactoryRunTerminal | None = None + + @staticmethod + def from_dict(obj: Any) -> 'FactoryRunDetail': + assert isinstance(obj, dict) + agents = from_list(FactoryAgentSummary.from_dict, obj.get("agents")) + consumed = FactoryRunConsumed.from_dict(obj.get("consumed")) + created_at = from_int(obj.get("createdAt")) + declared_limits = FactoryDeclaredLimits.from_dict(obj.get("declaredLimits")) + declared_phase_count = from_int(obj.get("declaredPhaseCount")) + description = from_str(obj.get("description")) + factory_name = from_str(obj.get("factoryName")) + live_agent_count = from_int(obj.get("liveAgentCount")) + observed_at = from_int(obj.get("observedAt")) + phases = from_list(FactoryPhaseObservation.from_dict, obj.get("phases")) + progress = FactoryProgressPage.from_dict(obj.get("progress")) + revision = from_int(obj.get("revision")) + run_id = from_str(obj.get("runId")) + status = FactoryRunStatus(obj.get("status")) + total_spawned_agent_count = from_int(obj.get("totalSpawnedAgentCount")) + updated_at = from_int(obj.get("updatedAt")) + active_segment_started_at = from_union([from_int, from_none], obj.get("activeSegmentStartedAt")) + approved = from_union([FactoryDeclaredLimits.from_dict, from_none], obj.get("approved")) + completed_at = from_union([from_int, from_none], obj.get("completedAt")) + current_phase = from_union([FactoryCurrentPhase.from_dict, from_none], obj.get("currentPhase")) + started_at = from_union([from_int, from_none], obj.get("startedAt")) + terminal = from_union([FactoryRunTerminal.from_dict, from_none], obj.get("terminal")) + return FactoryRunDetail(agents, consumed, created_at, declared_limits, declared_phase_count, description, factory_name, live_agent_count, observed_at, phases, progress, revision, run_id, status, total_spawned_agent_count, updated_at, active_segment_started_at, approved, completed_at, current_phase, started_at, terminal) + + def to_dict(self) -> dict: + result: dict = {} + result["agents"] = from_list(lambda x: to_class(FactoryAgentSummary, x), self.agents) + result["consumed"] = to_class(FactoryRunConsumed, self.consumed) + result["createdAt"] = from_int(self.created_at) + result["declaredLimits"] = to_class(FactoryDeclaredLimits, self.declared_limits) + result["declaredPhaseCount"] = from_int(self.declared_phase_count) + result["description"] = from_str(self.description) + result["factoryName"] = from_str(self.factory_name) + result["liveAgentCount"] = from_int(self.live_agent_count) + result["observedAt"] = from_int(self.observed_at) + result["phases"] = from_list(lambda x: to_class(FactoryPhaseObservation, x), self.phases) + result["progress"] = to_class(FactoryProgressPage, self.progress) + result["revision"] = from_int(self.revision) + result["runId"] = from_str(self.run_id) + result["status"] = to_enum(FactoryRunStatus, self.status) + result["totalSpawnedAgentCount"] = from_int(self.total_spawned_agent_count) + result["updatedAt"] = from_int(self.updated_at) + result["activeSegmentStartedAt"] = from_union([from_int, from_none], self.active_segment_started_at) + result["approved"] = from_union([lambda x: to_class(FactoryDeclaredLimits, x), from_none], self.approved) + result["completedAt"] = from_union([from_int, from_none], self.completed_at) + result["currentPhase"] = from_union([lambda x: to_class(FactoryCurrentPhase, x), from_none], self.current_phase) + result["startedAt"] = from_union([from_int, from_none], self.started_at) + result["terminal"] = from_union([lambda x: to_class(FactoryRunTerminal, x), from_none], self.terminal) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionsSetAdditionalPluginsRequest: @@ -21743,6 +24582,26 @@ def to_dict(self) -> dict: result["sessions"] = from_list(lambda x: to_class(LocalSessionMetadataValue, x), self.sessions) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionsGetMetadataResult: + """Persisted local session metadata when the session exists.""" + + session: LocalSessionMetadataValue | None = None + """Local session metadata, omitted when the session does not exist.""" + + @staticmethod + def from_dict(obj: Any) -> 'SessionsGetMetadataResult': + assert isinstance(obj, dict) + session = from_union([LocalSessionMetadataValue.from_dict, from_none], obj.get("session")) + return SessionsGetMetadataResult(session) + + def to_dict(self) -> dict: + result: dict = {} + if self.session is not None: + result["session"] = from_union([lambda x: to_class(LocalSessionMetadataValue, x), from_none], self.session) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionOpenResult: @@ -22183,6 +25042,28 @@ def to_dict(self) -> dict: result["userPolicy"] = from_union([lambda x: to_class(SandboxConfigUserPolicy, x), from_none], self.user_policy) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionFSSqliteTransactionResult: + """Per-statement results, or a classified transaction error.""" + + results: list[SessionFSSqliteQueryResult] + error: SessionFSSqliteTransactionError | None = None + + @staticmethod + def from_dict(obj: Any) -> 'SessionFSSqliteTransactionResult': + assert isinstance(obj, dict) + results = from_list(SessionFSSqliteQueryResult.from_dict, obj.get("results")) + error = from_union([SessionFSSqliteTransactionError.from_dict, from_none], obj.get("error")) + return SessionFSSqliteTransactionResult(results, error) + + def to_dict(self) -> dict: + result: dict = {} + result["results"] = from_list(lambda x: to_class(SessionFSSqliteQueryResult, x), self.results) + if self.error is not None: + result["error"] = from_union([lambda x: to_class(SessionFSSqliteTransactionError, x), from_none], self.error) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPListToolsResult: @@ -22204,32 +25085,72 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class UIElicitationSchema: - """JSON Schema describing the form fields to present to the user""" - - properties: dict[str, UIElicitationSchemaProperty] - """Form field definitions, keyed by field name""" - - type: UIElicitationSchemaType - """Schema type indicator (always 'object')""" +class UIElicitationSchema: + """JSON Schema describing the form fields to present to the user""" + + properties: dict[str, UIElicitationSchemaProperty] + """Form field definitions, keyed by field name""" + + type: UIElicitationSchemaType + """Schema type indicator (always 'object')""" + + required: list[str] | None = None + """List of required field names""" + + @staticmethod + def from_dict(obj: Any) -> 'UIElicitationSchema': + assert isinstance(obj, dict) + properties = from_dict(UIElicitationSchemaProperty.from_dict, obj.get("properties")) + type = UIElicitationSchemaType(obj.get("type")) + required = from_union([lambda x: from_list(from_str, x), from_none], obj.get("required")) + return UIElicitationSchema(properties, type, required) + + def to_dict(self) -> dict: + result: dict = {} + result["properties"] = from_dict(lambda x: to_class(UIElicitationSchemaProperty, x), self.properties) + result["type"] = to_enum(UIElicitationSchemaType, self.type) + if self.required is not None: + result["required"] = from_union([lambda x: from_list(from_str, x), from_none], self.required) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class FactoryListRunsResult: + """Factory runs in durable creation order.""" + + runs: list[FactoryRunSummary] + + @staticmethod + def from_dict(obj: Any) -> 'FactoryListRunsResult': + assert isinstance(obj, dict) + runs = from_list(FactoryRunSummary.from_dict, obj.get("runs")) + return FactoryListRunsResult(runs) + + def to_dict(self) -> dict: + result: dict = {} + result["runs"] = from_list(lambda x: to_class(FactoryRunSummary, x), self.runs) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class BuiltInModelCatalogEntry: + """A well-known model in the runtime's built-in catalog.""" - required: list[str] | None = None - """List of required field names""" + id: str + """Well-known runtime model ID suitable for `ProviderConfig.modelId` or + `ProviderModelConfig.modelId`. This is not necessarily the provider-facing deployment or + model name and does not indicate CAPI entitlement or provider availability. + """ @staticmethod - def from_dict(obj: Any) -> 'UIElicitationSchema': + def from_dict(obj: Any) -> 'BuiltInModelCatalogEntry': assert isinstance(obj, dict) - properties = from_dict(UIElicitationSchemaProperty.from_dict, obj.get("properties")) - type = UIElicitationSchemaType(obj.get("type")) - required = from_union([lambda x: from_list(from_str, x), from_none], obj.get("required")) - return UIElicitationSchema(properties, type, required) + id = from_str(obj.get("id")) + return BuiltInModelCatalogEntry(id) def to_dict(self) -> dict: result: dict = {} - result["properties"] = from_dict(lambda x: to_class(UIElicitationSchemaProperty, x), self.properties) - result["type"] = to_enum(UIElicitationSchemaType, self.type) - if self.required is not None: - result["required"] = from_union([lambda x: from_list(from_str, x), from_none], self.required) + result["id"] = from_str(self.id) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -22279,6 +25200,15 @@ class SessionOpenOptions: additional_content_exclusion_policies: list[SessionOpenOptionsAdditionalContentExclusionPolicy] | None = None """Additional content-exclusion policies to merge into the session policy set.""" + additional_directories: list[str] | None = None + """Additional directories the agent may access beyond the working directory. Each entry is + granted to the session's file-access allow-list and surfaced to the model (system prompt + context and `@`-mention completion). Absolute paths are recommended; a relative path is + resolved against the session's working directory. Nonexistent or unresolvable entries are + skipped with a warning. This is applied on both session creation and resume, and is not + persisted: a resumed session that omits this option does not retain previously supplied + directories (re-supply them, exactly as the CLI re-passes `--add-dir`). + """ agent_context: str | None = None """Runtime context discriminator for agent filtering.""" @@ -22336,6 +25266,28 @@ class SessionOpenOptions: `assistant.message` event. Off by default; may change or be removed while the citations surface is experimental. """ + enable_file_change_tracking: bool | None = None + """Opt in to capturing file changes for session rewind and session diff. Capture cannot + reconstruct changes made before it was enabled. On create it starts capture from the + first turn. It is also honored on resume: for a session that already has tracked prior + turns, tracking continues automatically even if this is omitted; passing it on resume + additionally enables tracking for an eligible session that has no prior root turn yet. + Resuming a session whose prior root turns were never tracked has no restorable baseline, + so tracking stays disabled for it and rewind reports file change tracking as unavailable; + the resume itself still succeeds, so sessions that predate tracking remain loadable. The + opt-in is only rejected when the session can never track (a subagent session, or one + without local session storage). It is intentionally absent from the mutable options + update because enabling it after edits have occurred would create an incomplete, + misleading baseline. Subagents share the parent session's capture store and are not + tracked as separate rewind points: a file a subagent writes is attributed to whichever + root user turn was open when the capture was staged, just before the tool body ran. A + turn cannot open while a staged capture is still in flight, so a subagent tool that + staged under the spawning turn stays attributed to it however late the write lands, while + a capture it stages after the user's next message belongs to that later turn. Attribution + decides which turn's rewind point counts and file preview include that write; it does not + narrow which rewinds revert it, because a rewind restores every capture from the selected + turn onward, so the earlier spawning turn reverts it as well. + """ enable_managed_settings: bool | None = None """Opt-in: self-fetch and enforce enterprise managed settings at session bootstrap.""" @@ -22354,6 +25306,9 @@ class SessionOpenOptions: events_log_directory: str | None = None """Override directory for session event logs.""" + events_log_includes_subagents: bool | None = None + """Whether subagent callback events should be forwarded into the session event log sink.""" + excluded_builtin_agents: list[str] | None = None """Built-in subagent names to exclude from this session. Excluded built-ins are hidden from agent discovery and cannot be dispatched unless a custom agent with the same name is @@ -22449,11 +25404,14 @@ class SessionOpenOptions: session_limits: SessionLimitsConfig | None = None """Initial session limits.""" + shell: ShellOptions | None = None + """Per-session settings for built-in shell tools.""" + shell_init_profile: str | None = None - """Shell init profile.""" + """Use shell.initProfile instead. Shell init profile.""" shell_process_flags: list[str] | None = None - """Per-shell process flags.""" + """PowerShell process flags applied to built-in and user-requested shell commands.""" skill_directories: list[str] | None = None """Additional directories to search for skills.""" @@ -22477,6 +25435,7 @@ class SessionOpenOptions: def from_dict(obj: Any) -> 'SessionOpenOptions': assert isinstance(obj, dict) additional_content_exclusion_policies = from_union([lambda x: from_list(SessionOpenOptionsAdditionalContentExclusionPolicy.from_dict, x), from_none], obj.get("additionalContentExclusionPolicies")) + additional_directories = from_union([lambda x: from_list(from_str, x), from_none], obj.get("additionalDirectories")) agent_context = from_union([from_str, from_none], obj.get("agentContext")) allow_all_mcp_server_instructions = from_union([from_bool, from_none], obj.get("allowAllMcpServerInstructions")) ask_user_disabled = from_union([from_bool, from_none], obj.get("askUserDisabled")) @@ -22495,12 +25454,14 @@ def from_dict(obj: Any) -> 'SessionOpenOptions': disabled_instruction_sources = from_union([lambda x: from_list(from_str, x), from_none], obj.get("disabledInstructionSources")) disabled_skills = from_union([lambda x: from_list(from_str, x), from_none], obj.get("disabledSkills")) enable_citations = from_union([from_bool, from_none], obj.get("enableCitations")) + enable_file_change_tracking = from_union([from_bool, from_none], obj.get("enableFileChangeTracking")) enable_managed_settings = from_union([from_bool, from_none], obj.get("enableManagedSettings")) enable_on_demand_instruction_discovery = from_union([from_bool, from_none], obj.get("enableOnDemandInstructionDiscovery")) enable_script_safety = from_union([from_bool, from_none], obj.get("enableScriptSafety")) enable_streaming = from_union([from_bool, from_none], obj.get("enableStreaming")) env_value_mode = from_union([MCPSetEnvValueModeDetails, from_none], obj.get("envValueMode")) events_log_directory = from_union([from_str, from_none], obj.get("eventsLogDirectory")) + events_log_includes_subagents = from_union([from_bool, from_none], obj.get("eventsLogIncludesSubagents")) excluded_builtin_agents = from_union([lambda x: from_list(from_str, x), from_none], obj.get("excludedBuiltinAgents")) excluded_tools = from_union([lambda x: from_list(from_str, x), from_none], obj.get("excludedTools")) exp_assignments = obj.get("expAssignments") @@ -22529,6 +25490,7 @@ def from_dict(obj: Any) -> 'SessionOpenOptions': session_capabilities = from_union([lambda x: from_list(SessionCapability, x), from_none], obj.get("sessionCapabilities")) session_id = from_union([from_str, from_none], obj.get("sessionId")) session_limits = from_union([SessionLimitsConfig.from_dict, from_none], obj.get("sessionLimits")) + shell = from_union([ShellOptions.from_dict, from_none], obj.get("shell")) shell_init_profile = from_union([from_str, from_none], obj.get("shellInitProfile")) shell_process_flags = from_union([lambda x: from_list(from_str, x), from_none], obj.get("shellProcessFlags")) skill_directories = from_union([lambda x: from_list(from_str, x), from_none], obj.get("skillDirectories")) @@ -22537,12 +25499,14 @@ def from_dict(obj: Any) -> 'SessionOpenOptions': verbosity = from_union([Verbosity, from_none], obj.get("verbosity")) working_directory = from_union([from_str, from_none], obj.get("workingDirectory")) working_directory_context = from_union([SessionContext.from_dict, from_none], obj.get("workingDirectoryContext")) - return SessionOpenOptions(additional_content_exclusion_policies, agent_context, allow_all_mcp_server_instructions, ask_user_disabled, auth_info, available_tools, capi, client_kind, client_name, coauthor_enabled, config_dir, continue_on_auto_mode, copilot_url, custom_agents_local_only, detached_from_spawning_parent_engagement_id, detached_from_spawning_parent_session_id, disabled_instruction_sources, disabled_skills, enable_citations, enable_managed_settings, enable_on_demand_instruction_discovery, enable_script_safety, enable_streaming, env_value_mode, events_log_directory, excluded_builtin_agents, excluded_tools, exp_assignments, feature_flags, included_builtin_agents, installed_plugins, integration_id, is_experimental_mode, log_interactive_shells, lsp_client_name, max_inline_binary_bytes, memory, model, model_capabilities_overrides, models, name, provider, providers, reasoning_effort, reasoning_summary, remote_defaulted_on, remote_exporting, remote_steerable, running_in_interactive_mode, sandbox_config, session_capabilities, session_id, session_limits, shell_init_profile, shell_process_flags, skill_directories, skip_custom_instructions, trajectory_file, verbosity, working_directory, working_directory_context) + return SessionOpenOptions(additional_content_exclusion_policies, additional_directories, agent_context, allow_all_mcp_server_instructions, ask_user_disabled, auth_info, available_tools, capi, client_kind, client_name, coauthor_enabled, config_dir, continue_on_auto_mode, copilot_url, custom_agents_local_only, detached_from_spawning_parent_engagement_id, detached_from_spawning_parent_session_id, disabled_instruction_sources, disabled_skills, enable_citations, enable_file_change_tracking, enable_managed_settings, enable_on_demand_instruction_discovery, enable_script_safety, enable_streaming, env_value_mode, events_log_directory, events_log_includes_subagents, excluded_builtin_agents, excluded_tools, exp_assignments, feature_flags, included_builtin_agents, installed_plugins, integration_id, is_experimental_mode, log_interactive_shells, lsp_client_name, max_inline_binary_bytes, memory, model, model_capabilities_overrides, models, name, provider, providers, reasoning_effort, reasoning_summary, remote_defaulted_on, remote_exporting, remote_steerable, running_in_interactive_mode, sandbox_config, session_capabilities, session_id, session_limits, shell, shell_init_profile, shell_process_flags, skill_directories, skip_custom_instructions, trajectory_file, verbosity, working_directory, working_directory_context) def to_dict(self) -> dict: result: dict = {} if self.additional_content_exclusion_policies is not None: result["additionalContentExclusionPolicies"] = from_union([lambda x: from_list(lambda x: to_class(SessionOpenOptionsAdditionalContentExclusionPolicy, x), x), from_none], self.additional_content_exclusion_policies) + if self.additional_directories is not None: + result["additionalDirectories"] = from_union([lambda x: from_list(from_str, x), from_none], self.additional_directories) if self.agent_context is not None: result["agentContext"] = from_union([from_str, from_none], self.agent_context) if self.allow_all_mcp_server_instructions is not None: @@ -22579,6 +25543,8 @@ def to_dict(self) -> dict: result["disabledSkills"] = from_union([lambda x: from_list(from_str, x), from_none], self.disabled_skills) if self.enable_citations is not None: result["enableCitations"] = from_union([from_bool, from_none], self.enable_citations) + if self.enable_file_change_tracking is not None: + result["enableFileChangeTracking"] = from_union([from_bool, from_none], self.enable_file_change_tracking) if self.enable_managed_settings is not None: result["enableManagedSettings"] = from_union([from_bool, from_none], self.enable_managed_settings) if self.enable_on_demand_instruction_discovery is not None: @@ -22591,6 +25557,8 @@ def to_dict(self) -> dict: result["envValueMode"] = from_union([lambda x: to_enum(MCPSetEnvValueModeDetails, x), from_none], self.env_value_mode) if self.events_log_directory is not None: result["eventsLogDirectory"] = from_union([from_str, from_none], self.events_log_directory) + if self.events_log_includes_subagents is not None: + result["eventsLogIncludesSubagents"] = from_union([from_bool, from_none], self.events_log_includes_subagents) if self.excluded_builtin_agents is not None: result["excludedBuiltinAgents"] = from_union([lambda x: from_list(from_str, x), from_none], self.excluded_builtin_agents) if self.excluded_tools is not None: @@ -22647,6 +25615,8 @@ def to_dict(self) -> dict: result["sessionId"] = from_union([from_str, from_none], self.session_id) if self.session_limits is not None: result["sessionLimits"] = from_union([lambda x: to_class(SessionLimitsConfig, x), from_none], self.session_limits) + if self.shell is not None: + result["shell"] = from_union([lambda x: to_class(ShellOptions, x), from_none], self.shell) if self.shell_init_profile is not None: result["shellInitProfile"] = from_union([from_str, from_none], self.shell_init_profile) if self.shell_process_flags is not None: @@ -22726,7 +25696,7 @@ class SessionUpdateOptionsParams: enable_on_demand_instruction_discovery: bool | None = None """Whether to discover custom instructions on demand after successful file views (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md surfacing). Combined with - `skipCustomInstructions` and the runtime-side `ON_DEMAND_INSTRUCTIONS` feature flag. + `skipCustomInstructions`. """ enable_reasoning_summaries: bool | None = None """Whether to surface reasoning-summary events from the model.""" @@ -22752,6 +25722,9 @@ class SessionUpdateOptionsParams: """Override directory for the session-events log. When unset, the runtime's default events log directory is used. """ + events_log_includes_subagents: bool | None = None + """Whether subagent callback events should be forwarded into the session event log sink.""" + excluded_builtin_agents: list[str] | None = None """Built-in subagent names to exclude from this session. Excluded built-ins are hidden from agent discovery and cannot be dispatched unless a custom agent with the same name is @@ -22827,11 +25800,14 @@ class SessionUpdateOptionsParams: session_limits: SessionLimitsConfig | None = None """Optional session limits. Pass null to clear the session limits.""" + shell: ShellOptions | None = None + """Per-session settings for built-in shell tools.""" + shell_init_profile: str | None = None - """Shell init profile (`None` or `NonInteractive`).""" + """Use shell.initProfile instead. Shell init profile (`None` or `NonInteractive`).""" shell_process_flags: list[str] | None = None - """Per-shell process flags (e.g., `pwsh` arguments).""" + """PowerShell process flags applied to built-in and user-requested shell commands.""" skill_directories: list[str] | None = None """Additional directories to search for skills.""" @@ -22887,6 +25863,7 @@ def from_dict(obj: Any) -> 'SessionUpdateOptionsParams': enable_streaming = from_union([from_bool, from_none], obj.get("enableStreaming")) env_value_mode = from_union([MCPSetEnvValueModeDetails, from_none], obj.get("envValueMode")) events_log_directory = from_union([from_str, from_none], obj.get("eventsLogDirectory")) + events_log_includes_subagents = from_union([from_bool, from_none], obj.get("eventsLogIncludesSubagents")) excluded_builtin_agents = from_union([lambda x: from_list(from_str, x), from_none], obj.get("excludedBuiltinAgents")) excluded_tools = from_union([lambda x: from_list(from_str, x), from_none], obj.get("excludedTools")) feature_flags = from_union([lambda x: from_dict(from_bool, x), from_none], obj.get("featureFlags")) @@ -22908,6 +25885,7 @@ def from_dict(obj: Any) -> 'SessionUpdateOptionsParams': sandbox_config = from_union([SandboxConfig.from_dict, from_none], obj.get("sandboxConfig")) session_capabilities = from_union([lambda x: from_list(SessionCapability, x), from_none], obj.get("sessionCapabilities")) session_limits = from_union([SessionLimitsConfig.from_dict, from_none], obj.get("sessionLimits")) + shell = from_union([ShellOptions.from_dict, from_none], obj.get("shell")) shell_init_profile = from_union([from_str, from_none], obj.get("shellInitProfile")) shell_process_flags = from_union([lambda x: from_list(from_str, x), from_none], obj.get("shellProcessFlags")) skill_directories = from_union([lambda x: from_list(from_str, x), from_none], obj.get("skillDirectories")) @@ -22918,7 +25896,7 @@ def from_dict(obj: Any) -> 'SessionUpdateOptionsParams': trajectory_file = from_union([from_str, from_none], obj.get("trajectoryFile")) verbosity = from_union([Verbosity, from_none], obj.get("verbosity")) working_directory = from_union([from_str, from_none], obj.get("workingDirectory")) - return SessionUpdateOptionsParams(additional_content_exclusion_policies, agent_context, allow_all_mcp_server_instructions, ask_user_disabled, available_tools, capi, client_name, coauthor_enabled, context_tier, continue_on_auto_mode, copilot_url, custom_agents_local_only, disabled_instruction_sources, disabled_skills, enable_file_hooks, enable_host_git_operations, enable_on_demand_instruction_discovery, enable_reasoning_summaries, enable_script_safety, enable_session_store, enable_skills, enable_streaming, env_value_mode, events_log_directory, excluded_builtin_agents, excluded_tools, feature_flags, included_builtin_agents, installed_plugins, integration_id, is_experimental_mode, log_interactive_shells, lsp_client_name, manage_schedule_enabled, max_inline_binary_bytes, model, model_capabilities_overrides, organization_custom_instructions, provider, reasoning_effort, reasoning_summary, running_in_interactive_mode, sandbox_config, session_capabilities, session_limits, shell_init_profile, shell_process_flags, skill_directories, skip_custom_instructions, skip_embedding_retrieval, suppress_custom_agent_prompt, tool_filter_precedence, trajectory_file, verbosity, working_directory) + return SessionUpdateOptionsParams(additional_content_exclusion_policies, agent_context, allow_all_mcp_server_instructions, ask_user_disabled, available_tools, capi, client_name, coauthor_enabled, context_tier, continue_on_auto_mode, copilot_url, custom_agents_local_only, disabled_instruction_sources, disabled_skills, enable_file_hooks, enable_host_git_operations, enable_on_demand_instruction_discovery, enable_reasoning_summaries, enable_script_safety, enable_session_store, enable_skills, enable_streaming, env_value_mode, events_log_directory, events_log_includes_subagents, excluded_builtin_agents, excluded_tools, feature_flags, included_builtin_agents, installed_plugins, integration_id, is_experimental_mode, log_interactive_shells, lsp_client_name, manage_schedule_enabled, max_inline_binary_bytes, model, model_capabilities_overrides, organization_custom_instructions, provider, reasoning_effort, reasoning_summary, running_in_interactive_mode, sandbox_config, session_capabilities, session_limits, shell, shell_init_profile, shell_process_flags, skill_directories, skip_custom_instructions, skip_embedding_retrieval, suppress_custom_agent_prompt, tool_filter_precedence, trajectory_file, verbosity, working_directory) def to_dict(self) -> dict: result: dict = {} @@ -22970,6 +25948,8 @@ def to_dict(self) -> dict: result["envValueMode"] = from_union([lambda x: to_enum(MCPSetEnvValueModeDetails, x), from_none], self.env_value_mode) if self.events_log_directory is not None: result["eventsLogDirectory"] = from_union([from_str, from_none], self.events_log_directory) + if self.events_log_includes_subagents is not None: + result["eventsLogIncludesSubagents"] = from_union([from_bool, from_none], self.events_log_includes_subagents) if self.excluded_builtin_agents is not None: result["excludedBuiltinAgents"] = from_union([lambda x: from_list(from_str, x), from_none], self.excluded_builtin_agents) if self.excluded_tools is not None: @@ -23012,6 +25992,8 @@ def to_dict(self) -> dict: result["sessionCapabilities"] = from_union([lambda x: from_list(lambda x: to_enum(SessionCapability, x), x), from_none], self.session_capabilities) if self.session_limits is not None: result["sessionLimits"] = from_union([lambda x: to_class(SessionLimitsConfig, x), from_none], self.session_limits) + if self.shell is not None: + result["shell"] = from_union([lambda x: to_class(ShellOptions, x), from_none], self.shell) if self.shell_init_profile is not None: result["shellInitProfile"] = from_union([from_str, from_none], self.shell_init_profile) if self.shell_process_flags is not None: @@ -23058,6 +26040,26 @@ 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 BuiltInModelCatalog: + """The running runtime's complete catalog of well-known built-in model IDs, including + supported models and additional IDs with built-in metadata. + """ + models: list[BuiltInModelCatalogEntry] + """Built-in model entries.""" + + @staticmethod + def from_dict(obj: Any) -> 'BuiltInModelCatalog': + assert isinstance(obj, dict) + models = from_list(BuiltInModelCatalogEntry.from_dict, obj.get("models")) + return BuiltInModelCatalog(models) + + def to_dict(self) -> dict: + result: dict = {} + result["models"] = from_list(lambda x: to_class(BuiltInModelCatalogEntry, x), self.models) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionsOpenCreate: @@ -24471,6 +27473,13 @@ class ModelSwitchToRequest: """Explicit context tier for the selected model. `"default"` / `"long_context"` apply the requested tier; omit this field to use normal model behavior with no explicit tier. """ + defer_if_model_change_queued: bool | None = None + """When true, defer this switch (enqueue it) if another model change is already queued, even + when no turn is active — so it drains last (FIFO) and wins over the already-queued + change. Intended for genuine user-initiated model selections; internal restore/reapply + switches omit it and apply immediately when no turn is active. When no other model change + is queued this has no effect (a switch still applies immediately unless a turn is active). + """ model_capabilities: ModelCapabilitiesOverride | None = None """Override individual model capabilities resolved by the runtime""" @@ -24488,17 +27497,20 @@ def from_dict(obj: Any) -> 'ModelSwitchToRequest': assert isinstance(obj, dict) model_id = from_str(obj.get("modelId")) context_tier = from_union([ContextTier, from_none], obj.get("contextTier")) + defer_if_model_change_queued = from_union([from_bool, from_none], obj.get("deferIfModelChangeQueued")) model_capabilities = from_union([ModelCapabilitiesOverride.from_dict, from_none], obj.get("modelCapabilities")) reasoning_effort = from_union([from_str, from_none], obj.get("reasoningEffort")) reasoning_summary = from_union([ReasoningSummary, from_none], obj.get("reasoningSummary")) verbosity = from_union([Verbosity, from_none], obj.get("verbosity")) - return ModelSwitchToRequest(model_id, context_tier, model_capabilities, reasoning_effort, reasoning_summary, verbosity) + return ModelSwitchToRequest(model_id, context_tier, defer_if_model_change_queued, model_capabilities, reasoning_effort, reasoning_summary, verbosity) def to_dict(self) -> dict: result: dict = {} result["modelId"] = from_str(self.model_id) if self.context_tier is not None: result["contextTier"] = from_union([lambda x: to_enum(ContextTier, x), from_none], self.context_tier) + if self.defer_if_model_change_queued is not None: + result["deferIfModelChangeQueued"] = from_union([from_bool, from_none], self.defer_if_model_change_queued) if self.model_capabilities is not None: result["modelCapabilities"] = from_union([lambda x: to_class(ModelCapabilitiesOverride, x), from_none], self.model_capabilities) if self.reasoning_effort is not None: @@ -24585,47 +27597,137 @@ def to_dict(self) -> dict: return result # Experimental: this type is part of an experimental API and may change or be removed. +# Internal: this type is an internal SDK API and is not part of the public surface. @dataclass -class ProviderGetEndpointRequest: - """Optional model identifier to scope the endpoint snapshot to.""" +class _RegisterExtensionToolsResult: + """Handle for releasing the extension tool registration.""" - model_id: str | None = None - """Model identifier the caller intends to use against the returned endpoint. Used to pick - the correct wire shape. Omit to use whichever model the session is currently using. + unsubscribe: Any + """In-process unsubscribe function (CLI-only optimization). Marked internal: replaced by an + explicit `extensions.unregister` RPC in the SDK migration. """ @staticmethod - def from_dict(obj: Any) -> 'ProviderGetEndpointRequest': + def from_dict(obj: Any) -> '_RegisterExtensionToolsResult': assert isinstance(obj, dict) - model_id = from_union([from_str, from_none], obj.get("modelId")) - return ProviderGetEndpointRequest(model_id) + unsubscribe = obj.get("unsubscribe") + return _RegisterExtensionToolsResult(unsubscribe) def to_dict(self) -> dict: result: dict = {} - if self.model_id is not None: - result["modelId"] = from_union([from_str, from_none], self.model_id) + result["unsubscribe"] = self.unsubscribe return result # Experimental: this type is part of an experimental API and may change or be removed. -# Internal: this type is an internal SDK API and is not part of the public surface. @dataclass -class _RegisterExtensionToolsResult: - """Handle for releasing the extension tool registration.""" +class SessionLimitPredictionDetails: + """Explainable AI-credit session-limit prediction. - unsubscribe: Any - """In-process unsubscribe function (CLI-only optimization). Marked internal: replaced by an - explicit `extensions.unregister` RPC in the SDK migration. + Predicted session limit details. """ + baseline_data: SessionLimitPredictionBaselineData + """Baseline data provenance.""" + + client_type: SessionLimitPredictionClientType + """Client population used for the prediction.""" + + model_id: str + """Model identifier used for lookup.""" + + recommended_cap: float + """Recommended maximum AI credits for this session.""" + + recommended_tier: SessionLimitPredictionTier + """Tier chosen as the recommended cap.""" + + source: SessionLimitPredictionSource + """Baseline fallback level used to create the prediction.""" + + source_key: str + """Key matched at the source level, such as a model id, family id, or `global`.""" + + tiers: list[SessionLimitPredictionTierOption] + """Ordered usage tiers and their AI-credit caps.""" + + family: str | None = None + """Resolved model family when known.""" @staticmethod - def from_dict(obj: Any) -> '_RegisterExtensionToolsResult': + def from_dict(obj: Any) -> 'SessionLimitPredictionDetails': assert isinstance(obj, dict) - unsubscribe = obj.get("unsubscribe") - return _RegisterExtensionToolsResult(unsubscribe) + baseline_data = SessionLimitPredictionBaselineData.from_dict(obj.get("baselineData")) + client_type = SessionLimitPredictionClientType(obj.get("clientType")) + model_id = from_str(obj.get("modelId")) + recommended_cap = from_float(obj.get("recommendedCap")) + recommended_tier = SessionLimitPredictionTier(obj.get("recommendedTier")) + source = SessionLimitPredictionSource(obj.get("source")) + source_key = from_str(obj.get("sourceKey")) + tiers = from_list(SessionLimitPredictionTierOption.from_dict, obj.get("tiers")) + family = from_union([from_str, from_none], obj.get("family")) + return SessionLimitPredictionDetails(baseline_data, client_type, model_id, recommended_cap, recommended_tier, source, source_key, tiers, family) def to_dict(self) -> dict: result: dict = {} - result["unsubscribe"] = self.unsubscribe + result["baselineData"] = to_class(SessionLimitPredictionBaselineData, self.baseline_data) + result["clientType"] = to_enum(SessionLimitPredictionClientType, self.client_type) + result["modelId"] = from_str(self.model_id) + result["recommendedCap"] = to_float(self.recommended_cap) + result["recommendedTier"] = to_enum(SessionLimitPredictionTier, self.recommended_tier) + result["source"] = to_enum(SessionLimitPredictionSource, self.source) + result["sourceKey"] = from_str(self.source_key) + result["tiers"] = from_list(lambda x: to_class(SessionLimitPredictionTierOption, x), self.tiers) + if self.family is not None: + result["family"] = from_union([from_str, from_none], self.family) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionLimitPredictionResult: + """Prediction result. Available results include prediction details; unavailable results + include an explicit reason. + """ + kind: SessionLimitPredictionResultKind + prediction: SessionLimitPredictionDetails | None = None + """Predicted session limit details.""" + + reason: SessionLimitPredictionUnavailableReason | None = None + """Reason no prediction is available.""" + + @staticmethod + def from_dict(obj: Any) -> 'SessionLimitPredictionResult': + assert isinstance(obj, dict) + kind = SessionLimitPredictionResultKind(obj.get("kind")) + prediction = from_union([SessionLimitPredictionDetails.from_dict, from_none], obj.get("prediction")) + reason = from_union([SessionLimitPredictionUnavailableReason, from_none], obj.get("reason")) + return SessionLimitPredictionResult(kind, prediction, reason) + + def to_dict(self) -> dict: + result: dict = {} + result["kind"] = to_enum(SessionLimitPredictionResultKind, self.kind) + if self.prediction is not None: + result["prediction"] = from_union([lambda x: to_class(SessionLimitPredictionDetails, x), from_none], self.prediction) + if self.reason is not None: + result["reason"] = from_union([lambda x: to_enum(SessionLimitPredictionUnavailableReason, x), from_none], self.reason) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class SessionProviderGetEndpointRequest: + model_id: str | None = None + """Model identifier the caller intends to use against the returned endpoint. Used to pick + the correct wire shape. Omit to use whichever model the session is currently using. + """ + + @staticmethod + def from_dict(obj: Any) -> 'SessionProviderGetEndpointRequest': + assert isinstance(obj, dict) + model_id = from_union([from_str, from_none], obj.get("modelId")) + return SessionProviderGetEndpointRequest(model_id) + + def to_dict(self) -> dict: + result: dict = {} + if self.model_id is not None: + result["modelId"] = from_union([from_str, from_none], self.model_id) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -24985,6 +28087,7 @@ class RPC: agent_info: AgentInfo agent_info_source: AgentInfoSource agent_list: AgentList + agent_list_request: Any agent_registry_live_target_entry: AgentRegistryLiveTargetEntry agent_registry_live_target_entry_attention_kind: AgentRegistryLiveTargetEntryAttentionKind agent_registry_live_target_entry_kind: AgentRegistryLiveTargetEntryKind @@ -25011,6 +28114,8 @@ class RPC: api_key_auth_info: APIKeyAuthInfo auth_info: AuthInfo auth_info_type: AuthInfoType + built_in_model_catalog: BuiltInModelCatalog + built_in_model_catalog_entry: BuiltInModelCatalogEntry cancel_user_requested_shell_command_result: CancelUserRequestedShellCommandResult canvas_action: CanvasAction canvas_action_invoke_request: CanvasActionInvokeRequest @@ -25032,7 +28137,7 @@ class RPC: commands_handle_pending_command_request: CommandsHandlePendingCommandRequest commands_handle_pending_command_result: CommandsHandlePendingCommandResult commands_invoke_request: CommandsInvokeRequest - commands_list_request: CommandsListRequest + commands_list_request: Any commands_respond_to_queued_command_request: CommandsRespondToQueuedCommandRequest commands_respond_to_queued_command_result: CommandsRespondToQueuedCommandResult completions_get_trigger_characters_result: CompletionsGetTriggerCharactersResult @@ -25045,6 +28150,9 @@ class RPC: connect_remote_session_params: ConnectRemoteSessionParams connect_request: _ConnectRequest connect_result: _ConnectResult + content_exclusion_check_paths_request: ContentExclusionCheckPathsRequest + content_exclusion_check_paths_result: ContentExclusionCheckPathsResult + content_exclusion_path_check: ContentExclusionPathCheck content_filter_mode: ContentFilterMode context_heaviest_message: ContextHeaviestMessage copilot_api_token_auth_info: CopilotAPITokenAuthInfo @@ -25109,22 +28217,39 @@ class RPC: factory_agent_options: FactoryAgentOptions factory_agent_request: FactoryAgentRequest factory_agent_result: FactoryAgentResult + factory_agent_summary: FactoryAgentSummary factory_cancel_request: FactoryCancelRequest + factory_current_phase: FactoryCurrentPhase + factory_declared_limits: FactoryDeclaredLimits + factory_durable_operation: FactoryDurableOperation factory_execute_request: FactoryExecuteRequest factory_execute_result: FactoryExecuteResult + factory_get_run_progress_request: FactoryGetRunProgressRequest factory_get_run_request: FactoryGetRunRequest factory_journal_get_request: FactoryJournalGetRequest factory_journal_get_result: FactoryJournalGetResult factory_journal_put_request: FactoryJournalPutRequest + factory_list_runs_request: FactoryListRunsRequest + factory_list_runs_result: FactoryListRunsResult factory_log_line: FactoryLogLine factory_log_line_kind: FactoryLogLineKind factory_log_request: FactoryLogRequest + factory_phase_observation: FactoryPhaseObservation + factory_phase_status: FactoryPhaseStatus + factory_progress_line: FactoryProgressLine + factory_progress_page: FactoryProgressPage + factory_resume_request: FactoryResumeRequest + factory_resume_result: FactoryResumeResult + factory_run_consumed: FactoryRunConsumed + factory_run_detail: FactoryRunDetail factory_run_failure: FactoryRunFailure factory_run_failure_kind: FactoryRunFailureKind factory_run_limits: FactoryRunLimits factory_run_request: FactoryRunRequest factory_run_result: FactoryRunResult factory_run_status: FactoryRunStatus + factory_run_summary: FactoryRunSummary + factory_run_terminal: FactoryRunTerminal filter_mapping: dict[str, ContentFilterMode] | ContentFilterMode fleet_start_request: FleetStartRequest fleet_start_result: FleetStartResult @@ -25140,8 +28265,21 @@ 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_request: Any history_compact_result: HistoryCompactResult + history_file_restore_skip_reason: HistoryFileRestoreSkipReason + history_list_rewind_points_result: HistoryListRewindPointsResult + history_preview_rewind_request: HistoryPreviewRewindRequest + history_preview_rewind_result: HistoryPreviewRewindResult + history_rewind_change_type: HistoryRewindChangeType + history_rewind_file_preview: HistoryRewindFilePreview + history_rewind_mode: HistoryRewindMode + history_rewind_outcome: HistoryRewindOutcome + history_rewind_point: HistoryRewindPoint + history_rewind_request: HistoryRewindRequest + history_rewind_result: HistoryRewindResult + history_rewind_unavailable_reason: HistoryRewindUnavailableReason + history_skipped_file_restore: HistorySkippedFileRestore history_summarize_for_handoff_result: HistorySummarizeForHandoffResult history_truncate_request: HistoryTruncateRequest history_truncate_result: HistoryTruncateResult @@ -25165,6 +28303,8 @@ class RPC: instruction_source: InstructionSource instruction_source_location: InstructionLocation instruction_source_type: InstructionSourceType + interrupt_main_turn_request: InterruptMainTurnRequest + interrupt_main_turn_result: InterruptMainTurnResult llm_inference_headers: dict[str, list[str]] llm_inference_http_request_chunk_request: LlmInferenceHTTPRequestChunkRequest llm_inference_http_request_chunk_result: LlmInferenceHTTPRequestChunkResult @@ -25244,6 +28384,8 @@ class RPC: mcp_oauth_login_request: MCPOauthLoginRequest mcp_oauth_login_result: MCPOauthLoginResult mcp_oauth_pending_request_response: MCPOauthPendingRequestResponse + mcp_oauth_respond_request: MCPOauthRespondRequest + mcp_oauth_respond_result: MCPOauthRespondResult mcp_register_external_client_request: MCPRegisterExternalClientRequest mcp_reload_with_config_request: MCPReloadWithConfigRequest mcp_remove_git_hub_result: MCPRemoveGitHubResult @@ -25314,7 +28456,7 @@ class RPC: model_capabilities_override_supports: ModelCapabilitiesOverrideSupports model_capabilities_supports: ModelCapabilitiesSupports model_list: ModelList - model_list_request: ModelListRequest + model_list_request: Any model_picker_category: ModelPickerCategory model_picker_price_category: ModelPickerPriceCategory model_policy: ModelPolicy @@ -25454,7 +28596,7 @@ class RPC: plugins_marketplaces_browse_request: PluginsMarketplacesBrowseRequest plugins_marketplaces_refresh_request: PluginsMarketplacesRefreshRequest plugins_marketplaces_remove_request: PluginsMarketplacesRemoveRequest - plugins_reload_request: PluginsReloadRequest + plugins_reload_request: Any plugins_uninstall_request: PluginsUninstallRequest plugins_update_request: PluginsUpdateRequest plugin_update_all_entry: PluginUpdateAllEntry @@ -25471,7 +28613,7 @@ class RPC: provider_endpoint_transport: ProviderTransport provider_endpoint_type: ProviderType provider_endpoint_wire_api: ProviderWireAPI - provider_get_endpoint_request: ProviderGetEndpointRequest + provider_get_endpoint_request: Any provider_model_config: ProviderModelConfig provider_session_token: ProviderSessionToken provider_token_acquire_request: ProviderTokenAcquireRequest @@ -25499,13 +28641,36 @@ class RPC: push_attachment_selection_details_end: PushAttachmentSelectionDetailsEnd push_attachment_selection_details_start: PushAttachmentSelectionDetailsStart push_git_hub_repo_ref: PushGitHubRepoRef + queue_begin_deferred_idle_drain_request: QueueBeginDeferredIdleDrainRequest + queue_begin_deferred_idle_drain_result: QueueBeginDeferredIdleDrainResult + queue_consume_system_notifications_request: QueueConsumeSystemNotificationsRequest queued_command_handled: QueuedCommandHandled queued_command_not_handled: QueuedCommandNotHandled queued_command_result: QueuedCommandResult + queue_defer_session_idle_request: QueueDeferSessionIdleRequest + queue_duplicate_at_request: QueueDuplicateAtRequest + queue_duplicate_at_result: QueueDuplicateAtResult + queue_enqueue_resume_pending_result: QueueEnqueueResumePendingResult + queue_finish_deferred_idle_drain_request: QueueFinishDeferredIdleDrainRequest + queue_finish_deferred_idle_drain_result: QueueFinishDeferredIdleDrainResult + queue_has_pending_result: QueueHasPendingResult + queue_insert_at_request: QueueInsertAtRequest + queue_insert_at_result: QueueInsertAtResult + queue_insert_message: QueueInsertMessage + queue_move_item_request: QueueMoveItemRequest + queue_move_item_result: QueueMoveItemResult queue_pending_items: QueuePendingItems queue_pending_items_kind: QueuePendingItemsKind queue_pending_items_result: QueuePendingItemsResult + queue_remove_at_request: QueueRemoveAtRequest + queue_remove_at_result: QueueRemoveAtResult queue_remove_most_recent_result: QueueRemoveMostRecentResult + queue_send_now_request: QueueSendNowRequest + queue_send_now_result: QueueSendNowResult + queue_set_drain_paused_request: QueueSetDrainPausedRequest + queue_snapshot_result: QueueSnapshotResult + queue_update_text_request: QueueUpdateTextRequest + queue_update_text_result: QueueUpdateTextResult register_event_interest_params: RegisterEventInterestParams register_event_interest_result: RegisterEventInterestResult register_extension_tools_params: _RegisterExtensionToolsParams @@ -25538,9 +28703,17 @@ class RPC: sandbox_config_user_policy_experimental_seatbelt: SandboxConfigUserPolicyExperimentalSeatbelt sandbox_config_user_policy_filesystem: SandboxConfigUserPolicyFilesystem sandbox_config_user_policy_network: SandboxConfigUserPolicyNetwork + sandbox_config_user_policy_network_proxy: SandboxConfigUserPolicyNetworkProxy sandbox_config_user_policy_seatbelt: SandboxConfigUserPolicySeatbelt + schedule_add_at_request: ScheduleAddAtRequest + schedule_add_cron_request: ScheduleAddCronRequest + schedule_add_request: ScheduleAddRequest + schedule_add_result: ScheduleAddResult + schedule_add_self_paced_request: ScheduleAddSelfPacedRequest schedule_entry: ScheduleEntry + schedule_has_self_paced_result: ScheduleHasSelfPacedResult schedule_list: ScheduleList + schedule_rearm_self_paced_request: ScheduleRearmSelfPacedRequest schedule_stop_request: ScheduleStopRequest schedule_stop_result: ScheduleStopResult secrets_add_filter_values_request: SecretsAddFilterValuesRequest @@ -25553,14 +28726,18 @@ class RPC: send_mode: SendMode send_request: SendRequest send_result: SendResult + send_system_notification_request: SendSystemNotificationRequest server_agent_list: ServerAgentList server_instruction_source_list: ServerInstructionSourceList server_skill: ServerSkill server_skill_list: ServerSkillList session_activity: SessionActivity + session_agent_list_request: SessionAgentListRequest session_auth_status: SessionAuthStatus session_bulk_delete_result: SessionBulkDeleteResult + session_cancel_all_background_agents_result: int session_capability: SessionCapability + session_commands_list_request: SessionCommandsListRequest session_completion_item: SessionCompletionItem session_context: SessionContext session_context_host_type: HostType @@ -25590,14 +28767,30 @@ class RPC: session_fs_sqlite_query_request: SessionFSSqliteQueryRequest session_fs_sqlite_query_result: SessionFSSqliteQueryResult session_fs_sqlite_query_type: SessionFSSqliteQueryType + session_fs_sqlite_transaction_error: SessionFSSqliteTransactionError + session_fs_sqlite_transaction_error_class: SessionFSSqliteTransactionErrorClass + session_fs_sqlite_transaction_request: SessionFSSqliteTransactionRequest + session_fs_sqlite_transaction_result: SessionFSSqliteTransactionResult + session_fs_sqlite_transaction_statement: SessionFSSqliteTransactionStatement session_fs_stat_request: SessionFSStatRequest session_fs_stat_result: SessionFSStatResult session_fs_write_file_request: SessionFSWriteFileRequest + session_history_compact_request: SessionHistoryCompactRequest session_installed_plugin: SessionInstalledPlugin session_installed_plugin_source: SessionInstalledPluginSource | str session_installed_plugin_source_git_hub: SessionInstalledPluginSourceGitHub session_installed_plugin_source_local: SessionInstalledPluginSourceLocal session_installed_plugin_source_url: SessionInstalledPluginSourceURL + session_limit_prediction_baseline_data: SessionLimitPredictionBaselineData + session_limit_prediction_client_type: SessionLimitPredictionClientType + session_limit_prediction_details: SessionLimitPredictionDetails + session_limit_prediction_predict_request: SessionLimitPredictionPredictRequest + session_limit_prediction_request: Any + session_limit_prediction_result: SessionLimitPredictionResult + session_limit_prediction_source: SessionLimitPredictionSource + session_limit_prediction_tier: SessionLimitPredictionTier + session_limit_prediction_tier_option: SessionLimitPredictionTierOption + session_limit_prediction_unavailable_reason: SessionLimitPredictionUnavailableReason session_list: SessionList session_list_entry: SessionListEntry session_list_filter: SessionListFilter @@ -25607,6 +28800,7 @@ class RPC: session_metadata_snapshot: SessionMetadataSnapshot session_mode: SessionMode session_model_list: SessionModelList + session_model_list_request: SessionModelListRequest session_model_price_category: SessionModelPriceCategory session_open_options: SessionOpenOptions session_open_options_additional_content_exclusion_policy: SessionOpenOptionsAdditionalContentExclusionPolicy @@ -25617,12 +28811,15 @@ class RPC: session_open_options_reasoning_summary: ReasoningSummary session_open_params: SessionOpenParams session_open_result: SessionOpenResult + session_plugins_reload_request: SessionPluginsReloadRequest + session_provider_get_endpoint_request: SessionProviderGetEndpointRequest session_prune_result: SessionPruneResult sessions_bulk_delete_request: SessionsBulkDeleteRequest sessions_check_in_use_request: SessionsCheckInUseRequest sessions_check_in_use_result: SessionsCheckInUseResult sessions_close_request: SessionsCloseRequest sessions_close_result: SessionsCloseResult + sessions_delete_request: SessionsDeleteRequest sessions_enrich_metadata_request: SessionsEnrichMetadataRequest session_set_credentials_params: SessionSetCredentialsParams session_set_credentials_result: SessionSetCredentialsResult @@ -25648,9 +28845,13 @@ class RPC: sessions_get_event_file_path_result: SessionsGetEventFilePathResult sessions_get_last_for_context_request: SessionsGetLastForContextRequest sessions_get_last_for_context_result: SessionsGetLastForContextResult + sessions_get_metadata_request: SessionsGetMetadataRequest + sessions_get_metadata_result: SessionsGetMetadataResult sessions_get_persisted_remote_steerable_request: SessionsGetPersistedRemoteSteerableRequest sessions_get_persisted_remote_steerable_result: SessionsGetPersistedRemoteSteerableResult session_sizes: SessionSizes + sessions_list_non_empty_session_ids_request: SessionsListNonEmptySessionIDSRequest + sessions_list_non_empty_session_ids_result: SessionsListNonEmptySessionIDSResult sessions_list_request: SessionsListRequest sessions_load_deferred_repo_hooks_request: SessionsLoadDeferredRepoHooksRequest sessions_open_attach: SessionsOpenAttach @@ -25690,9 +28891,13 @@ class RPC: shell_exec_request: ShellExecRequest shell_exec_result: ShellExecResult shell_execute_user_requested_request: ShellExecuteUserRequestedRequest + shell_init_profile: ShellInitProfile + shell_init_script: ShellInitScript + shell_init_script_shell: ShellInitScriptShell shell_kill_request: ShellKillRequest shell_kill_result: ShellKillResult shell_kill_signal: ShellKillSignal + shell_options: ShellOptions shutdown_request: ShutdownRequest skill: Skill skill_discovery_path: SkillDiscoveryPath @@ -25815,20 +29020,30 @@ class RPC: workspace_diff_file_change_type: WorkspaceDiffFileChangeType workspace_diff_mode: WorkspaceDiffMode workspace_diff_result: WorkspaceDiffResult + workspaces_add_summary_request: WorkspacesAddSummaryRequest + workspaces_add_summary_result: WorkspacesAddSummaryResult + workspaces_autopilot_objective_exists_result: WorkspacesAutopilotObjectiveExistsResult workspaces_checkpoints: WorkspacesCheckpoints workspaces_create_file_request: WorkspacesCreateFileRequest + workspaces_delete_autopilot_objective_result: WorkspacesDeleteAutopilotObjectiveResult workspaces_diff_request: WorkspacesDiffRequest + workspaces_ensure_request: WorkspacesEnsureRequest workspaces_get_workspace_result: WorkspacesGetWorkspaceResult workspaces_list_checkpoints_result: WorkspacesListCheckpointsResult workspaces_list_files_result: WorkspacesListFilesResult + workspaces_read_autopilot_objective_result: WorkspacesReadAutopilotObjectiveResult workspaces_read_checkpoint_request: WorkspacesReadCheckpointRequest workspaces_read_checkpoint_result: WorkspacesReadCheckpointResult workspaces_read_file_request: WorkspacesReadFileRequest workspaces_read_file_result: WorkspacesReadFileResult workspaces_save_large_paste_request: WorkspacesSaveLargePasteRequest workspaces_save_large_paste_result: WorkspacesSaveLargePasteResult + workspaces_truncate_summaries_request: WorkspacesTruncateSummariesRequest workspace_summary_host_type: HostType + workspaces_update_metadata_request: WorkspacesUpdateMetadataRequest workspaces_workspace_details_host_type: HostType + workspaces_write_autopilot_objective_request: WorkspacesWriteAutopilotObjectiveRequest + workspaces_write_autopilot_objective_result: WorkspacesWriteAutopilotObjectiveResult session_context_attribution: SessionContextAttribution | None = None session_context_info: SessionContextInfo | None = None subagent_settings: SubagentSettings | None = None @@ -25858,6 +29073,7 @@ def from_dict(obj: Any) -> 'RPC': agent_info = AgentInfo.from_dict(obj.get("AgentInfo")) agent_info_source = AgentInfoSource(obj.get("AgentInfoSource")) agent_list = AgentList.from_dict(obj.get("AgentList")) + agent_list_request = obj.get("AgentListRequest") agent_registry_live_target_entry = AgentRegistryLiveTargetEntry.from_dict(obj.get("AgentRegistryLiveTargetEntry")) agent_registry_live_target_entry_attention_kind = AgentRegistryLiveTargetEntryAttentionKind(obj.get("AgentRegistryLiveTargetEntryAttentionKind")) agent_registry_live_target_entry_kind = AgentRegistryLiveTargetEntryKind(obj.get("AgentRegistryLiveTargetEntryKind")) @@ -25884,6 +29100,8 @@ def from_dict(obj: Any) -> 'RPC': api_key_auth_info = APIKeyAuthInfo.from_dict(obj.get("ApiKeyAuthInfo")) auth_info = _load_AuthInfo(obj.get("AuthInfo")) auth_info_type = AuthInfoType(obj.get("AuthInfoType")) + built_in_model_catalog = BuiltInModelCatalog.from_dict(obj.get("BuiltInModelCatalog")) + built_in_model_catalog_entry = BuiltInModelCatalogEntry.from_dict(obj.get("BuiltInModelCatalogEntry")) cancel_user_requested_shell_command_result = CancelUserRequestedShellCommandResult.from_dict(obj.get("CancelUserRequestedShellCommandResult")) canvas_action = CanvasAction.from_dict(obj.get("CanvasAction")) canvas_action_invoke_request = CanvasActionInvokeRequest.from_dict(obj.get("CanvasActionInvokeRequest")) @@ -25905,7 +29123,7 @@ def from_dict(obj: Any) -> 'RPC': commands_handle_pending_command_request = CommandsHandlePendingCommandRequest.from_dict(obj.get("CommandsHandlePendingCommandRequest")) commands_handle_pending_command_result = CommandsHandlePendingCommandResult.from_dict(obj.get("CommandsHandlePendingCommandResult")) commands_invoke_request = CommandsInvokeRequest.from_dict(obj.get("CommandsInvokeRequest")) - commands_list_request = CommandsListRequest.from_dict(obj.get("CommandsListRequest")) + commands_list_request = obj.get("CommandsListRequest") commands_respond_to_queued_command_request = CommandsRespondToQueuedCommandRequest.from_dict(obj.get("CommandsRespondToQueuedCommandRequest")) commands_respond_to_queued_command_result = CommandsRespondToQueuedCommandResult.from_dict(obj.get("CommandsRespondToQueuedCommandResult")) completions_get_trigger_characters_result = CompletionsGetTriggerCharactersResult.from_dict(obj.get("CompletionsGetTriggerCharactersResult")) @@ -25918,6 +29136,9 @@ def from_dict(obj: Any) -> 'RPC': connect_remote_session_params = ConnectRemoteSessionParams.from_dict(obj.get("ConnectRemoteSessionParams")) connect_request = _ConnectRequest.from_dict(obj.get("ConnectRequest")) connect_result = _ConnectResult.from_dict(obj.get("ConnectResult")) + content_exclusion_check_paths_request = ContentExclusionCheckPathsRequest.from_dict(obj.get("ContentExclusionCheckPathsRequest")) + content_exclusion_check_paths_result = ContentExclusionCheckPathsResult.from_dict(obj.get("ContentExclusionCheckPathsResult")) + content_exclusion_path_check = ContentExclusionPathCheck.from_dict(obj.get("ContentExclusionPathCheck")) content_filter_mode = ContentFilterMode(obj.get("ContentFilterMode")) context_heaviest_message = ContextHeaviestMessage.from_dict(obj.get("ContextHeaviestMessage")) copilot_api_token_auth_info = CopilotAPITokenAuthInfo.from_dict(obj.get("CopilotApiTokenAuthInfo")) @@ -25982,22 +29203,39 @@ def from_dict(obj: Any) -> 'RPC': factory_agent_options = FactoryAgentOptions.from_dict(obj.get("FactoryAgentOptions")) factory_agent_request = FactoryAgentRequest.from_dict(obj.get("FactoryAgentRequest")) factory_agent_result = FactoryAgentResult.from_dict(obj.get("FactoryAgentResult")) + factory_agent_summary = FactoryAgentSummary.from_dict(obj.get("FactoryAgentSummary")) factory_cancel_request = FactoryCancelRequest.from_dict(obj.get("FactoryCancelRequest")) + factory_current_phase = FactoryCurrentPhase.from_dict(obj.get("FactoryCurrentPhase")) + factory_declared_limits = FactoryDeclaredLimits.from_dict(obj.get("FactoryDeclaredLimits")) + factory_durable_operation = FactoryDurableOperation(obj.get("FactoryDurableOperation")) factory_execute_request = FactoryExecuteRequest.from_dict(obj.get("FactoryExecuteRequest")) factory_execute_result = FactoryExecuteResult.from_dict(obj.get("FactoryExecuteResult")) + factory_get_run_progress_request = FactoryGetRunProgressRequest.from_dict(obj.get("FactoryGetRunProgressRequest")) factory_get_run_request = FactoryGetRunRequest.from_dict(obj.get("FactoryGetRunRequest")) factory_journal_get_request = FactoryJournalGetRequest.from_dict(obj.get("FactoryJournalGetRequest")) factory_journal_get_result = FactoryJournalGetResult.from_dict(obj.get("FactoryJournalGetResult")) factory_journal_put_request = FactoryJournalPutRequest.from_dict(obj.get("FactoryJournalPutRequest")) + factory_list_runs_request = FactoryListRunsRequest.from_dict(obj.get("FactoryListRunsRequest")) + factory_list_runs_result = FactoryListRunsResult.from_dict(obj.get("FactoryListRunsResult")) factory_log_line = FactoryLogLine.from_dict(obj.get("FactoryLogLine")) factory_log_line_kind = FactoryLogLineKind(obj.get("FactoryLogLineKind")) factory_log_request = FactoryLogRequest.from_dict(obj.get("FactoryLogRequest")) + factory_phase_observation = FactoryPhaseObservation.from_dict(obj.get("FactoryPhaseObservation")) + factory_phase_status = FactoryPhaseStatus(obj.get("FactoryPhaseStatus")) + factory_progress_line = FactoryProgressLine.from_dict(obj.get("FactoryProgressLine")) + factory_progress_page = FactoryProgressPage.from_dict(obj.get("FactoryProgressPage")) + factory_resume_request = FactoryResumeRequest.from_dict(obj.get("FactoryResumeRequest")) + factory_resume_result = FactoryResumeResult.from_dict(obj.get("FactoryResumeResult")) + factory_run_consumed = FactoryRunConsumed.from_dict(obj.get("FactoryRunConsumed")) + factory_run_detail = FactoryRunDetail.from_dict(obj.get("FactoryRunDetail")) factory_run_failure = FactoryRunFailure.from_dict(obj.get("FactoryRunFailure")) factory_run_failure_kind = FactoryRunFailureKind(obj.get("FactoryRunFailureKind")) factory_run_limits = FactoryRunLimits.from_dict(obj.get("FactoryRunLimits")) factory_run_request = FactoryRunRequest.from_dict(obj.get("FactoryRunRequest")) factory_run_result = FactoryRunResult.from_dict(obj.get("FactoryRunResult")) factory_run_status = FactoryRunStatus(obj.get("FactoryRunStatus")) + factory_run_summary = FactoryRunSummary.from_dict(obj.get("FactoryRunSummary")) + factory_run_terminal = FactoryRunTerminal.from_dict(obj.get("FactoryRunTerminal")) filter_mapping = from_union([lambda x: from_dict(ContentFilterMode, x), ContentFilterMode], obj.get("FilterMapping")) fleet_start_request = FleetStartRequest.from_dict(obj.get("FleetStartRequest")) fleet_start_result = FleetStartResult.from_dict(obj.get("FleetStartResult")) @@ -26013,8 +29251,21 @@ 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_request = obj.get("HistoryCompactRequest") history_compact_result = HistoryCompactResult.from_dict(obj.get("HistoryCompactResult")) + history_file_restore_skip_reason = HistoryFileRestoreSkipReason(obj.get("HistoryFileRestoreSkipReason")) + history_list_rewind_points_result = HistoryListRewindPointsResult.from_dict(obj.get("HistoryListRewindPointsResult")) + history_preview_rewind_request = HistoryPreviewRewindRequest.from_dict(obj.get("HistoryPreviewRewindRequest")) + history_preview_rewind_result = HistoryPreviewRewindResult.from_dict(obj.get("HistoryPreviewRewindResult")) + history_rewind_change_type = HistoryRewindChangeType(obj.get("HistoryRewindChangeType")) + history_rewind_file_preview = HistoryRewindFilePreview.from_dict(obj.get("HistoryRewindFilePreview")) + history_rewind_mode = HistoryRewindMode(obj.get("HistoryRewindMode")) + history_rewind_outcome = HistoryRewindOutcome(obj.get("HistoryRewindOutcome")) + history_rewind_point = HistoryRewindPoint.from_dict(obj.get("HistoryRewindPoint")) + history_rewind_request = HistoryRewindRequest.from_dict(obj.get("HistoryRewindRequest")) + history_rewind_result = HistoryRewindResult.from_dict(obj.get("HistoryRewindResult")) + history_rewind_unavailable_reason = HistoryRewindUnavailableReason(obj.get("HistoryRewindUnavailableReason")) + history_skipped_file_restore = HistorySkippedFileRestore.from_dict(obj.get("HistorySkippedFileRestore")) history_summarize_for_handoff_result = HistorySummarizeForHandoffResult.from_dict(obj.get("HistorySummarizeForHandoffResult")) history_truncate_request = HistoryTruncateRequest.from_dict(obj.get("HistoryTruncateRequest")) history_truncate_result = HistoryTruncateResult.from_dict(obj.get("HistoryTruncateResult")) @@ -26038,6 +29289,8 @@ def from_dict(obj: Any) -> 'RPC': instruction_source = InstructionSource.from_dict(obj.get("InstructionSource")) instruction_source_location = InstructionLocation(obj.get("InstructionSourceLocation")) instruction_source_type = InstructionSourceType(obj.get("InstructionSourceType")) + interrupt_main_turn_request = InterruptMainTurnRequest.from_dict(obj.get("InterruptMainTurnRequest")) + interrupt_main_turn_result = InterruptMainTurnResult.from_dict(obj.get("InterruptMainTurnResult")) llm_inference_headers = from_dict(lambda x: from_list(from_str, x), obj.get("LlmInferenceHeaders")) llm_inference_http_request_chunk_request = LlmInferenceHTTPRequestChunkRequest.from_dict(obj.get("LlmInferenceHttpRequestChunkRequest")) llm_inference_http_request_chunk_result = LlmInferenceHTTPRequestChunkResult.from_dict(obj.get("LlmInferenceHttpRequestChunkResult")) @@ -26117,6 +29370,8 @@ def from_dict(obj: Any) -> 'RPC': mcp_oauth_login_request = MCPOauthLoginRequest.from_dict(obj.get("McpOauthLoginRequest")) mcp_oauth_login_result = MCPOauthLoginResult.from_dict(obj.get("McpOauthLoginResult")) mcp_oauth_pending_request_response = MCPOauthPendingRequestResponse.from_dict(obj.get("McpOauthPendingRequestResponse")) + mcp_oauth_respond_request = MCPOauthRespondRequest.from_dict(obj.get("McpOauthRespondRequest")) + mcp_oauth_respond_result = MCPOauthRespondResult.from_dict(obj.get("McpOauthRespondResult")) mcp_register_external_client_request = MCPRegisterExternalClientRequest.from_dict(obj.get("McpRegisterExternalClientRequest")) mcp_reload_with_config_request = MCPReloadWithConfigRequest.from_dict(obj.get("McpReloadWithConfigRequest")) mcp_remove_git_hub_result = MCPRemoveGitHubResult.from_dict(obj.get("McpRemoveGitHubResult")) @@ -26187,7 +29442,7 @@ def from_dict(obj: Any) -> 'RPC': model_capabilities_override_supports = ModelCapabilitiesOverrideSupports.from_dict(obj.get("ModelCapabilitiesOverrideSupports")) model_capabilities_supports = ModelCapabilitiesSupports.from_dict(obj.get("ModelCapabilitiesSupports")) model_list = ModelList.from_dict(obj.get("ModelList")) - model_list_request = ModelListRequest.from_dict(obj.get("ModelListRequest")) + model_list_request = obj.get("ModelListRequest") model_picker_category = ModelPickerCategory(obj.get("ModelPickerCategory")) model_picker_price_category = ModelPickerPriceCategory(obj.get("ModelPickerPriceCategory")) model_policy = ModelPolicy.from_dict(obj.get("ModelPolicy")) @@ -26327,7 +29582,7 @@ def from_dict(obj: Any) -> 'RPC': plugins_marketplaces_browse_request = PluginsMarketplacesBrowseRequest.from_dict(obj.get("PluginsMarketplacesBrowseRequest")) plugins_marketplaces_refresh_request = PluginsMarketplacesRefreshRequest.from_dict(obj.get("PluginsMarketplacesRefreshRequest")) plugins_marketplaces_remove_request = PluginsMarketplacesRemoveRequest.from_dict(obj.get("PluginsMarketplacesRemoveRequest")) - plugins_reload_request = PluginsReloadRequest.from_dict(obj.get("PluginsReloadRequest")) + plugins_reload_request = obj.get("PluginsReloadRequest") plugins_uninstall_request = PluginsUninstallRequest.from_dict(obj.get("PluginsUninstallRequest")) plugins_update_request = PluginsUpdateRequest.from_dict(obj.get("PluginsUpdateRequest")) plugin_update_all_entry = PluginUpdateAllEntry.from_dict(obj.get("PluginUpdateAllEntry")) @@ -26344,7 +29599,7 @@ def from_dict(obj: Any) -> 'RPC': provider_endpoint_transport = ProviderTransport(obj.get("ProviderEndpointTransport")) provider_endpoint_type = ProviderType(obj.get("ProviderEndpointType")) provider_endpoint_wire_api = ProviderWireAPI(obj.get("ProviderEndpointWireApi")) - provider_get_endpoint_request = ProviderGetEndpointRequest.from_dict(obj.get("ProviderGetEndpointRequest")) + provider_get_endpoint_request = obj.get("ProviderGetEndpointRequest") provider_model_config = ProviderModelConfig.from_dict(obj.get("ProviderModelConfig")) provider_session_token = ProviderSessionToken.from_dict(obj.get("ProviderSessionToken")) provider_token_acquire_request = ProviderTokenAcquireRequest.from_dict(obj.get("ProviderTokenAcquireRequest")) @@ -26372,13 +29627,36 @@ def from_dict(obj: Any) -> 'RPC': push_attachment_selection_details_end = PushAttachmentSelectionDetailsEnd.from_dict(obj.get("PushAttachmentSelectionDetailsEnd")) push_attachment_selection_details_start = PushAttachmentSelectionDetailsStart.from_dict(obj.get("PushAttachmentSelectionDetailsStart")) push_git_hub_repo_ref = PushGitHubRepoRef.from_dict(obj.get("PushGitHubRepoRef")) + queue_begin_deferred_idle_drain_request = QueueBeginDeferredIdleDrainRequest.from_dict(obj.get("QueueBeginDeferredIdleDrainRequest")) + queue_begin_deferred_idle_drain_result = QueueBeginDeferredIdleDrainResult.from_dict(obj.get("QueueBeginDeferredIdleDrainResult")) + queue_consume_system_notifications_request = QueueConsumeSystemNotificationsRequest.from_dict(obj.get("QueueConsumeSystemNotificationsRequest")) queued_command_handled = QueuedCommandHandled.from_dict(obj.get("QueuedCommandHandled")) queued_command_not_handled = QueuedCommandNotHandled.from_dict(obj.get("QueuedCommandNotHandled")) queued_command_result = _load_QueuedCommandResult(obj.get("QueuedCommandResult")) + queue_defer_session_idle_request = QueueDeferSessionIdleRequest.from_dict(obj.get("QueueDeferSessionIdleRequest")) + queue_duplicate_at_request = QueueDuplicateAtRequest.from_dict(obj.get("QueueDuplicateAtRequest")) + queue_duplicate_at_result = QueueDuplicateAtResult.from_dict(obj.get("QueueDuplicateAtResult")) + queue_enqueue_resume_pending_result = QueueEnqueueResumePendingResult.from_dict(obj.get("QueueEnqueueResumePendingResult")) + queue_finish_deferred_idle_drain_request = QueueFinishDeferredIdleDrainRequest.from_dict(obj.get("QueueFinishDeferredIdleDrainRequest")) + queue_finish_deferred_idle_drain_result = QueueFinishDeferredIdleDrainResult.from_dict(obj.get("QueueFinishDeferredIdleDrainResult")) + queue_has_pending_result = QueueHasPendingResult.from_dict(obj.get("QueueHasPendingResult")) + queue_insert_at_request = QueueInsertAtRequest.from_dict(obj.get("QueueInsertAtRequest")) + queue_insert_at_result = QueueInsertAtResult.from_dict(obj.get("QueueInsertAtResult")) + queue_insert_message = QueueInsertMessage.from_dict(obj.get("QueueInsertMessage")) + queue_move_item_request = QueueMoveItemRequest.from_dict(obj.get("QueueMoveItemRequest")) + queue_move_item_result = QueueMoveItemResult.from_dict(obj.get("QueueMoveItemResult")) queue_pending_items = QueuePendingItems.from_dict(obj.get("QueuePendingItems")) queue_pending_items_kind = QueuePendingItemsKind(obj.get("QueuePendingItemsKind")) queue_pending_items_result = QueuePendingItemsResult.from_dict(obj.get("QueuePendingItemsResult")) + queue_remove_at_request = QueueRemoveAtRequest.from_dict(obj.get("QueueRemoveAtRequest")) + queue_remove_at_result = QueueRemoveAtResult.from_dict(obj.get("QueueRemoveAtResult")) queue_remove_most_recent_result = QueueRemoveMostRecentResult.from_dict(obj.get("QueueRemoveMostRecentResult")) + queue_send_now_request = QueueSendNowRequest.from_dict(obj.get("QueueSendNowRequest")) + queue_send_now_result = QueueSendNowResult.from_dict(obj.get("QueueSendNowResult")) + queue_set_drain_paused_request = QueueSetDrainPausedRequest.from_dict(obj.get("QueueSetDrainPausedRequest")) + queue_snapshot_result = QueueSnapshotResult.from_dict(obj.get("QueueSnapshotResult")) + queue_update_text_request = QueueUpdateTextRequest.from_dict(obj.get("QueueUpdateTextRequest")) + queue_update_text_result = QueueUpdateTextResult.from_dict(obj.get("QueueUpdateTextResult")) register_event_interest_params = RegisterEventInterestParams.from_dict(obj.get("RegisterEventInterestParams")) register_event_interest_result = RegisterEventInterestResult.from_dict(obj.get("RegisterEventInterestResult")) register_extension_tools_params = _RegisterExtensionToolsParams.from_dict(obj.get("RegisterExtensionToolsParams")) @@ -26411,9 +29689,17 @@ def from_dict(obj: Any) -> 'RPC': sandbox_config_user_policy_experimental_seatbelt = SandboxConfigUserPolicyExperimentalSeatbelt.from_dict(obj.get("SandboxConfigUserPolicyExperimentalSeatbelt")) sandbox_config_user_policy_filesystem = SandboxConfigUserPolicyFilesystem.from_dict(obj.get("SandboxConfigUserPolicyFilesystem")) sandbox_config_user_policy_network = SandboxConfigUserPolicyNetwork.from_dict(obj.get("SandboxConfigUserPolicyNetwork")) + sandbox_config_user_policy_network_proxy = SandboxConfigUserPolicyNetworkProxy.from_dict(obj.get("SandboxConfigUserPolicyNetworkProxy")) sandbox_config_user_policy_seatbelt = SandboxConfigUserPolicySeatbelt.from_dict(obj.get("SandboxConfigUserPolicySeatbelt")) + schedule_add_at_request = ScheduleAddAtRequest.from_dict(obj.get("ScheduleAddAtRequest")) + schedule_add_cron_request = ScheduleAddCronRequest.from_dict(obj.get("ScheduleAddCronRequest")) + schedule_add_request = ScheduleAddRequest.from_dict(obj.get("ScheduleAddRequest")) + schedule_add_result = ScheduleAddResult.from_dict(obj.get("ScheduleAddResult")) + schedule_add_self_paced_request = ScheduleAddSelfPacedRequest.from_dict(obj.get("ScheduleAddSelfPacedRequest")) schedule_entry = ScheduleEntry.from_dict(obj.get("ScheduleEntry")) + schedule_has_self_paced_result = ScheduleHasSelfPacedResult.from_dict(obj.get("ScheduleHasSelfPacedResult")) schedule_list = ScheduleList.from_dict(obj.get("ScheduleList")) + schedule_rearm_self_paced_request = ScheduleRearmSelfPacedRequest.from_dict(obj.get("ScheduleRearmSelfPacedRequest")) schedule_stop_request = ScheduleStopRequest.from_dict(obj.get("ScheduleStopRequest")) schedule_stop_result = ScheduleStopResult.from_dict(obj.get("ScheduleStopResult")) secrets_add_filter_values_request = SecretsAddFilterValuesRequest.from_dict(obj.get("SecretsAddFilterValuesRequest")) @@ -26426,14 +29712,18 @@ def from_dict(obj: Any) -> 'RPC': send_mode = SendMode(obj.get("SendMode")) send_request = SendRequest.from_dict(obj.get("SendRequest")) send_result = SendResult.from_dict(obj.get("SendResult")) + send_system_notification_request = SendSystemNotificationRequest.from_dict(obj.get("SendSystemNotificationRequest")) server_agent_list = ServerAgentList.from_dict(obj.get("ServerAgentList")) server_instruction_source_list = ServerInstructionSourceList.from_dict(obj.get("ServerInstructionSourceList")) server_skill = ServerSkill.from_dict(obj.get("ServerSkill")) server_skill_list = ServerSkillList.from_dict(obj.get("ServerSkillList")) session_activity = SessionActivity.from_dict(obj.get("SessionActivity")) + session_agent_list_request = SessionAgentListRequest.from_dict(obj.get("SessionAgentListRequest")) session_auth_status = SessionAuthStatus.from_dict(obj.get("SessionAuthStatus")) session_bulk_delete_result = SessionBulkDeleteResult.from_dict(obj.get("SessionBulkDeleteResult")) + session_cancel_all_background_agents_result = from_int(obj.get("SessionCancelAllBackgroundAgentsResult")) session_capability = SessionCapability(obj.get("SessionCapability")) + session_commands_list_request = SessionCommandsListRequest.from_dict(obj.get("SessionCommandsListRequest")) session_completion_item = SessionCompletionItem.from_dict(obj.get("SessionCompletionItem")) session_context = SessionContext.from_dict(obj.get("SessionContext")) session_context_host_type = HostType(obj.get("SessionContextHostType")) @@ -26463,14 +29753,30 @@ def from_dict(obj: Any) -> 'RPC': session_fs_sqlite_query_request = SessionFSSqliteQueryRequest.from_dict(obj.get("SessionFsSqliteQueryRequest")) session_fs_sqlite_query_result = SessionFSSqliteQueryResult.from_dict(obj.get("SessionFsSqliteQueryResult")) session_fs_sqlite_query_type = SessionFSSqliteQueryType(obj.get("SessionFsSqliteQueryType")) + session_fs_sqlite_transaction_error = SessionFSSqliteTransactionError.from_dict(obj.get("SessionFsSqliteTransactionError")) + session_fs_sqlite_transaction_error_class = SessionFSSqliteTransactionErrorClass(obj.get("SessionFsSqliteTransactionErrorClass")) + session_fs_sqlite_transaction_request = SessionFSSqliteTransactionRequest.from_dict(obj.get("SessionFsSqliteTransactionRequest")) + session_fs_sqlite_transaction_result = SessionFSSqliteTransactionResult.from_dict(obj.get("SessionFsSqliteTransactionResult")) + session_fs_sqlite_transaction_statement = SessionFSSqliteTransactionStatement.from_dict(obj.get("SessionFsSqliteTransactionStatement")) session_fs_stat_request = SessionFSStatRequest.from_dict(obj.get("SessionFsStatRequest")) session_fs_stat_result = SessionFSStatResult.from_dict(obj.get("SessionFsStatResult")) session_fs_write_file_request = SessionFSWriteFileRequest.from_dict(obj.get("SessionFsWriteFileRequest")) + session_history_compact_request = SessionHistoryCompactRequest.from_dict(obj.get("SessionHistoryCompactRequest")) session_installed_plugin = SessionInstalledPlugin.from_dict(obj.get("SessionInstalledPlugin")) session_installed_plugin_source = from_union([SessionInstalledPluginSource.from_dict, from_str], obj.get("SessionInstalledPluginSource")) session_installed_plugin_source_git_hub = SessionInstalledPluginSourceGitHub.from_dict(obj.get("SessionInstalledPluginSourceGitHub")) session_installed_plugin_source_local = SessionInstalledPluginSourceLocal.from_dict(obj.get("SessionInstalledPluginSourceLocal")) session_installed_plugin_source_url = SessionInstalledPluginSourceURL.from_dict(obj.get("SessionInstalledPluginSourceUrl")) + session_limit_prediction_baseline_data = SessionLimitPredictionBaselineData.from_dict(obj.get("SessionLimitPredictionBaselineData")) + session_limit_prediction_client_type = SessionLimitPredictionClientType(obj.get("SessionLimitPredictionClientType")) + session_limit_prediction_details = SessionLimitPredictionDetails.from_dict(obj.get("SessionLimitPredictionDetails")) + session_limit_prediction_predict_request = SessionLimitPredictionPredictRequest.from_dict(obj.get("SessionLimitPredictionPredictRequest")) + session_limit_prediction_request = obj.get("SessionLimitPredictionRequest") + session_limit_prediction_result = SessionLimitPredictionResult.from_dict(obj.get("SessionLimitPredictionResult")) + session_limit_prediction_source = SessionLimitPredictionSource(obj.get("SessionLimitPredictionSource")) + session_limit_prediction_tier = SessionLimitPredictionTier(obj.get("SessionLimitPredictionTier")) + session_limit_prediction_tier_option = SessionLimitPredictionTierOption.from_dict(obj.get("SessionLimitPredictionTierOption")) + session_limit_prediction_unavailable_reason = SessionLimitPredictionUnavailableReason(obj.get("SessionLimitPredictionUnavailableReason")) session_list = SessionList.from_dict(obj.get("SessionList")) session_list_entry = _load_SessionListEntry(obj.get("SessionListEntry")) session_list_filter = SessionListFilter.from_dict(obj.get("SessionListFilter")) @@ -26480,6 +29786,7 @@ def from_dict(obj: Any) -> 'RPC': session_metadata_snapshot = SessionMetadataSnapshot.from_dict(obj.get("SessionMetadataSnapshot")) session_mode = SessionMode(obj.get("SessionMode")) session_model_list = SessionModelList.from_dict(obj.get("SessionModelList")) + session_model_list_request = SessionModelListRequest.from_dict(obj.get("SessionModelListRequest")) session_model_price_category = SessionModelPriceCategory.from_dict(obj.get("SessionModelPriceCategory")) session_open_options = SessionOpenOptions.from_dict(obj.get("SessionOpenOptions")) session_open_options_additional_content_exclusion_policy = SessionOpenOptionsAdditionalContentExclusionPolicy.from_dict(obj.get("SessionOpenOptionsAdditionalContentExclusionPolicy")) @@ -26490,12 +29797,15 @@ def from_dict(obj: Any) -> 'RPC': session_open_options_reasoning_summary = ReasoningSummary(obj.get("SessionOpenOptionsReasoningSummary")) session_open_params = _load_SessionOpenParams(obj.get("SessionOpenParams")) session_open_result = SessionOpenResult.from_dict(obj.get("SessionOpenResult")) + session_plugins_reload_request = SessionPluginsReloadRequest.from_dict(obj.get("SessionPluginsReloadRequest")) + session_provider_get_endpoint_request = SessionProviderGetEndpointRequest.from_dict(obj.get("SessionProviderGetEndpointRequest")) session_prune_result = SessionPruneResult.from_dict(obj.get("SessionPruneResult")) sessions_bulk_delete_request = SessionsBulkDeleteRequest.from_dict(obj.get("SessionsBulkDeleteRequest")) sessions_check_in_use_request = SessionsCheckInUseRequest.from_dict(obj.get("SessionsCheckInUseRequest")) sessions_check_in_use_result = SessionsCheckInUseResult.from_dict(obj.get("SessionsCheckInUseResult")) sessions_close_request = SessionsCloseRequest.from_dict(obj.get("SessionsCloseRequest")) sessions_close_result = SessionsCloseResult.from_dict(obj.get("SessionsCloseResult")) + sessions_delete_request = SessionsDeleteRequest.from_dict(obj.get("SessionsDeleteRequest")) sessions_enrich_metadata_request = SessionsEnrichMetadataRequest.from_dict(obj.get("SessionsEnrichMetadataRequest")) session_set_credentials_params = SessionSetCredentialsParams.from_dict(obj.get("SessionSetCredentialsParams")) session_set_credentials_result = SessionSetCredentialsResult.from_dict(obj.get("SessionSetCredentialsResult")) @@ -26521,9 +29831,13 @@ def from_dict(obj: Any) -> 'RPC': sessions_get_event_file_path_result = SessionsGetEventFilePathResult.from_dict(obj.get("SessionsGetEventFilePathResult")) sessions_get_last_for_context_request = SessionsGetLastForContextRequest.from_dict(obj.get("SessionsGetLastForContextRequest")) sessions_get_last_for_context_result = SessionsGetLastForContextResult.from_dict(obj.get("SessionsGetLastForContextResult")) + sessions_get_metadata_request = SessionsGetMetadataRequest.from_dict(obj.get("SessionsGetMetadataRequest")) + sessions_get_metadata_result = SessionsGetMetadataResult.from_dict(obj.get("SessionsGetMetadataResult")) sessions_get_persisted_remote_steerable_request = SessionsGetPersistedRemoteSteerableRequest.from_dict(obj.get("SessionsGetPersistedRemoteSteerableRequest")) sessions_get_persisted_remote_steerable_result = SessionsGetPersistedRemoteSteerableResult.from_dict(obj.get("SessionsGetPersistedRemoteSteerableResult")) session_sizes = SessionSizes.from_dict(obj.get("SessionSizes")) + sessions_list_non_empty_session_ids_request = SessionsListNonEmptySessionIDSRequest.from_dict(obj.get("SessionsListNonEmptySessionIdsRequest")) + sessions_list_non_empty_session_ids_result = SessionsListNonEmptySessionIDSResult.from_dict(obj.get("SessionsListNonEmptySessionIdsResult")) sessions_list_request = SessionsListRequest.from_dict(obj.get("SessionsListRequest")) sessions_load_deferred_repo_hooks_request = SessionsLoadDeferredRepoHooksRequest.from_dict(obj.get("SessionsLoadDeferredRepoHooksRequest")) sessions_open_attach = SessionsOpenAttach.from_dict(obj.get("SessionsOpenAttach")) @@ -26563,9 +29877,13 @@ def from_dict(obj: Any) -> 'RPC': shell_exec_request = ShellExecRequest.from_dict(obj.get("ShellExecRequest")) shell_exec_result = ShellExecResult.from_dict(obj.get("ShellExecResult")) shell_execute_user_requested_request = ShellExecuteUserRequestedRequest.from_dict(obj.get("ShellExecuteUserRequestedRequest")) + shell_init_profile = ShellInitProfile(obj.get("ShellInitProfile")) + shell_init_script = ShellInitScript.from_dict(obj.get("ShellInitScript")) + shell_init_script_shell = ShellInitScriptShell(obj.get("ShellInitScriptShell")) shell_kill_request = ShellKillRequest.from_dict(obj.get("ShellKillRequest")) shell_kill_result = ShellKillResult.from_dict(obj.get("ShellKillResult")) shell_kill_signal = ShellKillSignal(obj.get("ShellKillSignal")) + shell_options = ShellOptions.from_dict(obj.get("ShellOptions")) shutdown_request = ShutdownRequest.from_dict(obj.get("ShutdownRequest")) skill = Skill.from_dict(obj.get("Skill")) skill_discovery_path = SkillDiscoveryPath.from_dict(obj.get("SkillDiscoveryPath")) @@ -26688,26 +30006,36 @@ def from_dict(obj: Any) -> 'RPC': workspace_diff_file_change_type = WorkspaceDiffFileChangeType(obj.get("WorkspaceDiffFileChangeType")) workspace_diff_mode = WorkspaceDiffMode(obj.get("WorkspaceDiffMode")) workspace_diff_result = WorkspaceDiffResult.from_dict(obj.get("WorkspaceDiffResult")) + workspaces_add_summary_request = WorkspacesAddSummaryRequest.from_dict(obj.get("WorkspacesAddSummaryRequest")) + workspaces_add_summary_result = WorkspacesAddSummaryResult.from_dict(obj.get("WorkspacesAddSummaryResult")) + workspaces_autopilot_objective_exists_result = WorkspacesAutopilotObjectiveExistsResult.from_dict(obj.get("WorkspacesAutopilotObjectiveExistsResult")) workspaces_checkpoints = WorkspacesCheckpoints.from_dict(obj.get("WorkspacesCheckpoints")) workspaces_create_file_request = WorkspacesCreateFileRequest.from_dict(obj.get("WorkspacesCreateFileRequest")) + workspaces_delete_autopilot_objective_result = WorkspacesDeleteAutopilotObjectiveResult.from_dict(obj.get("WorkspacesDeleteAutopilotObjectiveResult")) workspaces_diff_request = WorkspacesDiffRequest.from_dict(obj.get("WorkspacesDiffRequest")) + workspaces_ensure_request = WorkspacesEnsureRequest.from_dict(obj.get("WorkspacesEnsureRequest")) workspaces_get_workspace_result = WorkspacesGetWorkspaceResult.from_dict(obj.get("WorkspacesGetWorkspaceResult")) workspaces_list_checkpoints_result = WorkspacesListCheckpointsResult.from_dict(obj.get("WorkspacesListCheckpointsResult")) workspaces_list_files_result = WorkspacesListFilesResult.from_dict(obj.get("WorkspacesListFilesResult")) + workspaces_read_autopilot_objective_result = WorkspacesReadAutopilotObjectiveResult.from_dict(obj.get("WorkspacesReadAutopilotObjectiveResult")) workspaces_read_checkpoint_request = WorkspacesReadCheckpointRequest.from_dict(obj.get("WorkspacesReadCheckpointRequest")) workspaces_read_checkpoint_result = WorkspacesReadCheckpointResult.from_dict(obj.get("WorkspacesReadCheckpointResult")) workspaces_read_file_request = WorkspacesReadFileRequest.from_dict(obj.get("WorkspacesReadFileRequest")) workspaces_read_file_result = WorkspacesReadFileResult.from_dict(obj.get("WorkspacesReadFileResult")) workspaces_save_large_paste_request = WorkspacesSaveLargePasteRequest.from_dict(obj.get("WorkspacesSaveLargePasteRequest")) workspaces_save_large_paste_result = WorkspacesSaveLargePasteResult.from_dict(obj.get("WorkspacesSaveLargePasteResult")) + workspaces_truncate_summaries_request = WorkspacesTruncateSummariesRequest.from_dict(obj.get("WorkspacesTruncateSummariesRequest")) workspace_summary_host_type = HostType(obj.get("WorkspaceSummaryHostType")) + workspaces_update_metadata_request = WorkspacesUpdateMetadataRequest.from_dict(obj.get("WorkspacesUpdateMetadataRequest")) workspaces_workspace_details_host_type = HostType(obj.get("WorkspacesWorkspaceDetailsHostType")) + workspaces_write_autopilot_objective_request = WorkspacesWriteAutopilotObjectiveRequest.from_dict(obj.get("WorkspacesWriteAutopilotObjectiveRequest")) + workspaces_write_autopilot_objective_result = WorkspacesWriteAutopilotObjectiveResult.from_dict(obj.get("WorkspacesWriteAutopilotObjectiveResult")) session_context_attribution = from_union([SessionContextAttribution.from_dict, from_none], obj.get("SessionContextAttribution")) session_context_info = from_union([SessionContextInfo.from_dict, from_none], obj.get("SessionContextInfo")) subagent_settings = from_union([SubagentSettings.from_dict, from_none], obj.get("SubagentSettings")) 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_all_users, account_get_all_users_result, account_get_current_auth_result, account_get_quota_request, account_get_quota_result, account_login_request, account_login_result, account_logout_request, account_logout_result, account_quota_snapshot, adaptive_thinking_support, agent_discovery_path, agent_discovery_path_list, agent_discovery_path_scope, agent_get_current_result, agent_info, agent_info_source, agent_list, agent_registry_live_target_entry, agent_registry_live_target_entry_attention_kind, agent_registry_live_target_entry_kind, agent_registry_live_target_entry_last_terminal_event, agent_registry_live_target_entry_status, agent_registry_log_capture, agent_registry_log_capture_open_error_reason, agent_registry_spawn_error, agent_registry_spawn_permission_mode, agent_registry_spawn_registry_timeout, agent_registry_spawn_request, agent_registry_spawn_result, agent_registry_spawn_spawned, agent_registry_spawn_validation_error, agent_registry_spawn_validation_error_field, agent_registry_spawn_validation_error_reason, agent_reload_result, agents_discover_request, agent_select_request, agent_select_result, agents_get_discovery_paths_request, allow_all_permission_set_result, allow_all_permission_state, api_key_auth_info, auth_info, auth_info_type, cancel_user_requested_shell_command_result, canvas_action, canvas_action_invoke_request, canvas_action_invoke_result, canvas_close_request, canvas_host_context, canvas_host_context_capabilities, canvas_json_schema, canvas_list, canvas_list_open_result, canvas_open_request, canvas_provider_close_request, canvas_provider_invoke_action_request, canvas_provider_open_request, canvas_provider_open_result, canvas_session_context, capi_session_options, 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, completions_get_trigger_characters_result, completions_request_request, completions_request_result, configure_session_extensions_params, 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, context_heaviest_message, 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, current_tool_metadata, debug_collect_logs_collected_entry, debug_collect_logs_destination, debug_collect_logs_entry, debug_collect_logs_entry_kind, debug_collect_logs_include, debug_collect_logs_redaction, debug_collect_logs_request, debug_collect_logs_result, debug_collect_logs_result_kind, debug_collect_logs_skipped_entry, debug_collect_logs_source, discovered_canvas, 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_context_push_input, 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_shell_exit, external_tool_text_result_for_llm_content_terminal, external_tool_text_result_for_llm_content_text, factory_abort_request, factory_ack_result, factory_agent_options, factory_agent_request, factory_agent_result, factory_cancel_request, factory_execute_request, factory_execute_result, factory_get_run_request, factory_journal_get_request, factory_journal_get_result, factory_journal_put_request, factory_log_line, factory_log_line_kind, factory_log_request, factory_run_failure, factory_run_failure_kind, factory_run_limits, factory_run_request, factory_run_result, factory_run_status, filter_mapping, fleet_start_request, fleet_start_result, folder_trust_add_params, folder_trust_check_params, folder_trust_check_result, gh_cli_auth_info, git_hub_telemetry_client_info, git_hub_telemetry_event, git_hub_telemetry_notification, 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, hook_invoke_request, hook_invoke_response, hook_type, installed_plugin, installed_plugin_info, installed_plugin_source, installed_plugin_source_git_hub, installed_plugin_source_local, installed_plugin_source_url, instruction_discovery_path, instruction_discovery_path_kind, instruction_discovery_path_list, instruction_discovery_path_location, instructions_discover_request, instructions_get_discovery_paths_request, instructions_get_sources_result, instruction_source, instruction_source_location, instruction_source_type, llm_inference_headers, llm_inference_http_request_chunk_request, llm_inference_http_request_chunk_result, llm_inference_http_request_start_request, llm_inference_http_request_start_result, llm_inference_http_request_start_transport, llm_inference_http_response_chunk_error, llm_inference_http_response_chunk_request, llm_inference_http_response_chunk_result, llm_inference_http_response_start_request, llm_inference_http_response_start_result, llm_inference_set_provider_result, local_session_metadata_value, log_request, log_result, lsp_initialize_request, marketplace_add_result, marketplace_browse_result, marketplace_info, marketplace_list_result, marketplace_plugin_info, marketplace_refresh_entry, marketplace_refresh_result, marketplace_remove_result, mcp_allowed_server, mcp_apps_call_tool_request, mcp_apps_diagnose_capability, mcp_apps_diagnose_request, mcp_apps_diagnose_result, mcp_apps_diagnose_server, mcp_apps_host_context, mcp_apps_host_context_details, mcp_apps_host_context_details_available_display_mode, mcp_apps_host_context_details_display_mode, mcp_apps_host_context_details_platform, mcp_apps_host_context_details_theme, mcp_apps_list_tools_request, mcp_apps_list_tools_result, mcp_apps_read_resource_request, mcp_apps_read_resource_result, mcp_apps_resource_content, mcp_apps_set_host_context_details, mcp_apps_set_host_context_details_available_display_mode, mcp_apps_set_host_context_details_display_mode, mcp_apps_set_host_context_details_platform, mcp_apps_set_host_context_details_theme, mcp_apps_set_host_context_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_configure_git_hub_request, mcp_configure_git_hub_result, 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_filtered_server, mcp_headers_handle_pending_headers_refresh_request, mcp_headers_handle_pending_headers_refresh_request_request, mcp_headers_handle_pending_headers_refresh_request_result, mcp_host_state, mcp_is_server_running_request, mcp_is_server_running_result, mcp_list_tools_request, mcp_list_tools_result, mcp_oauth_handle_pending_request, mcp_oauth_handle_pending_result, mcp_oauth_login_grant_type, mcp_oauth_login_request, mcp_oauth_login_result, mcp_oauth_pending_request_response, mcp_register_external_client_request, mcp_reload_with_config_request, mcp_remove_git_hub_result, mcp_resource, mcp_resource_annotations, mcp_resource_content, mcp_resource_icon, mcp_resources_list_request, mcp_resources_list_result, mcp_resources_list_templates_request, mcp_resources_list_templates_result, mcp_resources_read_request, mcp_resources_read_result, mcp_resource_template, mcp_restart_server_request, mcp_sampling_execution_action, mcp_sampling_execution_result, mcp_server, mcp_server_auth_config, mcp_server_auth_config_redirect_port, mcp_server_config, mcp_server_config_defer_tools, mcp_server_config_http, mcp_server_config_http_oauth_grant_type, mcp_server_config_http_type, mcp_server_config_stdio, mcp_server_failure_info, mcp_server_list, mcp_server_needs_auth_info, mcp_set_env_value_mode_details, mcp_set_env_value_mode_params, mcp_set_env_value_mode_result, mcp_start_server_request, mcp_start_servers_result, mcp_stop_server_request, mcp_tools, mcp_tool_ui, mcp_tool_ui_visibility, mcp_unregister_external_client_request, memory_configuration, metadata_context_attribution_result, metadata_context_heaviest_messages_request, metadata_context_heaviest_messages_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_promo, model_billing_token_prices, model_billing_token_prices_long_context, 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_list_request, 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, named_provider_config, name_get_result, name_set_auto_request, name_set_auto_result, name_set_request, open_canvas_instance, options_update_additional_content_exclusion_policy, options_update_additional_content_exclusion_policy_rule, options_update_additional_content_exclusion_policy_rule_source, options_update_additional_content_exclusion_policy_scope, options_update_context_tier, options_update_env_value_mode, options_update_reasoning_summary, options_update_tool_filter_precedence, 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_allow_all_mode, 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_get_allow_all_request, 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_allow_all_request, permissions_set_allow_all_source, 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_read_sql_todos_result, plan_read_sql_todos_with_dependencies_result, plan_sql_todo_dependency, plan_sql_todos_row, plan_update_request, plugin, plugin_install_result, plugin_list, plugin_list_result, plugins_disable_request, plugins_enable_request, plugins_install_request, plugins_marketplaces_add_request, plugins_marketplaces_browse_request, plugins_marketplaces_refresh_request, plugins_marketplaces_remove_request, plugins_reload_request, plugins_uninstall_request, plugins_update_request, plugin_update_all_entry, plugin_update_all_result, plugin_update_result, provider_add_request, provider_add_result, provider_config, provider_config_azure, provider_config_transport, provider_config_type, provider_config_wire_api, provider_endpoint, provider_endpoint_transport, provider_endpoint_type, provider_endpoint_wire_api, provider_get_endpoint_request, provider_model_config, provider_session_token, provider_token_acquire_request, provider_token_acquire_result, push_attachment, push_attachment_blob, push_attachment_directory, push_attachment_file, push_attachment_file_line_range, push_attachment_git_hub_actions_job, push_attachment_git_hub_commit, push_attachment_git_hub_file, push_attachment_git_hub_file_diff, push_attachment_git_hub_file_diff_side, push_attachment_git_hub_reference, push_attachment_git_hub_reference_type, push_attachment_git_hub_release, push_attachment_git_hub_repository, push_attachment_git_hub_snippet, push_attachment_git_hub_tree_comparison, push_attachment_git_hub_tree_comparison_side, push_attachment_git_hub_url, push_attachment_selection, push_attachment_selection_details, push_attachment_selection_details_end, push_attachment_selection_details_start, push_git_hub_repo_ref, 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, register_extension_tools_params, register_extension_tools_result, release_event_interest_params, remote_control_config, remote_control_config_existing_mc_session, remote_control_status, remote_control_status_active, remote_control_status_connecting, remote_control_status_error, remote_control_status_off, remote_control_status_result, remote_control_stop_result, remote_control_transfer_result, remote_enable_request, remote_enable_result, remote_notify_steerable_changed_request, remote_notify_steerable_changed_result, remote_session_connection_result, remote_session_metadata_repository, remote_session_metadata_task_type, remote_session_metadata_value, remote_session_mode, remote_session_repository, run_options, sandbox_config, sandbox_config_user_policy, sandbox_config_user_policy_experimental, sandbox_config_user_policy_experimental_seatbelt, sandbox_config_user_policy_filesystem, sandbox_config_user_policy_network, sandbox_config_user_policy_seatbelt, schedule_entry, schedule_list, schedule_stop_request, schedule_stop_result, secrets_add_filter_values_request, secrets_add_filter_values_result, send_agent_mode, send_attachments_to_message_params, send_message_item, send_messages_request, send_messages_result, send_mode, send_request, send_result, server_agent_list, server_instruction_source_list, server_skill, server_skill_list, session_activity, session_auth_status, session_bulk_delete_result, session_capability, session_completion_item, 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_git_hub, session_installed_plugin_source_local, session_installed_plugin_source_url, session_list, session_list_entry, session_list_filter, session_load_deferred_repo_hooks_result, session_log_level, session_mcp_apps_call_tool_result, session_metadata_snapshot, session_mode, session_model_list, session_model_price_category, session_open_options, session_open_options_additional_content_exclusion_policy, session_open_options_additional_content_exclusion_policy_rule, session_open_options_additional_content_exclusion_policy_rule_source, session_open_options_additional_content_exclusion_policy_scope, session_open_options_env_value_mode, session_open_options_reasoning_summary, session_open_params, session_open_result, 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, session_settings_built_in_tool_availability_snapshot, session_settings_evaluate_predicate_request, session_settings_evaluate_predicate_result, session_settings_job_snapshot, session_settings_model_snapshot, session_settings_online_evaluation_snapshot, session_settings_predicate_name, session_settings_repo_snapshot, session_settings_snapshot, session_settings_validation_snapshot, 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_board_entry_count_request, sessions_get_board_entry_count_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_open_attach, sessions_open_cloud, sessions_open_create, sessions_open_handoff, sessions_open_handoff_task_type, sessions_open_progress, sessions_open_progress_status, sessions_open_progress_step, sessions_open_remote, sessions_open_resume, sessions_open_resume_last, sessions_open_status, session_source, sessions_prune_old_request, sessions_register_extension_tools_on_session_options, 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, sessions_set_remote_control_steering_request, sessions_start_remote_control_request, sessions_stop_remote_control_request, sessions_transfer_remote_control_request, session_telemetry_engagement, session_update_options_params, session_update_options_result, session_visibility_status, session_working_directory_context, session_working_directory_context_host_type, shell_cancel_user_requested_request, shell_exec_request, shell_exec_result, shell_execute_user_requested_request, shell_kill_request, shell_kill_result, shell_kill_signal, shutdown_request, skill, skill_discovery_path, skill_discovery_path_list, skill_discovery_scope, skill_list, skills_config_set_disabled_skills_request, skills_disable_request, skills_discover_request, skills_enable_request, skills_get_discovery_paths_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_choice, 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, subagent_settings_entry, subagent_settings_entry_context_tier, 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_get_current_metadata_result, tools_initialize_and_validate_result, tools_list_request, tools_update_subagent_settings_result, 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_ephemeral_query_request, ui_ephemeral_query_result, 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_session_limits_exhausted_request, ui_handle_pending_user_input_request, ui_register_direct_auto_mode_switch_handler_result, ui_session_limits_exhausted_response, ui_session_limits_exhausted_response_action, ui_unregister_direct_auto_mode_switch_handler_request, ui_unregister_direct_auto_mode_switch_handler_result, ui_user_input_response, update_subagent_settings_request, 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_requested_shell_command_result, user_setting_metadata, user_settings_get_result, user_settings_set_request, user_settings_set_result, visibility_get_result, visibility_set_request, visibility_set_result, workspace_diff_file_change, workspace_diff_file_change_type, workspace_diff_mode, workspace_diff_result, workspaces_checkpoints, workspaces_create_file_request, workspaces_diff_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_attribution, session_context_info, subagent_settings, task_progress, workspace_summary) + return RPC(abort_request, abort_result, account_all_users, account_get_all_users_result, account_get_current_auth_result, account_get_quota_request, account_get_quota_result, account_login_request, account_login_result, account_logout_request, account_logout_result, account_quota_snapshot, adaptive_thinking_support, agent_discovery_path, agent_discovery_path_list, agent_discovery_path_scope, agent_get_current_result, agent_info, agent_info_source, agent_list, agent_list_request, agent_registry_live_target_entry, agent_registry_live_target_entry_attention_kind, agent_registry_live_target_entry_kind, agent_registry_live_target_entry_last_terminal_event, agent_registry_live_target_entry_status, agent_registry_log_capture, agent_registry_log_capture_open_error_reason, agent_registry_spawn_error, agent_registry_spawn_permission_mode, agent_registry_spawn_registry_timeout, agent_registry_spawn_request, agent_registry_spawn_result, agent_registry_spawn_spawned, agent_registry_spawn_validation_error, agent_registry_spawn_validation_error_field, agent_registry_spawn_validation_error_reason, agent_reload_result, agents_discover_request, agent_select_request, agent_select_result, agents_get_discovery_paths_request, allow_all_permission_set_result, allow_all_permission_state, api_key_auth_info, auth_info, auth_info_type, built_in_model_catalog, built_in_model_catalog_entry, cancel_user_requested_shell_command_result, canvas_action, canvas_action_invoke_request, canvas_action_invoke_result, canvas_close_request, canvas_host_context, canvas_host_context_capabilities, canvas_json_schema, canvas_list, canvas_list_open_result, canvas_open_request, canvas_provider_close_request, canvas_provider_invoke_action_request, canvas_provider_open_request, canvas_provider_open_result, canvas_session_context, capi_session_options, 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, completions_get_trigger_characters_result, completions_request_request, completions_request_result, configure_session_extensions_params, connected_remote_session_metadata, connected_remote_session_metadata_kind, connected_remote_session_metadata_repository, connect_remote_session_params, connect_request, connect_result, content_exclusion_check_paths_request, content_exclusion_check_paths_result, content_exclusion_path_check, content_filter_mode, context_heaviest_message, 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, current_tool_metadata, debug_collect_logs_collected_entry, debug_collect_logs_destination, debug_collect_logs_entry, debug_collect_logs_entry_kind, debug_collect_logs_include, debug_collect_logs_redaction, debug_collect_logs_request, debug_collect_logs_result, debug_collect_logs_result_kind, debug_collect_logs_skipped_entry, debug_collect_logs_source, discovered_canvas, 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_context_push_input, 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_shell_exit, external_tool_text_result_for_llm_content_terminal, external_tool_text_result_for_llm_content_text, factory_abort_request, factory_ack_result, factory_agent_options, factory_agent_request, factory_agent_result, factory_agent_summary, factory_cancel_request, factory_current_phase, factory_declared_limits, factory_durable_operation, factory_execute_request, factory_execute_result, factory_get_run_progress_request, factory_get_run_request, factory_journal_get_request, factory_journal_get_result, factory_journal_put_request, factory_list_runs_request, factory_list_runs_result, factory_log_line, factory_log_line_kind, factory_log_request, factory_phase_observation, factory_phase_status, factory_progress_line, factory_progress_page, factory_resume_request, factory_resume_result, factory_run_consumed, factory_run_detail, factory_run_failure, factory_run_failure_kind, factory_run_limits, factory_run_request, factory_run_result, factory_run_status, factory_run_summary, factory_run_terminal, filter_mapping, fleet_start_request, fleet_start_result, folder_trust_add_params, folder_trust_check_params, folder_trust_check_result, gh_cli_auth_info, git_hub_telemetry_client_info, git_hub_telemetry_event, git_hub_telemetry_notification, 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_file_restore_skip_reason, history_list_rewind_points_result, history_preview_rewind_request, history_preview_rewind_result, history_rewind_change_type, history_rewind_file_preview, history_rewind_mode, history_rewind_outcome, history_rewind_point, history_rewind_request, history_rewind_result, history_rewind_unavailable_reason, history_skipped_file_restore, history_summarize_for_handoff_result, history_truncate_request, history_truncate_result, hmac_auth_info, hook_invoke_request, hook_invoke_response, hook_type, installed_plugin, installed_plugin_info, installed_plugin_source, installed_plugin_source_git_hub, installed_plugin_source_local, installed_plugin_source_url, instruction_discovery_path, instruction_discovery_path_kind, instruction_discovery_path_list, instruction_discovery_path_location, instructions_discover_request, instructions_get_discovery_paths_request, instructions_get_sources_result, instruction_source, instruction_source_location, instruction_source_type, interrupt_main_turn_request, interrupt_main_turn_result, llm_inference_headers, llm_inference_http_request_chunk_request, llm_inference_http_request_chunk_result, llm_inference_http_request_start_request, llm_inference_http_request_start_result, llm_inference_http_request_start_transport, llm_inference_http_response_chunk_error, llm_inference_http_response_chunk_request, llm_inference_http_response_chunk_result, llm_inference_http_response_start_request, llm_inference_http_response_start_result, llm_inference_set_provider_result, local_session_metadata_value, log_request, log_result, lsp_initialize_request, marketplace_add_result, marketplace_browse_result, marketplace_info, marketplace_list_result, marketplace_plugin_info, marketplace_refresh_entry, marketplace_refresh_result, marketplace_remove_result, mcp_allowed_server, mcp_apps_call_tool_request, mcp_apps_diagnose_capability, mcp_apps_diagnose_request, mcp_apps_diagnose_result, mcp_apps_diagnose_server, mcp_apps_host_context, mcp_apps_host_context_details, mcp_apps_host_context_details_available_display_mode, mcp_apps_host_context_details_display_mode, mcp_apps_host_context_details_platform, mcp_apps_host_context_details_theme, mcp_apps_list_tools_request, mcp_apps_list_tools_result, mcp_apps_read_resource_request, mcp_apps_read_resource_result, mcp_apps_resource_content, mcp_apps_set_host_context_details, mcp_apps_set_host_context_details_available_display_mode, mcp_apps_set_host_context_details_display_mode, mcp_apps_set_host_context_details_platform, mcp_apps_set_host_context_details_theme, mcp_apps_set_host_context_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_configure_git_hub_request, mcp_configure_git_hub_result, 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_filtered_server, mcp_headers_handle_pending_headers_refresh_request, mcp_headers_handle_pending_headers_refresh_request_request, mcp_headers_handle_pending_headers_refresh_request_result, mcp_host_state, mcp_is_server_running_request, mcp_is_server_running_result, mcp_list_tools_request, mcp_list_tools_result, mcp_oauth_handle_pending_request, mcp_oauth_handle_pending_result, mcp_oauth_login_grant_type, mcp_oauth_login_request, mcp_oauth_login_result, mcp_oauth_pending_request_response, mcp_oauth_respond_request, mcp_oauth_respond_result, mcp_register_external_client_request, mcp_reload_with_config_request, mcp_remove_git_hub_result, mcp_resource, mcp_resource_annotations, mcp_resource_content, mcp_resource_icon, mcp_resources_list_request, mcp_resources_list_result, mcp_resources_list_templates_request, mcp_resources_list_templates_result, mcp_resources_read_request, mcp_resources_read_result, mcp_resource_template, mcp_restart_server_request, mcp_sampling_execution_action, mcp_sampling_execution_result, mcp_server, mcp_server_auth_config, mcp_server_auth_config_redirect_port, mcp_server_config, mcp_server_config_defer_tools, mcp_server_config_http, mcp_server_config_http_oauth_grant_type, mcp_server_config_http_type, mcp_server_config_stdio, mcp_server_failure_info, mcp_server_list, mcp_server_needs_auth_info, mcp_set_env_value_mode_details, mcp_set_env_value_mode_params, mcp_set_env_value_mode_result, mcp_start_server_request, mcp_start_servers_result, mcp_stop_server_request, mcp_tools, mcp_tool_ui, mcp_tool_ui_visibility, mcp_unregister_external_client_request, memory_configuration, metadata_context_attribution_result, metadata_context_heaviest_messages_request, metadata_context_heaviest_messages_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_promo, model_billing_token_prices, model_billing_token_prices_long_context, 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_list_request, 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, named_provider_config, name_get_result, name_set_auto_request, name_set_auto_result, name_set_request, open_canvas_instance, options_update_additional_content_exclusion_policy, options_update_additional_content_exclusion_policy_rule, options_update_additional_content_exclusion_policy_rule_source, options_update_additional_content_exclusion_policy_scope, options_update_context_tier, options_update_env_value_mode, options_update_reasoning_summary, options_update_tool_filter_precedence, 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_allow_all_mode, 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_get_allow_all_request, 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_allow_all_request, permissions_set_allow_all_source, 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_read_sql_todos_result, plan_read_sql_todos_with_dependencies_result, plan_sql_todo_dependency, plan_sql_todos_row, plan_update_request, plugin, plugin_install_result, plugin_list, plugin_list_result, plugins_disable_request, plugins_enable_request, plugins_install_request, plugins_marketplaces_add_request, plugins_marketplaces_browse_request, plugins_marketplaces_refresh_request, plugins_marketplaces_remove_request, plugins_reload_request, plugins_uninstall_request, plugins_update_request, plugin_update_all_entry, plugin_update_all_result, plugin_update_result, provider_add_request, provider_add_result, provider_config, provider_config_azure, provider_config_transport, provider_config_type, provider_config_wire_api, provider_endpoint, provider_endpoint_transport, provider_endpoint_type, provider_endpoint_wire_api, provider_get_endpoint_request, provider_model_config, provider_session_token, provider_token_acquire_request, provider_token_acquire_result, push_attachment, push_attachment_blob, push_attachment_directory, push_attachment_file, push_attachment_file_line_range, push_attachment_git_hub_actions_job, push_attachment_git_hub_commit, push_attachment_git_hub_file, push_attachment_git_hub_file_diff, push_attachment_git_hub_file_diff_side, push_attachment_git_hub_reference, push_attachment_git_hub_reference_type, push_attachment_git_hub_release, push_attachment_git_hub_repository, push_attachment_git_hub_snippet, push_attachment_git_hub_tree_comparison, push_attachment_git_hub_tree_comparison_side, push_attachment_git_hub_url, push_attachment_selection, push_attachment_selection_details, push_attachment_selection_details_end, push_attachment_selection_details_start, push_git_hub_repo_ref, queue_begin_deferred_idle_drain_request, queue_begin_deferred_idle_drain_result, queue_consume_system_notifications_request, queued_command_handled, queued_command_not_handled, queued_command_result, queue_defer_session_idle_request, queue_duplicate_at_request, queue_duplicate_at_result, queue_enqueue_resume_pending_result, queue_finish_deferred_idle_drain_request, queue_finish_deferred_idle_drain_result, queue_has_pending_result, queue_insert_at_request, queue_insert_at_result, queue_insert_message, queue_move_item_request, queue_move_item_result, queue_pending_items, queue_pending_items_kind, queue_pending_items_result, queue_remove_at_request, queue_remove_at_result, queue_remove_most_recent_result, queue_send_now_request, queue_send_now_result, queue_set_drain_paused_request, queue_snapshot_result, queue_update_text_request, queue_update_text_result, register_event_interest_params, register_event_interest_result, register_extension_tools_params, register_extension_tools_result, release_event_interest_params, remote_control_config, remote_control_config_existing_mc_session, remote_control_status, remote_control_status_active, remote_control_status_connecting, remote_control_status_error, remote_control_status_off, remote_control_status_result, remote_control_stop_result, remote_control_transfer_result, remote_enable_request, remote_enable_result, remote_notify_steerable_changed_request, remote_notify_steerable_changed_result, remote_session_connection_result, remote_session_metadata_repository, remote_session_metadata_task_type, remote_session_metadata_value, remote_session_mode, remote_session_repository, run_options, sandbox_config, sandbox_config_user_policy, sandbox_config_user_policy_experimental, sandbox_config_user_policy_experimental_seatbelt, sandbox_config_user_policy_filesystem, sandbox_config_user_policy_network, sandbox_config_user_policy_network_proxy, sandbox_config_user_policy_seatbelt, schedule_add_at_request, schedule_add_cron_request, schedule_add_request, schedule_add_result, schedule_add_self_paced_request, schedule_entry, schedule_has_self_paced_result, schedule_list, schedule_rearm_self_paced_request, schedule_stop_request, schedule_stop_result, secrets_add_filter_values_request, secrets_add_filter_values_result, send_agent_mode, send_attachments_to_message_params, send_message_item, send_messages_request, send_messages_result, send_mode, send_request, send_result, send_system_notification_request, server_agent_list, server_instruction_source_list, server_skill, server_skill_list, session_activity, session_agent_list_request, session_auth_status, session_bulk_delete_result, session_cancel_all_background_agents_result, session_capability, session_commands_list_request, session_completion_item, 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_sqlite_transaction_error, session_fs_sqlite_transaction_error_class, session_fs_sqlite_transaction_request, session_fs_sqlite_transaction_result, session_fs_sqlite_transaction_statement, session_fs_stat_request, session_fs_stat_result, session_fs_write_file_request, session_history_compact_request, session_installed_plugin, session_installed_plugin_source, session_installed_plugin_source_git_hub, session_installed_plugin_source_local, session_installed_plugin_source_url, session_limit_prediction_baseline_data, session_limit_prediction_client_type, session_limit_prediction_details, session_limit_prediction_predict_request, session_limit_prediction_request, session_limit_prediction_result, session_limit_prediction_source, session_limit_prediction_tier, session_limit_prediction_tier_option, session_limit_prediction_unavailable_reason, session_list, session_list_entry, session_list_filter, session_load_deferred_repo_hooks_result, session_log_level, session_mcp_apps_call_tool_result, session_metadata_snapshot, session_mode, session_model_list, session_model_list_request, session_model_price_category, session_open_options, session_open_options_additional_content_exclusion_policy, session_open_options_additional_content_exclusion_policy_rule, session_open_options_additional_content_exclusion_policy_rule_source, session_open_options_additional_content_exclusion_policy_scope, session_open_options_env_value_mode, session_open_options_reasoning_summary, session_open_params, session_open_result, session_plugins_reload_request, session_provider_get_endpoint_request, session_prune_result, sessions_bulk_delete_request, sessions_check_in_use_request, sessions_check_in_use_result, sessions_close_request, sessions_close_result, sessions_delete_request, sessions_enrich_metadata_request, session_set_credentials_params, session_set_credentials_result, session_settings_built_in_tool_availability_snapshot, session_settings_evaluate_predicate_request, session_settings_evaluate_predicate_result, session_settings_job_snapshot, session_settings_model_snapshot, session_settings_online_evaluation_snapshot, session_settings_predicate_name, session_settings_repo_snapshot, session_settings_snapshot, session_settings_validation_snapshot, 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_board_entry_count_request, sessions_get_board_entry_count_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_metadata_request, sessions_get_metadata_result, sessions_get_persisted_remote_steerable_request, sessions_get_persisted_remote_steerable_result, session_sizes, sessions_list_non_empty_session_ids_request, sessions_list_non_empty_session_ids_result, sessions_list_request, sessions_load_deferred_repo_hooks_request, sessions_open_attach, sessions_open_cloud, sessions_open_create, sessions_open_handoff, sessions_open_handoff_task_type, sessions_open_progress, sessions_open_progress_status, sessions_open_progress_step, sessions_open_remote, sessions_open_resume, sessions_open_resume_last, sessions_open_status, session_source, sessions_prune_old_request, sessions_register_extension_tools_on_session_options, 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, sessions_set_remote_control_steering_request, sessions_start_remote_control_request, sessions_stop_remote_control_request, sessions_transfer_remote_control_request, session_telemetry_engagement, session_update_options_params, session_update_options_result, session_visibility_status, session_working_directory_context, session_working_directory_context_host_type, shell_cancel_user_requested_request, shell_exec_request, shell_exec_result, shell_execute_user_requested_request, shell_init_profile, shell_init_script, shell_init_script_shell, shell_kill_request, shell_kill_result, shell_kill_signal, shell_options, shutdown_request, skill, skill_discovery_path, skill_discovery_path_list, skill_discovery_scope, skill_list, skills_config_set_disabled_skills_request, skills_disable_request, skills_discover_request, skills_enable_request, skills_get_discovery_paths_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_choice, 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, subagent_settings_entry, subagent_settings_entry_context_tier, 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_get_current_metadata_result, tools_initialize_and_validate_result, tools_list_request, tools_update_subagent_settings_result, 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_ephemeral_query_request, ui_ephemeral_query_result, 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_session_limits_exhausted_request, ui_handle_pending_user_input_request, ui_register_direct_auto_mode_switch_handler_result, ui_session_limits_exhausted_response, ui_session_limits_exhausted_response_action, ui_unregister_direct_auto_mode_switch_handler_request, ui_unregister_direct_auto_mode_switch_handler_result, ui_user_input_response, update_subagent_settings_request, 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_requested_shell_command_result, user_setting_metadata, user_settings_get_result, user_settings_set_request, user_settings_set_result, visibility_get_result, visibility_set_request, visibility_set_result, workspace_diff_file_change, workspace_diff_file_change_type, workspace_diff_mode, workspace_diff_result, workspaces_add_summary_request, workspaces_add_summary_result, workspaces_autopilot_objective_exists_result, workspaces_checkpoints, workspaces_create_file_request, workspaces_delete_autopilot_objective_result, workspaces_diff_request, workspaces_ensure_request, workspaces_get_workspace_result, workspaces_list_checkpoints_result, workspaces_list_files_result, workspaces_read_autopilot_objective_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, workspaces_truncate_summaries_request, workspace_summary_host_type, workspaces_update_metadata_request, workspaces_workspace_details_host_type, workspaces_write_autopilot_objective_request, workspaces_write_autopilot_objective_result, session_context_attribution, session_context_info, subagent_settings, task_progress, workspace_summary) def to_dict(self) -> dict: result: dict = {} @@ -26731,6 +30059,7 @@ def to_dict(self) -> dict: result["AgentInfo"] = to_class(AgentInfo, self.agent_info) result["AgentInfoSource"] = to_enum(AgentInfoSource, self.agent_info_source) result["AgentList"] = to_class(AgentList, self.agent_list) + result["AgentListRequest"] = self.agent_list_request result["AgentRegistryLiveTargetEntry"] = to_class(AgentRegistryLiveTargetEntry, self.agent_registry_live_target_entry) result["AgentRegistryLiveTargetEntryAttentionKind"] = to_enum(AgentRegistryLiveTargetEntryAttentionKind, self.agent_registry_live_target_entry_attention_kind) result["AgentRegistryLiveTargetEntryKind"] = to_enum(AgentRegistryLiveTargetEntryKind, self.agent_registry_live_target_entry_kind) @@ -26757,6 +30086,8 @@ def to_dict(self) -> dict: result["ApiKeyAuthInfo"] = to_class(APIKeyAuthInfo, self.api_key_auth_info) result["AuthInfo"] = (self.auth_info).to_dict() result["AuthInfoType"] = to_enum(AuthInfoType, self.auth_info_type) + result["BuiltInModelCatalog"] = to_class(BuiltInModelCatalog, self.built_in_model_catalog) + result["BuiltInModelCatalogEntry"] = to_class(BuiltInModelCatalogEntry, self.built_in_model_catalog_entry) result["CancelUserRequestedShellCommandResult"] = to_class(CancelUserRequestedShellCommandResult, self.cancel_user_requested_shell_command_result) result["CanvasAction"] = to_class(CanvasAction, self.canvas_action) result["CanvasActionInvokeRequest"] = to_class(CanvasActionInvokeRequest, self.canvas_action_invoke_request) @@ -26778,7 +30109,7 @@ def to_dict(self) -> dict: result["CommandsHandlePendingCommandRequest"] = to_class(CommandsHandlePendingCommandRequest, self.commands_handle_pending_command_request) result["CommandsHandlePendingCommandResult"] = to_class(CommandsHandlePendingCommandResult, self.commands_handle_pending_command_result) result["CommandsInvokeRequest"] = to_class(CommandsInvokeRequest, self.commands_invoke_request) - result["CommandsListRequest"] = to_class(CommandsListRequest, self.commands_list_request) + result["CommandsListRequest"] = self.commands_list_request result["CommandsRespondToQueuedCommandRequest"] = to_class(CommandsRespondToQueuedCommandRequest, self.commands_respond_to_queued_command_request) result["CommandsRespondToQueuedCommandResult"] = to_class(CommandsRespondToQueuedCommandResult, self.commands_respond_to_queued_command_result) result["CompletionsGetTriggerCharactersResult"] = to_class(CompletionsGetTriggerCharactersResult, self.completions_get_trigger_characters_result) @@ -26791,6 +30122,9 @@ def to_dict(self) -> dict: result["ConnectRemoteSessionParams"] = to_class(ConnectRemoteSessionParams, self.connect_remote_session_params) result["ConnectRequest"] = to_class(_ConnectRequest, self.connect_request) result["ConnectResult"] = to_class(_ConnectResult, self.connect_result) + result["ContentExclusionCheckPathsRequest"] = to_class(ContentExclusionCheckPathsRequest, self.content_exclusion_check_paths_request) + result["ContentExclusionCheckPathsResult"] = to_class(ContentExclusionCheckPathsResult, self.content_exclusion_check_paths_result) + result["ContentExclusionPathCheck"] = to_class(ContentExclusionPathCheck, self.content_exclusion_path_check) result["ContentFilterMode"] = to_enum(ContentFilterMode, self.content_filter_mode) result["ContextHeaviestMessage"] = to_class(ContextHeaviestMessage, self.context_heaviest_message) result["CopilotApiTokenAuthInfo"] = to_class(CopilotAPITokenAuthInfo, self.copilot_api_token_auth_info) @@ -26855,22 +30189,39 @@ def to_dict(self) -> dict: result["FactoryAgentOptions"] = to_class(FactoryAgentOptions, self.factory_agent_options) result["FactoryAgentRequest"] = to_class(FactoryAgentRequest, self.factory_agent_request) result["FactoryAgentResult"] = to_class(FactoryAgentResult, self.factory_agent_result) + result["FactoryAgentSummary"] = to_class(FactoryAgentSummary, self.factory_agent_summary) result["FactoryCancelRequest"] = to_class(FactoryCancelRequest, self.factory_cancel_request) + result["FactoryCurrentPhase"] = to_class(FactoryCurrentPhase, self.factory_current_phase) + result["FactoryDeclaredLimits"] = to_class(FactoryDeclaredLimits, self.factory_declared_limits) + result["FactoryDurableOperation"] = to_enum(FactoryDurableOperation, self.factory_durable_operation) result["FactoryExecuteRequest"] = to_class(FactoryExecuteRequest, self.factory_execute_request) result["FactoryExecuteResult"] = to_class(FactoryExecuteResult, self.factory_execute_result) + result["FactoryGetRunProgressRequest"] = to_class(FactoryGetRunProgressRequest, self.factory_get_run_progress_request) result["FactoryGetRunRequest"] = to_class(FactoryGetRunRequest, self.factory_get_run_request) result["FactoryJournalGetRequest"] = to_class(FactoryJournalGetRequest, self.factory_journal_get_request) result["FactoryJournalGetResult"] = to_class(FactoryJournalGetResult, self.factory_journal_get_result) result["FactoryJournalPutRequest"] = to_class(FactoryJournalPutRequest, self.factory_journal_put_request) + result["FactoryListRunsRequest"] = to_class(FactoryListRunsRequest, self.factory_list_runs_request) + result["FactoryListRunsResult"] = to_class(FactoryListRunsResult, self.factory_list_runs_result) result["FactoryLogLine"] = to_class(FactoryLogLine, self.factory_log_line) result["FactoryLogLineKind"] = to_enum(FactoryLogLineKind, self.factory_log_line_kind) result["FactoryLogRequest"] = to_class(FactoryLogRequest, self.factory_log_request) + result["FactoryPhaseObservation"] = to_class(FactoryPhaseObservation, self.factory_phase_observation) + result["FactoryPhaseStatus"] = to_enum(FactoryPhaseStatus, self.factory_phase_status) + result["FactoryProgressLine"] = to_class(FactoryProgressLine, self.factory_progress_line) + result["FactoryProgressPage"] = to_class(FactoryProgressPage, self.factory_progress_page) + result["FactoryResumeRequest"] = to_class(FactoryResumeRequest, self.factory_resume_request) + result["FactoryResumeResult"] = to_class(FactoryResumeResult, self.factory_resume_result) + result["FactoryRunConsumed"] = to_class(FactoryRunConsumed, self.factory_run_consumed) + result["FactoryRunDetail"] = to_class(FactoryRunDetail, self.factory_run_detail) result["FactoryRunFailure"] = to_class(FactoryRunFailure, self.factory_run_failure) result["FactoryRunFailureKind"] = to_enum(FactoryRunFailureKind, self.factory_run_failure_kind) result["FactoryRunLimits"] = to_class(FactoryRunLimits, self.factory_run_limits) result["FactoryRunRequest"] = to_class(FactoryRunRequest, self.factory_run_request) result["FactoryRunResult"] = to_class(FactoryRunResult, self.factory_run_result) result["FactoryRunStatus"] = to_enum(FactoryRunStatus, self.factory_run_status) + result["FactoryRunSummary"] = to_class(FactoryRunSummary, self.factory_run_summary) + result["FactoryRunTerminal"] = to_class(FactoryRunTerminal, self.factory_run_terminal) result["FilterMapping"] = from_union([lambda x: from_dict(lambda x: to_enum(ContentFilterMode, x), x), lambda x: to_enum(ContentFilterMode, x)], self.filter_mapping) result["FleetStartRequest"] = to_class(FleetStartRequest, self.fleet_start_request) result["FleetStartResult"] = to_class(FleetStartResult, self.fleet_start_result) @@ -26886,8 +30237,21 @@ 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["HistoryCompactRequest"] = self.history_compact_request result["HistoryCompactResult"] = to_class(HistoryCompactResult, self.history_compact_result) + result["HistoryFileRestoreSkipReason"] = to_enum(HistoryFileRestoreSkipReason, self.history_file_restore_skip_reason) + result["HistoryListRewindPointsResult"] = to_class(HistoryListRewindPointsResult, self.history_list_rewind_points_result) + result["HistoryPreviewRewindRequest"] = to_class(HistoryPreviewRewindRequest, self.history_preview_rewind_request) + result["HistoryPreviewRewindResult"] = to_class(HistoryPreviewRewindResult, self.history_preview_rewind_result) + result["HistoryRewindChangeType"] = to_enum(HistoryRewindChangeType, self.history_rewind_change_type) + result["HistoryRewindFilePreview"] = to_class(HistoryRewindFilePreview, self.history_rewind_file_preview) + result["HistoryRewindMode"] = to_enum(HistoryRewindMode, self.history_rewind_mode) + result["HistoryRewindOutcome"] = to_enum(HistoryRewindOutcome, self.history_rewind_outcome) + result["HistoryRewindPoint"] = to_class(HistoryRewindPoint, self.history_rewind_point) + result["HistoryRewindRequest"] = to_class(HistoryRewindRequest, self.history_rewind_request) + result["HistoryRewindResult"] = to_class(HistoryRewindResult, self.history_rewind_result) + result["HistoryRewindUnavailableReason"] = to_enum(HistoryRewindUnavailableReason, self.history_rewind_unavailable_reason) + result["HistorySkippedFileRestore"] = to_class(HistorySkippedFileRestore, self.history_skipped_file_restore) result["HistorySummarizeForHandoffResult"] = to_class(HistorySummarizeForHandoffResult, self.history_summarize_for_handoff_result) result["HistoryTruncateRequest"] = to_class(HistoryTruncateRequest, self.history_truncate_request) result["HistoryTruncateResult"] = to_class(HistoryTruncateResult, self.history_truncate_result) @@ -26911,6 +30275,8 @@ def to_dict(self) -> dict: result["InstructionSource"] = to_class(InstructionSource, self.instruction_source) result["InstructionSourceLocation"] = to_enum(InstructionLocation, self.instruction_source_location) result["InstructionSourceType"] = to_enum(InstructionSourceType, self.instruction_source_type) + result["InterruptMainTurnRequest"] = to_class(InterruptMainTurnRequest, self.interrupt_main_turn_request) + result["InterruptMainTurnResult"] = to_class(InterruptMainTurnResult, self.interrupt_main_turn_result) result["LlmInferenceHeaders"] = from_dict(lambda x: from_list(from_str, x), self.llm_inference_headers) result["LlmInferenceHttpRequestChunkRequest"] = to_class(LlmInferenceHTTPRequestChunkRequest, self.llm_inference_http_request_chunk_request) result["LlmInferenceHttpRequestChunkResult"] = to_class(LlmInferenceHTTPRequestChunkResult, self.llm_inference_http_request_chunk_result) @@ -26990,6 +30356,8 @@ def to_dict(self) -> dict: result["McpOauthLoginRequest"] = to_class(MCPOauthLoginRequest, self.mcp_oauth_login_request) result["McpOauthLoginResult"] = to_class(MCPOauthLoginResult, self.mcp_oauth_login_result) result["McpOauthPendingRequestResponse"] = to_class(MCPOauthPendingRequestResponse, self.mcp_oauth_pending_request_response) + result["McpOauthRespondRequest"] = to_class(MCPOauthRespondRequest, self.mcp_oauth_respond_request) + result["McpOauthRespondResult"] = to_class(MCPOauthRespondResult, self.mcp_oauth_respond_result) result["McpRegisterExternalClientRequest"] = to_class(MCPRegisterExternalClientRequest, self.mcp_register_external_client_request) result["McpReloadWithConfigRequest"] = to_class(MCPReloadWithConfigRequest, self.mcp_reload_with_config_request) result["McpRemoveGitHubResult"] = to_class(MCPRemoveGitHubResult, self.mcp_remove_git_hub_result) @@ -27060,7 +30428,7 @@ def to_dict(self) -> dict: result["ModelCapabilitiesOverrideSupports"] = to_class(ModelCapabilitiesOverrideSupports, self.model_capabilities_override_supports) result["ModelCapabilitiesSupports"] = to_class(ModelCapabilitiesSupports, self.model_capabilities_supports) result["ModelList"] = to_class(ModelList, self.model_list) - result["ModelListRequest"] = to_class(ModelListRequest, self.model_list_request) + result["ModelListRequest"] = self.model_list_request result["ModelPickerCategory"] = to_enum(ModelPickerCategory, self.model_picker_category) result["ModelPickerPriceCategory"] = to_enum(ModelPickerPriceCategory, self.model_picker_price_category) result["ModelPolicy"] = to_class(ModelPolicy, self.model_policy) @@ -27200,7 +30568,7 @@ def to_dict(self) -> dict: result["PluginsMarketplacesBrowseRequest"] = to_class(PluginsMarketplacesBrowseRequest, self.plugins_marketplaces_browse_request) result["PluginsMarketplacesRefreshRequest"] = to_class(PluginsMarketplacesRefreshRequest, self.plugins_marketplaces_refresh_request) result["PluginsMarketplacesRemoveRequest"] = to_class(PluginsMarketplacesRemoveRequest, self.plugins_marketplaces_remove_request) - result["PluginsReloadRequest"] = to_class(PluginsReloadRequest, self.plugins_reload_request) + result["PluginsReloadRequest"] = self.plugins_reload_request result["PluginsUninstallRequest"] = to_class(PluginsUninstallRequest, self.plugins_uninstall_request) result["PluginsUpdateRequest"] = to_class(PluginsUpdateRequest, self.plugins_update_request) result["PluginUpdateAllEntry"] = to_class(PluginUpdateAllEntry, self.plugin_update_all_entry) @@ -27217,7 +30585,7 @@ def to_dict(self) -> dict: result["ProviderEndpointTransport"] = to_enum(ProviderTransport, self.provider_endpoint_transport) result["ProviderEndpointType"] = to_enum(ProviderType, self.provider_endpoint_type) result["ProviderEndpointWireApi"] = to_enum(ProviderWireAPI, self.provider_endpoint_wire_api) - result["ProviderGetEndpointRequest"] = to_class(ProviderGetEndpointRequest, self.provider_get_endpoint_request) + result["ProviderGetEndpointRequest"] = self.provider_get_endpoint_request result["ProviderModelConfig"] = to_class(ProviderModelConfig, self.provider_model_config) result["ProviderSessionToken"] = to_class(ProviderSessionToken, self.provider_session_token) result["ProviderTokenAcquireRequest"] = to_class(ProviderTokenAcquireRequest, self.provider_token_acquire_request) @@ -27245,13 +30613,36 @@ def to_dict(self) -> dict: result["PushAttachmentSelectionDetailsEnd"] = to_class(PushAttachmentSelectionDetailsEnd, self.push_attachment_selection_details_end) result["PushAttachmentSelectionDetailsStart"] = to_class(PushAttachmentSelectionDetailsStart, self.push_attachment_selection_details_start) result["PushGitHubRepoRef"] = to_class(PushGitHubRepoRef, self.push_git_hub_repo_ref) + result["QueueBeginDeferredIdleDrainRequest"] = to_class(QueueBeginDeferredIdleDrainRequest, self.queue_begin_deferred_idle_drain_request) + result["QueueBeginDeferredIdleDrainResult"] = to_class(QueueBeginDeferredIdleDrainResult, self.queue_begin_deferred_idle_drain_result) + result["QueueConsumeSystemNotificationsRequest"] = to_class(QueueConsumeSystemNotificationsRequest, self.queue_consume_system_notifications_request) result["QueuedCommandHandled"] = to_class(QueuedCommandHandled, self.queued_command_handled) result["QueuedCommandNotHandled"] = to_class(QueuedCommandNotHandled, self.queued_command_not_handled) result["QueuedCommandResult"] = (self.queued_command_result).to_dict() + result["QueueDeferSessionIdleRequest"] = to_class(QueueDeferSessionIdleRequest, self.queue_defer_session_idle_request) + result["QueueDuplicateAtRequest"] = to_class(QueueDuplicateAtRequest, self.queue_duplicate_at_request) + result["QueueDuplicateAtResult"] = to_class(QueueDuplicateAtResult, self.queue_duplicate_at_result) + result["QueueEnqueueResumePendingResult"] = to_class(QueueEnqueueResumePendingResult, self.queue_enqueue_resume_pending_result) + result["QueueFinishDeferredIdleDrainRequest"] = to_class(QueueFinishDeferredIdleDrainRequest, self.queue_finish_deferred_idle_drain_request) + result["QueueFinishDeferredIdleDrainResult"] = to_class(QueueFinishDeferredIdleDrainResult, self.queue_finish_deferred_idle_drain_result) + result["QueueHasPendingResult"] = to_class(QueueHasPendingResult, self.queue_has_pending_result) + result["QueueInsertAtRequest"] = to_class(QueueInsertAtRequest, self.queue_insert_at_request) + result["QueueInsertAtResult"] = to_class(QueueInsertAtResult, self.queue_insert_at_result) + result["QueueInsertMessage"] = to_class(QueueInsertMessage, self.queue_insert_message) + result["QueueMoveItemRequest"] = to_class(QueueMoveItemRequest, self.queue_move_item_request) + result["QueueMoveItemResult"] = to_class(QueueMoveItemResult, self.queue_move_item_result) result["QueuePendingItems"] = to_class(QueuePendingItems, self.queue_pending_items) result["QueuePendingItemsKind"] = to_enum(QueuePendingItemsKind, self.queue_pending_items_kind) result["QueuePendingItemsResult"] = to_class(QueuePendingItemsResult, self.queue_pending_items_result) + result["QueueRemoveAtRequest"] = to_class(QueueRemoveAtRequest, self.queue_remove_at_request) + result["QueueRemoveAtResult"] = to_class(QueueRemoveAtResult, self.queue_remove_at_result) result["QueueRemoveMostRecentResult"] = to_class(QueueRemoveMostRecentResult, self.queue_remove_most_recent_result) + result["QueueSendNowRequest"] = to_class(QueueSendNowRequest, self.queue_send_now_request) + result["QueueSendNowResult"] = to_class(QueueSendNowResult, self.queue_send_now_result) + result["QueueSetDrainPausedRequest"] = to_class(QueueSetDrainPausedRequest, self.queue_set_drain_paused_request) + result["QueueSnapshotResult"] = to_class(QueueSnapshotResult, self.queue_snapshot_result) + result["QueueUpdateTextRequest"] = to_class(QueueUpdateTextRequest, self.queue_update_text_request) + result["QueueUpdateTextResult"] = to_class(QueueUpdateTextResult, self.queue_update_text_result) result["RegisterEventInterestParams"] = to_class(RegisterEventInterestParams, self.register_event_interest_params) result["RegisterEventInterestResult"] = to_class(RegisterEventInterestResult, self.register_event_interest_result) result["RegisterExtensionToolsParams"] = to_class(_RegisterExtensionToolsParams, self.register_extension_tools_params) @@ -27284,9 +30675,17 @@ def to_dict(self) -> dict: result["SandboxConfigUserPolicyExperimentalSeatbelt"] = to_class(SandboxConfigUserPolicyExperimentalSeatbelt, self.sandbox_config_user_policy_experimental_seatbelt) result["SandboxConfigUserPolicyFilesystem"] = to_class(SandboxConfigUserPolicyFilesystem, self.sandbox_config_user_policy_filesystem) result["SandboxConfigUserPolicyNetwork"] = to_class(SandboxConfigUserPolicyNetwork, self.sandbox_config_user_policy_network) + result["SandboxConfigUserPolicyNetworkProxy"] = to_class(SandboxConfigUserPolicyNetworkProxy, self.sandbox_config_user_policy_network_proxy) result["SandboxConfigUserPolicySeatbelt"] = to_class(SandboxConfigUserPolicySeatbelt, self.sandbox_config_user_policy_seatbelt) + result["ScheduleAddAtRequest"] = to_class(ScheduleAddAtRequest, self.schedule_add_at_request) + result["ScheduleAddCronRequest"] = to_class(ScheduleAddCronRequest, self.schedule_add_cron_request) + result["ScheduleAddRequest"] = to_class(ScheduleAddRequest, self.schedule_add_request) + result["ScheduleAddResult"] = to_class(ScheduleAddResult, self.schedule_add_result) + result["ScheduleAddSelfPacedRequest"] = to_class(ScheduleAddSelfPacedRequest, self.schedule_add_self_paced_request) result["ScheduleEntry"] = to_class(ScheduleEntry, self.schedule_entry) + result["ScheduleHasSelfPacedResult"] = to_class(ScheduleHasSelfPacedResult, self.schedule_has_self_paced_result) result["ScheduleList"] = to_class(ScheduleList, self.schedule_list) + result["ScheduleRearmSelfPacedRequest"] = to_class(ScheduleRearmSelfPacedRequest, self.schedule_rearm_self_paced_request) result["ScheduleStopRequest"] = to_class(ScheduleStopRequest, self.schedule_stop_request) result["ScheduleStopResult"] = to_class(ScheduleStopResult, self.schedule_stop_result) result["SecretsAddFilterValuesRequest"] = to_class(SecretsAddFilterValuesRequest, self.secrets_add_filter_values_request) @@ -27299,14 +30698,18 @@ def to_dict(self) -> dict: result["SendMode"] = to_enum(SendMode, self.send_mode) result["SendRequest"] = to_class(SendRequest, self.send_request) result["SendResult"] = to_class(SendResult, self.send_result) + result["SendSystemNotificationRequest"] = to_class(SendSystemNotificationRequest, self.send_system_notification_request) result["ServerAgentList"] = to_class(ServerAgentList, self.server_agent_list) result["ServerInstructionSourceList"] = to_class(ServerInstructionSourceList, self.server_instruction_source_list) result["ServerSkill"] = to_class(ServerSkill, self.server_skill) result["ServerSkillList"] = to_class(ServerSkillList, self.server_skill_list) result["SessionActivity"] = to_class(SessionActivity, self.session_activity) + result["SessionAgentListRequest"] = to_class(SessionAgentListRequest, self.session_agent_list_request) result["SessionAuthStatus"] = to_class(SessionAuthStatus, self.session_auth_status) result["SessionBulkDeleteResult"] = to_class(SessionBulkDeleteResult, self.session_bulk_delete_result) + result["SessionCancelAllBackgroundAgentsResult"] = from_int(self.session_cancel_all_background_agents_result) result["SessionCapability"] = to_enum(SessionCapability, self.session_capability) + result["SessionCommandsListRequest"] = to_class(SessionCommandsListRequest, self.session_commands_list_request) result["SessionCompletionItem"] = to_class(SessionCompletionItem, self.session_completion_item) result["SessionContext"] = to_class(SessionContext, self.session_context) result["SessionContextHostType"] = to_enum(HostType, self.session_context_host_type) @@ -27336,14 +30739,30 @@ def to_dict(self) -> dict: result["SessionFsSqliteQueryRequest"] = to_class(SessionFSSqliteQueryRequest, self.session_fs_sqlite_query_request) result["SessionFsSqliteQueryResult"] = to_class(SessionFSSqliteQueryResult, self.session_fs_sqlite_query_result) result["SessionFsSqliteQueryType"] = to_enum(SessionFSSqliteQueryType, self.session_fs_sqlite_query_type) + result["SessionFsSqliteTransactionError"] = to_class(SessionFSSqliteTransactionError, self.session_fs_sqlite_transaction_error) + result["SessionFsSqliteTransactionErrorClass"] = to_enum(SessionFSSqliteTransactionErrorClass, self.session_fs_sqlite_transaction_error_class) + result["SessionFsSqliteTransactionRequest"] = to_class(SessionFSSqliteTransactionRequest, self.session_fs_sqlite_transaction_request) + result["SessionFsSqliteTransactionResult"] = to_class(SessionFSSqliteTransactionResult, self.session_fs_sqlite_transaction_result) + result["SessionFsSqliteTransactionStatement"] = to_class(SessionFSSqliteTransactionStatement, self.session_fs_sqlite_transaction_statement) result["SessionFsStatRequest"] = to_class(SessionFSStatRequest, self.session_fs_stat_request) result["SessionFsStatResult"] = to_class(SessionFSStatResult, self.session_fs_stat_result) result["SessionFsWriteFileRequest"] = to_class(SessionFSWriteFileRequest, self.session_fs_write_file_request) + result["SessionHistoryCompactRequest"] = to_class(SessionHistoryCompactRequest, self.session_history_compact_request) result["SessionInstalledPlugin"] = to_class(SessionInstalledPlugin, self.session_installed_plugin) result["SessionInstalledPluginSource"] = from_union([lambda x: to_class(SessionInstalledPluginSource, x), from_str], self.session_installed_plugin_source) result["SessionInstalledPluginSourceGitHub"] = to_class(SessionInstalledPluginSourceGitHub, self.session_installed_plugin_source_git_hub) result["SessionInstalledPluginSourceLocal"] = to_class(SessionInstalledPluginSourceLocal, self.session_installed_plugin_source_local) result["SessionInstalledPluginSourceUrl"] = to_class(SessionInstalledPluginSourceURL, self.session_installed_plugin_source_url) + result["SessionLimitPredictionBaselineData"] = to_class(SessionLimitPredictionBaselineData, self.session_limit_prediction_baseline_data) + result["SessionLimitPredictionClientType"] = to_enum(SessionLimitPredictionClientType, self.session_limit_prediction_client_type) + result["SessionLimitPredictionDetails"] = to_class(SessionLimitPredictionDetails, self.session_limit_prediction_details) + result["SessionLimitPredictionPredictRequest"] = to_class(SessionLimitPredictionPredictRequest, self.session_limit_prediction_predict_request) + result["SessionLimitPredictionRequest"] = self.session_limit_prediction_request + result["SessionLimitPredictionResult"] = to_class(SessionLimitPredictionResult, self.session_limit_prediction_result) + result["SessionLimitPredictionSource"] = to_enum(SessionLimitPredictionSource, self.session_limit_prediction_source) + result["SessionLimitPredictionTier"] = to_enum(SessionLimitPredictionTier, self.session_limit_prediction_tier) + result["SessionLimitPredictionTierOption"] = to_class(SessionLimitPredictionTierOption, self.session_limit_prediction_tier_option) + result["SessionLimitPredictionUnavailableReason"] = to_enum(SessionLimitPredictionUnavailableReason, self.session_limit_prediction_unavailable_reason) result["SessionList"] = to_class(SessionList, self.session_list) result["SessionListEntry"] = (self.session_list_entry).to_dict() result["SessionListFilter"] = to_class(SessionListFilter, self.session_list_filter) @@ -27353,6 +30772,7 @@ def to_dict(self) -> dict: result["SessionMetadataSnapshot"] = to_class(SessionMetadataSnapshot, self.session_metadata_snapshot) result["SessionMode"] = to_enum(SessionMode, self.session_mode) result["SessionModelList"] = to_class(SessionModelList, self.session_model_list) + result["SessionModelListRequest"] = to_class(SessionModelListRequest, self.session_model_list_request) result["SessionModelPriceCategory"] = to_class(SessionModelPriceCategory, self.session_model_price_category) result["SessionOpenOptions"] = to_class(SessionOpenOptions, self.session_open_options) result["SessionOpenOptionsAdditionalContentExclusionPolicy"] = to_class(SessionOpenOptionsAdditionalContentExclusionPolicy, self.session_open_options_additional_content_exclusion_policy) @@ -27363,12 +30783,15 @@ def to_dict(self) -> dict: result["SessionOpenOptionsReasoningSummary"] = to_enum(ReasoningSummary, self.session_open_options_reasoning_summary) result["SessionOpenParams"] = (self.session_open_params).to_dict() result["SessionOpenResult"] = to_class(SessionOpenResult, self.session_open_result) + result["SessionPluginsReloadRequest"] = to_class(SessionPluginsReloadRequest, self.session_plugins_reload_request) + result["SessionProviderGetEndpointRequest"] = to_class(SessionProviderGetEndpointRequest, self.session_provider_get_endpoint_request) result["SessionPruneResult"] = to_class(SessionPruneResult, self.session_prune_result) result["SessionsBulkDeleteRequest"] = to_class(SessionsBulkDeleteRequest, self.sessions_bulk_delete_request) result["SessionsCheckInUseRequest"] = to_class(SessionsCheckInUseRequest, self.sessions_check_in_use_request) result["SessionsCheckInUseResult"] = to_class(SessionsCheckInUseResult, self.sessions_check_in_use_result) result["SessionsCloseRequest"] = to_class(SessionsCloseRequest, self.sessions_close_request) result["SessionsCloseResult"] = to_class(SessionsCloseResult, self.sessions_close_result) + result["SessionsDeleteRequest"] = to_class(SessionsDeleteRequest, self.sessions_delete_request) result["SessionsEnrichMetadataRequest"] = to_class(SessionsEnrichMetadataRequest, self.sessions_enrich_metadata_request) result["SessionSetCredentialsParams"] = to_class(SessionSetCredentialsParams, self.session_set_credentials_params) result["SessionSetCredentialsResult"] = to_class(SessionSetCredentialsResult, self.session_set_credentials_result) @@ -27394,9 +30817,13 @@ def to_dict(self) -> dict: result["SessionsGetEventFilePathResult"] = to_class(SessionsGetEventFilePathResult, self.sessions_get_event_file_path_result) result["SessionsGetLastForContextRequest"] = to_class(SessionsGetLastForContextRequest, self.sessions_get_last_for_context_request) result["SessionsGetLastForContextResult"] = to_class(SessionsGetLastForContextResult, self.sessions_get_last_for_context_result) + result["SessionsGetMetadataRequest"] = to_class(SessionsGetMetadataRequest, self.sessions_get_metadata_request) + result["SessionsGetMetadataResult"] = to_class(SessionsGetMetadataResult, self.sessions_get_metadata_result) result["SessionsGetPersistedRemoteSteerableRequest"] = to_class(SessionsGetPersistedRemoteSteerableRequest, self.sessions_get_persisted_remote_steerable_request) result["SessionsGetPersistedRemoteSteerableResult"] = to_class(SessionsGetPersistedRemoteSteerableResult, self.sessions_get_persisted_remote_steerable_result) result["SessionSizes"] = to_class(SessionSizes, self.session_sizes) + result["SessionsListNonEmptySessionIdsRequest"] = to_class(SessionsListNonEmptySessionIDSRequest, self.sessions_list_non_empty_session_ids_request) + result["SessionsListNonEmptySessionIdsResult"] = to_class(SessionsListNonEmptySessionIDSResult, self.sessions_list_non_empty_session_ids_result) result["SessionsListRequest"] = to_class(SessionsListRequest, self.sessions_list_request) result["SessionsLoadDeferredRepoHooksRequest"] = to_class(SessionsLoadDeferredRepoHooksRequest, self.sessions_load_deferred_repo_hooks_request) result["SessionsOpenAttach"] = to_class(SessionsOpenAttach, self.sessions_open_attach) @@ -27436,9 +30863,13 @@ def to_dict(self) -> dict: result["ShellExecRequest"] = to_class(ShellExecRequest, self.shell_exec_request) result["ShellExecResult"] = to_class(ShellExecResult, self.shell_exec_result) result["ShellExecuteUserRequestedRequest"] = to_class(ShellExecuteUserRequestedRequest, self.shell_execute_user_requested_request) + result["ShellInitProfile"] = to_enum(ShellInitProfile, self.shell_init_profile) + result["ShellInitScript"] = to_class(ShellInitScript, self.shell_init_script) + result["ShellInitScriptShell"] = to_enum(ShellInitScriptShell, self.shell_init_script_shell) result["ShellKillRequest"] = to_class(ShellKillRequest, self.shell_kill_request) result["ShellKillResult"] = to_class(ShellKillResult, self.shell_kill_result) result["ShellKillSignal"] = to_enum(ShellKillSignal, self.shell_kill_signal) + result["ShellOptions"] = to_class(ShellOptions, self.shell_options) result["ShutdownRequest"] = to_class(ShutdownRequest, self.shutdown_request) result["Skill"] = to_class(Skill, self.skill) result["SkillDiscoveryPath"] = to_class(SkillDiscoveryPath, self.skill_discovery_path) @@ -27561,20 +30992,30 @@ def to_dict(self) -> dict: result["WorkspaceDiffFileChangeType"] = to_enum(WorkspaceDiffFileChangeType, self.workspace_diff_file_change_type) result["WorkspaceDiffMode"] = to_enum(WorkspaceDiffMode, self.workspace_diff_mode) result["WorkspaceDiffResult"] = to_class(WorkspaceDiffResult, self.workspace_diff_result) + result["WorkspacesAddSummaryRequest"] = to_class(WorkspacesAddSummaryRequest, self.workspaces_add_summary_request) + result["WorkspacesAddSummaryResult"] = to_class(WorkspacesAddSummaryResult, self.workspaces_add_summary_result) + result["WorkspacesAutopilotObjectiveExistsResult"] = to_class(WorkspacesAutopilotObjectiveExistsResult, self.workspaces_autopilot_objective_exists_result) result["WorkspacesCheckpoints"] = to_class(WorkspacesCheckpoints, self.workspaces_checkpoints) result["WorkspacesCreateFileRequest"] = to_class(WorkspacesCreateFileRequest, self.workspaces_create_file_request) + result["WorkspacesDeleteAutopilotObjectiveResult"] = to_class(WorkspacesDeleteAutopilotObjectiveResult, self.workspaces_delete_autopilot_objective_result) result["WorkspacesDiffRequest"] = to_class(WorkspacesDiffRequest, self.workspaces_diff_request) + result["WorkspacesEnsureRequest"] = to_class(WorkspacesEnsureRequest, self.workspaces_ensure_request) result["WorkspacesGetWorkspaceResult"] = to_class(WorkspacesGetWorkspaceResult, self.workspaces_get_workspace_result) result["WorkspacesListCheckpointsResult"] = to_class(WorkspacesListCheckpointsResult, self.workspaces_list_checkpoints_result) result["WorkspacesListFilesResult"] = to_class(WorkspacesListFilesResult, self.workspaces_list_files_result) + result["WorkspacesReadAutopilotObjectiveResult"] = to_class(WorkspacesReadAutopilotObjectiveResult, self.workspaces_read_autopilot_objective_result) result["WorkspacesReadCheckpointRequest"] = to_class(WorkspacesReadCheckpointRequest, self.workspaces_read_checkpoint_request) result["WorkspacesReadCheckpointResult"] = to_class(WorkspacesReadCheckpointResult, self.workspaces_read_checkpoint_result) result["WorkspacesReadFileRequest"] = to_class(WorkspacesReadFileRequest, self.workspaces_read_file_request) result["WorkspacesReadFileResult"] = to_class(WorkspacesReadFileResult, self.workspaces_read_file_result) result["WorkspacesSaveLargePasteRequest"] = to_class(WorkspacesSaveLargePasteRequest, self.workspaces_save_large_paste_request) result["WorkspacesSaveLargePasteResult"] = to_class(WorkspacesSaveLargePasteResult, self.workspaces_save_large_paste_result) + result["WorkspacesTruncateSummariesRequest"] = to_class(WorkspacesTruncateSummariesRequest, self.workspaces_truncate_summaries_request) result["WorkspaceSummaryHostType"] = to_enum(HostType, self.workspace_summary_host_type) + result["WorkspacesUpdateMetadataRequest"] = to_class(WorkspacesUpdateMetadataRequest, self.workspaces_update_metadata_request) result["WorkspacesWorkspaceDetailsHostType"] = to_enum(HostType, self.workspaces_workspace_details_host_type) + result["WorkspacesWriteAutopilotObjectiveRequest"] = to_class(WorkspacesWriteAutopilotObjectiveRequest, self.workspaces_write_autopilot_objective_request) + result["WorkspacesWriteAutopilotObjectiveResult"] = to_class(WorkspacesWriteAutopilotObjectiveResult, self.workspaces_write_autopilot_objective_result) result["SessionContextAttribution"] = from_union([lambda x: to_class(SessionContextAttribution, x), from_none], self.session_context_attribution) result["SessionContextInfo"] = from_union([lambda x: to_class(SessionContextInfo, x), from_none], self.session_context_info) result["SubagentSettings"] = from_union([lambda x: to_class(SubagentSettings, x), from_none], self.subagent_settings) @@ -27812,11 +31253,14 @@ def _load_TaskInfo(obj: Any) -> "TaskInfo": AccountGetAllUsersResult = list +AgentListRequest = Any CanvasActionInvokeResult = Any CanvasJsonSchema = Any +CommandsListRequest = Any ExternalToolResult = ExternalToolTextResultForLlm ExternalToolTextResultForLlmContentResourceLinkIconTheme = Theme FilterMapping = dict +HistoryCompactRequest = Any InstructionDiscoveryPathKind = DebugCollectLogsEntryKind InstructionDiscoveryPathLocation = InstructionLocation InstructionSourceLocation = InstructionLocation @@ -27834,21 +31278,26 @@ def _load_TaskInfo(obj: Any) -> "TaskInfo": McpServerAuthConfig = bool McpServerConfigHttpOauthGrantType = MCPGrantType MetadataSnapshotRemoteMetadataTaskType = TaskType +ModelListRequest = Any OptionsUpdateAdditionalContentExclusionPolicyScope = AdditionalContentExclusionPolicyScope OptionsUpdateEnvValueMode = MCPSetEnvValueModeDetails OptionsUpdateReasoningSummary = ReasoningSummary PermissionsConfigureAdditionalContentExclusionPolicyScope = AdditionalContentExclusionPolicyScope PermissionsSetAllowAllSource = PermissionsSetAAllSource PermissionsSetApproveAllSource = PermissionsSetAAllSource +PluginsReloadRequest = Any ProviderConfigTransport = ProviderTransport ProviderConfigType = ProviderType ProviderConfigWireApi = ProviderWireAPI ProviderEndpointTransport = ProviderTransport ProviderEndpointType = ProviderType ProviderEndpointWireApi = ProviderWireAPI +ProviderGetEndpointRequest = Any RemoteSessionMetadataTaskType = TaskType +SessionCancelAllBackgroundAgentsResult = int SessionContextHostType = HostType SessionFsReaddirWithTypesEntryType = DebugCollectLogsEntryKind +SessionLimitPredictionRequest = Any SessionMcpAppsCallToolResult = dict SessionOpenOptionsAdditionalContentExclusionPolicyScope = AdditionalContentExclusionPolicyScope SessionOpenOptionsEnvValueMode = MCPSetEnvValueModeDetails @@ -27898,6 +31347,10 @@ async def list(self, params: ModelsListRequest, *, timeout: float | None = None) params_dict = {k: v for k, v in params.to_dict().items() if v is not None} return ModelList.from_dict(_patch_model_capabilities(await self._client.request("models.list", params_dict, **_timeout_kwargs(timeout)))) + async def get_built_in_catalog(self, *, timeout: float | None = None) -> BuiltInModelCatalog: + "Returns the running runtime's complete catalog of well-known built-in model IDs without authentication or network access.\n\nReturns:\n The running runtime's complete catalog of well-known built-in model IDs, including supported models and additional IDs with built-in metadata." + return BuiltInModelCatalog.from_dict(await self._client.request("models.getBuiltInCatalog", {}, **_timeout_kwargs(timeout))) + # Experimental: this API group is experimental and may change or be removed. class ServerToolsApi: @@ -28370,6 +31823,16 @@ class _InternalServerSessionsApi: def __init__(self, client: "JsonRpcClient"): self._client = client + async def _get_metadata(self, params: SessionsGetMetadataRequest, *, timeout: float | None = None) -> SessionsGetMetadataResult: + "Reads lightweight persisted metadata for one local session without opening it.\n\nArgs:\n params: Session ID whose persisted metadata should be read.\n\nReturns:\n Persisted local session metadata when the session exists.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." + params_dict = {k: v for k, v in params.to_dict().items() if v is not None} + return SessionsGetMetadataResult.from_dict(await self._client.request("sessions.getMetadata", params_dict, **_timeout_kwargs(timeout))) + + async def _list_non_empty_session_ids(self, params: SessionsListNonEmptySessionIDSRequest, *, timeout: float | None = None) -> SessionsListNonEmptySessionIDSResult: + "Lists recent local session IDs that contain user-visible history, omitting housekeeping-only sessions.\n\nArgs:\n params: Limit for non-empty local session IDs.\n\nReturns:\n Recent local session IDs that contain user-visible history.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." + params_dict = {k: v for k, v in params.to_dict().items() if v is not None} + return SessionsListNonEmptySessionIDSResult.from_dict(await self._client.request("sessions.listNonEmptySessionIds", params_dict, **_timeout_kwargs(timeout))) + async def _get_event_file_path(self, params: SessionsGetEventFilePathRequest, *, timeout: float | None = None) -> SessionsGetEventFilePathResult: "Computes the absolute path to a session's persisted events.jsonl file. Internal: filesystem paths are only meaningful in-process (CLI and runtime share a filesystem). Currently used by the CLI's contribution-graph feature to read historical events directly. Remote SDK consumers must not depend on this; a proper event-query API would replace it if the contribution graph ever needed to work over the wire.\n\nArgs:\n params: Session ID whose event-log file path to compute.\n\nReturns:\n Absolute path to the session's events.jsonl file on disk.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." params_dict = {k: v for k, v in params.to_dict().items() if v is not None} @@ -28380,6 +31843,11 @@ async def _get_persisted_remote_steerable(self, params: SessionsGetPersistedRemo params_dict = {k: v for k, v in params.to_dict().items() if v is not None} return SessionsGetPersistedRemoteSteerableResult.from_dict(await self._client.request("sessions.getPersistedRemoteSteerable", params_dict, **_timeout_kwargs(timeout))) + async def _delete(self, params: SessionsDeleteRequest, *, timeout: float | None = None) -> None: + "Deletes one local session from disk after running the same lifecycle hooks as the session manager.\n\nArgs:\n params: Session ID to delete from disk.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." + params_dict = {k: v for k, v in params.to_dict().items() if v is not None} + await self._client.request("sessions.delete", params_dict, **_timeout_kwargs(timeout)) + async def _get_board_entry_count(self, params: SessionsGetBoardEntryCountRequest, *, timeout: float | None = None) -> SessionsGetBoardEntryCountResult: "Gets the dynamic-context board entry count associated with a session, when available. Internal: this exists solely so CLI telemetry events (`rem_spawn_gate`, `rem_consolidation_complete`) can pair START / END board counts around the detached rem-agent spawn. \"Dynamic context board\" is a runtime-internal concept that is not part of the public SDK contract; the long-term plan is to relocate the telemetry emission into the runtime so this method can be deleted entirely.\n\nArgs:\n params: Session ID whose board entry count should be returned.\n\nReturns:\n Dynamic-context board entry count, when available.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." params_dict = {k: v for k, v in params.to_dict().items() if v is not None} @@ -28511,12 +31979,34 @@ async def run(self, params: FactoryRunRequest, *, timeout: float | None = None) params_dict["sessionId"] = self._session_id return FactoryRunResult.from_dict(await self._client.request("session.factory.run", params_dict, **_timeout_kwargs(timeout))) + async def resume(self, params: FactoryResumeRequest, *, timeout: float | None = None) -> FactoryResumeResult: + "Resumes a factory run using its persisted name, arguments, journal, and accounting.\n\nArgs:\n params: Parameters for resuming a factory run from its persisted identity.\n\nReturns:\n Resolved persisted factory identity and resumed run envelope." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return FactoryResumeResult.from_dict(await self._client.request("session.factory.resume", params_dict, **_timeout_kwargs(timeout))) + async def get_run(self, params: FactoryGetRunRequest, *, timeout: float | None = None) -> FactoryRunResult: "Gets the current or settled envelope for a factory run.\n\nArgs:\n params: Parameters for retrieving a factory run.\n\nReturns:\n Complete current or terminal factory run envelope." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} params_dict["sessionId"] = self._session_id return FactoryRunResult.from_dict(await self._client.request("session.factory.getRun", params_dict, **_timeout_kwargs(timeout))) + async def list_runs(self, *, timeout: float | None = None) -> FactoryListRunsResult: + "Lists durable factory runs for this session in creation order.\n\nReturns:\n Factory runs in durable creation order." + return FactoryListRunsResult.from_dict(await self._client.request("session.factory.listRuns", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) + + async def get_run_detail(self, params: FactoryGetRunRequest, *, timeout: float | None = None) -> FactoryRunDetail: + "Gets durable and live observability detail for one factory run.\n\nArgs:\n params: Parameters for retrieving a factory run.\n\nReturns:\n Full factory run observability detail." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return FactoryRunDetail.from_dict(await self._client.request("session.factory.getRunDetail", params_dict, **_timeout_kwargs(timeout))) + + async def get_run_progress(self, params: FactoryGetRunProgressRequest, *, timeout: float | None = None) -> FactoryProgressPage: + "Pages durable progress for one factory run.\n\nArgs:\n params: Parameters for paging factory progress.\n\nReturns:\n A bidirectional page of factory progress." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return FactoryProgressPage.from_dict(await self._client.request("session.factory.getRunProgress", params_dict, **_timeout_kwargs(timeout))) + async def cancel(self, params: FactoryCancelRequest, *, timeout: float | None = None) -> FactoryRunResult: "Requests cancellation of a factory run and returns its run envelope.\n\nArgs:\n params: Parameters for cancelling a factory run.\n\nReturns:\n Complete current or terminal factory run envelope." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} @@ -28558,7 +32048,7 @@ async def set_reasoning_effort(self, params: ModelSetReasoningEffortRequest, *, params_dict["sessionId"] = self._session_id return ModelSetReasoningEffortResult.from_dict(await self._client.request("session.model.setReasoningEffort", params_dict, **_timeout_kwargs(timeout))) - async def list(self, params: ModelListRequest | None = None, *, timeout: float | None = None) -> SessionModelList: + async def list(self, params: SessionModelListRequest | None = None, *, timeout: float | None = None) -> SessionModelList: "Lists models available to this session using its own auth and integration context. Connected hosts (CLI TUI, GitHub App) should call this through the session client so remote sessions return the remote CLI's available models rather than the caller's.\n\nArgs:\n params: Optional listing options.\n\nReturns:\n The list of models available to this session." 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 @@ -28644,6 +32134,18 @@ async def get_workspace(self, *, timeout: float | None = None) -> WorkspacesGetW "Gets current workspace metadata for the session.\n\nReturns:\n Current workspace metadata for the session, including its absolute filesystem path when available." return WorkspacesGetWorkspaceResult.from_dict(await self._client.request("session.workspaces.getWorkspace", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) + async def update_metadata(self, params: WorkspacesUpdateMetadataRequest, *, timeout: float | None = None) -> WorkspacesGetWorkspaceResult: + "Updates workspace metadata for a local session and returns the refreshed workspace.\n\nArgs:\n params: Workspace metadata fields to update.\n\nReturns:\n Current workspace metadata for the session, including its absolute filesystem path when available." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return WorkspacesGetWorkspaceResult.from_dict(await self._client.request("session.workspaces.updateMetadata", params_dict, **_timeout_kwargs(timeout))) + + async def ensure(self, params: WorkspacesEnsureRequest, *, timeout: float | None = None) -> WorkspacesGetWorkspaceResult: + "Ensures a local session workspace exists and returns it.\n\nArgs:\n params: Optional session context used when creating a local workspace.\n\nReturns:\n Current workspace metadata for the session, including its absolute filesystem path when available." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return WorkspacesGetWorkspaceResult.from_dict(await self._client.request("session.workspaces.ensure", params_dict, **_timeout_kwargs(timeout))) + async def list_files(self, *, timeout: float | None = None) -> WorkspacesListFilesResult: "Lists files stored in the session workspace files directory.\n\nReturns:\n Relative paths of files stored in the session workspace files directory." return WorkspacesListFilesResult.from_dict(await self._client.request("session.workspaces.listFiles", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) @@ -28670,6 +32172,36 @@ async def read_checkpoint(self, params: WorkspacesReadCheckpointRequest, *, time params_dict["sessionId"] = self._session_id return WorkspacesReadCheckpointResult.from_dict(await self._client.request("session.workspaces.readCheckpoint", params_dict, **_timeout_kwargs(timeout))) + async def add_summary(self, params: WorkspacesAddSummaryRequest, *, timeout: float | None = None) -> WorkspacesAddSummaryResult: + "Adds a compaction summary checkpoint to the local session workspace.\n\nArgs:\n params: Compaction summary checkpoint to persist.\n\nReturns:\n Persisted summary metadata and refreshed workspace metadata." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return WorkspacesAddSummaryResult.from_dict(await self._client.request("session.workspaces.addSummary", params_dict, **_timeout_kwargs(timeout))) + + async def truncate_summaries(self, params: WorkspacesTruncateSummariesRequest, *, timeout: float | None = None) -> WorkspacesGetWorkspaceResult: + "Truncates local workspace compaction summaries after a rollback.\n\nArgs:\n params: Rollback point for local workspace summaries.\n\nReturns:\n Current workspace metadata for the session, including its absolute filesystem path when available." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return WorkspacesGetWorkspaceResult.from_dict(await self._client.request("session.workspaces.truncateSummaries", params_dict, **_timeout_kwargs(timeout))) + + async def read_autopilot_objective(self, *, timeout: float | None = None) -> WorkspacesReadAutopilotObjectiveResult: + "Reads the autopilot objective state file from the local session workspace.\n\nReturns:\n Autopilot objective file content, or null when missing." + return WorkspacesReadAutopilotObjectiveResult.from_dict(await self._client.request("session.workspaces.readAutopilotObjective", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) + + async def write_autopilot_objective(self, params: WorkspacesWriteAutopilotObjectiveRequest, *, timeout: float | None = None) -> WorkspacesWriteAutopilotObjectiveResult: + "Writes the autopilot objective state file in the local session workspace.\n\nArgs:\n params: Autopilot objective file content to persist.\n\nReturns:\n Result of writing the autopilot objective file." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return WorkspacesWriteAutopilotObjectiveResult.from_dict(await self._client.request("session.workspaces.writeAutopilotObjective", params_dict, **_timeout_kwargs(timeout))) + + async def delete_autopilot_objective(self, *, timeout: float | None = None) -> WorkspacesDeleteAutopilotObjectiveResult: + "Deletes the autopilot objective state file from the local session workspace.\n\nReturns:\n Result of deleting the autopilot objective file." + return WorkspacesDeleteAutopilotObjectiveResult.from_dict(await self._client.request("session.workspaces.deleteAutopilotObjective", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) + + async def autopilot_objective_exists(self, *, timeout: float | None = None) -> WorkspacesAutopilotObjectiveExistsResult: + "Checks whether the local session workspace has an autopilot objective state file.\n\nReturns:\n Whether the autopilot objective file exists." + return WorkspacesAutopilotObjectiveExistsResult.from_dict(await self._client.request("session.workspaces.autopilotObjectiveExists", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) + async def save_large_paste(self, params: WorkspacesSaveLargePasteRequest, *, timeout: float | None = None) -> WorkspacesSaveLargePasteResult: "Saves pasted content as a UTF-8 file in the session workspace.\n\nArgs:\n params: Pasted content to save as a UTF-8 file in the session workspace.\n\nReturns:\n Descriptor for the saved paste file, or null when the workspace is unavailable." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} @@ -28677,7 +32209,7 @@ async def save_large_paste(self, params: WorkspacesSaveLargePasteRequest, *, tim return WorkspacesSaveLargePasteResult.from_dict(await self._client.request("session.workspaces.saveLargePaste", params_dict, **_timeout_kwargs(timeout))) async def diff(self, params: WorkspacesDiffRequest, *, timeout: float | None = None) -> WorkspaceDiffResult: - "Computes a diff for the session workspace.\n\nArgs:\n params: Parameters for computing a workspace diff.\n\nReturns:\n Workspace diff result for the requested mode." + "Computes a diff for the session workspace. Never rejects for a busy session: a `session`-mode diff that cannot read the session's file-change captures falls back to an unstaged git diff with `isFallback: true` and reports why in `unavailableReason`.\n\nArgs:\n params: Parameters for computing a workspace diff.\n\nReturns:\n Workspace diff result for the requested mode." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} params_dict["sessionId"] = self._session_id return WorkspaceDiffResult.from_dict(await self._client.request("session.workspaces.diff", params_dict, **_timeout_kwargs(timeout))) @@ -28730,9 +32262,11 @@ def __init__(self, client: "JsonRpcClient", session_id: str): self._client = client self._session_id = session_id - async def list(self, *, timeout: float | None = None) -> AgentList: - "Lists custom agents available to the session.\n\nReturns:\n Custom agents available to the session." - return AgentList.from_dict(await self._client.request("session.agent.list", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) + async def list(self, params: SessionAgentListRequest | None = None, *, timeout: float | None = None) -> AgentList: + "Lists agents available to the session. Defaults to custom agents only; pass includeBuiltInAgents to include the effective built-in agents.\n\nArgs:\n params: Controls whether built-in agents and authored prompt text are included.\n\nReturns:\n Agents available to the session." + 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 AgentList.from_dict(await self._client.request("session.agent.list", params_dict, **_timeout_kwargs(timeout))) async def get_current(self, *, timeout: float | None = None) -> AgentGetCurrentResult: "Gets the currently selected custom agent for the session.\n\nReturns:\n The currently selected custom agent, or null when using the default agent." @@ -28869,6 +32403,12 @@ async def login(self, params: MCPOauthLoginRequest, *, timeout: float | None = N params_dict["sessionId"] = self._session_id return MCPOauthLoginResult.from_dict(await self._client.request("session.mcp.oauth.login", params_dict, **_timeout_kwargs(timeout))) + async def respond(self, params: MCPOauthRespondRequest, *, timeout: float | None = None) -> MCPOauthRespondResult: + "Responds to a pending MCP OAuth authorization request by its request id.\n\nArgs:\n params: Pending MCP OAuth request id to respond to.\n\nReturns:\n Indicates whether the pending MCP OAuth response was accepted." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return MCPOauthRespondResult.from_dict(await self._client.request("session.mcp.oauth.respond", params_dict, **_timeout_kwargs(timeout))) + # Experimental: this API group is experimental and may change or be removed. class McpHeadersApi: @@ -29008,7 +32548,7 @@ async def remove_git_hub(self, *, timeout: float | None = None) -> MCPRemoveGitH return MCPRemoveGitHubResult.from_dict(await self._client.request("session.mcp.removeGitHub", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) async def start_server(self, params: MCPStartServerRequest, *, timeout: float | None = None) -> None: - "Starts an individual MCP server on the live session from a caller-supplied config. Session-scoped and ephemeral: the server is added to this session's running set only and is reaped when the session ends. Does NOT modify persistent user configuration (`mcp.config.*`), so it does not affect future sessions. The server surfaces through `session.mcp.list` and the `session.mcp_servers_loaded` / `session.mcp_server_status_changed` events like any other server.\n\nArgs:\n params: Server name and configuration for an individual MCP server start." + "Starts an individual MCP server on the live session. Omit `config` for a config-free start-by-name of an already-configured server (reuses the server's already-registered configuration); supply `config` to start from a caller-supplied configuration. Session-scoped and ephemeral: the server is added to this session's running set only and is reaped when the session ends. Does NOT modify persistent user configuration (`mcp.config.*`), so it does not affect future sessions. The server surfaces through `session.mcp.list` and the `session.mcp_servers_loaded` / `session.mcp_server_status_changed` events like any other server.\n\nArgs:\n params: Server name and optional configuration for an individual MCP server start. Omit `config` for a config-free start-by-name of an already-configured server." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} params_dict["sessionId"] = self._session_id await self._client.request("session.mcp.startServer", params_dict, **_timeout_kwargs(timeout)) @@ -29042,7 +32582,7 @@ async def list(self, *, timeout: float | None = None) -> PluginList: "Lists plugins installed for the session.\n\nReturns:\n Plugins installed for the session, with their enabled state and version metadata." return PluginList.from_dict(await self._client.request("session.plugins.list", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) - async def reload(self, params: PluginsReloadRequest | None = None, *, timeout: float | None = None) -> None: + async def reload(self, params: SessionPluginsReloadRequest | None = None, *, timeout: float | None = None) -> None: "Reloads the session's plugin set, refreshing MCP servers, custom agents, hooks, and skills cache so SDK-driven changes via `server.plugins.*` take effect immediately.\n\nArgs:\n params: Optional flags controlling which side effects the reload performs." 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 @@ -29055,7 +32595,7 @@ def __init__(self, client: "JsonRpcClient", session_id: str): self._client = client self._session_id = session_id - async def get_endpoint(self, params: ProviderGetEndpointRequest | None = None, *, timeout: float | None = None) -> ProviderEndpoint: + async def get_endpoint(self, params: SessionProviderGetEndpointRequest | None = None, *, timeout: float | None = None) -> ProviderEndpoint: "Returns the provider endpoint and credentials the session is currently configured to talk to, so the caller can make inference calls directly against the same backend the session uses.\n\nArgs:\n params: Optional model identifier to scope the endpoint snapshot to.\n\nReturns:\n A snapshot of the provider endpoint the session is currently configured to talk to." 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 @@ -29160,7 +32700,7 @@ def __init__(self, client: "JsonRpcClient", session_id: str): self._client = client self._session_id = session_id - async def list(self, params: CommandsListRequest | None = None, *, timeout: float | None = None) -> CommandList: + async def list(self, params: SessionCommandsListRequest | None = None, *, timeout: float | None = None) -> CommandList: "Lists slash commands available in the session.\n\nArgs:\n params: Optional filters controlling which command sources to include in the listing.\n\nReturns:\n Slash commands available in the session, after applying any include/exclude filters." 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 @@ -29425,9 +32965,11 @@ async def set_required(self, params: PermissionsSetRequiredRequest, *, timeout: params_dict["sessionId"] = self._session_id return PermissionsSetRequiredResult.from_dict(await self._client.request("session.permissions.setRequired", params_dict, **_timeout_kwargs(timeout))) - async def reset_session_approvals(self, *, timeout: float | None = None) -> PermissionsResetSessionApprovalsResult: - "Clears session-scoped tool permission approvals.\n\nReturns:\n Indicates whether the operation succeeded." - return PermissionsResetSessionApprovalsResult.from_dict(await self._client.request("session.permissions.resetSessionApprovals", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) + async def reset_session_approvals(self, params: PermissionsResetSessionApprovalsRequest, *, timeout: float | None = None) -> PermissionsResetSessionApprovalsResult: + "Clears session-scoped tool permission approvals.\n\nArgs:\n params: Clears session-scoped tool permission approvals, and optionally the location-scoped ones.\n\nReturns:\n Indicates whether the operation succeeded." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return PermissionsResetSessionApprovalsResult.from_dict(await self._client.request("session.permissions.resetSessionApprovals", params_dict, **_timeout_kwargs(timeout))) async def notify_prompt_shown(self, params: PermissionPromptShownNotification, *, timeout: float | None = None) -> PermissionsNotifyPromptShownResult: "Notifies the runtime that a permission prompt UI has been shown to the user.\n\nArgs:\n params: Notification payload describing the permission prompt that the client just rendered.\n\nReturns:\n Indicates whether the operation succeeded." @@ -29489,6 +33031,19 @@ async def recompute_context_tokens(self, params: MetadataRecomputeContextTokensR return MetadataRecomputeContextTokensResult.from_dict(await self._client.request("session.metadata.recomputeContextTokens", params_dict, **_timeout_kwargs(timeout))) +# Experimental: this API group is experimental and may change or be removed. +class ContentExclusionApi: + def __init__(self, client: "JsonRpcClient", session_id: str): + self._client = client + self._session_id = session_id + + async def check_paths(self, params: ContentExclusionCheckPathsRequest, *, timeout: float | None = None) -> ContentExclusionCheckPathsResult: + "Checks local file system absolute paths within the session working directory against its content-exclusion policy. Results preserve input order. Unsupported paths/filesystems and unavailable policy evaluation return available false, and callers must treat every requested path as excluded.\n\nArgs:\n params: Local file system absolute paths within the session working directory to check against its content-exclusion policy.\n\nReturns:\n Batch content-exclusion result. Callers must fail closed when policy evaluation is unavailable." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return ContentExclusionCheckPathsResult.from_dict(await self._client.request("session.contentExclusion.checkPaths", params_dict, **_timeout_kwargs(timeout))) + + # Experimental: this API group is experimental and may change or be removed. class ShellApi: def __init__(self, client: "JsonRpcClient", session_id: str): @@ -29496,13 +33051,13 @@ def __init__(self, client: "JsonRpcClient", session_id: str): self._session_id = session_id async def exec(self, params: ShellExecRequest, *, timeout: float | None = None) -> ShellExecResult: - "Starts a shell command and streams output through session notifications.\n\nArgs:\n params: Shell command to run, with optional working directory and timeout in milliseconds.\n\nReturns:\n Identifier of the spawned process, used to correlate streamed output and exit notifications." + "Starts a shell command and streams output through session notifications. The command runs as the leader of its own process group (POSIX) or in a dedicated job object (Windows), so a forced termination — via \"shell.kill\", the request timeout, or session disposal — signals that whole group/job rather than only the direct child. Two gaps are worth planning for: a command that exits on its own does not trigger that teardown, and on POSIX a descendant that moves itself into a new session or process group (for example via \"setsid\") leaves the signalled group, so either can leave a background process running.\n\nArgs:\n params: Shell command to run, with optional working directory and timeout in milliseconds.\n\nReturns:\n Identifier of the spawned process, used to correlate streamed output and exit notifications." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} params_dict["sessionId"] = self._session_id return ShellExecResult.from_dict(await self._client.request("session.shell.exec", params_dict, **_timeout_kwargs(timeout))) async def kill(self, params: ShellKillRequest, *, timeout: float | None = None) -> ShellKillResult: - "Sends a signal to a shell process previously started via \"shell.exec\".\n\nArgs:\n params: Identifier of a process previously returned by \"shell.exec\" and the signal to send.\n\nReturns:\n Indicates whether the signal was delivered; false if the process was unknown or already exited." + "Sends a signal to a shell process previously started via \"shell.exec\". The signal targets the command's whole process group (POSIX) or job object (Windows), so descendants still in that group are signalled too, not just the direct child. On POSIX a descendant that moved itself into a new session or process group (for example via \"setsid\") is no longer in the signalled group and survives.\n\nArgs:\n params: Identifier of a process previously returned by \"shell.exec\" and the signal to send.\n\nReturns:\n Indicates whether the signal was delivered; false if the process was unknown or already exited." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} params_dict["sessionId"] = self._session_id return ShellKillResult.from_dict(await self._client.request("session.shell.kill", params_dict, **_timeout_kwargs(timeout))) @@ -29526,7 +33081,7 @@ def __init__(self, client: "JsonRpcClient", session_id: str): self._client = client self._session_id = session_id - async def compact(self, params: HistoryCompactRequest | None = None, *, timeout: float | None = None) -> HistoryCompactResult: + async def compact(self, params: SessionHistoryCompactRequest | 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 @@ -29538,6 +33093,22 @@ async def truncate(self, params: HistoryTruncateRequest, *, timeout: float | Non params_dict["sessionId"] = self._session_id return HistoryTruncateResult.from_dict(await self._client.request("session.history.truncate", params_dict, **_timeout_kwargs(timeout))) + async def list_rewind_points(self, *, timeout: float | None = None) -> HistoryListRewindPointsResult: + "Lists the user turns that the session can rewind to. Never rejects for a busy session: rewind reads need the session's file-change captures to be settled, so a session that still holds active work answers with `unavailableReason: \"session-busy\"` and no points, which the caller can retry.\n\nReturns:\n Rewind points and file-change-tracking availability for the session." + return HistoryListRewindPointsResult.from_dict(await self._client.request("session.history.listRewindPoints", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) + + async def preview_rewind(self, params: HistoryPreviewRewindRequest, *, timeout: float | None = None) -> HistoryPreviewRewindResult: + "Previews the files that a conversation-and-files rewind would restore.\n\nArgs:\n params: Event boundary to preview for conversation-and-files rewind.\n\nReturns:\n Files and aggregate changes for a prospective rewind." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return HistoryPreviewRewindResult.from_dict(await self._client.request("session.history.previewRewind", params_dict, **_timeout_kwargs(timeout))) + + async def rewind(self, params: HistoryRewindRequest, *, timeout: float | None = None) -> HistoryRewindResult: + "Rewinds the session conversation, optionally restoring files changed by the discarded turns. Not crash-atomic: file restore and conversation truncation are separate stores, applied in that order, so a process crash between them can leave the workspace rewound while the conversation still contains the discarded turns. There is no recovery journal; re-running the same rewind is the recovery path for a crash before truncation lands, since file restore is idempotent (already-restored files are reported as skipped) and truncation is re-derived from the still-retained boundary event. After truncation lands that boundary no longer exists, so the same request is rejected; the only stage that can still be outstanding is snapshot pruning, whose failure leaves orphan snapshots the capture store tolerates. The reverse inconsistency cannot occur, because truncation is never applied before file restore succeeds.\n\nArgs:\n params: Boundary and mode for rewinding session history.\n\nReturns:\n Structured outcome of a rewind request." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return HistoryRewindResult.from_dict(await self._client.request("session.history.rewind", params_dict, **_timeout_kwargs(timeout))) + async def cancel_background_compaction(self, *, timeout: float | None = None) -> HistoryCancelBackgroundCompactionResult: "Cancels any in-progress background compaction on a local session.\n\nReturns:\n Indicates whether an in-progress background compaction was cancelled." return HistoryCancelBackgroundCompactionResult.from_dict(await self._client.request("session.history.cancelBackgroundCompaction", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) @@ -29561,6 +33132,48 @@ async def pending_items(self, *, timeout: float | None = None) -> QueuePendingIt "Returns the local session's pending user-facing queued items and steering messages.\n\nReturns:\n Snapshot of the session's pending queued items and immediate-steering messages." return QueuePendingItemsResult.from_dict(await self._client.request("session.queue.pendingItems", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) + async def move_item(self, params: QueueMoveItemRequest, *, timeout: float | None = None) -> QueueMoveItemResult: + "Moves an addressable queued item to a public visible position.\n\nArgs:\n params: Parameters for moving a queued item by stable id.\n\nReturns:\n Result of moving a queued item." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return QueueMoveItemResult.from_dict(await self._client.request("session.queue.moveItem", params_dict, **_timeout_kwargs(timeout))) + + async def insert_at(self, params: QueueInsertAtRequest, *, timeout: float | None = None) -> QueueInsertAtResult: + "Inserts a new queued message at a public visible position.\n\nArgs:\n params: Parameters for inserting a queued message at a public visible position.\n\nReturns:\n Result of inserting a queued message." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return QueueInsertAtResult.from_dict(await self._client.request("session.queue.insertAt", params_dict, **_timeout_kwargs(timeout))) + + async def remove_at(self, params: QueueRemoveAtRequest, *, timeout: float | None = None) -> QueueRemoveAtResult: + "Removes an addressable queued item by its stable id.\n\nArgs:\n params: Parameters for removing a queued item by stable id.\n\nReturns:\n Result of removing a queued item." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return QueueRemoveAtResult.from_dict(await self._client.request("session.queue.removeAt", params_dict, **_timeout_kwargs(timeout))) + + async def update_text(self, params: QueueUpdateTextRequest, *, timeout: float | None = None) -> QueueUpdateTextResult: + "Updates the text of an addressable single-message queue item.\n\nArgs:\n params: Parameters for editing a single queued message.\n\nReturns:\n Result of editing a queued message." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return QueueUpdateTextResult.from_dict(await self._client.request("session.queue.updateText", params_dict, **_timeout_kwargs(timeout))) + + async def duplicate_at(self, params: QueueDuplicateAtRequest, *, timeout: float | None = None) -> QueueDuplicateAtResult: + "Duplicates an addressable queued item immediately after its source.\n\nArgs:\n params: Parameters for duplicating a queued item.\n\nReturns:\n Result of duplicating a queued item." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return QueueDuplicateAtResult.from_dict(await self._client.request("session.queue.duplicateAt", params_dict, **_timeout_kwargs(timeout))) + + async def set_drain_paused(self, params: QueueSetDrainPausedRequest, *, timeout: float | None = None) -> None: + "Acquires or releases the queued-lane drain pause.\n\nArgs:\n params: Parameters for acquiring or releasing the queued-lane drain pause. Acquisition is exclusive and non-idempotent: `paused: true` against an already-paused session fails with `queue_already_paused`. The pause is never released automatically — it is not tied to the caller's lifetime, so a client that exits without sending `paused: false` leaves the lane frozen. Release is unowned: `paused: false` clears the pause for any caller, including one that never acquired it." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + await self._client.request("session.queue.setDrainPaused", params_dict, **_timeout_kwargs(timeout)) + + async def send_now(self, params: QueueSendNowRequest, *, timeout: float | None = None) -> QueueSendNowResult: + "Moves an addressable queued message into the live turn's steering lane.\n\nArgs:\n params: Parameters for steering a queued message into a live turn.\n\nReturns:\n Result of trying to steer a queued message into a live turn." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return QueueSendNowResult.from_dict(await self._client.request("session.queue.sendNow", params_dict, **_timeout_kwargs(timeout))) + async def remove_most_recent(self, *, timeout: float | None = None) -> QueueRemoveMostRecentResult: "Removes the most recently queued user-facing item (LIFO).\n\nReturns:\n Indicates whether a user-facing pending item was removed." return QueueRemoveMostRecentResult.from_dict(await self._client.request("session.queue.removeMostRecent", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) @@ -29610,6 +33223,19 @@ async def get_metrics(self, *, timeout: float | None = None) -> UsageGetMetricsR return UsageGetMetricsResult.from_dict(await self._client.request("session.usage.getMetrics", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) +# Experimental: this API group is experimental and may change or be removed. +class LimitPredictionApi: + def __init__(self, client: "JsonRpcClient", session_id: str): + self._client = client + self._session_id = session_id + + async def predict(self, params: SessionLimitPredictionPredictRequest | None = None, *, timeout: float | None = None) -> SessionLimitPredictionResult: + "Predicts an AI-credit session limit for the session's resolved model. Returns an unavailable result instead of falling back when the current model is unresolved auto.\n\nArgs:\n params: Parameters for predicting an AI-credit session limit. Omitting `modelId` uses the session's currently selected model.\n\nReturns:\n Prediction result. Available results include prediction details; unavailable results include an explicit reason." + 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 SessionLimitPredictionResult.from_dict(await self._client.request("session.limitPrediction.predict", params_dict, **_timeout_kwargs(timeout))) + + # Experimental: this API group is experimental and may change or be removed. class RemoteApi: def __init__(self, client: "JsonRpcClient", session_id: str): @@ -29699,11 +33325,13 @@ def __init__(self, client: "JsonRpcClient", session_id: str): self.ui = UiApi(client, session_id) self.permissions = PermissionsApi(client, session_id) self.metadata = MetadataApi(client, session_id) + self.content_exclusion = ContentExclusionApi(client, session_id) self.shell = ShellApi(client, session_id) self.history = HistoryApi(client, session_id) self.queue = QueueApi(client, session_id) self.event_log = EventLogApi(client, session_id) self.usage = UsageApi(client, session_id) + self.limit_prediction = LimitPredictionApi(client, session_id) self.remote = RemoteApi(client, session_id) self.visibility = VisibilityApi(client, session_id) self.schedule = ScheduleApi(client, session_id) @@ -29730,6 +33358,16 @@ async def abort(self, params: AbortRequest, *, timeout: float | None = None) -> params_dict["sessionId"] = self._session_id return AbortResult.from_dict(await self._client.request("session.abort", params_dict, **_timeout_kwargs(timeout))) + async def interrupt_main_turn(self, params: InterruptMainTurnRequest, *, timeout: float | None = None) -> InterruptMainTurnResult: + "Interrupts the current main agent turn while leaving running background work (subagents, sidekicks, and promoted attached shells) alive. No-op when the main loop is not processing.\n\nArgs:\n params: Parameters for interrupting the main agent turn.\n\nReturns:\n Result of interrupting the main agent turn.\n\n.. warning:: This API is experimental and may change or be removed in future versions." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return InterruptMainTurnResult.from_dict(await self._client.request("session.interruptMainTurn", params_dict, **_timeout_kwargs(timeout))) + + async def cancel_all_background_agents(self, *, timeout: float | None = None) -> int: + "Cancels every running background agent (task-registry subagents plus sidekick agents) without interrupting the main agent loop. Promoted attached shells are left running.\n\nReturns:\n The number of running background agents (task-registry agents) that were cancelled.\n\n.. warning:: This API is experimental and may change or be removed in future versions." + return int(await self._client.request("session.cancelAllBackgroundAgents", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) + async def shutdown(self, params: ShutdownRequest, *, timeout: float | None = None) -> None: "Shuts down the session and persists its final state. Awaits any deferred sessionEnd hooks before resolving so user-supplied hook scripts complete before the runtime tears down.\n\nArgs:\n params: Parameters for shutting down the session\n\n.. warning:: This API is experimental and may change or be removed in future versions." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} @@ -29791,6 +33429,98 @@ async def _evaluate_predicate(self, params: SessionSettingsEvaluatePredicateRequ return SessionSettingsEvaluatePredicateResult.from_dict(await self._client.request("session.settings.evaluatePredicate", params_dict, **_timeout_kwargs(timeout))) +# Experimental: this API group is experimental and may change or be removed. +class _InternalQueueApi: + def __init__(self, client: "JsonRpcClient", session_id: str): + self._client = client + self._session_id = session_id + + async def _snapshot(self, *, timeout: float | None = None) -> QueueSnapshotResult: + "Returns the internal native queue snapshot for in-process session orchestration.\n\nReturns:\n Internal snapshot of native queue state for local session orchestration.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." + return QueueSnapshotResult.from_dict(await self._client.request("session.queue.snapshot", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) + + async def _has_pending(self, *, timeout: float | None = None) -> QueueHasPendingResult: + "Reports whether the local session has native queued work pending.\n\nReturns:\n Whether the native queue has pending work.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." + return QueueHasPendingResult.from_dict(await self._client.request("session.queue.hasPending", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) + + async def _begin_deferred_idle_drain(self, params: QueueBeginDeferredIdleDrainRequest, *, timeout: float | None = None) -> QueueBeginDeferredIdleDrainResult: + "Begins a native deferred-idle drain when background work has quiesced.\n\nArgs:\n params: Inputs for starting a deferred-idle drain.\n\nReturns:\n Whether a deferred-idle drain should run.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return QueueBeginDeferredIdleDrainResult.from_dict(await self._client.request("session.queue.beginDeferredIdleDrain", params_dict, **_timeout_kwargs(timeout))) + + async def _finish_deferred_idle_drain(self, params: QueueFinishDeferredIdleDrainRequest, *, timeout: float | None = None) -> QueueFinishDeferredIdleDrainResult: + "Finishes a native deferred-idle drain and reports whether to drain queue work or emit idle.\n\nArgs:\n params: Inputs for completing a deferred-idle drain.\n\nReturns:\n Action selected by the native deferred-idle drain.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return QueueFinishDeferredIdleDrainResult.from_dict(await self._client.request("session.queue.finishDeferredIdleDrain", params_dict, **_timeout_kwargs(timeout))) + + async def _defer_session_idle(self, params: QueueDeferSessionIdleRequest, *, timeout: float | None = None) -> None: + "Marks session.idle as deferred by native background work state.\n\nArgs:\n params: Inputs for marking session.idle deferred in native state.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + await self._client.request("session.queue.deferSessionIdle", params_dict, **_timeout_kwargs(timeout)) + + async def _consume_system_notifications(self, params: QueueConsumeSystemNotificationsRequest, *, timeout: float | None = None) -> QueueRemoveMostRecentResult: + "Consumes queued native system notifications matching an internal filter.\n\nArgs:\n params: Internal filter for consuming queued system notifications.\n\nReturns:\n Indicates whether a user-facing pending item was removed.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return QueueRemoveMostRecentResult.from_dict(await self._client.request("session.queue.consumeSystemNotifications", params_dict, **_timeout_kwargs(timeout))) + + async def _enqueue_resume_pending(self, *, timeout: float | None = None) -> QueueEnqueueResumePendingResult: + "Enqueues the internal resume-pending wake item when orphan handling needs a follow-up turn.\n\nReturns:\n Result of enqueueing the resume-pending wake item.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." + return QueueEnqueueResumePendingResult.from_dict(await self._client.request("session.queue.enqueueResumePending", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) + + async def _process(self, *, timeout: float | None = None) -> None: + "Drains the native local-session work queue for in-process session orchestration.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." + await self._client.request("session.queue.process", {"sessionId": self._session_id}, **_timeout_kwargs(timeout)) + + +# Experimental: this API group is experimental and may change or be removed. +class _InternalScheduleApi: + def __init__(self, client: "JsonRpcClient", session_id: str): + self._client = client + self._session_id = session_id + + async def _hydrate(self, *, timeout: float | None = None) -> None: + "Hydrates the native schedule registry from persisted session events.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." + await self._client.request("session.schedule.hydrate", {"sessionId": self._session_id}, **_timeout_kwargs(timeout)) + + async def _has_self_paced(self, *, timeout: float | None = None) -> ScheduleHasSelfPacedResult: + "Reports whether the session has an active self-paced scheduled prompt.\n\nReturns:\n Whether the session currently has an active self-paced schedule.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." + return ScheduleHasSelfPacedResult.from_dict(await self._client.request("session.schedule.hasSelfPaced", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) + + async def _add(self, params: ScheduleAddRequest, *, timeout: float | None = None) -> ScheduleAddResult: + "Registers a relative-interval scheduled prompt.\n\nArgs:\n params: Register a relative-interval scheduled prompt.\n\nReturns:\n Result of registering or re-arming a scheduled prompt.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return ScheduleAddResult.from_dict(await self._client.request("session.schedule.add", params_dict, **_timeout_kwargs(timeout))) + + async def _add_cron(self, params: ScheduleAddCronRequest, *, timeout: float | None = None) -> ScheduleAddResult: + "Registers a recurring cron scheduled prompt.\n\nArgs:\n params: Register a cron scheduled prompt.\n\nReturns:\n Result of registering or re-arming a scheduled prompt.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return ScheduleAddResult.from_dict(await self._client.request("session.schedule.addCron", params_dict, **_timeout_kwargs(timeout))) + + async def _add_at(self, params: ScheduleAddAtRequest, *, timeout: float | None = None) -> ScheduleAddResult: + "Registers an absolute-time scheduled prompt.\n\nArgs:\n params: Register an absolute-time scheduled prompt.\n\nReturns:\n Result of registering or re-arming a scheduled prompt.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return ScheduleAddResult.from_dict(await self._client.request("session.schedule.addAt", params_dict, **_timeout_kwargs(timeout))) + + async def _add_self_paced(self, params: ScheduleAddSelfPacedRequest, *, timeout: float | None = None) -> ScheduleAddResult: + "Registers a self-paced scheduled prompt.\n\nArgs:\n params: Register a self-paced scheduled prompt.\n\nReturns:\n Result of registering or re-arming a scheduled prompt.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return ScheduleAddResult.from_dict(await self._client.request("session.schedule.addSelfPaced", params_dict, **_timeout_kwargs(timeout))) + + async def _rearm_self_paced(self, params: ScheduleRearmSelfPacedRequest, *, timeout: float | None = None) -> ScheduleAddResult: + "Re-arms an active self-paced scheduled prompt.\n\nArgs:\n params: Re-arm a self-paced scheduled prompt.\n\nReturns:\n Result of registering or re-arming a scheduled prompt.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return ScheduleAddResult.from_dict(await self._client.request("session.schedule.rearmSelfPaced", params_dict, **_timeout_kwargs(timeout))) + + class _InternalSessionRpc: """Internal SDK session-scoped RPC methods. Not part of the public API.""" def __init__(self, client: "JsonRpcClient", session_id: str): @@ -29798,6 +33528,14 @@ def __init__(self, client: "JsonRpcClient", session_id: str): self._session_id = session_id self.mcp = _InternalMcpApi(client, session_id) self.settings = _InternalSettingsApi(client, session_id) + self.queue = _InternalQueueApi(client, session_id) + self.schedule = _InternalScheduleApi(client, session_id) + + async def _send_system_notification(self, params: SendSystemNotificationRequest, *, timeout: float | None = None) -> None: + "Queues or sends an internal system notification to the session according to its passive policy.\n\nArgs:\n params: Internal request for sending a system notification.\n\n.. warning:: This API is experimental and may change or be removed in future versions.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + await self._client.request("session.sendSystemNotification", params_dict, **_timeout_kwargs(timeout)) # Experimental: this API group is experimental and may change or be removed. @@ -29848,7 +33586,10 @@ async def rename(self, params: SessionFSRenameRequest) -> SessionFSError | None: "Renames or moves a path in the client-provided session filesystem.\n\nArgs:\n params: Source and destination paths for renaming or moving an entry in the client-provided session filesystem.\n\nReturns:\n Describes a filesystem error." pass async def sqlite_query(self, params: SessionFSSqliteQueryRequest) -> SessionFSSqliteQueryResult: - "Executes a SQLite query against the per-session database.\n\nArgs:\n params: SQL query, query type, and optional bind parameters for executing a SQLite query against the per-session database.\n\nReturns:\n Query results including rows, columns, and rows affected, or a filesystem error if execution failed." + "Executes a SQLite query against the per-session database. Providers apply busy handling for every call.\n\nArgs:\n params: SQL query, query type, and optional bind parameters for executing a SQLite query against the per-session database. The provider applies its SQLite busy timeout for every call.\n\nReturns:\n Query results including rows, columns, and rows affected, or a filesystem error if execution failed." + pass + async def sqlite_transaction(self, params: SessionFSSqliteTransactionRequest) -> SessionFSSqliteTransactionResult: + "Executes SQLite statements atomically on the provider-owned connection.\n\nArgs:\n params: Statements to execute atomically. Providers apply busy handling for every call.\n\nReturns:\n Per-statement results, or a classified transaction error." pass async def sqlite_exists(self, params: SessionFSSqliteExistsRequest) -> SessionFSSqliteExistsResult: "Checks whether the per-session SQLite database already exists, without creating it.\n\nArgs:\n params: Identifies the target session.\n\nReturns:\n Indicates whether the per-session SQLite database already exists." @@ -29976,6 +33717,13 @@ async def handle_session_fs_sqlite_query(params: dict) -> dict | None: result = await handler.sqlite_query(request) return result.to_dict() client.set_request_handler("sessionFs.sqliteQuery", handle_session_fs_sqlite_query) + async def handle_session_fs_sqlite_transaction(params: dict) -> dict | None: + request = SessionFSSqliteTransactionRequest.from_dict(params) + handler = get_handlers(request.session_id).session_fs + if handler is None: raise RuntimeError(f"No session_fs handler registered for session: {request.session_id}") + result = await handler.sqlite_transaction(request) + return result.to_dict() + client.set_request_handler("sessionFs.sqliteTransaction", handle_session_fs_sqlite_transaction) async def handle_session_fs_sqlite_exists(params: dict) -> dict | None: request = SessionFSSqliteExistsRequest.from_dict(params) handler = get_handlers(request.session_id).session_fs @@ -30096,6 +33844,7 @@ async def handle_git_hub_telemetry_event(params: dict) -> None: "AgentInfo", "AgentInfoSource", "AgentList", + "AgentListRequest", "AgentRegistryLiveTargetEntry", "AgentRegistryLiveTargetEntryAttentionKind", "AgentRegistryLiveTargetEntryKind", @@ -30127,6 +33876,8 @@ async def handle_git_hub_telemetry_event(params: dict) -> None: "ApprovalKind", "AuthInfo", "AuthInfoType", + "BuiltInModelCatalog", + "BuiltInModelCatalogEntry", "CancelUserRequestedShellCommandResult", "CanvasAction", "CanvasActionApi", @@ -30166,6 +33917,10 @@ async def handle_git_hub_telemetry_event(params: dict) -> None: "ConnectedRemoteSessionMetadata", "ConnectedRemoteSessionMetadataKind", "ConnectedRemoteSessionMetadataRepository", + "ContentExclusionApi", + "ContentExclusionCheckPathsRequest", + "ContentExclusionCheckPathsResult", + "ContentExclusionPathCheck", "ContentFilterMode", "ContextHeaviestMessage", "CopilotAPITokenAuthInfo", @@ -30244,19 +33999,34 @@ async def handle_git_hub_telemetry_event(params: dict) -> None: "FactoryAgentOptions", "FactoryAgentRequest", "FactoryAgentResult", + "FactoryAgentSummary", "FactoryApi", "FactoryCancelRequest", + "FactoryCurrentPhase", + "FactoryDeclaredLimits", + "FactoryDurableOperation", "FactoryExecuteRequest", "FactoryExecuteResult", + "FactoryGetRunProgressRequest", "FactoryGetRunRequest", "FactoryHandler", "FactoryJournalApi", "FactoryJournalGetRequest", "FactoryJournalGetResult", "FactoryJournalPutRequest", + "FactoryListRunsRequest", + "FactoryListRunsResult", "FactoryLogLine", "FactoryLogLineKind", "FactoryLogRequest", + "FactoryPhaseObservation", + "FactoryPhaseStatus", + "FactoryProgressLine", + "FactoryProgressPage", + "FactoryResumeRequest", + "FactoryResumeResult", + "FactoryRunConsumed", + "FactoryRunDetail", "FactoryRunFailure", "FactoryRunFailureKind", "FactoryRunFailureType", @@ -30264,6 +34034,8 @@ async def handle_git_hub_telemetry_event(params: dict) -> None: "FactoryRunRequest", "FactoryRunResult", "FactoryRunStatus", + "FactoryRunSummary", + "FactoryRunTerminal", "FilterMapping", "FleetApi", "FleetStartRequest", @@ -30289,6 +34061,19 @@ async def handle_git_hub_telemetry_event(params: dict) -> None: "HistoryCompactContextWindow", "HistoryCompactRequest", "HistoryCompactResult", + "HistoryFileRestoreSkipReason", + "HistoryListRewindPointsResult", + "HistoryPreviewRewindRequest", + "HistoryPreviewRewindResult", + "HistoryRewindChangeType", + "HistoryRewindFilePreview", + "HistoryRewindMode", + "HistoryRewindOutcome", + "HistoryRewindPoint", + "HistoryRewindRequest", + "HistoryRewindResult", + "HistoryRewindUnavailableReason", + "HistorySkippedFileRestore", "HistorySummarizeForHandoffResult", "HistoryTruncateRequest", "HistoryTruncateResult", @@ -30313,7 +34098,10 @@ async def handle_git_hub_telemetry_event(params: dict) -> None: "InstructionsDiscoverRequest", "InstructionsGetDiscoveryPathsRequest", "InstructionsGetSourcesResult", + "InterruptMainTurnRequest", + "InterruptMainTurnResult", "KindEnum", + "LimitPredictionApi", "LlmInferenceHTTPRequestChunkRequest", "LlmInferenceHTTPRequestChunkResult", "LlmInferenceHTTPRequestStartRequest", @@ -30381,6 +34169,8 @@ async def handle_git_hub_telemetry_event(params: dict) -> None: "MCPOauthLoginResult", "MCPOauthPendingRequestResponse", "MCPOauthPendingRequestResponseKind", + "MCPOauthRespondRequest", + "MCPOauthRespondResult", "MCPRegisterExternalClientRequest", "MCPReloadWithConfigRequest", "MCPRemoveGitHubResult", @@ -30720,10 +34510,33 @@ async def handle_git_hub_telemetry_event(params: dict) -> None: "PushAttachmentType", "PushGitHubRepoRef", "QueueApi", + "QueueBeginDeferredIdleDrainRequest", + "QueueBeginDeferredIdleDrainResult", + "QueueConsumeSystemNotificationsRequest", + "QueueDeferSessionIdleRequest", + "QueueDuplicateAtRequest", + "QueueDuplicateAtResult", + "QueueEnqueueResumePendingResult", + "QueueFinishDeferredIdleDrainRequest", + "QueueFinishDeferredIdleDrainResult", + "QueueHasPendingResult", + "QueueInsertAtRequest", + "QueueInsertAtResult", + "QueueInsertMessage", + "QueueMoveItemRequest", + "QueueMoveItemResult", "QueuePendingItems", "QueuePendingItemsKind", "QueuePendingItemsResult", + "QueueRemoveAtRequest", + "QueueRemoveAtResult", "QueueRemoveMostRecentResult", + "QueueSendNowRequest", + "QueueSendNowResult", + "QueueSetDrainPausedRequest", + "QueueSnapshotResult", + "QueueUpdateTextRequest", + "QueueUpdateTextResult", "QueuedCommandHandled", "QueuedCommandNotHandled", "QueuedCommandResult", @@ -30764,11 +34577,19 @@ async def handle_git_hub_telemetry_event(params: dict) -> None: "SandboxConfigUserPolicyExperimentalSeatbelt", "SandboxConfigUserPolicyFilesystem", "SandboxConfigUserPolicyNetwork", + "SandboxConfigUserPolicyNetworkProxy", "SandboxConfigUserPolicySeatbelt", "Saved", + "ScheduleAddAtRequest", + "ScheduleAddCronRequest", + "ScheduleAddRequest", + "ScheduleAddResult", + "ScheduleAddSelfPacedRequest", "ScheduleApi", "ScheduleEntry", + "ScheduleHasSelfPacedResult", "ScheduleList", + "ScheduleRearmSelfPacedRequest", "ScheduleStopRequest", "ScheduleStopResult", "SecretsAddFilterValuesRequest", @@ -30781,6 +34602,7 @@ async def handle_git_hub_telemetry_event(params: dict) -> None: "SendMode", "SendRequest", "SendResult", + "SendSystemNotificationRequest", "ServerAccountApi", "ServerAgentList", "ServerAgentRegistryApi", @@ -30807,9 +34629,12 @@ async def handle_git_hub_telemetry_event(params: dict) -> None: "ServerUserApi", "ServerUserSettingsApi", "SessionActivity", + "SessionAgentListRequest", "SessionAuthStatus", "SessionBulkDeleteResult", + "SessionCancelAllBackgroundAgentsResult", "SessionCapability", + "SessionCommandsListRequest", "SessionCompletionItem", "SessionContext", "SessionContextAttribution", @@ -30840,16 +34665,33 @@ async def handle_git_hub_telemetry_event(params: dict) -> None: "SessionFSSqliteQueryRequest", "SessionFSSqliteQueryResult", "SessionFSSqliteQueryType", + "SessionFSSqliteTransactionError", + "SessionFSSqliteTransactionErrorClass", + "SessionFSSqliteTransactionRequest", + "SessionFSSqliteTransactionResult", + "SessionFSSqliteTransactionStatement", "SessionFSStatRequest", "SessionFSStatResult", "SessionFSWriteFileRequest", "SessionFsHandler", "SessionFsReaddirWithTypesEntryType", + "SessionHistoryCompactRequest", "SessionInstalledPlugin", "SessionInstalledPluginSource", "SessionInstalledPluginSourceGitHub", "SessionInstalledPluginSourceLocal", "SessionInstalledPluginSourceURL", + "SessionLimitPredictionBaselineData", + "SessionLimitPredictionClientType", + "SessionLimitPredictionDetails", + "SessionLimitPredictionPredictRequest", + "SessionLimitPredictionRequest", + "SessionLimitPredictionResult", + "SessionLimitPredictionResultKind", + "SessionLimitPredictionSource", + "SessionLimitPredictionTier", + "SessionLimitPredictionTierOption", + "SessionLimitPredictionUnavailableReason", "SessionList", "SessionListEntry", "SessionListFilter", @@ -30858,6 +34700,7 @@ async def handle_git_hub_telemetry_event(params: dict) -> None: "SessionMcpAppsCallToolResult", "SessionMetadataSnapshot", "SessionModelList", + "SessionModelListRequest", "SessionModelPriceCategory", "SessionOpenOptions", "SessionOpenOptionsAdditionalContentExclusionPolicy", @@ -30869,6 +34712,8 @@ async def handle_git_hub_telemetry_event(params: dict) -> None: "SessionOpenParams", "SessionOpenParamsKind", "SessionOpenResult", + "SessionPluginsReloadRequest", + "SessionProviderGetEndpointRequest", "SessionPruneResult", "SessionRpc", "SessionSetCredentialsParams", @@ -30896,6 +34741,7 @@ async def handle_git_hub_telemetry_event(params: dict) -> None: "SessionsCheckInUseResult", "SessionsCloseRequest", "SessionsCloseResult", + "SessionsDeleteRequest", "SessionsEnrichMetadataRequest", "SessionsFindByPrefixRequest", "SessionsFindByPrefixResult", @@ -30909,8 +34755,12 @@ async def handle_git_hub_telemetry_event(params: dict) -> None: "SessionsGetEventFilePathResult", "SessionsGetLastForContextRequest", "SessionsGetLastForContextResult", + "SessionsGetMetadataRequest", + "SessionsGetMetadataResult", "SessionsGetPersistedRemoteSteerableRequest", "SessionsGetPersistedRemoteSteerableResult", + "SessionsListNonEmptySessionIDSRequest", + "SessionsListNonEmptySessionIDSResult", "SessionsListRequest", "SessionsLoadDeferredRepoHooksRequest", "SessionsOpenAttach", @@ -30951,9 +34801,13 @@ async def handle_git_hub_telemetry_event(params: dict) -> None: "ShellExecRequest", "ShellExecResult", "ShellExecuteUserRequestedRequest", + "ShellInitProfile", + "ShellInitScript", + "ShellInitScriptShell", "ShellKillRequest", "ShellKillResult", "ShellKillSignal", + "ShellOptions", "ShutdownRequest", "Skill", "SkillDiscoveryPath", @@ -31035,6 +34889,7 @@ async def handle_git_hub_telemetry_event(params: dict) -> None: "ToolsInitializeAndValidateResult", "ToolsListRequest", "ToolsUpdateSubagentSettingsResult", + "Trigger", "UIAutoModeSwitchResponse", "UIElicitationArrayAnyOfField", "UIElicitationArrayAnyOfFieldItems", @@ -31106,20 +34961,30 @@ async def handle_git_hub_telemetry_event(params: dict) -> None: "WorkspaceDiffResult", "WorkspaceSummary", "WorkspaceSummaryHostType", + "WorkspacesAddSummaryRequest", + "WorkspacesAddSummaryResult", "WorkspacesApi", + "WorkspacesAutopilotObjectiveExistsResult", "WorkspacesCheckpoints", "WorkspacesCreateFileRequest", + "WorkspacesDeleteAutopilotObjectiveResult", "WorkspacesDiffRequest", + "WorkspacesEnsureRequest", "WorkspacesGetWorkspaceResult", "WorkspacesListCheckpointsResult", "WorkspacesListFilesResult", + "WorkspacesReadAutopilotObjectiveResult", "WorkspacesReadCheckpointRequest", "WorkspacesReadCheckpointResult", "WorkspacesReadFileRequest", "WorkspacesReadFileResult", "WorkspacesSaveLargePasteRequest", "WorkspacesSaveLargePasteResult", + "WorkspacesTruncateSummariesRequest", + "WorkspacesUpdateMetadataRequest", "WorkspacesWorkspaceDetailsHostType", + "WorkspacesWriteAutopilotObjectiveRequest", + "WorkspacesWriteAutopilotObjectiveResult", "rpc_from_dict", "rpc_to_dict", ] diff --git a/python/copilot/generated/session_events.py b/python/copilot/generated/session_events.py index fecd5839ed..8099ecd59b 100644 --- a/python/copilot/generated/session_events.py +++ b/python/copilot/generated/session_events.py @@ -223,6 +223,8 @@ class SessionEventType(Enum): EXIT_PLAN_MODE_COMPLETED = "exit_plan_mode.completed" SESSION_TOOLS_UPDATED = "session.tools_updated" SESSION_BACKGROUND_TASKS_CHANGED = "session.background_tasks_changed" + # Experimental: this event is part of an experimental API and may change or be removed. + FACTORY_RUN_UPDATED = "factory.run_updated" SESSION_SKILLS_LOADED = "session.skills_loaded" SESSION_CUSTOM_AGENTS_UPDATED = "session.custom_agents_updated" SESSION_MCP_SERVERS_LOADED = "session.mcp_servers_loaded" @@ -774,6 +776,30 @@ def to_dict(self) -> dict: return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class FactoryRunUpdatedData: + "Ephemeral invalidation signal for a changed factory run." + revision: int + run_id: str + + @staticmethod + def from_dict(obj: Any) -> "FactoryRunUpdatedData": + assert isinstance(obj, dict) + revision = from_int(obj.get("revision")) + run_id = from_str(obj.get("runId")) + return FactoryRunUpdatedData( + revision=revision, + run_id=run_id, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["revision"] = to_int(self.revision) + result["runId"] = from_str(self.run_id) + return result + + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class OmittedBinaryResult: @@ -821,21 +847,31 @@ def to_dict(self) -> dict: class PermissionAutoApproval: "Auto-approval judge information attached to a permission request. Present (non-null) only when the session's allow-all mode is \"auto\"; its absence means auto mode was off and the judge did not evaluate the request. The `recommendation` conveys the judge's disposition for this request." recommendation: AutoApprovalRecommendation + failure_reason: AutoApprovalJudgeFailureReason | None = None + model: str | None = None reason: str | None = None @staticmethod def from_dict(obj: Any) -> "PermissionAutoApproval": assert isinstance(obj, dict) recommendation = parse_enum(AutoApprovalRecommendation, obj.get("recommendation")) + failure_reason = from_union([from_none, lambda x: parse_enum(AutoApprovalJudgeFailureReason, x)], obj.get("failureReason")) + model = from_union([from_none, from_str], obj.get("model")) reason = from_union([from_none, from_str], obj.get("reason")) return PermissionAutoApproval( recommendation=recommendation, + failure_reason=failure_reason, + model=model, reason=reason, ) def to_dict(self) -> dict: result: dict = {} result["recommendation"] = to_enum(AutoApprovalRecommendation, self.recommendation) + if self.failure_reason is not None: + result["failureReason"] = from_union([from_none, lambda x: to_enum(AutoApprovalJudgeFailureReason, x)], self.failure_reason) + if self.model is not None: + result["model"] = from_union([from_none, from_str], self.model) if self.reason is not None: result["reason"] = from_union([from_none, from_str], self.reason) return result @@ -846,43 +882,88 @@ def to_dict(self) -> dict: class SessionAutoModeResolvedData: "Auto Intent resolution: the concrete model the session settled on for the first prompt of an auto-mode session, and why. Lets SDK clients render the chosen model and the full reason it was picked. The core selection fields (chosenModel/reasoningBucket/categoryScores) are stable; the routing-analytics fields (predictedLabel/confidence/candidateModels) mirror the upstream intent service and may evolve, hence the event's experimental stability." chosen_model: str + available_models: list[str] | None = None candidate_models: list[str] | None = None category_scores: dict[str, float] | None = None + chosen_shortfall: float | None = None confidence: float | None = None + end_to_end_latency_ms: float | None = None + fallback: bool | None = None + fallback_reason: str | None = None + has_image: bool | None = None predicted_label: str | None = None reasoning_bucket: AutoModeResolvedReasoningBucket | None = None + router_latency_ms: float | None = None + routing_method: str | None = None + sticky_override: bool | None = None @staticmethod def from_dict(obj: Any) -> "SessionAutoModeResolvedData": assert isinstance(obj, dict) chosen_model = from_str(obj.get("chosenModel")) + available_models = from_union([from_none, lambda x: from_list(from_str, x)], obj.get("availableModels")) candidate_models = from_union([from_none, lambda x: from_list(from_str, x)], obj.get("candidateModels")) category_scores = from_union([from_none, lambda x: from_dict(from_float, x)], obj.get("categoryScores")) + chosen_shortfall = from_union([from_none, from_float], obj.get("chosenShortfall")) confidence = from_union([from_none, from_float], obj.get("confidence")) + end_to_end_latency_ms = from_union([from_none, from_float], obj.get("endToEndLatencyMs")) + fallback = from_union([from_none, from_bool], obj.get("fallback")) + fallback_reason = from_union([from_none, from_str], obj.get("fallbackReason")) + has_image = from_union([from_none, from_bool], obj.get("hasImage")) predicted_label = from_union([from_none, from_str], obj.get("predictedLabel")) reasoning_bucket = from_union([from_none, lambda x: parse_enum(AutoModeResolvedReasoningBucket, x)], obj.get("reasoningBucket")) + router_latency_ms = from_union([from_none, from_float], obj.get("routerLatencyMs")) + routing_method = from_union([from_none, from_str], obj.get("routingMethod")) + sticky_override = from_union([from_none, from_bool], obj.get("stickyOverride")) return SessionAutoModeResolvedData( chosen_model=chosen_model, + available_models=available_models, candidate_models=candidate_models, category_scores=category_scores, + chosen_shortfall=chosen_shortfall, confidence=confidence, + end_to_end_latency_ms=end_to_end_latency_ms, + fallback=fallback, + fallback_reason=fallback_reason, + has_image=has_image, predicted_label=predicted_label, reasoning_bucket=reasoning_bucket, + router_latency_ms=router_latency_ms, + routing_method=routing_method, + sticky_override=sticky_override, ) def to_dict(self) -> dict: result: dict = {} result["chosenModel"] = from_str(self.chosen_model) + if self.available_models is not None: + result["availableModels"] = from_union([from_none, lambda x: from_list(from_str, x)], self.available_models) if self.candidate_models is not None: result["candidateModels"] = from_union([from_none, lambda x: from_list(from_str, x)], self.candidate_models) if self.category_scores is not None: result["categoryScores"] = from_union([from_none, lambda x: from_dict(to_float, x)], self.category_scores) + if self.chosen_shortfall is not None: + result["chosenShortfall"] = from_union([from_none, to_float], self.chosen_shortfall) if self.confidence is not None: result["confidence"] = from_union([from_none, to_float], self.confidence) + if self.end_to_end_latency_ms is not None: + result["endToEndLatencyMs"] = from_union([from_none, to_float], self.end_to_end_latency_ms) + if self.fallback is not None: + result["fallback"] = from_union([from_none, from_bool], self.fallback) + if self.fallback_reason is not None: + result["fallbackReason"] = from_union([from_none, from_str], self.fallback_reason) + if self.has_image is not None: + result["hasImage"] = from_union([from_none, from_bool], self.has_image) if self.predicted_label is not None: result["predictedLabel"] = from_union([from_none, from_str], self.predicted_label) if self.reasoning_bucket is not None: result["reasoningBucket"] = from_union([from_none, lambda x: to_enum(AutoModeResolvedReasoningBucket, x)], self.reasoning_bucket) + if self.router_latency_ms is not None: + result["routerLatencyMs"] = from_union([from_none, to_float], self.router_latency_ms) + if self.routing_method is not None: + result["routingMethod"] = from_union([from_none, from_str], self.routing_method) + if self.sticky_override is not None: + result["stickyOverride"] = from_union([from_none, from_bool], self.sticky_override) return result @@ -1133,6 +1214,7 @@ class SessionManagedSettingsResolvedData: managed_keys: list[str] server_managed: bool source: ManagedSettingsResolvedSource + permissions_allow_intersected: bool | None = None settings: Any = None @staticmethod @@ -1144,6 +1226,7 @@ def from_dict(obj: Any) -> "SessionManagedSettingsResolvedData": managed_keys = from_list(from_str, obj.get("managedKeys")) server_managed = from_bool(obj.get("serverManaged")) source = parse_enum(ManagedSettingsResolvedSource, obj.get("source")) + permissions_allow_intersected = from_union([from_none, from_bool], obj.get("permissionsAllowIntersected")) settings = obj.get("settings") return SessionManagedSettingsResolvedData( bypass_permissions_disabled=bypass_permissions_disabled, @@ -1152,6 +1235,7 @@ def from_dict(obj: Any) -> "SessionManagedSettingsResolvedData": managed_keys=managed_keys, server_managed=server_managed, source=source, + permissions_allow_intersected=permissions_allow_intersected, settings=settings, ) @@ -1163,6 +1247,8 @@ def to_dict(self) -> dict: result["managedKeys"] = from_list(from_str, self.managed_keys) result["serverManaged"] = from_bool(self.server_managed) result["source"] = to_enum(ManagedSettingsResolvedSource, self.source) + if self.permissions_allow_intersected is not None: + result["permissionsAllowIntersected"] = from_union([from_none, from_bool], self.permissions_allow_intersected) if self.settings is not None: result["settings"] = self.settings return result @@ -1246,6 +1332,7 @@ class AssistantMessageData: reasoning_text: str | None = None reasoning_wire_field: str | None = None request_id: str | None = None + rte: bool | None = None server_tools: AssistantMessageServerTools | None = None service_request_id: str | None = None tool_requests: list[AssistantMessageToolRequest] | None = None @@ -1269,6 +1356,7 @@ def from_dict(obj: Any) -> "AssistantMessageData": reasoning_text = from_union([from_none, from_str], obj.get("reasoningText")) reasoning_wire_field = from_union([from_none, from_str], obj.get("reasoningWireField")) request_id = from_union([from_none, from_str], obj.get("requestId")) + rte = from_union([from_none, from_bool], obj.get("rte")) server_tools = from_union([from_none, AssistantMessageServerTools.from_dict], obj.get("serverTools")) service_request_id = from_union([from_none, from_str], obj.get("serviceRequestId")) tool_requests = from_union([from_none, lambda x: from_list(AssistantMessageToolRequest.from_dict, x)], obj.get("toolRequests")) @@ -1289,6 +1377,7 @@ def from_dict(obj: Any) -> "AssistantMessageData": reasoning_text=reasoning_text, reasoning_wire_field=reasoning_wire_field, request_id=request_id, + rte=rte, server_tools=server_tools, service_request_id=service_request_id, tool_requests=tool_requests, @@ -1325,6 +1414,8 @@ def to_dict(self) -> dict: result["reasoningWireField"] = from_union([from_none, from_str], self.reasoning_wire_field) if self.request_id is not None: result["requestId"] = from_union([from_none, from_str], self.request_id) + if self.rte is not None: + result["rte"] = from_union([from_none, from_bool], self.rte) if self.server_tools is not None: result["serverTools"] = from_union([from_none, lambda x: to_class(AssistantMessageServerTools, x)], self.server_tools) if self.service_request_id is not None: @@ -1447,21 +1538,26 @@ class AssistantReasoningData: "Assistant reasoning content for timeline display with complete thinking text" content: str reasoning_id: str + rte: bool | None = None @staticmethod def from_dict(obj: Any) -> "AssistantReasoningData": assert isinstance(obj, dict) content = from_str(obj.get("content")) reasoning_id = from_str(obj.get("reasoningId")) + rte = from_union([from_none, from_bool], obj.get("rte")) return AssistantReasoningData( content=content, reasoning_id=reasoning_id, + rte=rte, ) def to_dict(self) -> dict: result: dict = {} result["content"] = from_str(self.content) result["reasoningId"] = from_str(self.reasoning_id) + if self.rte is not None: + result["rte"] = from_union([from_none, from_bool], self.rte) return result @@ -1722,6 +1818,7 @@ class AssistantUsageData: finish_reason: str | None = None initiator: str | None = None input_tokens: int | None = None + interaction_type: str | None = None inter_token_latency: timedelta | None = None output_tokens: int | None = None # Deprecated: this field is deprecated. @@ -1731,6 +1828,7 @@ class AssistantUsageData: _quota_snapshots: dict[str, _AssistantUsageQuotaSnapshot] | None = None reasoning_effort: str | None = None reasoning_tokens: int | None = None + rte: bool | None = None service_request_id: str | None = None time_to_first_token: timedelta | None = None @@ -1750,6 +1848,7 @@ def from_dict(obj: Any) -> "AssistantUsageData": finish_reason = from_union([from_none, from_str], obj.get("finishReason")) initiator = from_union([from_none, from_str], obj.get("initiator")) input_tokens = from_union([from_none, from_int], obj.get("inputTokens")) + interaction_type = from_union([from_none, from_str], obj.get("interactionType")) inter_token_latency = from_union([from_none, from_timedelta], obj.get("interTokenLatencyMs")) output_tokens = from_union([from_none, from_int], obj.get("outputTokens")) parent_tool_call_id = from_union([from_none, from_str], obj.get("parentToolCallId")) @@ -1757,6 +1856,7 @@ def from_dict(obj: Any) -> "AssistantUsageData": _quota_snapshots = from_union([from_none, lambda x: from_dict(_AssistantUsageQuotaSnapshot.from_dict, x)], obj.get("quotaSnapshots")) reasoning_effort = from_union([from_none, from_str], obj.get("reasoningEffort")) reasoning_tokens = from_union([from_none, from_int], obj.get("reasoningTokens")) + rte = from_union([from_none, from_bool], obj.get("rte")) service_request_id = from_union([from_none, from_str], obj.get("serviceRequestId")) time_to_first_token = from_union([from_none, from_timedelta], obj.get("timeToFirstTokenMs")) return AssistantUsageData( @@ -1773,6 +1873,7 @@ def from_dict(obj: Any) -> "AssistantUsageData": finish_reason=finish_reason, initiator=initiator, input_tokens=input_tokens, + interaction_type=interaction_type, inter_token_latency=inter_token_latency, output_tokens=output_tokens, parent_tool_call_id=parent_tool_call_id, @@ -1780,6 +1881,7 @@ def from_dict(obj: Any) -> "AssistantUsageData": _quota_snapshots=_quota_snapshots, reasoning_effort=reasoning_effort, reasoning_tokens=reasoning_tokens, + rte=rte, service_request_id=service_request_id, time_to_first_token=time_to_first_token, ) @@ -1811,6 +1913,8 @@ def to_dict(self) -> dict: result["initiator"] = from_union([from_none, from_str], self.initiator) if self.input_tokens is not None: result["inputTokens"] = from_union([from_none, to_int], self.input_tokens) + if self.interaction_type is not None: + result["interactionType"] = from_union([from_none, from_str], self.interaction_type) if self.inter_token_latency is not None: result["interTokenLatencyMs"] = from_union([from_none, to_timedelta], self.inter_token_latency) if self.output_tokens is not None: @@ -1825,6 +1929,8 @@ def to_dict(self) -> dict: result["reasoningEffort"] = from_union([from_none, from_str], self.reasoning_effort) if self.reasoning_tokens is not None: result["reasoningTokens"] = from_union([from_none, to_int], self.reasoning_tokens) + if self.rte is not None: + result["rte"] = from_union([from_none, from_bool], self.rte) if self.service_request_id is not None: result["serviceRequestId"] = from_union([from_none, from_str], self.service_request_id) if self.time_to_first_token is not None: @@ -3956,6 +4062,7 @@ class ModelCallFailureData: _quota_snapshots: dict[str, _AssistantUsageQuotaSnapshot] | None = None reasoning_effort: str | None = None request_fingerprint: ModelCallFailureRequestFingerprint | None = None + rte: bool | None = None service_request_id: str | None = None status_code: int | None = None transport: ModelCallFailureTransport | None = None @@ -3982,6 +4089,7 @@ def from_dict(obj: Any) -> "ModelCallFailureData": _quota_snapshots = from_union([from_none, lambda x: from_dict(_AssistantUsageQuotaSnapshot.from_dict, x)], obj.get("quotaSnapshots")) reasoning_effort = from_union([from_none, from_str], obj.get("reasoningEffort")) request_fingerprint = from_union([from_none, ModelCallFailureRequestFingerprint.from_dict], obj.get("requestFingerprint")) + rte = from_union([from_none, from_bool], obj.get("rte")) service_request_id = from_union([from_none, from_str], obj.get("serviceRequestId")) status_code = from_union([from_none, from_int], obj.get("statusCode")) transport = from_union([from_none, lambda x: parse_enum(ModelCallFailureTransport, x)], obj.get("transport")) @@ -4005,6 +4113,7 @@ def from_dict(obj: Any) -> "ModelCallFailureData": _quota_snapshots=_quota_snapshots, reasoning_effort=reasoning_effort, request_fingerprint=request_fingerprint, + rte=rte, service_request_id=service_request_id, status_code=status_code, transport=transport, @@ -4049,6 +4158,8 @@ def to_dict(self) -> dict: result["reasoningEffort"] = from_union([from_none, from_str], self.reasoning_effort) if self.request_fingerprint is not None: result["requestFingerprint"] = from_union([from_none, lambda x: to_class(ModelCallFailureRequestFingerprint, x)], self.request_fingerprint) + if self.rte is not None: + result["rte"] = from_union([from_none, from_bool], self.rte) if self.service_request_id is not None: result["serviceRequestId"] = from_union([from_none, from_str], self.service_request_id) if self.status_code is not None: @@ -4107,15 +4218,19 @@ class ModelCallStartData: "Model API dispatch metadata for internal telemetry" turn_id: str model: str | None = None + # Internal: this field is an internal SDK API and is not part of the public surface. + _previous_response_id: str | None = None @staticmethod def from_dict(obj: Any) -> "ModelCallStartData": assert isinstance(obj, dict) turn_id = from_str(obj.get("turnId")) model = from_union([from_none, from_str], obj.get("model")) + _previous_response_id = from_union([from_none, from_str], obj.get("previousResponseId")) return ModelCallStartData( turn_id=turn_id, model=model, + _previous_response_id=_previous_response_id, ) def to_dict(self) -> dict: @@ -4123,6 +4238,8 @@ def to_dict(self) -> dict: result["turnId"] = from_str(self.turn_id) if self.model is not None: result["model"] = from_union([from_none, from_str], self.model) + if self._previous_response_id is not None: + result["previousResponseId"] = from_union([from_none, from_str], self._previous_response_id) return result @@ -4378,6 +4495,7 @@ class PermissionPromptRequestCommands: kind: ClassVar[str] = "commands" # Experimental: this field is part of an experimental API and may change or be removed. auto_approval: PermissionAutoApproval | None = None + managed_approval_required: bool | None = None tool_call_id: str | None = None warning: str | None = None @@ -4389,6 +4507,7 @@ def from_dict(obj: Any) -> "PermissionPromptRequestCommands": full_command_text = from_str(obj.get("fullCommandText")) intention = from_str(obj.get("intention")) auto_approval = from_union([from_none, PermissionAutoApproval.from_dict], obj.get("autoApproval")) + managed_approval_required = from_union([from_none, from_bool], obj.get("managedApprovalRequired")) tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) warning = from_union([from_none, from_str], obj.get("warning")) return PermissionPromptRequestCommands( @@ -4397,6 +4516,7 @@ def from_dict(obj: Any) -> "PermissionPromptRequestCommands": full_command_text=full_command_text, intention=intention, auto_approval=auto_approval, + managed_approval_required=managed_approval_required, tool_call_id=tool_call_id, warning=warning, ) @@ -4410,6 +4530,8 @@ def to_dict(self) -> dict: result["kind"] = self.kind if self.auto_approval is not None: result["autoApproval"] = from_union([from_none, lambda x: to_class(PermissionAutoApproval, x)], self.auto_approval) + if self.managed_approval_required is not None: + result["managedApprovalRequired"] = from_union([from_none, from_bool], self.managed_approval_required) if self.tool_call_id is not None: result["toolCallId"] = from_union([from_none, from_str], self.tool_call_id) if self.warning is not None: @@ -4719,6 +4841,7 @@ class PermissionPromptRequestRead: path: str # Experimental: this field is part of an experimental API and may change or be removed. auto_approval: PermissionAutoApproval | None = None + managed_approval_required: bool | None = None tool_call_id: str | None = None @staticmethod @@ -4727,11 +4850,13 @@ def from_dict(obj: Any) -> "PermissionPromptRequestRead": intention = from_str(obj.get("intention")) path = from_str(obj.get("path")) auto_approval = from_union([from_none, PermissionAutoApproval.from_dict], obj.get("autoApproval")) + managed_approval_required = from_union([from_none, from_bool], obj.get("managedApprovalRequired")) tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) return PermissionPromptRequestRead( intention=intention, path=path, auto_approval=auto_approval, + managed_approval_required=managed_approval_required, tool_call_id=tool_call_id, ) @@ -4742,6 +4867,8 @@ def to_dict(self) -> dict: result["path"] = from_str(self.path) if self.auto_approval is not None: result["autoApproval"] = from_union([from_none, lambda x: to_class(PermissionAutoApproval, x)], self.auto_approval) + if self.managed_approval_required is not None: + result["managedApprovalRequired"] = from_union([from_none, from_bool], self.managed_approval_required) if self.tool_call_id is not None: result["toolCallId"] = from_union([from_none, from_str], self.tool_call_id) return result @@ -4755,6 +4882,8 @@ class PermissionPromptRequestUrl: url: str # Experimental: this field is part of an experimental API and may change or be removed. auto_approval: PermissionAutoApproval | None = None + managed_approval_required: bool | None = None + redirected_from: str | None = None request_sandbox_bypass: bool | None = None request_sandbox_bypass_reason: str | None = None tool_call_id: str | None = None @@ -4765,6 +4894,8 @@ def from_dict(obj: Any) -> "PermissionPromptRequestUrl": intention = from_str(obj.get("intention")) url = from_str(obj.get("url")) auto_approval = from_union([from_none, PermissionAutoApproval.from_dict], obj.get("autoApproval")) + managed_approval_required = from_union([from_none, from_bool], obj.get("managedApprovalRequired")) + redirected_from = from_union([from_none, from_str], obj.get("redirectedFrom")) request_sandbox_bypass = from_union([from_none, from_bool], obj.get("requestSandboxBypass")) request_sandbox_bypass_reason = from_union([from_none, from_str], obj.get("requestSandboxBypassReason")) tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) @@ -4772,6 +4903,8 @@ def from_dict(obj: Any) -> "PermissionPromptRequestUrl": intention=intention, url=url, auto_approval=auto_approval, + managed_approval_required=managed_approval_required, + redirected_from=redirected_from, request_sandbox_bypass=request_sandbox_bypass, request_sandbox_bypass_reason=request_sandbox_bypass_reason, tool_call_id=tool_call_id, @@ -4784,6 +4917,10 @@ def to_dict(self) -> dict: result["url"] = from_str(self.url) if self.auto_approval is not None: result["autoApproval"] = from_union([from_none, lambda x: to_class(PermissionAutoApproval, x)], self.auto_approval) + if self.managed_approval_required is not None: + result["managedApprovalRequired"] = from_union([from_none, from_bool], self.managed_approval_required) + if self.redirected_from is not None: + result["redirectedFrom"] = from_union([from_none, from_str], self.redirected_from) if self.request_sandbox_bypass is not None: result["requestSandboxBypass"] = from_union([from_none, from_bool], self.request_sandbox_bypass) if self.request_sandbox_bypass_reason is not None: @@ -4803,6 +4940,7 @@ class PermissionPromptRequestWrite: kind: ClassVar[str] = "write" # Experimental: this field is part of an experimental API and may change or be removed. auto_approval: PermissionAutoApproval | None = None + managed_approval_required: bool | None = None new_file_contents: str | None = None tool_call_id: str | None = None @@ -4814,6 +4952,7 @@ def from_dict(obj: Any) -> "PermissionPromptRequestWrite": file_name = from_str(obj.get("fileName")) intention = from_str(obj.get("intention")) auto_approval = from_union([from_none, PermissionAutoApproval.from_dict], obj.get("autoApproval")) + managed_approval_required = from_union([from_none, from_bool], obj.get("managedApprovalRequired")) new_file_contents = from_union([from_none, from_str], obj.get("newFileContents")) tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) return PermissionPromptRequestWrite( @@ -4822,6 +4961,7 @@ def from_dict(obj: Any) -> "PermissionPromptRequestWrite": file_name=file_name, intention=intention, auto_approval=auto_approval, + managed_approval_required=managed_approval_required, new_file_contents=new_file_contents, tool_call_id=tool_call_id, ) @@ -4835,6 +4975,8 @@ def to_dict(self) -> dict: result["kind"] = self.kind if self.auto_approval is not None: result["autoApproval"] = from_union([from_none, lambda x: to_class(PermissionAutoApproval, x)], self.auto_approval) + if self.managed_approval_required is not None: + result["managedApprovalRequired"] = from_union([from_none, from_bool], self.managed_approval_required) if self.new_file_contents is not None: result["newFileContents"] = from_union([from_none, from_str], self.new_file_contents) if self.tool_call_id is not None: @@ -5074,6 +5216,7 @@ class PermissionRequestRead: intention: str kind: ClassVar[str] = "read" path: str + managed_approval_required: bool | None = None request_sandbox_bypass: bool | None = None request_sandbox_bypass_reason: str | None = None tool_call_id: str | None = None @@ -5083,12 +5226,14 @@ def from_dict(obj: Any) -> "PermissionRequestRead": assert isinstance(obj, dict) intention = from_str(obj.get("intention")) path = from_str(obj.get("path")) + managed_approval_required = from_union([from_none, from_bool], obj.get("managedApprovalRequired")) request_sandbox_bypass = from_union([from_none, from_bool], obj.get("requestSandboxBypass")) request_sandbox_bypass_reason = from_union([from_none, from_str], obj.get("requestSandboxBypassReason")) tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) return PermissionRequestRead( intention=intention, path=path, + managed_approval_required=managed_approval_required, request_sandbox_bypass=request_sandbox_bypass, request_sandbox_bypass_reason=request_sandbox_bypass_reason, tool_call_id=tool_call_id, @@ -5099,6 +5244,8 @@ def to_dict(self) -> dict: result["intention"] = from_str(self.intention) result["kind"] = self.kind result["path"] = from_str(self.path) + if self.managed_approval_required is not None: + result["managedApprovalRequired"] = from_union([from_none, from_bool], self.managed_approval_required) if self.request_sandbox_bypass is not None: result["requestSandboxBypass"] = from_union([from_none, from_bool], self.request_sandbox_bypass) if self.request_sandbox_bypass_reason is not None: @@ -5119,6 +5266,8 @@ class PermissionRequestShell: kind: ClassVar[str] = "shell" possible_paths: list[str] possible_urls: list[PermissionRequestShellPossibleUrl] + command_segments: list[PermissionRequestShellCommandSegment] | None = None + managed_approval_required: bool | None = None request_sandbox_bypass: bool | None = None request_sandbox_bypass_reason: str | None = None tool_call_id: str | None = None @@ -5134,6 +5283,8 @@ def from_dict(obj: Any) -> "PermissionRequestShell": intention = from_str(obj.get("intention")) possible_paths = from_list(from_str, obj.get("possiblePaths")) possible_urls = from_list(PermissionRequestShellPossibleUrl.from_dict, obj.get("possibleUrls")) + command_segments = from_union([from_none, lambda x: from_list(PermissionRequestShellCommandSegment.from_dict, x)], obj.get("commandSegments")) + managed_approval_required = from_union([from_none, from_bool], obj.get("managedApprovalRequired")) request_sandbox_bypass = from_union([from_none, from_bool], obj.get("requestSandboxBypass")) request_sandbox_bypass_reason = from_union([from_none, from_str], obj.get("requestSandboxBypassReason")) tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) @@ -5146,6 +5297,8 @@ def from_dict(obj: Any) -> "PermissionRequestShell": intention=intention, possible_paths=possible_paths, possible_urls=possible_urls, + command_segments=command_segments, + managed_approval_required=managed_approval_required, request_sandbox_bypass=request_sandbox_bypass, request_sandbox_bypass_reason=request_sandbox_bypass_reason, tool_call_id=tool_call_id, @@ -5162,6 +5315,10 @@ def to_dict(self) -> dict: result["kind"] = self.kind result["possiblePaths"] = from_list(from_str, self.possible_paths) result["possibleUrls"] = from_list(lambda x: to_class(PermissionRequestShellPossibleUrl, x), self.possible_urls) + if self.command_segments is not None: + result["commandSegments"] = from_union([from_none, lambda x: from_list(lambda x: to_class(PermissionRequestShellCommandSegment, x), x)], self.command_segments) + if self.managed_approval_required is not None: + result["managedApprovalRequired"] = from_union([from_none, from_bool], self.managed_approval_required) if self.request_sandbox_bypass is not None: result["requestSandboxBypass"] = from_union([from_none, from_bool], self.request_sandbox_bypass) if self.request_sandbox_bypass_reason is not None: @@ -5196,6 +5353,29 @@ def to_dict(self) -> dict: return result +@dataclass +class PermissionRequestShellCommandSegment: + "A parsed shell command segment used for argument-aware managed policy matching." + full_command_text: str + identifier: str + + @staticmethod + def from_dict(obj: Any) -> "PermissionRequestShellCommandSegment": + assert isinstance(obj, dict) + full_command_text = from_str(obj.get("fullCommandText")) + identifier = from_str(obj.get("identifier")) + return PermissionRequestShellCommandSegment( + full_command_text=full_command_text, + identifier=identifier, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["fullCommandText"] = from_str(self.full_command_text) + result["identifier"] = from_str(self.identifier) + return result + + @dataclass class PermissionRequestShellPossibleUrl: "A URL that may be accessed by a command in a shell permission request." @@ -5221,6 +5401,8 @@ class PermissionRequestUrl: intention: str kind: ClassVar[str] = "url" url: str + managed_approval_required: bool | None = None + redirected_from: str | None = None request_sandbox_bypass: bool | None = None request_sandbox_bypass_reason: str | None = None tool_call_id: str | None = None @@ -5230,12 +5412,16 @@ def from_dict(obj: Any) -> "PermissionRequestUrl": assert isinstance(obj, dict) intention = from_str(obj.get("intention")) url = from_str(obj.get("url")) + managed_approval_required = from_union([from_none, from_bool], obj.get("managedApprovalRequired")) + redirected_from = from_union([from_none, from_str], obj.get("redirectedFrom")) request_sandbox_bypass = from_union([from_none, from_bool], obj.get("requestSandboxBypass")) request_sandbox_bypass_reason = from_union([from_none, from_str], obj.get("requestSandboxBypassReason")) tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) return PermissionRequestUrl( intention=intention, url=url, + managed_approval_required=managed_approval_required, + redirected_from=redirected_from, request_sandbox_bypass=request_sandbox_bypass, request_sandbox_bypass_reason=request_sandbox_bypass_reason, tool_call_id=tool_call_id, @@ -5246,6 +5432,10 @@ def to_dict(self) -> dict: result["intention"] = from_str(self.intention) result["kind"] = self.kind result["url"] = from_str(self.url) + if self.managed_approval_required is not None: + result["managedApprovalRequired"] = from_union([from_none, from_bool], self.managed_approval_required) + if self.redirected_from is not None: + result["redirectedFrom"] = from_union([from_none, from_str], self.redirected_from) if self.request_sandbox_bypass is not None: result["requestSandboxBypass"] = from_union([from_none, from_bool], self.request_sandbox_bypass) if self.request_sandbox_bypass_reason is not None: @@ -5263,6 +5453,7 @@ class PermissionRequestWrite: file_name: str intention: str kind: ClassVar[str] = "write" + managed_approval_required: bool | None = None new_file_contents: str | None = None request_sandbox_bypass: bool | None = None request_sandbox_bypass_reason: str | None = None @@ -5275,6 +5466,7 @@ def from_dict(obj: Any) -> "PermissionRequestWrite": diff = from_str(obj.get("diff")) file_name = from_str(obj.get("fileName")) intention = from_str(obj.get("intention")) + managed_approval_required = from_union([from_none, from_bool], obj.get("managedApprovalRequired")) new_file_contents = from_union([from_none, from_str], obj.get("newFileContents")) request_sandbox_bypass = from_union([from_none, from_bool], obj.get("requestSandboxBypass")) request_sandbox_bypass_reason = from_union([from_none, from_str], obj.get("requestSandboxBypassReason")) @@ -5284,6 +5476,7 @@ def from_dict(obj: Any) -> "PermissionRequestWrite": diff=diff, file_name=file_name, intention=intention, + managed_approval_required=managed_approval_required, new_file_contents=new_file_contents, request_sandbox_bypass=request_sandbox_bypass, request_sandbox_bypass_reason=request_sandbox_bypass_reason, @@ -5297,6 +5490,8 @@ def to_dict(self) -> dict: result["fileName"] = from_str(self.file_name) result["intention"] = from_str(self.intention) result["kind"] = self.kind + if self.managed_approval_required is not None: + result["managedApprovalRequired"] = from_union([from_none, from_bool], self.managed_approval_required) if self.new_file_contents is not None: result["newFileContents"] = from_union([from_none, from_str], self.new_file_contents) if self.request_sandbox_bypass is not None: @@ -5315,6 +5510,7 @@ class PermissionRequestedData: request_id: str prompt_request: PermissionPromptRequest | None = None resolved_by_hook: bool | None = None + risk_assessment: Any = None @staticmethod def from_dict(obj: Any) -> "PermissionRequestedData": @@ -5323,11 +5519,13 @@ def from_dict(obj: Any) -> "PermissionRequestedData": request_id = from_str(obj.get("requestId")) prompt_request = from_union([from_none, _load_PermissionPromptRequest], obj.get("promptRequest")) resolved_by_hook = from_union([from_none, from_bool], obj.get("resolvedByHook")) + risk_assessment = obj.get("riskAssessment") return PermissionRequestedData( permission_request=permission_request, request_id=request_id, prompt_request=prompt_request, resolved_by_hook=resolved_by_hook, + risk_assessment=risk_assessment, ) def to_dict(self) -> dict: @@ -5338,6 +5536,8 @@ def to_dict(self) -> dict: result["promptRequest"] = from_union([from_none, lambda x: x.to_dict()], self.prompt_request) if self.resolved_by_hook is not None: result["resolvedByHook"] = from_union([from_none, from_bool], self.resolved_by_hook) + if self.risk_assessment is not None: + result["riskAssessment"] = self.risk_assessment return result @@ -5552,8 +5752,10 @@ class SessionCompactionCompleteData: status_code: int | None = None summary_content: str | None = None system_tokens: int | None = None + token_limit: int | None = None tokens_removed: int | None = None tool_definitions_tokens: int | None = None + trigger: CompactionTrigger | None = None @staticmethod def from_dict(obj: Any) -> "SessionCompactionCompleteData": @@ -5574,8 +5776,10 @@ def from_dict(obj: Any) -> "SessionCompactionCompleteData": status_code = from_union([from_none, from_int], obj.get("statusCode")) summary_content = from_union([from_none, from_str], obj.get("summaryContent")) system_tokens = from_union([from_none, from_int], obj.get("systemTokens")) + token_limit = from_union([from_none, from_int], obj.get("tokenLimit")) tokens_removed = from_union([from_none, from_int], obj.get("tokensRemoved")) tool_definitions_tokens = from_union([from_none, from_int], obj.get("toolDefinitionsTokens")) + trigger = from_union([from_none, lambda x: parse_enum(CompactionTrigger, x)], obj.get("trigger")) return SessionCompactionCompleteData( success=success, checkpoint_number=checkpoint_number, @@ -5593,8 +5797,10 @@ def from_dict(obj: Any) -> "SessionCompactionCompleteData": status_code=status_code, summary_content=summary_content, system_tokens=system_tokens, + token_limit=token_limit, tokens_removed=tokens_removed, tool_definitions_tokens=tool_definitions_tokens, + trigger=trigger, ) def to_dict(self) -> dict: @@ -5630,10 +5836,14 @@ def to_dict(self) -> dict: result["summaryContent"] = from_union([from_none, from_str], self.summary_content) if self.system_tokens is not None: result["systemTokens"] = from_union([from_none, to_int], self.system_tokens) + if self.token_limit is not None: + result["tokenLimit"] = from_union([from_none, to_int], self.token_limit) if self.tokens_removed is not None: result["tokensRemoved"] = from_union([from_none, to_int], self.tokens_removed) if self.tool_definitions_tokens is not None: result["toolDefinitionsTokens"] = from_union([from_none, to_int], self.tool_definitions_tokens) + if self.trigger is not None: + result["trigger"] = from_union([from_none, lambda x: to_enum(CompactionTrigger, x)], self.trigger) return result @@ -5641,34 +5851,49 @@ def to_dict(self) -> dict: class SessionCompactionStartData: "Context window breakdown at the start of LLM-powered conversation compaction" conversation_tokens: int | None = None + current_tokens: int | None = None model: str | None = None system_tokens: int | None = None + token_limit: int | None = None tool_definitions_tokens: int | None = None + trigger: CompactionTrigger | None = None @staticmethod def from_dict(obj: Any) -> "SessionCompactionStartData": assert isinstance(obj, dict) conversation_tokens = from_union([from_none, from_int], obj.get("conversationTokens")) + current_tokens = from_union([from_none, from_int], obj.get("currentTokens")) model = from_union([from_none, from_str], obj.get("model")) system_tokens = from_union([from_none, from_int], obj.get("systemTokens")) + token_limit = from_union([from_none, from_int], obj.get("tokenLimit")) tool_definitions_tokens = from_union([from_none, from_int], obj.get("toolDefinitionsTokens")) + trigger = from_union([from_none, lambda x: parse_enum(CompactionTrigger, x)], obj.get("trigger")) return SessionCompactionStartData( conversation_tokens=conversation_tokens, + current_tokens=current_tokens, model=model, system_tokens=system_tokens, + token_limit=token_limit, tool_definitions_tokens=tool_definitions_tokens, + trigger=trigger, ) def to_dict(self) -> dict: result: dict = {} if self.conversation_tokens is not None: result["conversationTokens"] = from_union([from_none, to_int], self.conversation_tokens) + if self.current_tokens is not None: + result["currentTokens"] = from_union([from_none, to_int], self.current_tokens) if self.model is not None: result["model"] = from_union([from_none, from_str], self.model) if self.system_tokens is not None: result["systemTokens"] = from_union([from_none, to_int], self.system_tokens) + if self.token_limit is not None: + result["tokenLimit"] = from_union([from_none, to_int], self.token_limit) if self.tool_definitions_tokens is not None: result["toolDefinitionsTokens"] = from_union([from_none, to_int], self.tool_definitions_tokens) + if self.trigger is not None: + result["trigger"] = from_union([from_none, lambda x: to_enum(CompactionTrigger, x)], self.trigger) return result @@ -5681,6 +5906,7 @@ class SessionContextChangedData: git_root: str | None = None head_commit: str | None = None host_type: WorkingDirectoryContextHostType | None = None + pending_git_context: bool | None = None repository: str | None = None repository_host: str | None = None @@ -5693,6 +5919,7 @@ def from_dict(obj: Any) -> "SessionContextChangedData": git_root = from_union([from_none, from_str], obj.get("gitRoot")) head_commit = from_union([from_none, from_str], obj.get("headCommit")) host_type = from_union([from_none, lambda x: parse_enum(WorkingDirectoryContextHostType, x)], obj.get("hostType")) + pending_git_context = from_union([from_none, from_bool], obj.get("pendingGitContext")) repository = from_union([from_none, from_str], obj.get("repository")) repository_host = from_union([from_none, from_str], obj.get("repositoryHost")) return SessionContextChangedData( @@ -5702,6 +5929,7 @@ def from_dict(obj: Any) -> "SessionContextChangedData": git_root=git_root, head_commit=head_commit, host_type=host_type, + pending_git_context=pending_git_context, repository=repository, repository_host=repository_host, ) @@ -5719,6 +5947,8 @@ def to_dict(self) -> dict: result["headCommit"] = from_union([from_none, from_str], self.head_commit) if self.host_type is not None: result["hostType"] = from_union([from_none, lambda x: to_enum(WorkingDirectoryContextHostType, x)], self.host_type) + if self.pending_git_context is not None: + result["pendingGitContext"] = from_union([from_none, from_bool], self.pending_git_context) if self.repository is not None: result["repository"] = from_union([from_none, from_str], self.repository) if self.repository_host is not None: @@ -6404,6 +6634,7 @@ class SessionScheduleCreatedData: cron: str | None = None display_prompt: str | None = None interval: timedelta | None = None + origin: ScheduleOrigin | None = None recurring: bool | None = None self_paced: bool | None = None tz: str | None = None @@ -6417,6 +6648,7 @@ def from_dict(obj: Any) -> "SessionScheduleCreatedData": cron = from_union([from_none, from_str], obj.get("cron")) display_prompt = from_union([from_none, from_str], obj.get("displayPrompt")) interval = from_union([from_none, from_timedelta], obj.get("intervalMs")) + origin = from_union([from_none, lambda x: parse_enum(ScheduleOrigin, x)], obj.get("origin")) recurring = from_union([from_none, from_bool], obj.get("recurring")) self_paced = from_union([from_none, from_bool], obj.get("selfPaced")) tz = from_union([from_none, from_str], obj.get("tz")) @@ -6427,6 +6659,7 @@ def from_dict(obj: Any) -> "SessionScheduleCreatedData": cron=cron, display_prompt=display_prompt, interval=interval, + origin=origin, recurring=recurring, self_paced=self_paced, tz=tz, @@ -6444,6 +6677,8 @@ def to_dict(self) -> dict: result["displayPrompt"] = from_union([from_none, from_str], self.display_prompt) if self.interval is not None: result["intervalMs"] = from_union([from_none, to_timedelta_int], self.interval) + if self.origin is not None: + result["origin"] = from_union([from_none, lambda x: to_enum(ScheduleOrigin, x)], self.origin) if self.recurring is not None: result["recurring"] = from_union([from_none, from_bool], self.recurring) if self.self_paced is not None: @@ -6712,21 +6947,36 @@ def to_dict(self) -> dict: @dataclass class SessionTaskCompleteData: "Task completion notification with summary from the agent" + objective_id: int | None = None + outcome: TaskCompletionOutcome | None = None + reason: str | None = None success: bool | None = None summary: str | None = None @staticmethod def from_dict(obj: Any) -> "SessionTaskCompleteData": assert isinstance(obj, dict) + objective_id = from_union([from_none, from_int], obj.get("objectiveId")) + outcome = from_union([from_none, lambda x: parse_enum(TaskCompletionOutcome, x)], obj.get("outcome")) + reason = from_union([from_none, from_str], obj.get("reason")) success = from_union([from_none, from_bool], obj.get("success")) summary = from_union([from_none, from_str], obj.get("summary")) return SessionTaskCompleteData( + objective_id=objective_id, + outcome=outcome, + reason=reason, success=success, summary=summary, ) def to_dict(self) -> dict: result: dict = {} + if self.objective_id is not None: + result["objectiveId"] = from_union([from_none, to_int], self.objective_id) + if self.outcome is not None: + result["outcome"] = from_union([from_none, lambda x: to_enum(TaskCompletionOutcome, x)], self.outcome) + if self.reason is not None: + result["reason"] = from_union([from_none, from_str], self.reason) if self.success is not None: result["success"] = from_union([from_none, from_bool], self.success) if self.summary is not None: @@ -7407,6 +7657,7 @@ class SystemMessageData: "System/developer instruction content with role and optional template metadata" content: str role: SystemMessageRole + interaction_id: str | None = None metadata: SystemMessageMetadata | None = None name: str | None = None @@ -7415,11 +7666,13 @@ def from_dict(obj: Any) -> "SystemMessageData": assert isinstance(obj, dict) content = from_str(obj.get("content")) role = parse_enum(SystemMessageRole, obj.get("role")) + interaction_id = from_union([from_none, from_str], obj.get("interactionId")) metadata = from_union([from_none, SystemMessageMetadata.from_dict], obj.get("metadata")) name = from_union([from_none, from_str], obj.get("name")) return SystemMessageData( content=content, role=role, + interaction_id=interaction_id, metadata=metadata, name=name, ) @@ -7428,6 +7681,8 @@ def to_dict(self) -> dict: result: dict = {} result["content"] = from_str(self.content) result["role"] = to_enum(SystemMessageRole, self.role) + if self.interaction_id is not None: + result["interactionId"] = from_union([from_none, from_str], self.interaction_id) if self.metadata is not None: result["metadata"] = from_union([from_none, lambda x: to_class(SystemMessageMetadata, x)], self.metadata) if self.name is not None: @@ -7676,6 +7931,28 @@ def to_dict(self) -> dict: return result +@dataclass +class SystemNotificationUnclassified: + "System notification metadata from an external host that does not match a runtime-owned notification kind." + type: ClassVar[str] = "unclassified" + metadata: Any = None + + @staticmethod + def from_dict(obj: Any) -> "SystemNotificationUnclassified": + assert isinstance(obj, dict) + metadata = obj.get("metadata") + return SystemNotificationUnclassified( + metadata=metadata, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["type"] = self.type + if self.metadata is not None: + result["metadata"] = self.metadata + return result + + @dataclass class ToolExecutionCompleteContentAudio: "Audio content block with base64-encoded data" @@ -7906,6 +8183,7 @@ class ToolExecutionCompleteData: # Deprecated: this field is deprecated. parent_tool_call_id: str | None = None result: ToolExecutionCompleteResult | None = None + rte: bool | None = None sandboxed: bool | None = None tool_description: ToolExecutionCompleteToolDescription | None = None tool_telemetry: dict[str, Any] | None = None @@ -7923,6 +8201,7 @@ def from_dict(obj: Any) -> "ToolExecutionCompleteData": model = from_union([from_none, from_str], obj.get("model")) parent_tool_call_id = from_union([from_none, from_str], obj.get("parentToolCallId")) result = from_union([from_none, ToolExecutionCompleteResult.from_dict], obj.get("result")) + rte = from_union([from_none, from_bool], obj.get("rte")) sandboxed = from_union([from_none, from_bool], obj.get("sandboxed")) tool_description = from_union([from_none, ToolExecutionCompleteToolDescription.from_dict], obj.get("toolDescription")) tool_telemetry = from_union([from_none, lambda x: from_dict(lambda x: x, x)], obj.get("toolTelemetry")) @@ -7937,6 +8216,7 @@ def from_dict(obj: Any) -> "ToolExecutionCompleteData": model=model, parent_tool_call_id=parent_tool_call_id, result=result, + rte=rte, sandboxed=sandboxed, tool_description=tool_description, tool_telemetry=tool_telemetry, @@ -7961,6 +8241,8 @@ def to_dict(self) -> dict: result["parentToolCallId"] = from_union([from_none, from_str], self.parent_tool_call_id) if self.result is not None: result["result"] = from_union([from_none, lambda x: to_class(ToolExecutionCompleteResult, x)], self.result) + if self.rte is not None: + result["rte"] = from_union([from_none, from_bool], self.rte) if self.sandboxed is not None: result["sandboxed"] = from_union([from_none, from_bool], self.sandboxed) if self.tool_description is not None: @@ -8396,6 +8678,7 @@ class ToolExecutionStartData: model: str | None = None # Deprecated: this field is deprecated. parent_tool_call_id: str | None = None + rte: bool | None = None shell_tool_info: ToolExecutionStartShellToolInfo | None = None tool_description: ToolExecutionStartToolDescription | None = None turn_id: str | None = None @@ -8411,6 +8694,7 @@ def from_dict(obj: Any) -> "ToolExecutionStartData": mcp_tool_name = from_union([from_none, from_str], obj.get("mcpToolName")) model = from_union([from_none, from_str], obj.get("model")) parent_tool_call_id = from_union([from_none, from_str], obj.get("parentToolCallId")) + rte = from_union([from_none, from_bool], obj.get("rte")) shell_tool_info = from_union([from_none, ToolExecutionStartShellToolInfo.from_dict], obj.get("shellToolInfo")) tool_description = from_union([from_none, ToolExecutionStartToolDescription.from_dict], obj.get("toolDescription")) turn_id = from_union([from_none, from_str], obj.get("turnId")) @@ -8423,6 +8707,7 @@ def from_dict(obj: Any) -> "ToolExecutionStartData": mcp_tool_name=mcp_tool_name, model=model, parent_tool_call_id=parent_tool_call_id, + rte=rte, shell_tool_info=shell_tool_info, tool_description=tool_description, turn_id=turn_id, @@ -8444,6 +8729,8 @@ def to_dict(self) -> dict: result["model"] = from_union([from_none, from_str], self.model) if self.parent_tool_call_id is not None: result["parentToolCallId"] = from_union([from_none, from_str], self.parent_tool_call_id) + if self.rte is not None: + result["rte"] = from_union([from_none, from_bool], self.rte) if self.shell_tool_info is not None: result["shellToolInfo"] = from_union([from_none, lambda x: to_class(ToolExecutionStartShellToolInfo, x)], self.shell_tool_info) if self.tool_description is not None: @@ -8935,6 +9222,7 @@ class WorkingDirectoryContext: git_root: str | None = None head_commit: str | None = None host_type: WorkingDirectoryContextHostType | None = None + pending_git_context: bool | None = None repository: str | None = None repository_host: str | None = None @@ -8947,6 +9235,7 @@ def from_dict(obj: Any) -> "WorkingDirectoryContext": git_root = from_union([from_none, from_str], obj.get("gitRoot")) head_commit = from_union([from_none, from_str], obj.get("headCommit")) host_type = from_union([from_none, lambda x: parse_enum(WorkingDirectoryContextHostType, x)], obj.get("hostType")) + pending_git_context = from_union([from_none, from_bool], obj.get("pendingGitContext")) repository = from_union([from_none, from_str], obj.get("repository")) repository_host = from_union([from_none, from_str], obj.get("repositoryHost")) return WorkingDirectoryContext( @@ -8956,6 +9245,7 @@ def from_dict(obj: Any) -> "WorkingDirectoryContext": git_root=git_root, head_commit=head_commit, host_type=host_type, + pending_git_context=pending_git_context, repository=repository, repository_host=repository_host, ) @@ -8973,6 +9263,8 @@ def to_dict(self) -> dict: result["headCommit"] = from_union([from_none, from_str], self.head_commit) if self.host_type is not None: result["hostType"] = from_union([from_none, lambda x: to_enum(WorkingDirectoryContextHostType, x)], self.host_type) + if self.pending_git_context is not None: + result["pendingGitContext"] = from_union([from_none, from_bool], self.pending_git_context) if self.repository is not None: result["repository"] = from_union([from_none, from_str], self.repository) if self.repository_host is not None: @@ -9073,6 +9365,7 @@ def _load_SystemNotification(obj: Any) -> "SystemNotification": case "shell_completed": return SystemNotificationShellCompleted.from_dict(obj) case "shell_detached_completed": return SystemNotificationShellDetachedCompleted.from_dict(obj) case "instruction_discovered": return SystemNotificationInstructionDiscovered.from_dict(obj) + case "unclassified": return SystemNotificationUnclassified.from_dict(obj) case _: raise ValueError(f"Unknown SystemNotification type: {kind!r}") @@ -9130,7 +9423,7 @@ def _load_UserToolSessionApproval(obj: Any) -> "UserToolSessionApproval": # Structured metadata identifying what triggered this notification -SystemNotification = SystemNotificationAgentCompleted | SystemNotificationAgentIdle | SystemNotificationNewInboxMessage | SystemNotificationShellCompleted | SystemNotificationShellDetachedCompleted | SystemNotificationInstructionDiscovered +SystemNotification = SystemNotificationAgentCompleted | SystemNotificationAgentIdle | SystemNotificationNewInboxMessage | SystemNotificationShellCompleted | SystemNotificationShellDetachedCompleted | SystemNotificationInstructionDiscovered | SystemNotificationUnclassified # The approval to add as a session-scoped rule @@ -9145,6 +9438,21 @@ def _load_UserToolSessionApproval(obj: Any) -> "UserToolSessionApproval": PermissionResult = PermissionApproved | PermissionApprovedForSession | PermissionApprovedForLocation | PermissionCancelled | PermissionDeniedByRules | PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser | PermissionDeniedInteractivelyByUser | PermissionDeniedByContentExclusionPolicy | PermissionDeniedByPermissionRequestHook +# Experimental: this enum is part of an experimental API and may change or be removed. +class AutoApprovalJudgeFailureReason(Enum): + "Why the auto-approval judge produced no usable recommendation. Present only alongside an `error` recommendation, where the human-readable reason is a fixed string and therefore cannot distinguish these cases. Intended to make a judge failure reportable by a consumer that has no access to the host's logs." + # The judge model call exceeded its deadline. + TIMEOUT = "timeout" + # The judge model call was cancelled before it returned. + ABORT = "abort" + # The judge model call completed but returned no content. + EMPTY_RESPONSE = "empty_response" + # The judge model call failed (for example a transport, authentication, or rate-limit error). + MODEL_ERROR = "model_error" + # The judge model replied, but the reply carried no ALLOW/DENY verdict. + PARSE_ERROR = "parse_error" + + # Experimental: this enum is part of an experimental API and may change or be removed. class AutoApprovalRecommendation(Enum): "Outcome of the auto-approval safety judge for a permission request. Present only when auto mode is enabled; its absence means the judge did not evaluate the request (auto mode was off)." @@ -9278,6 +9586,20 @@ class BinaryAssetType(Enum): RESOURCE = "resource" +class CompactionTrigger(Enum): + "What initiated a conversation compaction" + # Background compaction started automatically because context utilization crossed the background threshold. + THRESHOLD = "threshold" + # Compaction forced by a context-limit model response (e.g. HTTP 413) before retrying the request. + CONTEXT_LIMIT_RETRY = "context_limit_retry" + # User-requested compaction, e.g. the /compact command or the history.compact API. + MANUAL = "manual" + # Emergency compaction triggered by high process memory usage. + MEMORY_PRESSURE = "memory_pressure" + # Compaction requested while switching to a model with a smaller context window. + MODEL_SWITCH = "model_switch" + + class ContextTier(Enum): "Allowed values for the `ContextTier` enumeration." # Default context tier with standard context window size. @@ -9562,6 +9884,14 @@ class ReasoningSummary(Enum): DETAILED = "detailed" +class ScheduleOrigin(Enum): + "Who created the schedule: `user` (an explicit user action such as `/every` or `/after`) or `model` (the agent via the `manage_schedule` tool). Gates whether a scheduled skill that opted out of model invocation may fire: only user-created schedules may." + # The schedule was created by an explicit user action, such as `/every` or `/after`. + USER = "user" + # The schedule was created by the agent via the `manage_schedule` tool. + MODEL = "model" + + class SessionLimitsExhaustedResponseAction(Enum): "User action selected for an exhausted session limit." # Increase the current max by an exact AI Credits amount. @@ -9636,6 +9966,16 @@ class SystemNotificationAgentCompletedStatus(Enum): FAILED = "failed" +class TaskCompletionOutcome(Enum): + "Semantic result of evaluating a task completion request" + # The completion request was accepted and the objective is complete. + COMPLETED = "completed" + # The completion request was rejected because more work or validation remains. + CONTINUE = "continue" + # Completion cannot proceed without intervention; the active objective is paused when one is identified. + BLOCKED = "blocked" + + class ToolExecutionCompleteContentResourceLinkIconTheme(Enum): "Theme variant this icon is intended for" # Icon intended for light themes. @@ -9708,7 +10048,7 @@ class WorkspaceFileChangedOperation(Enum): UPDATE = "update" -SessionEventData = SessionStartData | SessionResumeData | SessionRemoteSteerableChangedData | SessionErrorData | SessionIdleData | SessionTitleChangedData | SessionScheduleCreatedData | SessionScheduleCancelledData | SessionScheduleRearmedData | SessionAutopilotObjectiveChangedData | SessionInfoData | SessionWarningData | SessionModelChangeData | SessionModeChangedData | SessionSessionLimitsChangedData | SessionPermissionsChangedData | SessionPlanChangedData | SessionTodosChangedData | SessionWorkspaceFileChangedData | SessionHandoffData | SessionTruncationData | SessionSnapshotRewindData | SessionShutdownData | SessionUsageCheckpointData | SessionContextChangedData | SessionUsageInfoData | SessionCompactionStartData | SessionCompactionCompleteData | SessionTaskCompleteData | UserMessageData | PendingMessagesModifiedData | AssistantTurnStartData | AssistantTurnRetryData | AssistantIntentData | AssistantServerToolProgressData | AssistantReasoningData | AssistantReasoningDeltaData | AssistantToolCallDeltaData | AssistantStreamingDeltaData | AssistantMessageData | AssistantMessageStartData | AssistantMessageDeltaData | AssistantTurnEndData | AssistantIdleData | AssistantUsageData | ModelCallFailureData | ModelCallStartData | AbortData | ToolUserRequestedData | ToolExecutionStartData | ToolExecutionPartialResultData | ToolExecutionProgressData | ToolExecutionCompleteData | ToolSearchActivatedData | SkillInvokedData | SubagentStartedData | SubagentCompletedData | SubagentFailedData | SubagentSelectedData | SubagentDeselectedData | HookStartData | HookEndData | HookProgressData | SessionBinaryAssetData | SystemMessageData | SystemNotificationData | PermissionRequestedData | PermissionCompletedData | UserInputRequestedData | UserInputCompletedData | ElicitationRequestedData | ElicitationCompletedData | SamplingRequestedData | SamplingCompletedData | McpOauthRequiredData | McpOauthCompletedData | McpHeadersRefreshRequiredData | McpHeadersRefreshCompletedData | SessionCustomNotificationData | ExternalToolRequestedData | ExternalToolCompletedData | CommandQueuedData | CommandExecuteData | CommandCompletedData | AutoModeSwitchRequestedData | AutoModeSwitchCompletedData | SessionLimitsExhaustedRequestedData | SessionLimitsExhaustedCompletedData | SessionAutoModeResolvedData | SessionManagedSettingsResolvedData | SessionManagedSettingsEnforcedData | CommandsChangedData | CapabilitiesChangedData | ExitPlanModeRequestedData | ExitPlanModeCompletedData | SessionToolsUpdatedData | SessionBackgroundTasksChangedData | SessionSkillsLoadedData | SessionCustomAgentsUpdatedData | SessionMcpServersLoadedData | SessionMcpServerStatusChangedData | McpToolsListChangedData | McpResourcesListChangedData | McpPromptsListChangedData | SessionExtensionsLoadedData | SessionCanvasOpenedData | SessionCanvasRegistryChangedData | SessionCanvasClosedData | SessionCanvasUnavailableData | SessionCanvasRecordedData | SessionCanvasRemovedData | SessionExtensionsAttachmentsPushedData | McpAppToolCallCompleteData | RawSessionEventData | Data +SessionEventData = SessionStartData | SessionResumeData | SessionRemoteSteerableChangedData | SessionErrorData | SessionIdleData | SessionTitleChangedData | SessionScheduleCreatedData | SessionScheduleCancelledData | SessionScheduleRearmedData | SessionAutopilotObjectiveChangedData | SessionInfoData | SessionWarningData | SessionModelChangeData | SessionModeChangedData | SessionSessionLimitsChangedData | SessionPermissionsChangedData | SessionPlanChangedData | SessionTodosChangedData | SessionWorkspaceFileChangedData | SessionHandoffData | SessionTruncationData | SessionSnapshotRewindData | SessionShutdownData | SessionUsageCheckpointData | SessionContextChangedData | SessionUsageInfoData | SessionCompactionStartData | SessionCompactionCompleteData | SessionTaskCompleteData | UserMessageData | PendingMessagesModifiedData | AssistantTurnStartData | AssistantTurnRetryData | AssistantIntentData | AssistantServerToolProgressData | AssistantReasoningData | AssistantReasoningDeltaData | AssistantToolCallDeltaData | AssistantStreamingDeltaData | AssistantMessageData | AssistantMessageStartData | AssistantMessageDeltaData | AssistantTurnEndData | AssistantIdleData | AssistantUsageData | ModelCallFailureData | ModelCallStartData | AbortData | ToolUserRequestedData | ToolExecutionStartData | ToolExecutionPartialResultData | ToolExecutionProgressData | ToolExecutionCompleteData | ToolSearchActivatedData | SkillInvokedData | SubagentStartedData | SubagentCompletedData | SubagentFailedData | SubagentSelectedData | SubagentDeselectedData | HookStartData | HookEndData | HookProgressData | SessionBinaryAssetData | SystemMessageData | SystemNotificationData | PermissionRequestedData | PermissionCompletedData | UserInputRequestedData | UserInputCompletedData | ElicitationRequestedData | ElicitationCompletedData | SamplingRequestedData | SamplingCompletedData | McpOauthRequiredData | McpOauthCompletedData | McpHeadersRefreshRequiredData | McpHeadersRefreshCompletedData | SessionCustomNotificationData | ExternalToolRequestedData | ExternalToolCompletedData | CommandQueuedData | CommandExecuteData | CommandCompletedData | AutoModeSwitchRequestedData | AutoModeSwitchCompletedData | SessionLimitsExhaustedRequestedData | SessionLimitsExhaustedCompletedData | SessionAutoModeResolvedData | SessionManagedSettingsResolvedData | SessionManagedSettingsEnforcedData | CommandsChangedData | CapabilitiesChangedData | ExitPlanModeRequestedData | ExitPlanModeCompletedData | SessionToolsUpdatedData | SessionBackgroundTasksChangedData | FactoryRunUpdatedData | SessionSkillsLoadedData | SessionCustomAgentsUpdatedData | SessionMcpServersLoadedData | SessionMcpServerStatusChangedData | McpToolsListChangedData | McpResourcesListChangedData | McpPromptsListChangedData | SessionExtensionsLoadedData | SessionCanvasOpenedData | SessionCanvasRegistryChangedData | SessionCanvasClosedData | SessionCanvasUnavailableData | SessionCanvasRecordedData | SessionCanvasRemovedData | SessionExtensionsAttachmentsPushedData | McpAppToolCallCompleteData | RawSessionEventData | Data @dataclass @@ -9831,6 +10171,7 @@ def from_dict(obj: Any) -> "SessionEvent": case SessionEventType.EXIT_PLAN_MODE_COMPLETED: data = ExitPlanModeCompletedData.from_dict(data_obj) case SessionEventType.SESSION_TOOLS_UPDATED: data = SessionToolsUpdatedData.from_dict(data_obj) case SessionEventType.SESSION_BACKGROUND_TASKS_CHANGED: data = SessionBackgroundTasksChangedData.from_dict(data_obj) + case SessionEventType.FACTORY_RUN_UPDATED: data = FactoryRunUpdatedData.from_dict(data_obj) case SessionEventType.SESSION_SKILLS_LOADED: data = SessionSkillsLoadedData.from_dict(data_obj) case SessionEventType.SESSION_CUSTOM_AGENTS_UPDATED: data = SessionCustomAgentsUpdatedData.from_dict(data_obj) case SessionEventType.SESSION_MCP_SERVERS_LOADED: data = SessionMcpServersLoadedData.from_dict(data_obj) @@ -9926,6 +10267,7 @@ def session_event_to_dict(x: SessionEvent) -> Any: "AttachmentSelectionDetails", "AttachmentSelectionDetailsEnd", "AttachmentSelectionDetailsStart", + "AutoApprovalJudgeFailureReason", "AutoApprovalRecommendation", "AutoModeResolvedReasoningBucket", "AutoModeSwitchCompletedData", @@ -9957,6 +10299,7 @@ def session_event_to_dict(x: SessionEvent) -> Any: "CommandsChangedData", "CompactionCompleteCompactionTokensUsed", "CompactionCompleteCompactionTokensUsedCopilotUsageTokenDetail", + "CompactionTrigger", "ContextTier", "CustomAgentsUpdatedAgent", "Data", @@ -9975,6 +10318,7 @@ def session_event_to_dict(x: SessionEvent) -> Any: "ExtensionsLoadedExtensionStatus", "ExternalToolCompletedData", "ExternalToolRequestedData", + "FactoryRunUpdatedData", "GitHubRepoRef", "HandoffRepository", "HandoffSourceType", @@ -10056,6 +10400,7 @@ def session_event_to_dict(x: SessionEvent) -> Any: "PermissionRequestRead", "PermissionRequestShell", "PermissionRequestShellCommand", + "PermissionRequestShellCommandSegment", "PermissionRequestShellPossibleUrl", "PermissionRequestUrl", "PermissionRequestWrite", @@ -10070,6 +10415,7 @@ def session_event_to_dict(x: SessionEvent) -> Any: "ReasoningSummary", "SamplingCompletedData", "SamplingRequestedData", + "ScheduleOrigin", "SessionAutoModeResolvedData", "SessionAutopilotObjectiveChangedData", "SessionBackgroundTasksChangedData", @@ -10155,6 +10501,8 @@ def session_event_to_dict(x: SessionEvent) -> Any: "SystemNotificationNewInboxMessage", "SystemNotificationShellCompleted", "SystemNotificationShellDetachedCompleted", + "SystemNotificationUnclassified", + "TaskCompletionOutcome", "ToolExecutionCompleteContent", "ToolExecutionCompleteContentAudio", "ToolExecutionCompleteContentImage", diff --git a/rust/src/generated/api_types.rs b/rust/src/generated/api_types.rs index bd32d490cd..909b3b8f58 100644 --- a/rust/src/generated/api_types.rs +++ b/rust/src/generated/api_types.rs @@ -24,6 +24,8 @@ pub mod rpc_methods { pub const CONNECT: &str = "connect"; /// `models.list` pub const MODELS_LIST: &str = "models.list"; + /// `models.getBuiltInCatalog` + pub const MODELS_GETBUILTINCATALOG: &str = "models.getBuiltInCatalog"; /// `tools.list` pub const TOOLS_LIST: &str = "tools.list"; /// `account.getQuota` @@ -118,6 +120,10 @@ pub mod rpc_methods { pub const SESSIONS_CONNECT: &str = "sessions.connect"; /// `sessions.list` pub const SESSIONS_LIST: &str = "sessions.list"; + /// `sessions.getMetadata` + pub const SESSIONS_GETMETADATA: &str = "sessions.getMetadata"; + /// `sessions.listNonEmptySessionIds` + pub const SESSIONS_LISTNONEMPTYSESSIONIDS: &str = "sessions.listNonEmptySessionIds"; /// `sessions.findByTaskId` pub const SESSIONS_FINDBYTASKID: &str = "sessions.findByTaskId"; /// `sessions.findByPrefix` @@ -136,6 +142,8 @@ pub mod rpc_methods { pub const SESSIONS_CLOSE: &str = "sessions.close"; /// `sessions.bulkDelete` pub const SESSIONS_BULKDELETE: &str = "sessions.bulkDelete"; + /// `sessions.delete` + pub const SESSIONS_DELETE: &str = "sessions.delete"; /// `sessions.pruneOld` pub const SESSIONS_PRUNEOLD: &str = "sessions.pruneOld"; /// `sessions.save` @@ -175,8 +183,14 @@ pub mod rpc_methods { pub const SESSION_SEND: &str = "session.send"; /// `session.sendMessages` pub const SESSION_SENDMESSAGES: &str = "session.sendMessages"; + /// `session.sendSystemNotification` + pub const SESSION_SENDSYSTEMNOTIFICATION: &str = "session.sendSystemNotification"; /// `session.abort` pub const SESSION_ABORT: &str = "session.abort"; + /// `session.interruptMainTurn` + pub const SESSION_INTERRUPTMAINTURN: &str = "session.interruptMainTurn"; + /// `session.cancelAllBackgroundAgents` + pub const SESSION_CANCELALLBACKGROUNDAGENTS: &str = "session.cancelAllBackgroundAgents"; /// `session.shutdown` pub const SESSION_SHUTDOWN: &str = "session.shutdown"; /// `session.gitHubAuth.getStatus` @@ -197,8 +211,16 @@ pub mod rpc_methods { pub const SESSION_CANVAS_ACTION_INVOKE: &str = "session.canvas.action.invoke"; /// `session.factory.run` pub const SESSION_FACTORY_RUN: &str = "session.factory.run"; + /// `session.factory.resume` + pub const SESSION_FACTORY_RESUME: &str = "session.factory.resume"; /// `session.factory.getRun` pub const SESSION_FACTORY_GETRUN: &str = "session.factory.getRun"; + /// `session.factory.listRuns` + pub const SESSION_FACTORY_LISTRUNS: &str = "session.factory.listRuns"; + /// `session.factory.getRunDetail` + pub const SESSION_FACTORY_GETRUNDETAIL: &str = "session.factory.getRunDetail"; + /// `session.factory.getRunProgress` + pub const SESSION_FACTORY_GETRUNPROGRESS: &str = "session.factory.getRunProgress"; /// `session.factory.cancel` pub const SESSION_FACTORY_CANCEL: &str = "session.factory.cancel"; /// `session.factory.log` @@ -240,6 +262,10 @@ pub mod rpc_methods { "session.plan.readSqlTodosWithDependencies"; /// `session.workspaces.getWorkspace` pub const SESSION_WORKSPACES_GETWORKSPACE: &str = "session.workspaces.getWorkspace"; + /// `session.workspaces.updateMetadata` + pub const SESSION_WORKSPACES_UPDATEMETADATA: &str = "session.workspaces.updateMetadata"; + /// `session.workspaces.ensure` + pub const SESSION_WORKSPACES_ENSURE: &str = "session.workspaces.ensure"; /// `session.workspaces.listFiles` pub const SESSION_WORKSPACES_LISTFILES: &str = "session.workspaces.listFiles"; /// `session.workspaces.readFile` @@ -250,6 +276,22 @@ pub mod rpc_methods { pub const SESSION_WORKSPACES_LISTCHECKPOINTS: &str = "session.workspaces.listCheckpoints"; /// `session.workspaces.readCheckpoint` pub const SESSION_WORKSPACES_READCHECKPOINT: &str = "session.workspaces.readCheckpoint"; + /// `session.workspaces.addSummary` + pub const SESSION_WORKSPACES_ADDSUMMARY: &str = "session.workspaces.addSummary"; + /// `session.workspaces.truncateSummaries` + pub const SESSION_WORKSPACES_TRUNCATESUMMARIES: &str = "session.workspaces.truncateSummaries"; + /// `session.workspaces.readAutopilotObjective` + pub const SESSION_WORKSPACES_READAUTOPILOTOBJECTIVE: &str = + "session.workspaces.readAutopilotObjective"; + /// `session.workspaces.writeAutopilotObjective` + pub const SESSION_WORKSPACES_WRITEAUTOPILOTOBJECTIVE: &str = + "session.workspaces.writeAutopilotObjective"; + /// `session.workspaces.deleteAutopilotObjective` + pub const SESSION_WORKSPACES_DELETEAUTOPILOTOBJECTIVE: &str = + "session.workspaces.deleteAutopilotObjective"; + /// `session.workspaces.autopilotObjectiveExists` + pub const SESSION_WORKSPACES_AUTOPILOTOBJECTIVEEXISTS: &str = + "session.workspaces.autopilotObjectiveExists"; /// `session.workspaces.saveLargePaste` pub const SESSION_WORKSPACES_SAVELARGEPASTE: &str = "session.workspaces.saveLargePaste"; /// `session.workspaces.diff` @@ -347,6 +389,8 @@ pub mod rpc_methods { "session.mcp.oauth.handlePendingRequest"; /// `session.mcp.oauth.login` pub const SESSION_MCP_OAUTH_LOGIN: &str = "session.mcp.oauth.login"; + /// `session.mcp.oauth.respond` + pub const SESSION_MCP_OAUTH_RESPOND: &str = "session.mcp.oauth.respond"; /// `session.mcp.headers.handlePendingHeadersRefreshRequest` pub const SESSION_MCP_HEADERS_HANDLEPENDINGHEADERSREFRESHREQUEST: &str = "session.mcp.headers.handlePendingHeadersRefreshRequest"; @@ -518,6 +562,8 @@ pub mod rpc_methods { pub const SESSION_SETTINGS_SNAPSHOT: &str = "session.settings.snapshot"; /// `session.settings.evaluatePredicate` pub const SESSION_SETTINGS_EVALUATEPREDICATE: &str = "session.settings.evaluatePredicate"; + /// `session.contentExclusion.checkPaths` + pub const SESSION_CONTENTEXCLUSION_CHECKPATHS: &str = "session.contentExclusion.checkPaths"; /// `session.shell.exec` pub const SESSION_SHELL_EXEC: &str = "session.shell.exec"; /// `session.shell.kill` @@ -530,6 +576,12 @@ pub mod rpc_methods { pub const SESSION_HISTORY_COMPACT: &str = "session.history.compact"; /// `session.history.truncate` pub const SESSION_HISTORY_TRUNCATE: &str = "session.history.truncate"; + /// `session.history.listRewindPoints` + pub const SESSION_HISTORY_LISTREWINDPOINTS: &str = "session.history.listRewindPoints"; + /// `session.history.previewRewind` + pub const SESSION_HISTORY_PREVIEWREWIND: &str = "session.history.previewRewind"; + /// `session.history.rewind` + pub const SESSION_HISTORY_REWIND: &str = "session.history.rewind"; /// `session.history.cancelBackgroundCompaction` pub const SESSION_HISTORY_CANCELBACKGROUNDCOMPACTION: &str = "session.history.cancelBackgroundCompaction"; @@ -539,10 +591,41 @@ pub mod rpc_methods { pub const SESSION_HISTORY_SUMMARIZEFORHANDOFF: &str = "session.history.summarizeForHandoff"; /// `session.queue.pendingItems` pub const SESSION_QUEUE_PENDINGITEMS: &str = "session.queue.pendingItems"; + /// `session.queue.snapshot` + pub const SESSION_QUEUE_SNAPSHOT: &str = "session.queue.snapshot"; + /// `session.queue.moveItem` + pub const SESSION_QUEUE_MOVEITEM: &str = "session.queue.moveItem"; + /// `session.queue.insertAt` + pub const SESSION_QUEUE_INSERTAT: &str = "session.queue.insertAt"; + /// `session.queue.removeAt` + pub const SESSION_QUEUE_REMOVEAT: &str = "session.queue.removeAt"; + /// `session.queue.updateText` + pub const SESSION_QUEUE_UPDATETEXT: &str = "session.queue.updateText"; + /// `session.queue.duplicateAt` + pub const SESSION_QUEUE_DUPLICATEAT: &str = "session.queue.duplicateAt"; + /// `session.queue.setDrainPaused` + pub const SESSION_QUEUE_SETDRAINPAUSED: &str = "session.queue.setDrainPaused"; + /// `session.queue.sendNow` + pub const SESSION_QUEUE_SENDNOW: &str = "session.queue.sendNow"; + /// `session.queue.hasPending` + pub const SESSION_QUEUE_HASPENDING: &str = "session.queue.hasPending"; + /// `session.queue.beginDeferredIdleDrain` + pub const SESSION_QUEUE_BEGINDEFERREDIDLEDRAIN: &str = "session.queue.beginDeferredIdleDrain"; + /// `session.queue.finishDeferredIdleDrain` + pub const SESSION_QUEUE_FINISHDEFERREDIDLEDRAIN: &str = "session.queue.finishDeferredIdleDrain"; + /// `session.queue.deferSessionIdle` + pub const SESSION_QUEUE_DEFERSESSIONIDLE: &str = "session.queue.deferSessionIdle"; /// `session.queue.removeMostRecent` pub const SESSION_QUEUE_REMOVEMOSTRECENT: &str = "session.queue.removeMostRecent"; /// `session.queue.clear` pub const SESSION_QUEUE_CLEAR: &str = "session.queue.clear"; + /// `session.queue.consumeSystemNotifications` + pub const SESSION_QUEUE_CONSUMESYSTEMNOTIFICATIONS: &str = + "session.queue.consumeSystemNotifications"; + /// `session.queue.enqueueResumePending` + pub const SESSION_QUEUE_ENQUEUERESUMEPENDING: &str = "session.queue.enqueueResumePending"; + /// `session.queue.process` + pub const SESSION_QUEUE_PROCESS: &str = "session.queue.process"; /// `session.eventLog.read` pub const SESSION_EVENTLOG_READ: &str = "session.eventLog.read"; /// `session.eventLog.tail` @@ -553,6 +636,8 @@ pub mod rpc_methods { pub const SESSION_EVENTLOG_RELEASEINTEREST: &str = "session.eventLog.releaseInterest"; /// `session.usage.getMetrics` pub const SESSION_USAGE_GETMETRICS: &str = "session.usage.getMetrics"; + /// `session.limitPrediction.predict` + pub const SESSION_LIMITPREDICTION_PREDICT: &str = "session.limitPrediction.predict"; /// `session.remote.enable` pub const SESSION_REMOTE_ENABLE: &str = "session.remote.enable"; /// `session.remote.disable` @@ -565,6 +650,20 @@ pub mod rpc_methods { pub const SESSION_VISIBILITY_SET: &str = "session.visibility.set"; /// `session.schedule.list` pub const SESSION_SCHEDULE_LIST: &str = "session.schedule.list"; + /// `session.schedule.hydrate` + pub const SESSION_SCHEDULE_HYDRATE: &str = "session.schedule.hydrate"; + /// `session.schedule.hasSelfPaced` + pub const SESSION_SCHEDULE_HASSELFPACED: &str = "session.schedule.hasSelfPaced"; + /// `session.schedule.add` + pub const SESSION_SCHEDULE_ADD: &str = "session.schedule.add"; + /// `session.schedule.addCron` + pub const SESSION_SCHEDULE_ADDCRON: &str = "session.schedule.addCron"; + /// `session.schedule.addAt` + pub const SESSION_SCHEDULE_ADDAT: &str = "session.schedule.addAt"; + /// `session.schedule.addSelfPaced` + pub const SESSION_SCHEDULE_ADDSELFPACED: &str = "session.schedule.addSelfPaced"; + /// `session.schedule.rearmSelfPaced` + pub const SESSION_SCHEDULE_REARMSELFPACED: &str = "session.schedule.rearmSelfPaced"; /// `session.schedule.stop` pub const SESSION_SCHEDULE_STOP: &str = "session.schedule.stop"; /// `providerToken.getToken` @@ -595,6 +694,8 @@ pub mod rpc_methods { pub const SESSIONFS_RENAME: &str = "sessionFs.rename"; /// `sessionFs.sqliteQuery` pub const SESSIONFS_SQLITEQUERY: &str = "sessionFs.sqliteQuery"; + /// `sessionFs.sqliteTransaction` + pub const SESSIONFS_SQLITETRANSACTION: &str = "sessionFs.sqliteTransaction"; /// `sessionFs.sqliteExists` pub const SESSIONFS_SQLITEEXISTS: &str = "sessionFs.sqliteExists"; /// `canvas.open` @@ -838,7 +939,7 @@ pub struct AgentDiscoveryPathList { pub paths: Vec, } -/// Custom agent metadata, including identifiers, display details, source, tools, model, MCP servers, skills, and file path. +/// Agent metadata, including identifiers, display details, source, tools, model, MCP servers, skills, and file path. /// ///

/// @@ -865,14 +966,17 @@ pub struct AgentInfo { ///
#[serde(skip_serializing_if = "Option::is_none")] pub mcp_servers: Option>, - /// Preferred model id for this agent. When omitted, inherits the outer agent's model. + /// Authored preferred model id for this agent. Runtime model selection may choose a different model; omitted means no authored preference. #[serde(skip_serializing_if = "Option::is_none")] pub model: Option, - /// Unique identifier of the custom agent + /// Name of the agent. Use `id` as the stable selection identifier. pub name: String, /// Absolute local file path of the agent definition. Only set for file-based agents loaded from disk; remote agents do not have a path. #[serde(skip_serializing_if = "Option::is_none")] pub path: Option, + /// Authored base prompt for the agent. Runtime prompt assembly may add dynamic context at invocation time. Omitted from `session.agent.list` unless `includePrompt` is true. + #[serde(skip_serializing_if = "Option::is_none")] + pub prompt: Option, /// Skill names preloaded into this agent's context. Omitted means none. #[serde(skip_serializing_if = "Option::is_none")] pub skills: Option>, @@ -902,7 +1006,7 @@ pub struct AgentGetCurrentResult { pub agent: AgentInfo, } -/// Custom agents available to the session. +/// Agents available to the session. /// ///
/// @@ -913,10 +1017,29 @@ pub struct AgentGetCurrentResult { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AgentList { - /// Available custom agents + /// Available agents pub agents: Vec, } +/// Controls whether built-in agents and authored prompt text are included. +/// +///
+/// +/// **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 AgentListRequest { + /// When true, request the session's configured built-in agents alongside custom agents. Listing applies feature, context, inclusion, exclusion, and user-disabled-agent policy, but does not evaluate transient invocation requirements such as model availability. Built-in metadata may be omitted when the session cannot project it, such as a relay session. + #[serde(skip_serializing_if = "Option::is_none")] + pub include_built_in_agents: Option, + /// When true, request authored base prompt text on each AgentInfo. Prompt text may be omitted when unavailable, such as for agents projected through a relay session. + #[serde(skip_serializing_if = "Option::is_none")] + pub include_prompt: Option, +} + /// Full registry entry for the spawned child. Lets the controller call `handleLiveTargetSelected(entry)` directly without re-reading the registry (avoids a TOCTOU window). /// ///
@@ -2092,6 +2215,36 @@ pub struct AttachmentSelection { pub r#type: AttachmentSelectionType, } +/// A well-known model in the runtime's built-in catalog. +/// +///
+/// +/// **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 BuiltInModelCatalogEntry { + /// Well-known runtime model ID suitable for `ProviderConfig.modelId` or `ProviderModelConfig.modelId`. This is not necessarily the provider-facing deployment or model name and does not indicate CAPI entitlement or provider availability. + pub id: String, +} + +/// The running runtime's complete catalog of well-known built-in model IDs, including supported models and additional IDs with built-in metadata. +/// +///
+/// +/// **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 BuiltInModelCatalog { + /// Built-in model entries. + pub models: Vec, +} + /// Cancellation result for a user-requested shell command. /// ///
@@ -2853,7 +3006,7 @@ pub struct ConnectRemoteSessionParams { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub(crate) struct ConnectRequest { - /// Opt this connection in to GitHub telemetry forwarding for its lifetime. When set, the runtime forwards every internal telemetry event it emits — across all sessions, plus sessionless events — to this connection over the `gitHubTelemetry.event` notification, in addition to the runtime's normal GitHub/CTS emission (dual-write). Intended for first-party hosts that re-emit the events into their own telemetry stores. Both unrestricted and restricted events are forwarded, each tagged with a `restricted` discriminator; a backstop drops restricted events when restricted telemetry is disabled. + /// Opt this connection in to GitHub telemetry forwarding for its lifetime. When set, the runtime forwards every internal telemetry event it emits — across all sessions, plus sessionless events — to this connection over the `gitHubTelemetry.event` notification. Regular events are also written to the runtime's normal GitHub/CTS path (dual-write); host-only compatibility events are forward-only and intentionally skip that path. Intended for first-party hosts that re-emit the events into their own telemetry stores. Both unrestricted and restricted events are forwarded, each tagged with a `restricted` discriminator; a backstop drops restricted events when restricted telemetry is disabled — using the process-global gate for ordinary events and an explicit session-scoped decision for host-only events. #[serde(skip_serializing_if = "Option::is_none")] pub enable_git_hub_telemetry_forwarding: Option, /// Connection token; required when the server was started with COPILOT_CONNECTION_TOKEN @@ -2880,6 +3033,55 @@ pub(crate) struct ConnectResult { pub version: String, } +/// Local file system absolute paths within the session working directory to check against its content-exclusion policy. +/// +///
+/// +/// **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 ContentExclusionCheckPathsRequest { + /// Local file system absolute paths within the session working directory to check. Results are returned in the same order, including duplicates. + pub paths: Vec, +} + +/// Content-exclusion decision for one requested path. +/// +///
+/// +/// **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 ContentExclusionPathCheck { + /// Whether the session's complete content-exclusion policy excludes the path. + pub excluded: bool, + /// The path supplied by the caller. + pub path: String, +} + +/// Batch content-exclusion result. Callers must fail closed when policy evaluation is unavailable. +/// +///
+/// +/// **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 ContentExclusionCheckPathsResult { + /// Whether the session's policy service was available for the complete batch. When false, checks is empty and callers must treat every requested path as excluded. + pub available: bool, + /// Per-path decisions in request order. Empty when available is false. + pub checks: Vec, +} + /// A single large message currently in context. /// ///
@@ -3237,6 +3439,9 @@ pub struct EventLogReadRequest { /// Opaque cursor returned by a previous read. Omit on the first call to start from the beginning of the session's persisted history. #[serde(skip_serializing_if = "Option::is_none")] pub cursor: Option, + /// When false, skip ephemeral events entirely and return only durable (persisted) events. History-backfill callers that discard ephemerals anyway should set this so the read is bounded by the durable log length instead of racing the ephemeral ring on a busy session. Defaults to true (ephemerals are interleaved with durable events in creation order). + #[serde(skip_serializing_if = "Option::is_none")] + pub include_ephemeral: Option, /// Maximum number of events to return in this batch (1–1000, default 200). #[serde(skip_serializing_if = "Option::is_none")] pub max: Option, @@ -3293,7 +3498,7 @@ pub struct EventsReadResult { pub cursor: String, /// Cursor status: 'ok' means the cursor was applied successfully; 'expired' means the cursor referred to an event that no longer exists in history (e.g. truncated or compacted away) and the read started from the beginning of the remaining history. pub cursor_status: EventsCursorStatus, - /// Events are delivered in two batches per read: persisted events first (in append order), then ephemeral events (in seq order). When `waitMs > 0` and the catch-up batches were empty, post-wait events follow the same two-batch ordering. Persisted and ephemeral events do not interleave within a single read. + /// Session events for this batch, merged into a single stream in creation order: durable (persisted) events and ephemeral events interleave exactly as they were emitted. Set `includeEphemeral: false` to receive only durable events. Ephemeral events are never replayable once pruned from the in-memory ring, so a consumer that needs them should keep reading with a non-zero `waitMs`. pub events: Vec, /// True when the read returned `max` events and more events are available immediately. When false, the next read with a non-zero `waitMs` will block until a new event arrives or the wait expires. pub has_more: bool, @@ -3724,6 +3929,8 @@ pub struct FactoryAgentOptions { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct FactoryAgentRequest { + /// Opaque token identifying the current factory execution attempt. + pub execution_token: String, /// Factory run identifier that owns the subagent. pub factory_run_id: String, /// Subagent execution options. @@ -3748,6 +3955,37 @@ pub struct FactoryAgentResult { pub result: Option, } +/// Prompt-safe durable identity and live status for a direct factory agent. +/// +///
+/// +/// **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 FactoryAgentSummary { + pub active_ms: i64, + #[serde(skip_serializing_if = "Option::is_none")] + pub activity: Option, + pub agent_id: String, + pub agent_type: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub completed_at: Option, + pub label: String, + pub phase_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub requested_model: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub resolved_model: Option, + pub run_id: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub started_at: Option, + pub status: String, + pub tool_call_id: String, +} + /// Parameters for cancelling a factory run. /// ///
@@ -3763,6 +4001,42 @@ pub struct FactoryCancelRequest { pub run_id: String, } +/// Current factory phase identity. +/// +///
+/// +/// **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 FactoryCurrentPhase { + pub id: String, + pub ordinal: Option, +} + +/// Declared or approved factory resource ceilings. +/// +///
+/// +/// **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 FactoryDeclaredLimits { + #[serde(skip_serializing_if = "Option::is_none")] + pub max_ai_credits: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub max_concurrent_subagents: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub max_total_subagents: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub timeout_seconds: Option, +} + /// Parameters sent to the owning extension to execute a factory closure. /// ///
@@ -3780,6 +4054,8 @@ pub struct FactoryExecuteRequest { pub name: String, /// Factory run identifier. pub run_id: String, + /// Opaque token identifying this factory execution attempt. + pub execution_token: String, /// Factory input value. pub args: serde_json::Value, } @@ -3796,7 +4072,35 @@ pub struct FactoryExecuteRequest { #[serde(rename_all = "camelCase")] pub struct FactoryExecuteResult { /// Factory result value. - pub result: serde_json::Value, + #[serde(skip_serializing_if = "Option::is_none")] + pub result: Option, +} + +/// Parameters for paging factory progress. +/// +///
+/// +/// **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 FactoryGetRunProgressRequest { + /// Exclusive forward cursor. + #[serde(skip_serializing_if = "Option::is_none")] + pub after_seq: Option, + /// Exclusive backward cursor. + #[serde(skip_serializing_if = "Option::is_none")] + pub before_seq: Option, + /// Maximum records to return. Defaults to 200 and is capped at 500. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, + /// Optional phase identifier used to scope records and cursors. + #[serde(skip_serializing_if = "Option::is_none")] + pub phase_id: Option, + /// Factory run identifier. + pub run_id: String, } /// Parameters for retrieving a factory run. @@ -3825,6 +4129,8 @@ pub struct FactoryGetRunRequest { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct FactoryJournalGetRequest { + /// Opaque token identifying the current factory execution attempt. + pub execution_token: String, /// Namespaced journal key. pub key: String, /// Factory run identifier. @@ -3860,6 +4166,8 @@ pub struct FactoryJournalGetResult { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct FactoryJournalPutRequest { + /// Opaque token identifying the current factory execution attempt. + pub execution_token: String, /// Namespaced journal key. pub key: String, /// JSON result to memoize. @@ -3868,7 +4176,7 @@ pub struct FactoryJournalPutRequest { pub run_id: String, } -/// One ordered factory progress line. +/// Empty parameters for listing factory runs. /// ///
/// @@ -3878,16 +4186,9 @@ pub struct FactoryJournalPutRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct FactoryLogLine { - /// Progress line kind. - pub kind: FactoryLogLineKind, - /// Monotonic sequence number within the factory run. - pub seq: i64, - /// Progress text. - pub text: String, -} +pub struct FactoryListRunsRequest {} -/// Parameters for recording factory progress. +/// Durable factory resource consumption. /// ///
/// @@ -3897,14 +4198,13 @@ pub struct FactoryLogLine { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct FactoryLogRequest { - /// Ordered progress lines to append. - pub lines: Vec, - /// Factory run identifier. - pub run_id: String, +pub struct FactoryRunConsumed { + pub active_ms: i64, + pub nano_aiu: i64, + pub subagents: i64, } -/// Wire-only per-invocation factory resource ceiling overrides. +/// Prompt-safe terminal factory outcome. /// ///
/// @@ -3914,19 +4214,18 @@ pub struct FactoryLogRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct FactoryRunLimits { - /// Maximum number of factory subagents that may run concurrently. +pub struct FactoryRunTerminal { #[serde(skip_serializing_if = "Option::is_none")] - pub max_concurrent_subagents: Option, - /// Maximum total number of factory subagents that may be admitted. + pub error: Option, #[serde(skip_serializing_if = "Option::is_none")] - pub max_total_subagents: Option, - /// Factory active-run timeout in milliseconds. + pub failure: Option, #[serde(skip_serializing_if = "Option::is_none")] - pub timeout: Option, + pub reason: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub result_preview: Option, } -/// Options controlling factory invocation. +/// Durable factory run summary with read-time live overlays. /// ///
/// @@ -3936,16 +4235,29 @@ pub struct FactoryRunLimits { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RunOptions { - /// Per-invocation resource ceiling overrides. - #[serde(skip_serializing_if = "Option::is_none")] - pub limits: Option, - /// Run identifier whose journal and progress should seed this resumed run. - #[serde(skip_serializing_if = "Option::is_none")] - pub resume_from_run_id: Option, +pub struct FactoryRunSummary { + pub active_segment_started_at: Option, + pub approved: Option, + pub completed_at: Option, + pub consumed: FactoryRunConsumed, + pub created_at: i64, + pub current_phase: Option, + pub declared_limits: FactoryDeclaredLimits, + pub declared_phase_count: i64, + pub description: String, + pub factory_name: String, + pub live_agent_count: i64, + pub observed_at: i64, + pub revision: i64, + pub run_id: String, + pub started_at: Option, + pub status: FactoryRunStatus, + pub terminal: Option, + pub total_spawned_agent_count: i64, + pub updated_at: i64, } -/// Parameters for invoking a registered factory. +/// Factory runs in durable creation order. /// ///
/// @@ -3955,17 +4267,11 @@ pub struct RunOptions { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct FactoryRunRequest { - /// Factory input value. - pub args: serde_json::Value, - /// Registered factory name. - pub name: String, - /// Factory invocation options. - #[serde(skip_serializing_if = "Option::is_none")] - pub options: Option, +pub struct FactoryListRunsResult { + pub runs: Vec, } -/// Complete current or terminal factory run envelope. +/// One ordered factory progress line. /// ///
/// @@ -3975,29 +4281,16 @@ pub struct FactoryRunRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct FactoryRunResult { - /// Error message for an errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - /// Machine-readable failure details for an errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub failure: Option, - /// Reason for a halted or cancelled run. - #[serde(skip_serializing_if = "Option::is_none")] - pub reason: Option, - /// Completed factory result. - #[serde(skip_serializing_if = "Option::is_none")] - pub result: Option, - /// Factory run identifier. - pub run_id: String, - /// Partial journal and progress snapshot for a halted, cancelled, or errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub snapshot: Option, - /// Current or terminal factory run status. - pub status: FactoryRunStatus, +pub struct FactoryLogLine { + /// Progress line kind. + pub kind: FactoryLogLineKind, + /// Monotonic sequence number within the factory run. + pub seq: i64, + /// Progress text. + pub text: String, } -/// Optional user prompt to combine with the fleet orchestration instructions. +/// Parameters for recording factory progress. /// ///
/// @@ -4007,13 +4300,16 @@ pub struct FactoryRunResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct FleetStartRequest { - /// Optional user prompt to combine with fleet instructions - #[serde(skip_serializing_if = "Option::is_none")] - pub prompt: Option, +pub struct FactoryLogRequest { + /// Opaque token identifying the current factory execution attempt. + pub execution_token: String, + /// Ordered progress lines to append. + pub lines: Vec, + /// Factory run identifier. + pub run_id: String, } -/// Indicates whether fleet mode was successfully activated. +/// Durable lifecycle and timing for one factory phase. /// ///
/// @@ -4023,12 +4319,26 @@ pub struct FleetStartRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct FleetStartResult { - /// Whether fleet mode was successfully activated - pub started: bool, +pub struct FactoryPhaseObservation { + pub accumulated_active_ms: i64, + #[serde(skip_serializing_if = "Option::is_none")] + pub completed_at: Option, + pub current_active_ms: i64, + #[serde(skip_serializing_if = "Option::is_none")] + pub detail: Option, + pub entry_count: i64, + pub id: String, + pub last_entered_run_attempt: i64, + pub live_agent_count: i64, + pub ordinal: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub started_at: Option, + pub status: FactoryPhaseStatus, + pub title: String, + pub total_agent_count: i64, } -/// Folder path to add to trusted folders. +/// One durable factory progress record. /// ///
/// @@ -4038,12 +4348,22 @@ pub struct FleetStartResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct FolderTrustAddParams { - /// Folder path to mark as trusted - pub path: String, +pub struct FactoryProgressLine { + /// Resume attempt that emitted this record. + pub attempt: i64, + /// Progress record kind. + pub kind: FactoryLogLineKind, + /// Phase active when the record was emitted, or null before any phase. + pub phase_id: Option, + /// Epoch milliseconds when the record was persisted. + pub recorded_at: i64, + /// Global monotonic sequence number within the run. + pub seq: i64, + /// Prompt-safe progress text. + pub text: String, } -/// Folder path to check for trust. +/// A bidirectional page of factory progress. /// ///
/// @@ -4053,12 +4373,17 @@ pub struct FolderTrustAddParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct FolderTrustCheckParams { - /// Folder path to check - pub path: String, +pub struct FactoryProgressPage { + pub has_more_newer: bool, + pub has_more_older: bool, + pub newest_seq: Option, + pub oldest_seq: Option, + pub records: Vec, + /// Run revision reflected by this page. + pub revision: i64, } -/// Folder trust check result. +/// Wire-only per-invocation factory resource ceiling overrides. /// ///
/// @@ -4068,8 +4393,235 @@ pub struct FolderTrustCheckParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct FolderTrustCheckResult { - /// Whether the folder is trusted +pub struct FactoryRunLimits { + /// Maximum AI credits consumed by factory subagents and their descendants. The post-paid ceiling is soft: parallel turns can settle beyond it before the run stops. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_ai_credits: Option, + /// Maximum number of factory subagents that may run concurrently. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_concurrent_subagents: Option, + /// Maximum total number of factory subagents that may be admitted. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_total_subagents: Option, + /// Maximum accumulated active-execution time in seconds. Active execution includes the entire extension body, subprocess waits, queued-agent waits, and sleeps; time between resumed attempts is not counted. + #[serde(skip_serializing_if = "Option::is_none")] + pub timeout_seconds: Option, +} + +/// Parameters for resuming a factory run from its persisted identity. +/// +///
+/// +/// **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 FactoryResumeRequest { + /// Optional per-invocation resource ceiling overrides. + #[serde(skip_serializing_if = "Option::is_none")] + pub limits: Option, + /// Factory run identifier. + pub run_id: String, +} + +/// Complete current or terminal factory run envelope. +/// +///
+/// +/// **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 FactoryRunResult { + /// Error message for an errored run. + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, + /// Machine-readable failure details for an errored run. + #[serde(skip_serializing_if = "Option::is_none")] + pub failure: Option, + /// Reason for a halted or cancelled run. + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, + /// Completed factory result. + #[serde(skip_serializing_if = "Option::is_none")] + pub result: Option, + /// Factory run identifier. + pub run_id: String, + /// Partial journal and progress snapshot for a halted, cancelled, or errored run. + #[serde(skip_serializing_if = "Option::is_none")] + pub snapshot: Option, + /// Current or terminal factory run status. + pub status: FactoryRunStatus, +} + +/// Resolved persisted factory identity and resumed run envelope. +/// +///
+/// +/// **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 FactoryResumeResult { + /// Persisted factory name resolved for the resumed run. + pub factory_name: String, + /// Terminal resumed run envelope. + pub run: FactoryRunResult, +} + +/// Full factory run observability detail. +/// +///
+/// +/// **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 FactoryRunDetail { + pub active_segment_started_at: Option, + pub agents: Vec, + pub approved: Option, + pub completed_at: Option, + pub consumed: FactoryRunConsumed, + pub created_at: i64, + pub current_phase: Option, + pub declared_limits: FactoryDeclaredLimits, + pub declared_phase_count: i64, + pub description: String, + pub factory_name: String, + pub live_agent_count: i64, + pub observed_at: i64, + pub phases: Vec, + pub progress: FactoryProgressPage, + pub revision: i64, + pub run_id: String, + pub started_at: Option, + pub status: FactoryRunStatus, + pub terminal: Option, + pub total_spawned_agent_count: i64, + pub updated_at: i64, +} + +/// Options controlling factory invocation. +/// +///
+/// +/// **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 RunOptions { + /// Per-invocation resource ceiling overrides. + #[serde(skip_serializing_if = "Option::is_none")] + pub limits: Option, + /// Run identifier whose journal and progress should seed this resumed run. + #[serde(skip_serializing_if = "Option::is_none")] + pub resume_from_run_id: Option, +} + +/// Parameters for invoking a registered factory. +/// +///
+/// +/// **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 FactoryRunRequest { + /// Factory input value. + pub args: serde_json::Value, + /// Registered factory name. + pub name: String, + /// Factory invocation options. + #[serde(skip_serializing_if = "Option::is_none")] + pub options: Option, +} + +/// Optional user prompt to combine with the fleet orchestration instructions. +/// +///
+/// +/// **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 FleetStartRequest { + /// Optional user prompt to combine with fleet instructions + #[serde(skip_serializing_if = "Option::is_none")] + pub prompt: Option, +} + +/// Indicates whether fleet mode was successfully activated. +/// +///
+/// +/// **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 FleetStartResult { + /// Whether fleet mode was successfully activated + pub started: bool, +} + +/// Folder path to add to trusted folders. +/// +///
+/// +/// **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 FolderTrustAddParams { + /// Folder path to mark as trusted + pub path: String, +} + +/// Folder path to check for trust. +/// +///
+/// +/// **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 FolderTrustCheckParams { + /// Folder path to check + pub path: String, +} + +/// Folder trust check result. +/// +///
+/// +/// **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 FolderTrustCheckResult { + /// Whether the folder is trusted pub trusted: bool, } @@ -4314,6 +4866,12 @@ pub struct HistoryCompactRequest { /// Optional user-provided instructions to focus the compaction summary #[serde(skip_serializing_if = "Option::is_none")] pub custom_instructions: Option, + /// Context window token limit this compaction is targeting, recorded as the `tokenLimit` on the persisted `session.compaction_start` / `session.compaction_complete` events. Set it when the compaction targets a window other than the compacting model's own, e.g. switching to a model with a smaller context window: the compaction still runs on the current model, so the limit that motivated it would otherwise be lost. When absent, the events record the compacting model's own resolved limit. Attribution metadata only - it does not change how much the compaction removes. + #[serde(skip_serializing_if = "Option::is_none")] + pub token_limit: Option, + /// What initiated this compaction request, recorded as the `trigger` on the persisted `session.compaction_start` / `session.compaction_complete` events. When absent, the compaction is persisted without trigger attribution (initiator unknown). + #[serde(skip_serializing_if = "Option::is_none")] + pub trigger: Option, } /// Compaction outcome with the number of tokens and messages removed, summary text, and the resulting context window breakdown. @@ -4341,7 +4899,7 @@ pub struct HistoryCompactResult { pub tokens_removed: i64, } -/// Markdown summary of the conversation context (empty when not available). +/// A root user turn that the session can rewind to. /// ///
/// @@ -4351,12 +4909,28 @@ pub struct HistoryCompactResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct HistorySummarizeForHandoffResult { - /// Markdown summary of the conversation context produced by an LLM. Empty string when there are no messages or when the session does not support local summarization. - pub summary: String, +pub struct HistoryRewindPoint { + /// Whether at least one file in this turn or a later turn can be restored. + pub can_restore_files: bool, + /// ID of the user.message event that begins the discarded suffix. + pub event_id: String, + /// Number of unique files in this turn and all later turns that have captured changes. + pub file_count: i64, + /// Whether this turn was an automatically injected autopilot continuation. + pub is_autopilot_continuation: bool, + /// Lines added by this turn's captured file changes. + pub lines_added: i64, + /// Lines removed by this turn's captured file changes. + pub lines_removed: i64, + /// ISO timestamp of the user turn. + pub timestamp: String, + /// Whether this turn itself captured any file changes. + pub turn_changed_files: bool, + /// User-visible message text for the turn. + pub user_message: String, } -/// Identifier of the event to truncate to; this event and all later events are removed. +/// Rewind points and file-change-tracking availability for the session. /// ///
/// @@ -4366,12 +4940,17 @@ pub struct HistorySummarizeForHandoffResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct HistoryTruncateRequest { - /// Event ID to truncate to. This event and all events after it are removed from the session. - pub event_id: String, +pub struct HistoryListRewindPointsResult { + /// Whether this session captured file changes from its first turn. + pub file_change_tracking_enabled: bool, + /// Root user turns in chronological order. Empty when `unavailableReason` is set. + pub points: Vec, + /// Why the listed points could not be produced, when applicable; the points list is empty whenever it is set. `unsupported-remote-session` is permanent for the session and comes with `fileChangeTrackingEnabled: false`. `session-busy` is transient and only ever reported by a session that *is* tracking (`fileChangeTrackingEnabled: true`), because the file-change captures cannot be read while work that may still mutate them is in flight; the same request succeeds once the session settles, so a client that wants points should retry rather than treat it as a failure. It is never `file-change-tracking-disabled`: an untracked local session still lists conversation-only points and reports that through `fileChangeTrackingEnabled: false`. + #[serde(skip_serializing_if = "Option::is_none")] + pub unavailable_reason: Option, } -/// Number of events that were removed by the truncation. +/// Event boundary to preview for conversation-and-files rewind. /// ///
/// @@ -4381,12 +4960,12 @@ pub struct HistoryTruncateRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct HistoryTruncateResult { - /// Number of events that were removed - pub events_removed: i64, +pub struct HistoryPreviewRewindRequest { + /// ID of the user.message event that begins the discarded suffix. + pub event_id: String, } -/// Authentication-info variant for GitHub-internal HMAC auth, carrying the public GitHub host and HMAC secret. +/// A file that a conversation-and-files rewind would restore. /// ///
/// @@ -4396,37 +4975,40 @@ pub struct HistoryTruncateResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct HMACAuthInfo { - /// 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. - #[serde(skip_serializing_if = "Option::is_none")] - pub copilot_user: Option, - /// HMAC secret used to sign requests. - pub hmac: String, - /// Authentication host. HMAC auth always targets the public GitHub host. - pub host: HMACAuthInfoHost, - /// HMAC-based authentication used by GitHub-internal services. - pub r#type: HMACAuthInfoType, -} - -/// Runtime-owned wire payload for a server-to-client hook callback invocation. -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct HookInvokeRequest { - #[doc(hidden)] - pub(crate) hook_type: HookType, - pub input: serde_json::Value, - pub session_id: SessionId, +pub struct HistoryRewindFilePreview { + /// Aggregate change made across the discarded turns. + pub change_type: HistoryRewindChangeType, + /// Lines added across the discarded turns. + pub lines_added: i64, + /// Lines removed across the discarded turns. + pub lines_removed: i64, + /// Absolute path of the captured file. + pub path: String, } -/// Optional output returned by an SDK callback hook. +/// Files and aggregate changes for a prospective rewind. +/// +///
+/// +/// **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(crate) struct HookInvokeResponse { +pub struct HistoryPreviewRewindResult { + /// Whether file restore is available for this session. This is authoritative: switch on it and read `reason` only when it is false. + pub available: bool, + /// Number of unique files in the preview. + pub file_count: i64, + /// Files ordered by path. + pub files: Vec, + /// Why file restore is unavailable, when applicable. Populated only when `available` is false and never set when `available` is true. #[serde(skip_serializing_if = "Option::is_none")] - pub output: Option, + pub reason: Option, } -/// Installed plugin record from global state, with marketplace, version, install time, enabled state, cache path, and source. +/// Boundary and mode for rewinding session history. /// ///
/// @@ -4436,11 +5018,161 @@ pub(crate) struct HookInvokeResponse { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct InstalledPlugin { - /// Path where the plugin is cached locally - #[serde(rename = "cache_path", skip_serializing_if = "Option::is_none")] - pub cache_path: Option, - /// Whether the plugin is currently enabled +pub struct HistoryRewindRequest { + /// ID of the user.message event that begins the discarded suffix. + pub event_id: String, + /// Whether to rewind only conversation history or also restore captured files. + pub mode: HistoryRewindMode, +} + +/// A captured file that rewind intentionally left unchanged. +/// +///
+/// +/// **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 HistorySkippedFileRestore { + /// Absolute path of the skipped file. + pub path: String, + /// Reason the file was not restored. + pub reason: HistoryFileRestoreSkipReason, +} + +/// Structured outcome of a rewind request. +/// +///
+/// +/// **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 HistoryRewindResult { + /// Failure detail. Set only for the failure and partial-failure outcomes (`files-rolled-back`, `rollback-incomplete`, `truncation-failed`, `checkpoint-cleanup-failed`, `snapshot-prune-failed`); omitted for `success` and for the unavailable outcomes (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`). + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, + /// Number of persisted events removed by conversation truncation. Present only when truncation succeeded (outcomes `success`, `checkpoint-cleanup-failed`, and `snapshot-prune-failed`); omitted for every unavailable outcome (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`) and for `truncation-failed`, `files-rolled-back`, and `rollback-incomplete`. + #[serde(skip_serializing_if = "Option::is_none")] + pub events_removed: Option, + /// Overall rewind outcome. This discriminates the result: it governs which of the remaining fields are populated, so consumers must switch on it before reading `eventsRemoved`, `restoredFiles`, `skippedFiles`, or `error`. See each field for the outcomes that populate it. + pub outcome: HistoryRewindOutcome, + /// Absolute paths restored to their captured preimages. Always empty for conversation-only rewinds and for the unavailable outcomes (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`); only conversation-and-files outcomes that reached the file-restore stage populate it. + pub restored_files: Vec, + /// Captured files intentionally left unchanged. Always empty for conversation-only rewinds and for the unavailable outcomes (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`); only conversation-and-files outcomes that reached the file-restore stage populate it. + pub skipped_files: Vec, +} + +/// Markdown summary of the conversation context (empty when not available). +/// +///
+/// +/// **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 HistorySummarizeForHandoffResult { + /// Markdown summary of the conversation context produced by an LLM. Empty string when there are no messages or when the session does not support local summarization. + pub summary: String, +} + +/// Identifier of the event to truncate to; this event and all later events are removed. +/// +///
+/// +/// **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 HistoryTruncateRequest { + /// Event ID to truncate to. This event and all events after it are removed from the session. + pub event_id: String, +} + +/// Number of events that were removed by the truncation. +/// +///
+/// +/// **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 HistoryTruncateResult { + /// Failure detail when checkpointCleanupFailed is true. + #[serde(skip_serializing_if = "Option::is_none")] + pub checkpoint_cleanup_error: Option, + /// True when conversation truncation succeeded but post-truncation workspace checkpoint cleanup failed. History is already truncated; callers may still prune snapshots but should report a checkpoint-cleanup rather than a truncation failure. + #[serde(skip_serializing_if = "Option::is_none")] + pub checkpoint_cleanup_failed: Option, + /// Number of events that were removed + pub events_removed: i64, +} + +/// Authentication-info variant for GitHub-internal HMAC auth, carrying the public GitHub host and HMAC secret. +/// +///
+/// +/// **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 HMACAuthInfo { + /// 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. + #[serde(skip_serializing_if = "Option::is_none")] + pub copilot_user: Option, + /// HMAC secret used to sign requests. + pub hmac: String, + /// Authentication host. HMAC auth always targets the public GitHub host. + pub host: HMACAuthInfoHost, + /// HMAC-based authentication used by GitHub-internal services. + pub r#type: HMACAuthInfoType, +} + +/// Runtime-owned wire payload for a server-to-client hook callback invocation. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct HookInvokeRequest { + #[doc(hidden)] + pub(crate) hook_type: HookType, + pub input: serde_json::Value, + pub session_id: SessionId, +} + +/// Optional output returned by an SDK callback hook. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct HookInvokeResponse { + #[serde(skip_serializing_if = "Option::is_none")] + pub output: Option, +} + +/// Installed plugin record from global state, with marketplace, version, install time, enabled state, cache path, and source. +/// +///
+/// +/// **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 InstalledPlugin { + /// Path where the plugin is cached locally + #[serde(rename = "cache_path", skip_serializing_if = "Option::is_none")] + pub cache_path: Option, + /// Whether the plugin is currently enabled pub enabled: bool, /// Installation timestamp #[serde(rename = "installed_at")] @@ -4482,7 +5214,7 @@ pub struct InstalledPluginInfo { pub version: Option, } -/// Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref, and optional subpath. +/// Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref or full commit SHA, and optional subpath. /// ///
/// @@ -4498,6 +5230,9 @@ pub struct InstalledPluginSourceGitHub { #[serde(skip_serializing_if = "Option::is_none")] pub r#ref: Option, pub repo: String, + /// Optional full 40-character hexadecimal commit SHA. + #[serde(skip_serializing_if = "Option::is_none")] + pub sha: Option, /// Constant value. Always "github". pub source: InstalledPluginSourceGitHubSource, } @@ -4518,7 +5253,7 @@ pub struct InstalledPluginSourceLocal { pub source: InstalledPluginSourceLocalSource, } -/// Source descriptor for a direct URL plugin install, with URL, optional ref, and optional subpath. +/// Source descriptor for a direct URL plugin install, with URL, optional ref or full commit SHA, and optional subpath. /// ///
/// @@ -4533,6 +5268,9 @@ pub struct InstalledPluginSourceUrl { pub path: Option, #[serde(skip_serializing_if = "Option::is_none")] pub r#ref: Option, + /// Optional full 40-character hexadecimal commit SHA. + #[serde(skip_serializing_if = "Option::is_none")] + pub sha: Option, /// Constant value. Always "url". pub source: InstalledPluginSourceUrlSource, pub url: String, @@ -4643,7 +5381,7 @@ pub struct InstructionSource { pub label: String, /// Where this source lives — used for UI grouping pub location: InstructionSourceLocation, - /// The project path this source was discovered from. Only set by sessionless discovery for repository/working-directory sources, where it disambiguates same-named files (e.g. .github/copilot-instructions.md) across multiple workspace roots. The session-scoped getSources leaves it unset. + /// The project path this source was discovered from. Only set by sessionless discovery for repository, working-directory, and project-scoped plugin sources, where it disambiguates sources across multiple workspace roots. The session-scoped getSources leaves it unset. #[serde(skip_serializing_if = "Option::is_none")] pub project_path: Option, /// File path relative to repo or absolute for home @@ -4667,6 +5405,37 @@ pub struct InstructionsGetSourcesResult { pub sources: Vec, } +/// Parameters for interrupting the main agent turn. +/// +///
+/// +/// **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 InterruptMainTurnRequest { + /// When true, the user's queued prompts are preserved and run as the next turn once the interrupted turn unwinds; when false (the default), the queue is cleared like a plain abort. + #[serde(skip_serializing_if = "Option::is_none")] + pub flush_queued: Option, +} + +/// Result of interrupting the main agent turn. +/// +///
+/// +/// **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 InterruptMainTurnResult { + /// Whether an in-flight main agent turn was interrupted. False when the main loop was not processing. + pub interrupted: bool, +} + /// A request body chunk or cancellation signal. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -5662,7 +6431,7 @@ pub struct McpExecuteSamplingParams { pub server_name: String, } -/// MCP server filtered by policy, with name, reason, optional redacted reason, and enterprise login. +/// MCP server filtered by policy, with name, reason, and optional redacted reason. /// ///
/// @@ -5673,7 +6442,9 @@ pub struct McpExecuteSamplingParams { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpFilteredServer { - /// Enterprise login associated with an allowlist policy + /// Deprecated. This field is no longer populated. + #[doc(hidden)] + #[deprecated] #[serde(skip_serializing_if = "Option::is_none")] pub enterprise_name: Option, /// Filtered server name @@ -5780,7 +6551,7 @@ pub struct McpHostState { pub disabled_servers: Vec, /// Map of server name to recorded connection failure. pub failed_servers: HashMap, - /// Configured servers filtered out by enterprise allowlist policy. + /// Configured servers filtered out by MCP server policy. pub filtered_servers: Vec, /// Whether third-party MCP servers are policy-enabled for this session. pub mcp3p_enabled: bool, @@ -5994,6 +6765,36 @@ pub struct McpOauthLoginResult { pub authorization_url: Option, } +/// Pending MCP OAuth request id to respond to. +/// +///
+/// +/// **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 McpOauthRespondRequest { + /// OAuth request identifier from the mcp.oauth_required event + pub request_id: RequestId, +} + +/// Indicates whether the pending MCP OAuth response was accepted. +/// +///
+/// +/// **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 McpOauthRespondResult { + /// Whether the response was accepted. False if the request was unknown, timed out, or already resolved. + pub success: bool, +} + /// Registration parameters for an external MCP client. /// ///
@@ -6412,6 +7213,9 @@ pub struct McpServerConfigHttp { /// Controls if tools provided by this server can be loaded on demand via tool search (auto) or always included in the initial tool list (never) #[serde(skip_serializing_if = "Option::is_none")] pub defer_tools: Option, + /// Set to true to disable persisted MCP tool snapshots for this server. Live tool discovery is unaffected. + #[serde(skip_serializing_if = "Option::is_none")] + pub disable_tool_cache: Option, /// Content filtering mode to apply to all tools, or a map of tool name to content filtering mode. #[serde(skip_serializing_if = "Option::is_none")] pub filter_mapping: Option, @@ -6471,6 +7275,9 @@ pub struct McpServerConfigStdio { /// Controls if tools provided by this server can be loaded on demand via tool search (auto) or always included in the initial tool list (never) #[serde(skip_serializing_if = "Option::is_none")] pub defer_tools: Option, + /// Set to true to disable persisted MCP tool snapshots for this server. Live tool discovery is unaffected. + #[serde(skip_serializing_if = "Option::is_none")] + pub disable_tool_cache: Option, /// Environment variables to pass to the Stdio MCP server process. #[serde(skip_serializing_if = "Option::is_none")] pub env: Option>, @@ -6539,7 +7346,7 @@ pub struct McpSetEnvValueModeResult { pub mode: McpSetEnvValueModeDetails, } -/// Server name and configuration for an individual MCP server start. +/// Server name and optional configuration for an individual MCP server start. Omit `config` for a config-free start-by-name of an already-configured server. /// ///
/// @@ -6550,8 +7357,9 @@ pub struct McpSetEnvValueModeResult { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct McpStartServerRequest { - /// MCP server configuration (stdio process or remote HTTP/SSE) - pub config: serde_json::Value, + /// MCP server configuration (stdio process or remote HTTP/SSE). Omit to start the server with its already-registered configuration (config-free start-by-name). + #[serde(skip_serializing_if = "Option::is_none")] + pub config: Option, /// Name of the MCP server to start pub server_name: String, } @@ -6952,7 +7760,7 @@ pub struct MetadataSnapshotRemoteMetadata { pub task_type: Option, } -/// Active server-driven promotion for a model, including its discount and expiry. +/// Active server-driven promotion for a model, including its discount and optional expiry. /// ///
/// @@ -6966,12 +7774,13 @@ pub struct ModelBillingPromo { /// Percentage discount (0-100) applied while the promotion is active. May be fractional. #[serde(skip_serializing_if = "Option::is_none")] pub discount_percent: Option, - /// UTC ISO 8601 timestamp marking when the promotion ends. Always present: the API only surfaces a promo whose expiry parses and is in the future. Consumers should treat a past value as expired. - pub ends_at: String, + /// UTC ISO 8601 timestamp marking when the promotion ends. Optional: an open-ended promotion omits this field. When present, the API only surfaces a promo whose expiry parses and is in the future, so consumers should treat a past value as expired. + #[serde(skip_serializing_if = "Option::is_none")] + pub ends_at: Option, /// Stable identifier for the promotion campaign. #[serde(skip_serializing_if = "Option::is_none")] pub id: Option, - /// Human-readable promotion message. Does not include the expiry timestamp; consumers may format endsAt and append it. + /// Human-readable promotion message. Does not include the expiry timestamp; consumers may format endsAt and append it when present. #[serde(skip_serializing_if = "Option::is_none")] pub message: Option, } @@ -7075,7 +7884,7 @@ pub struct ModelBilling { /// Billing cost multiplier relative to the base rate #[serde(skip_serializing_if = "Option::is_none")] pub multiplier: Option, - /// Active server-driven promotion for this model, if any. Present when the model is being promoted with a time-boxed discount. + /// Active server-driven promotion for this model, if any. Present when the model is being promoted with a discount, which may be time-boxed or open-ended. #[serde(skip_serializing_if = "Option::is_none")] pub promo: Option, /// Token-level pricing information for this model @@ -7417,6 +8226,9 @@ pub struct ModelSwitchToRequest { /// Explicit context tier for the selected model. `"default"` / `"long_context"` apply the requested tier; omit this field to use normal model behavior with no explicit tier. #[serde(skip_serializing_if = "Option::is_none")] pub context_tier: Option, + /// When true, defer this switch (enqueue it) if another model change is already queued, even when no turn is active — so it drains last (FIFO) and wins over the already-queued change. Intended for genuine user-initiated model selections; internal restore/reapply switches omit it and apply immediately when no turn is active. When no other model change is queued this has no effect (a switch still applies immediately unless a turn is active). + #[serde(skip_serializing_if = "Option::is_none")] + pub defer_if_model_change_queued: Option, /// Override individual model capabilities resolved by the runtime #[serde(skip_serializing_if = "Option::is_none")] pub model_capabilities: Option, @@ -7444,6 +8256,9 @@ pub struct ModelSwitchToRequest { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ModelSwitchToResult { + /// True when the switch was deferred (enqueued as a cancellable `/model` command) because a turn was active or another model change was already queued, rather than applied immediately. When true, the session's live model is unchanged until the queued change drains. + #[serde(skip_serializing_if = "Option::is_none")] + pub deferred: Option, /// Currently active model identifier after the switch #[serde(skip_serializing_if = "Option::is_none")] pub model_id: Option, @@ -7677,6 +8492,9 @@ pub struct PendingPermissionRequestList { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PermissionDecisionApproveOnce { + /// True only when a host surfaced this request to a user who approved it. + #[serde(skip_serializing_if = "Option::is_none")] + pub approved_interactively: Option, /// Approve this single request only pub kind: PermissionDecisionApproveOnceKind, } @@ -8937,7 +9755,7 @@ pub struct PermissionsPathsUpdatePrimaryResult { #[serde(rename_all = "camelCase")] pub struct PermissionsPendingRequestsRequest {} -/// No parameters; clears all session-scoped tool permission approvals. +/// Clears session-scoped tool permission approvals, and optionally the location-scoped ones. /// ///
/// @@ -8947,7 +9765,11 @@ pub struct PermissionsPendingRequestsRequest {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct PermissionsResetSessionApprovalsRequest {} +pub struct PermissionsResetSessionApprovalsRequest { + /// Whether location-scoped approvals are cleared too. Defaults to `true`. + #[serde(skip_serializing_if = "Option::is_none")] + pub include_location: Option, +} /// Indicates whether the operation succeeded. /// @@ -10214,7 +11036,7 @@ pub struct PushAttachmentSelection { pub r#type: PushAttachmentSelectionType, } -/// Queued-command response indicating the host executed the command, with an optional flag to stop queue processing. +/// Inputs for starting a deferred-idle drain. /// ///
/// @@ -10224,15 +11046,12 @@ pub struct PushAttachmentSelection { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct QueuedCommandHandled { - /// The host actually executed the queued command. - pub handled: bool, - /// When true, the runtime will not process subsequent queued commands until a new request comes in. - #[serde(skip_serializing_if = "Option::is_none")] - pub stop_processing_queue: Option, +pub struct QueueBeginDeferredIdleDrainRequest { + /// Whether the host still has active background work. + pub active_background_work: bool, } -/// Queued-command response indicating the host did not execute the command and the queue may continue. +/// Whether a deferred-idle drain should run. /// ///
/// @@ -10242,12 +11061,12 @@ pub struct QueuedCommandHandled { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct QueuedCommandNotHandled { - /// The host did not execute the queued command. Unblocks the queue without claiming the command was processed (e.g. when the handler threw before completing). - pub handled: bool, +pub struct QueueBeginDeferredIdleDrainResult { + /// True when the host should run finishDeferredIdleDrain asynchronously. + pub should_drain: bool, } -/// User-facing pending queue entry, with kind and display text for a queued message, slash command, or model change. +/// Internal filter for consuming queued system notifications. /// ///
/// @@ -10257,14 +11076,12 @@ pub struct QueuedCommandNotHandled { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct QueuePendingItems { - /// Human-readable text to display for this queue entry in the UI - pub display_text: String, - /// Whether this item is a queued user message or a queued slash command / model change - pub kind: QueuePendingItemsKind, +pub struct QueueConsumeSystemNotificationsRequest { + /// Opaque runtime-owned filter object. + pub filter: serde_json::Value, } -/// Snapshot of the session's pending queued items and immediate-steering messages. +/// Queued-command response indicating the host executed the command, with an optional flag to stop queue processing. /// ///
/// @@ -10274,14 +11091,15 @@ pub struct QueuePendingItems { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct QueuePendingItemsResult { - /// Pending queued items in submission order. Includes user messages, queued slash commands, and queued model changes; omits internal system items. - pub items: Vec, - /// Display text for messages currently in the immediate steering queue (interjections sent during a running turn). - pub steering_messages: Vec, +pub struct QueuedCommandHandled { + /// The host actually executed the queued command. + pub handled: bool, + /// When true, the runtime will not process subsequent queued commands until a new request comes in. + #[serde(skip_serializing_if = "Option::is_none")] + pub stop_processing_queue: Option, } -/// Indicates whether a user-facing pending item was removed. +/// Queued-command response indicating the host did not execute the command and the queue may continue. /// ///
/// @@ -10291,12 +11109,12 @@ pub struct QueuePendingItemsResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct QueueRemoveMostRecentResult { - /// True if a user-facing pending item was removed (LIFO across both queues); false when no removable items remained. - pub removed: bool, +pub struct QueuedCommandNotHandled { + /// The host did not execute the queued command. Unblocks the queue without claiming the command was processed (e.g. when the handler threw before completing). + pub handled: bool, } -/// Event type to register consumer interest for, used by runtime gating logic. +/// Inputs for marking session.idle deferred in native state. /// ///
/// @@ -10306,12 +11124,12 @@ pub struct QueueRemoveMostRecentResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RegisterEventInterestParams { - /// The event type the consumer wants the runtime to treat as 'observed' for behavior-switching gating. Some runtime code paths inspect whether any consumer is interested in a specific event type and choose a different implementation accordingly (e.g. `mcp.oauth_required`: when interest is registered the runtime delegates interactive OAuth token acquisition to the consumer via `mcp.oauth_required` events; when no interest is registered the runtime still attempts non-interactive reconnect from cached or refreshable tokens, and only marks the server `needs-auth` if usable credentials are unavailable — it does not open a browser or start interactive OAuth without a consumer). SDK clients that long-poll events do NOT automatically appear as listeners to these gating checks — they must explicitly call `registerInterest` for each event type they want the runtime to count as having a consumer. Multiple registrations for the same event type from the same or different consumers are tracked independently and must each be released. See: `mcp.oauth_required`, `sampling.requested`, `auto_mode_switch.requested`, `session_limits_exhausted.requested`, `user_input.requested`, `elicitation.requested`, `command.queued`, `exit_plan_mode.requested`. - pub event_type: String, +pub struct QueueDeferSessionIdleRequest { + /// Whether the deferred idle was caused by an aborted foreground turn. + pub aborted: bool, } -/// Opaque handle representing an event-type interest registration. +/// Parameters for duplicating a queued item. /// ///
/// @@ -10321,12 +11139,11 @@ pub struct RegisterEventInterestParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RegisterEventInterestResult { - /// Opaque handle for this registration. Pass to releaseInterest to release. Each call to registerInterest produces a fresh handle, even when the same eventType is registered multiple times. - pub handle: String, +pub struct QueueDuplicateAtRequest { + pub id: String, } -/// Optional registration options. +/// Result of duplicating a queued item. /// ///
/// @@ -10336,14 +11153,12 @@ pub struct RegisterEventInterestResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsRegisterExtensionToolsOnSessionOptions { - /// In-process `() => boolean` gating callback (CLI-only optimization). Marked internal: replaced by runtime-side enable/disable RPCs in the SDK migration. - #[doc(hidden)] - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) enabled: Option, +pub struct QueueDuplicateAtResult { + /// Fresh stable opaque id assigned to the duplicate. + pub id: String, } -/// Params to attach an extension loader's tools to a session. +/// Result of enqueueing the resume-pending wake item. /// ///
/// @@ -10353,18 +11168,12 @@ pub struct SessionsRegisterExtensionToolsOnSessionOptions { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub(crate) struct RegisterExtensionToolsParams { - /// In-process ExtensionLoader handle (CLI-only optimization). Marked internal: this field is excluded from the public SDK surface. When the CLI migrates to a process-separated SDK, extension discovery/launch moves entirely into the runtime — the CLI passes pure config (search paths, disabled ids) via SessionOptions instead. - #[doc(hidden)] - pub(crate) loader: serde_json::Value, - /// Optional registration options. - #[serde(skip_serializing_if = "Option::is_none")] - pub options: Option, - /// Session to register extension tools on. - pub session_id: SessionId, +pub struct QueueEnqueueResumePendingResult { + /// True when a wake item was newly queued. + pub queued: bool, } -/// Handle for releasing the extension tool registration. +/// Inputs for completing a deferred-idle drain. /// ///
/// @@ -10374,13 +11183,14 @@ pub(crate) struct RegisterExtensionToolsParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub(crate) struct RegisterExtensionToolsResult { - /// In-process unsubscribe function (CLI-only optimization). Marked internal: replaced by an explicit `extensions.unregister` RPC in the SDK migration. - #[doc(hidden)] - pub(crate) unsubscribe: serde_json::Value, +pub struct QueueFinishDeferredIdleDrainRequest { + /// Whether the host still has active background work. + pub active_background_work: bool, + /// Whether native queued work remains. + pub has_pending: bool, } -/// Opaque handle previously returned by `registerInterest` to release. +/// Action selected by the native deferred-idle drain. /// ///
/// @@ -10390,12 +11200,14 @@ pub(crate) struct RegisterExtensionToolsResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ReleaseEventInterestParams { - /// Handle returned by a previous `registerInterest` call. Idempotent: releasing an unknown or already-released handle is a no-op (returns success). When the last outstanding handle for an event type is released, the runtime reverts to its 'no consumer' code path for that event type. - pub handle: String, +pub struct QueueFinishDeferredIdleDrainResult { + /// Whether the deferred idle was caused by an aborted foreground turn. + pub aborted: bool, + /// One of none, processQueue, or emitSessionIdle. + pub action: String, } -/// Reattach to an existing MC session without creating a new one. +/// Whether the native queue has pending work. /// ///
/// @@ -10405,14 +11217,12 @@ pub struct ReleaseEventInterestParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RemoteControlConfigExistingMcSession { - /// Existing MC session ID to reattach to. - pub mc_session_id: String, - /// Existing MC task ID for the reattached session. - pub mc_task_id: String, +pub struct QueueHasPendingResult { + /// True when queued or immediate native work is pending. + pub has_pending: bool, } -/// Configuration for the runtime-managed remote-control singleton. +/// Serializable message fields accepted by queue.insertAt. /// ///
/// @@ -10422,54 +11232,45 @@ pub struct RemoteControlConfigExistingMcSession { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RemoteControlConfig { - /// Reattach to an existing MC session without creating a new one. +pub struct QueueInsertMessage { + /// Optional explicit agent mode. When omitted, the session's current mode is assigned. #[serde(skip_serializing_if = "Option::is_none")] - pub existing_mc_session: Option, - /// Whether the user explicitly requested remote (vs. implicit session-sync). Controls warning surfacing for missing-repo cases. - pub explicit: bool, - /// Whether remote export should be enabled. - pub remote: bool, - /// When true, suppresses timeline messages on successful setup. - pub silent: bool, - /// Whether the MC session may steer the local session (write mode). - pub steerable: bool, - /// Existing Mission Control task ID to attach the exported session to. + pub agent_mode: Option, + /// Optional attachments for the message. #[serde(skip_serializing_if = "Option::is_none")] - pub task_id: Option, -} - -/// Remote control is connected to a local 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 RemoteControlStatusActive { - /// Session id remote control is pointed at. - pub attached_session_id: String, - /// True while a read-only/session-sync export is deferred, awaiting the first `user.message` before its MC session exists. Marked internal: this field is excluded from the public SDK surface and is populated only on the CLI in-process path. - #[doc(hidden)] + pub attachments: Option>, + /// Whether the message is billable. #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) awaiting_first_message: Option, - /// MC frontend URL for this session, when known. + pub billable: Option, + /// Accepted for internal SendOptions compatibility but ignored; delivery is derived from current session activity. #[serde(skip_serializing_if = "Option::is_none")] - pub frontend_url: Option, - /// Whether the MC session may steer this session. - pub is_steerable: bool, - /// In-process prompt-manager handle (CLI-only optimization). Marked internal: this field is excluded from the public SDK surface. When the CLI migrates to a process-separated SDK, the same bidirectional prompt-routing handshake is expressed via dedicated remote-control RPCs (register/resolve) rather than a shared in-process object. - #[doc(hidden)] + pub delivery: Option, + /// Optional user-facing display text. #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) prompt_manager: Option, - /// Remote control state tag: active. - pub state: RemoteControlStatusActiveState, + pub display_prompt: Option, + /// Accepted for SendOptions compatibility but ignored; inserted items always use queued delivery semantics. + #[serde(skip_serializing_if = "Option::is_none")] + pub mode: Option, + /// Accepted for SendOptions compatibility but ignored; the requested public position controls placement. + #[serde(skip_serializing_if = "Option::is_none")] + pub prepend: Option, + /// The user message text. + pub prompt: String, + /// Per-turn request headers. + #[serde(skip_serializing_if = "Option::is_none")] + pub request_headers: Option>, + /// Required tool name for the turn, when any. + #[serde(skip_serializing_if = "Option::is_none")] + pub required_tool: Option, + /// Optional provenance source. `system` is rejected: it would hide the inserted row from `pendingItems` and make it unaddressable while still executing, so inserted items must stay visible. + #[serde(skip_serializing_if = "Option::is_none")] + pub source: Option, + /// Accepted for SendOptions compatibility but ignored; insertion scheduling is controlled by the queue drain state. + #[serde(skip_serializing_if = "Option::is_none")] + pub wait: Option, } -/// Remote control is in the middle of initial setup. +/// Parameters for inserting a queued message at a public visible position. /// ///
/// @@ -10479,14 +11280,13 @@ pub struct RemoteControlStatusActive { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RemoteControlStatusConnecting { - /// Session id the connection is attaching to. - pub attached_session_id: String, - /// Remote control state tag: connecting. - pub state: RemoteControlStatusConnectingState, +pub struct QueueInsertAtRequest { + pub message: QueueInsertMessage, + /// Zero-based position in the public visible queue. Values outside the queue clamp to an end. + pub position: i64, } -/// The last setup attempt failed. The singleton is otherwise off. +/// Result of inserting a queued message. /// ///
/// @@ -10496,17 +11296,12 @@ pub struct RemoteControlStatusConnecting { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RemoteControlStatusError { - /// Session id the failing setup attempt targeted, when known. - #[serde(skip_serializing_if = "Option::is_none")] - pub attached_session_id: Option, - /// Human-readable error message from the last setup attempt. - pub error: String, - /// Remote control state tag: setup failed. - pub state: RemoteControlStatusErrorState, +pub struct QueueInsertAtResult { + /// Fresh stable opaque id assigned to the inserted item. + pub id: String, } -/// Remote control is not connected. +/// Parameters for moving a queued item by stable id. /// ///
/// @@ -10516,12 +11311,14 @@ pub struct RemoteControlStatusError { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RemoteControlStatusOff { - /// Remote control state tag: not connected. - pub state: RemoteControlStatusOffState, +pub struct QueueMoveItemRequest { + /// Stable opaque queued-item id. + pub id: String, + /// Zero-based target position in the public visible queue. Values outside the queue clamp to an end. + pub to_position: i64, } -/// Wrapper for the singleton's current status. +/// Result of moving a queued item. /// ///
/// @@ -10531,12 +11328,12 @@ pub struct RemoteControlStatusOff { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RemoteControlStatusResult { - /// State of the runtime-managed remote-control singleton. - pub status: serde_json::Value, +pub struct QueueMoveItemResult { + /// True when the item changed position; false when it was already at the requested position. + pub changed: bool, } -/// Outcome of a stopRemoteControl call. +/// User-facing pending queue entry, with kind and display text for a queued message, slash command, or model change. /// ///
/// @@ -10546,14 +11343,18 @@ pub struct RemoteControlStatusResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RemoteControlStopResult { - /// State of the runtime-managed remote-control singleton. - pub status: serde_json::Value, - /// Whether the singleton was actually torn down by this call. - pub stopped: bool, +pub struct QueuePendingItems { + /// Agent mode stored on this queued entry, as stamped when it was enqueued. Items without an explicit mode report interactive. This is not necessarily the mode that will constrain the turn: a plan or autopilot session applies its own write gate, continuation loop and permission posture to every drained item regardless of the mode stored here. + pub agent_mode: SendAgentMode, + /// Human-readable text to display for this queue entry in the UI + pub display_text: String, + /// Stable opaque id for the canonical queued item. Batch rows share one id. + pub id: String, + /// Whether this item is a queued user message or a queued slash command / model change + pub kind: QueuePendingItemsKind, } -/// Outcome of a transferRemoteControl call. +/// Snapshot of the session's pending queued items and immediate-steering messages. /// ///
/// @@ -10563,14 +11364,14 @@ pub struct RemoteControlStopResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RemoteControlTransferResult { - /// State of the runtime-managed remote-control singleton. - pub status: serde_json::Value, - /// Whether the rebinding actually happened. - pub transferred: bool, +pub struct QueuePendingItemsResult { + /// Pending queued items in submission order. Includes user messages, queued slash commands, and queued model changes; omits internal system items. + pub items: Vec, + /// Display text for messages currently in the immediate steering queue (interjections sent during a running turn). + pub steering_messages: Vec, } -/// Optional remote session mode ("off", "export", or "on"); defaults to enabling both export and remote steering. +/// Parameters for removing a queued item by stable id. /// ///
/// @@ -10580,13 +11381,11 @@ pub struct RemoteControlTransferResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RemoteEnableRequest { - /// Per-session remote mode. "off" disables remote, "export" exports session events to GitHub without enabling remote steering, "on" enables both export and remote steering. - #[serde(skip_serializing_if = "Option::is_none")] - pub mode: Option, +pub struct QueueRemoveAtRequest { + pub id: String, } -/// GitHub URL for the session and a flag indicating whether remote steering is enabled. +/// Result of removing a queued item. /// ///
/// @@ -10596,15 +11395,12 @@ pub struct RemoteEnableRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RemoteEnableResult { - /// Whether remote steering is enabled - pub remote_steerable: bool, - /// GitHub frontend URL for this session - #[serde(skip_serializing_if = "Option::is_none")] - pub url: Option, +pub struct QueueRemoveAtResult { + /// True when the addressed item was removed. + pub removed: bool, } -/// New remote-steerability state to persist as a `session.remote_steerable_changed` event. +/// Indicates whether a user-facing pending item was removed. /// ///
/// @@ -10614,12 +11410,12 @@ pub struct RemoteEnableResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RemoteNotifySteerableChangedRequest { - /// Whether the session now supports remote steering via GitHub. The runtime persists this as a `session.remote_steerable_changed` event so resume/replay sees the up-to-date capability. - pub remote_steerable: bool, +pub struct QueueRemoveMostRecentResult { + /// True if a user-facing pending item was removed (LIFO across both queues); false when no removable items remained. + pub removed: bool, } -/// Persist a steerability change as a `session.remote_steerable_changed` event. Used by the host (CLI / SDK consumer) when it has just finished enabling or disabling steering on a remote exporter that the runtime does not directly own. +/// Parameters for steering a queued message into a live turn. /// ///
/// @@ -10629,9 +11425,11 @@ pub struct RemoteNotifySteerableChangedRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RemoteNotifySteerableChangedResult {} +pub struct QueueSendNowRequest { + pub id: String, +} -/// Remote session connection result. +/// Result of trying to steer a queued message into a live turn. /// ///
/// @@ -10641,14 +11439,12 @@ pub struct RemoteNotifySteerableChangedResult {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RemoteSessionConnectionResult { - /// Metadata for a connected remote session. - pub metadata: ConnectedRemoteSessionMetadata, - /// SDK session ID for the connected remote session. - pub session_id: SessionId, +pub struct QueueSendNowResult { + /// True when the item was accepted into the steering lane; false when no main turn was live. + pub steered: bool, } -/// GitHub repository the remote session belongs to. +/// Parameters for acquiring or releasing the queued-lane drain pause. Acquisition is exclusive and non-idempotent: `paused: true` against an already-paused session fails with `queue_already_paused`. The pause is never released automatically — it is not tied to the caller's lifetime, so a client that exits without sending `paused: false` leaves the lane frozen. Release is unowned: `paused: false` clears the pause for any caller, including one that never acquired it. /// ///
/// @@ -10658,16 +11454,11 @@ pub struct RemoteSessionConnectionResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RemoteSessionMetadataRepository { - /// Branch associated with the remote session. - pub branch: String, - /// Repository name. - pub name: String, - /// Repository owner. - pub owner: String, +pub struct QueueSetDrainPausedRequest { + pub paused: bool, } -/// Remote session metadata for the session to hand off (typically obtained from `sessions.list` with `source: "remote"`). +/// Internal snapshot of native queue state for local session orchestration. /// ///
/// @@ -10677,46 +11468,20 @@ pub struct RemoteSessionMetadataRepository { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RemoteSessionMetadataValue { - /// Most recent working directory context. - #[serde(skip_serializing_if = "Option::is_none")] - pub context: Option, - /// Always true for remote sessions. - pub is_remote: bool, - /// Last-modified time as an ISO 8601 timestamp. - pub modified_time: String, - /// Optional human-friendly name set via /rename. - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - /// Pull request number associated with the session. - #[serde(skip_serializing_if = "Option::is_none")] - pub pull_request_number: Option, - /// Backing remote session IDs (most recent first). - pub remote_session_ids: Vec, - /// GitHub repository the remote session belongs to. - pub repository: RemoteSessionMetadataRepository, - /// Original remote resource identifier (task ID or PR node ID). - #[serde(skip_serializing_if = "Option::is_none")] - pub resource_id: Option, - /// Stable session identifier. - pub session_id: SessionId, - /// Deadline (ISO 8601) at which a CLI remote session becomes stale without further heartbeats. - #[serde(skip_serializing_if = "Option::is_none")] - pub stale_at: Option, - /// Session creation time as an ISO 8601 timestamp. - pub start_time: String, - /// Server-side task state returned by GitHub. - #[serde(skip_serializing_if = "Option::is_none")] - pub state: Option, - /// Short summary of the session, when one has been derived. +pub struct QueueSnapshotResult { + /// Insertion orders for queued items, aligned with `items`. #[serde(skip_serializing_if = "Option::is_none")] - pub summary: Option, - /// Whether the remote task originated from CCA or CLI `--remote`. + pub item_orders: Option>, + /// User-facing pending items in FIFO order. + pub items: Vec, + /// Insertion orders for immediate steering messages, aligned with `steeringMessages`. #[serde(skip_serializing_if = "Option::is_none")] - pub task_type: Option, + pub steering_message_orders: Option>, + /// Immediate steering messages waiting for an active turn. + pub steering_messages: Vec, } -/// Repository context for the remote session. +/// Parameters for editing a single queued message. /// ///
/// @@ -10726,17 +11491,14 @@ pub struct RemoteSessionMetadataValue { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct RemoteSessionRepository { - /// Optional branch associated with the remote session. +pub struct QueueUpdateTextRequest { #[serde(skip_serializing_if = "Option::is_none")] - pub branch: Option, - /// Repository name. - pub name: String, - /// Repository owner or organization login. - pub owner: String, + pub display_prompt: Option, + pub id: String, + pub prompt: String, } -/// macOS seatbelt experimental options. +/// Result of editing a queued message. /// ///
/// @@ -10746,13 +11508,12 @@ pub struct RemoteSessionRepository { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SandboxConfigUserPolicyExperimentalSeatbelt { - /// Whether the macOS seatbelt profile may access the keychain. - #[serde(skip_serializing_if = "Option::is_none")] - pub keychain_access: Option, +pub struct QueueUpdateTextResult { + /// True when the stored text changed. + pub updated: bool, } -/// Platform-specific experimental policy fields. +/// Event type to register consumer interest for, used by runtime gating logic. /// ///
/// @@ -10762,13 +11523,12 @@ pub struct SandboxConfigUserPolicyExperimentalSeatbelt { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SandboxConfigUserPolicyExperimental { - /// macOS seatbelt experimental options. - #[serde(skip_serializing_if = "Option::is_none")] - pub seatbelt: Option, +pub struct RegisterEventInterestParams { + /// The event type the consumer wants the runtime to treat as 'observed' for behavior-switching gating. Some runtime code paths inspect whether any consumer is interested in a specific event type and choose a different implementation accordingly (e.g. `mcp.oauth_required`: when interest is registered the runtime delegates interactive OAuth token acquisition to the consumer via `mcp.oauth_required` events; when no interest is registered the runtime still attempts non-interactive reconnect from cached or refreshable tokens, and only marks the server `needs-auth` if usable credentials are unavailable — it does not open a browser or start interactive OAuth without a consumer). SDK clients that long-poll events do NOT automatically appear as listeners to these gating checks — they must explicitly call `registerInterest` for each event type they want the runtime to count as having a consumer. Multiple registrations for the same event type from the same or different consumers are tracked independently and must each be released. See: `mcp.oauth_required`, `sampling.requested`, `auto_mode_switch.requested`, `session_limits_exhausted.requested`, `user_input.requested`, `elicitation.requested`, `command.queued`, `exit_plan_mode.requested`. + pub event_type: String, } -/// Filesystem rules to merge into the base policy. +/// Opaque handle representing an event-type interest registration. /// ///
/// @@ -10778,22 +11538,12 @@ pub struct SandboxConfigUserPolicyExperimental { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SandboxConfigUserPolicyFilesystem { - /// Whether to clear the policy when the session exits. - #[serde(skip_serializing_if = "Option::is_none")] - pub clear_policy_on_exit: Option, - /// Paths explicitly denied. - #[serde(skip_serializing_if = "Option::is_none")] - pub denied_paths: Option>, - /// Paths granted read-only access. - #[serde(skip_serializing_if = "Option::is_none")] - pub readonly_paths: Option>, - /// Paths granted read/write access. - #[serde(skip_serializing_if = "Option::is_none")] - pub readwrite_paths: Option>, +pub struct RegisterEventInterestResult { + /// Opaque handle for this registration. Pass to releaseInterest to release. Each call to registerInterest produces a fresh handle, even when the same eventType is registered multiple times. + pub handle: String, } -/// Network rules to merge into the base policy. +/// Optional registration options. /// ///
/// @@ -10803,16 +11553,14 @@ pub struct SandboxConfigUserPolicyFilesystem { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SandboxConfigUserPolicyNetwork { - /// Whether traffic to local/loopback addresses is allowed. - #[serde(skip_serializing_if = "Option::is_none")] - pub allow_local_network: Option, - /// Whether outbound network traffic is allowed at all. +pub struct SessionsRegisterExtensionToolsOnSessionOptions { + /// In-process `() => boolean` gating callback (CLI-only optimization). Marked internal: replaced by runtime-side enable/disable RPCs in the SDK migration. + #[doc(hidden)] #[serde(skip_serializing_if = "Option::is_none")] - pub allow_outbound: Option, + pub(crate) enabled: Option, } -/// macOS seatbelt-specific options. +/// Params to attach an extension loader's tools to a session. /// ///
/// @@ -10822,13 +11570,18 @@ pub struct SandboxConfigUserPolicyNetwork { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SandboxConfigUserPolicySeatbelt { - /// Whether the macOS seatbelt profile may access the keychain. +pub(crate) struct RegisterExtensionToolsParams { + /// In-process ExtensionLoader handle (CLI-only optimization). Marked internal: this field is excluded from the public SDK surface. When the CLI migrates to a process-separated SDK, extension discovery/launch moves entirely into the runtime — the CLI passes pure config (search paths, disabled ids) via SessionOptions instead. + #[doc(hidden)] + pub(crate) loader: serde_json::Value, + /// Optional registration options. #[serde(skip_serializing_if = "Option::is_none")] - pub keychain_access: Option, + pub options: Option, + /// Session to register extension tools on. + pub session_id: SessionId, } -/// User-managed sandbox policy fragment merged into the auto-discovered base policy. +/// Handle for releasing the extension tool registration. /// ///
/// @@ -10838,22 +11591,13 @@ pub struct SandboxConfigUserPolicySeatbelt { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SandboxConfigUserPolicy { - /// Deprecated legacy location for `seatbelt`; read only when the top-level `seatbelt` is absent. - #[serde(skip_serializing_if = "Option::is_none")] - pub experimental: Option, - /// Filesystem rules to merge into the base policy. - #[serde(skip_serializing_if = "Option::is_none")] - pub filesystem: Option, - /// Network rules to merge into the base policy. - #[serde(skip_serializing_if = "Option::is_none")] - pub network: Option, - /// macOS seatbelt options to merge into the base policy. - #[serde(skip_serializing_if = "Option::is_none")] - pub seatbelt: Option, +pub(crate) struct RegisterExtensionToolsResult { + /// In-process unsubscribe function (CLI-only optimization). Marked internal: replaced by an explicit `extensions.unregister` RPC in the SDK migration. + #[doc(hidden)] + pub(crate) unsubscribe: serde_json::Value, } -/// Resolved sandbox configuration. +/// Opaque handle previously returned by `registerInterest` to release. /// ///
/// @@ -10863,24 +11607,12 @@ pub struct SandboxConfigUserPolicy { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SandboxConfig { - /// Whether to auto-add the current working directory to readwritePaths. Default: true. - #[serde(skip_serializing_if = "Option::is_none")] - pub add_current_working_directory: Option, - /// Whether sandboxing is enabled for the session. - pub enabled: bool, - /// Whether to export `GH_TOKEN` so the `gh` CLI authenticates inside the sandbox without the OS keyring the sandbox blocks. Default: false (opt-in). - #[serde(skip_serializing_if = "Option::is_none")] - pub gh_auth: Option, - /// Whether to inject the Copilot GitHub token as an `http..extraheader` so authenticated HTTPS git works inside the sandbox without the shell-based credential helper the sandbox blocks. Default: false (opt-in). - #[serde(skip_serializing_if = "Option::is_none")] - pub git_auth: Option, - /// User-managed sandbox policy fragment merged into the auto-discovered base policy. - #[serde(skip_serializing_if = "Option::is_none")] - pub user_policy: Option, +pub struct ReleaseEventInterestParams { + /// Handle returned by a previous `registerInterest` call. Idempotent: releasing an unknown or already-released handle is a no-op (returns success). When the last outstanding handle for an event type is released, the runtime reverts to its 'no consumer' code path for that event type. + pub handle: String, } -/// Scheduled prompt entry with ID, timing (`intervalMs`, `cron`, or `at`), prompt text, recurrence, and next run time. +/// Reattach to an existing MC session without creating a new one. /// ///
/// @@ -10890,36 +11622,14 @@ pub struct SandboxConfig { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ScheduleEntry { - /// Absolute fire time (epoch milliseconds) for a one-shot calendar schedule. - #[serde(skip_serializing_if = "Option::is_none")] - pub at: Option, - /// 5-field cron expression for a recurring calendar schedule, evaluated in `tz`. - #[serde(skip_serializing_if = "Option::is_none")] - pub cron: Option, - /// Display-only label for the prompt as shown in the UI (e.g. `/skill-name` for a skill-invocation schedule). The actual enqueued prompt is `prompt`. - #[serde(skip_serializing_if = "Option::is_none")] - pub display_prompt: Option, - /// Sequential id assigned by the runtime within the session. Stable across resumes (rebuilt from the event log). - pub id: i64, - /// Interval between scheduled ticks, in milliseconds (relative-interval schedules). - #[serde(skip_serializing_if = "Option::is_none")] - pub interval_ms: Option, - /// ISO 8601 timestamp when the next tick is scheduled to fire. - pub next_run_at: String, - /// Prompt text that gets enqueued on every tick. - pub prompt: String, - /// Whether the schedule re-arms after each tick (`/every`) or fires once (`/after`). - pub recurring: bool, - /// True for a self-paced (`dynamic`) schedule: no fixed cadence; the model arms each next run via the `manage_schedule` `wakeup` action. `nextRunAt` is model-controlled. - #[serde(skip_serializing_if = "Option::is_none")] - pub self_paced: Option, - /// IANA timezone the `cron` expression is evaluated in. - #[serde(skip_serializing_if = "Option::is_none")] - pub tz: Option, +pub struct RemoteControlConfigExistingMcSession { + /// Existing MC session ID to reattach to. + pub mc_session_id: String, + /// Existing MC task ID for the reattached session. + pub mc_task_id: String, } -/// Snapshot of the currently active recurring prompts for this session. +/// Configuration for the runtime-managed remote-control singleton. /// ///
/// @@ -10929,12 +11639,24 @@ pub struct ScheduleEntry { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ScheduleList { - /// Active scheduled prompts, ordered by id. - pub entries: Vec, +pub struct RemoteControlConfig { + /// Reattach to an existing MC session without creating a new one. + #[serde(skip_serializing_if = "Option::is_none")] + pub existing_mc_session: Option, + /// Whether the user explicitly requested remote (vs. implicit session-sync). Controls warning surfacing for missing-repo cases. + pub explicit: bool, + /// Whether remote export should be enabled. + pub remote: bool, + /// When true, suppresses timeline messages on successful setup. + pub silent: bool, + /// Whether the MC session may steer the local session (write mode). + pub steerable: bool, + /// Existing Mission Control task ID to attach the exported session to. + #[serde(skip_serializing_if = "Option::is_none")] + pub task_id: Option, } -/// Identifier of the scheduled prompt to remove. +/// Remote control is connected to a local session. /// ///
/// @@ -10944,12 +11666,27 @@ pub struct ScheduleList { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ScheduleStopRequest { - /// Id of the scheduled prompt to remove. - pub id: i64, +pub struct RemoteControlStatusActive { + /// Session id remote control is pointed at. + pub attached_session_id: String, + /// True while a read-only/session-sync export is deferred, awaiting the first `user.message` before its MC session exists. Marked internal: this field is excluded from the public SDK surface and is populated only on the CLI in-process path. + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) awaiting_first_message: Option, + /// MC frontend URL for this session, when known. + #[serde(skip_serializing_if = "Option::is_none")] + pub frontend_url: Option, + /// Whether the MC session may steer this session. + pub is_steerable: bool, + /// In-process prompt-manager handle (CLI-only optimization). Marked internal: this field is excluded from the public SDK surface. When the CLI migrates to a process-separated SDK, the same bidirectional prompt-routing handshake is expressed via dedicated remote-control RPCs (register/resolve) rather than a shared in-process object. + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) prompt_manager: Option, + /// Remote control state tag: active. + pub state: RemoteControlStatusActiveState, } -/// Remove a scheduled prompt by id. The result entry is omitted if the id was unknown. +/// Remote control is in the middle of initial setup. /// ///
/// @@ -10959,13 +11696,14 @@ pub struct ScheduleStopRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ScheduleStopResult { - /// The removed entry, or omitted if no entry matched. - #[serde(skip_serializing_if = "Option::is_none")] - pub entry: Option, +pub struct RemoteControlStatusConnecting { + /// Session id the connection is attaching to. + pub attached_session_id: String, + /// Remote control state tag: connecting. + pub state: RemoteControlStatusConnectingState, } -/// Secret values to add to the redaction filter. +/// The last setup attempt failed. The singleton is otherwise off. /// ///
/// @@ -10975,12 +11713,17 @@ pub struct ScheduleStopResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SecretsAddFilterValuesRequest { - /// Raw secret values to register for redaction - pub values: Vec, +pub struct RemoteControlStatusError { + /// Session id the failing setup attempt targeted, when known. + #[serde(skip_serializing_if = "Option::is_none")] + pub attached_session_id: Option, + /// Human-readable error message from the last setup attempt. + pub error: String, + /// Remote control state tag: setup failed. + pub state: RemoteControlStatusErrorState, } -/// Confirmation that the secret values were registered. +/// Remote control is not connected. /// ///
/// @@ -10990,12 +11733,12 @@ pub struct SecretsAddFilterValuesRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SecretsAddFilterValuesResult { - /// Whether the values were successfully registered - pub ok: bool, +pub struct RemoteControlStatusOff { + /// Remote control state tag: not connected. + pub state: RemoteControlStatusOffState, } -/// Parameters for session.extensions.sendAttachmentsToMessage. +/// Wrapper for the singleton's current status. /// ///
/// @@ -11005,15 +11748,12 @@ pub struct SecretsAddFilterValuesResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SendAttachmentsToMessageParams { - /// Attachments to push into the next user-message turn. extension_context entries take the slim shape; standard variants take their full AttachmentSchema shape. - pub attachments: Vec, - /// Optional canvas instance binding the push for provenance. When supplied, the runtime resolves the canvas, verifies it is owned by the calling extension, and stamps canvasId/instanceId onto each extension_context entry. When omitted, no resolution runs and those fields stay unset on the attachment. - #[serde(skip_serializing_if = "Option::is_none")] - pub instance_id: Option, +pub struct RemoteControlStatusResult { + /// State of the runtime-managed remote-control singleton. + pub status: serde_json::Value, } -/// A single user message to append to the session as part of a `session.sendMessages` turn +/// Outcome of a stopRemoteControl call. /// ///
/// @@ -11023,29 +11763,14 @@ pub struct SendAttachmentsToMessageParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SendMessageItem { - /// Optional attachments (files, directories, selections, blobs, GitHub references) to include with this message - #[serde(skip_serializing_if = "Option::is_none")] - pub attachments: Option>, - /// If false, this message will not trigger a Premium Request Unit charge. User messages default to billable. - #[doc(hidden)] - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) billable: Option, - /// If provided, this is shown in the timeline instead of `prompt` - #[serde(skip_serializing_if = "Option::is_none")] - pub display_prompt: Option, - /// The user message text - pub prompt: String, - /// If set, the request will fail if the named tool is not available when this message is among the user messages at the start of the current exchange - #[serde(skip_serializing_if = "Option::is_none")] - pub required_tool: Option, - /// Optional provenance tag copied to the resulting user.message event. Must match one of three forms: the literal `system`, `command-` for messages originating from a command (e.g. slash command, Mission Control command), or `schedule-` for messages originating from a scheduled job. - #[doc(hidden)] - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) source: Option, +pub struct RemoteControlStopResult { + /// State of the runtime-managed remote-control singleton. + pub status: serde_json::Value, + /// Whether the singleton was actually torn down by this call. + pub stopped: bool, } -/// Parameters for sending zero or more user messages to the session in a single turn. Remote-backed (Mission Control) sessions do not support this method and will return an error. +/// Outcome of a transferRemoteControl call. /// ///
/// @@ -11055,33 +11780,14 @@ pub struct SendMessageItem { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SendMessagesRequest { - /// The UI mode the agent was in when these messages were sent. Defaults to the session's current mode. - #[serde(skip_serializing_if = "Option::is_none")] - pub agent_mode: Option, - /// The user messages to append to the conversation, in order. May be empty, in which case a single turn runs over the existing history with no new user message. - pub messages: Vec, - /// How to deliver the messages. `enqueue` (default) appends to the message queue. `immediate` interjects during an in-progress turn. - #[serde(skip_serializing_if = "Option::is_none")] - pub mode: Option, - /// If true, adds the messages to the front of the queue instead of the end - #[serde(skip_serializing_if = "Option::is_none")] - pub prepend: Option, - /// 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. - #[serde(skip_serializing_if = "Option::is_none")] - pub request_headers: Option>, - /// W3C Trace Context traceparent header for distributed tracing of this agent turn - #[serde(skip_serializing_if = "Option::is_none")] - pub traceparent: Option, - /// W3C Trace Context tracestate header for distributed tracing - #[serde(skip_serializing_if = "Option::is_none")] - pub tracestate: Option, - /// If true, await completion of the agentic loop for this turn before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageIds`; the caller can rely on the agent having processed the messages before the call resolves. - #[serde(skip_serializing_if = "Option::is_none")] - pub wait: Option, +pub struct RemoteControlTransferResult { + /// State of the runtime-managed remote-control singleton. + pub status: serde_json::Value, + /// Whether the rebinding actually happened. + pub transferred: bool, } -/// Result of sending zero or more user messages +/// Optional remote session mode ("off", "export", or "on"); defaults to enabling both export and remote steering. /// ///
/// @@ -11091,12 +11797,13 @@ pub struct SendMessagesRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SendMessagesResult { - /// Unique identifiers assigned to the messages, one per provided message in order. Empty when no messages were provided. - pub message_ids: Vec, +pub struct RemoteEnableRequest { + /// Per-session remote mode. "off" disables remote, "export" exports session events to GitHub without enabling remote steering, "on" enables both export and remote steering. + #[serde(skip_serializing_if = "Option::is_none")] + pub mode: Option, } -/// Parameters for sending a user message to the session +/// GitHub URL for the session and a flag indicating whether remote steering is enabled. /// ///
/// @@ -11106,49 +11813,15 @@ pub struct SendMessagesResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SendRequest { - /// The UI mode the agent was in when this message was sent. Defaults to the session's current mode. - #[serde(skip_serializing_if = "Option::is_none")] - pub agent_mode: Option, - /// Optional attachments (files, directories, selections, blobs, GitHub references) to include with the message +pub struct RemoteEnableResult { + /// Whether remote steering is enabled + pub remote_steerable: bool, + /// GitHub frontend URL for this session #[serde(skip_serializing_if = "Option::is_none")] - pub attachments: Option>, - /// If false, this message will not trigger a Premium Request Unit charge. User messages default to billable. - #[serde(skip_serializing_if = "Option::is_none")] - pub billable: Option, - /// If provided, this is shown in the timeline instead of `prompt` - #[serde(skip_serializing_if = "Option::is_none")] - pub display_prompt: Option, - /// How to deliver the message. `enqueue` (default) appends to the message queue. `immediate` interjects during an in-progress turn. - #[serde(skip_serializing_if = "Option::is_none")] - pub mode: Option, - /// If true, adds the message to the front of the queue instead of the end - #[serde(skip_serializing_if = "Option::is_none")] - pub prepend: Option, - /// The user message text - pub prompt: String, - /// 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. - #[serde(skip_serializing_if = "Option::is_none")] - pub request_headers: Option>, - /// If set, the request will fail if the named tool is not available when this message is among the user messages at the start of the current exchange - #[serde(skip_serializing_if = "Option::is_none")] - pub required_tool: Option, - /// Optional provenance tag copied to the resulting user.message event. Must match one of three forms: the literal `system`, `command-` for messages originating from a command (e.g. slash command, Mission Control command), or `schedule-` for messages originating from a scheduled job. - #[doc(hidden)] - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) source: Option, - /// W3C Trace Context traceparent header for distributed tracing of this agent turn - #[serde(skip_serializing_if = "Option::is_none")] - pub traceparent: Option, - /// W3C Trace Context tracestate header for distributed tracing - #[serde(skip_serializing_if = "Option::is_none")] - pub tracestate: Option, - /// If true, await completion of the agentic loop for this message before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageId`; the caller can rely on the agent having processed the message before the call resolves. - #[serde(skip_serializing_if = "Option::is_none")] - pub wait: Option, + pub url: Option, } -/// Result of sending a user message +/// New remote-steerability state to persist as a `session.remote_steerable_changed` event. /// ///
/// @@ -11158,12 +11831,12 @@ pub struct SendRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SendResult { - /// Unique identifier assigned to the message - pub message_id: String, +pub struct RemoteNotifySteerableChangedRequest { + /// Whether the session now supports remote steering via GitHub. The runtime persists this as a `session.remote_steerable_changed` event so resume/replay sees the up-to-date capability. + pub remote_steerable: bool, } -/// Agents discovered across user, project, plugin, and remote sources. +/// Persist a steerability change as a `session.remote_steerable_changed` event. Used by the host (CLI / SDK consumer) when it has just finished enabling or disabling steering on a remote exporter that the runtime does not directly own. /// ///
/// @@ -11173,12 +11846,26 @@ pub struct SendResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ServerAgentList { - /// All discovered agents across all sources - pub agents: Vec, +pub struct RemoteNotifySteerableChangedResult {} + +/// Remote session connection result. +/// +///
+/// +/// **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 RemoteSessionConnectionResult { + /// Metadata for a connected remote session. + pub metadata: ConnectedRemoteSessionMetadata, + /// SDK session ID for the connected remote session. + pub session_id: SessionId, } -/// Instruction sources discovered across user, repository, and plugin sources. +/// GitHub repository the remote session belongs to. /// ///
/// @@ -11188,12 +11875,16 @@ pub struct ServerAgentList { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ServerInstructionSourceList { - /// All discovered instruction sources - pub sources: Vec, +pub struct RemoteSessionMetadataRepository { + /// Branch associated with the remote session. + pub branch: String, + /// Repository name. + pub name: String, + /// Repository owner. + pub owner: String, } -/// Server-side skill metadata, including name, description, source, enabled/invocable state, path, project path, and argument hint. +/// Remote session metadata for the session to hand off (typically obtained from `sessions.list` with `source: "remote"`). /// ///
/// @@ -11203,29 +11894,46 @@ pub struct ServerInstructionSourceList { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ServerSkill { - /// Optional freeform hint describing the skill's expected arguments, from the `argument-hint` frontmatter field +pub struct RemoteSessionMetadataValue { + /// Most recent working directory context. #[serde(skip_serializing_if = "Option::is_none")] - pub argument_hint: Option, - /// Description of what the skill does - pub description: String, - /// Whether the skill is currently enabled (based on global config) - pub enabled: bool, - /// Unique identifier for the skill - pub name: String, - /// Absolute path to the skill file + pub context: Option, + /// Always true for remote sessions. + pub is_remote: bool, + /// Last-modified time as an ISO 8601 timestamp. + pub modified_time: String, + /// Optional human-friendly name set via /rename. #[serde(skip_serializing_if = "Option::is_none")] - pub path: Option, - /// The project path this skill belongs to (only for project/inherited skills) + pub name: Option, + /// Pull request number associated with the session. #[serde(skip_serializing_if = "Option::is_none")] - pub project_path: Option, - /// Source location type (e.g., project, personal-copilot, plugin, builtin) - pub source: SkillSource, - /// Whether the skill can be invoked by the user as a slash command - pub user_invocable: bool, + pub pull_request_number: Option, + /// Backing remote session IDs (most recent first). + pub remote_session_ids: Vec, + /// GitHub repository the remote session belongs to. + pub repository: RemoteSessionMetadataRepository, + /// Original remote resource identifier (task ID or PR node ID). + #[serde(skip_serializing_if = "Option::is_none")] + pub resource_id: Option, + /// Stable session identifier. + pub session_id: SessionId, + /// Deadline (ISO 8601) at which a CLI remote session becomes stale without further heartbeats. + #[serde(skip_serializing_if = "Option::is_none")] + pub stale_at: Option, + /// Session creation time as an ISO 8601 timestamp. + pub start_time: String, + /// Server-side task state returned by GitHub. + #[serde(skip_serializing_if = "Option::is_none")] + pub state: Option, + /// Short summary of the session, when one has been derived. + #[serde(skip_serializing_if = "Option::is_none")] + pub summary: Option, + /// Whether the remote task originated from CCA or CLI `--remote`. + #[serde(skip_serializing_if = "Option::is_none")] + pub task_type: Option, } -/// Skills discovered across global and project sources. +/// Repository context for the remote session. /// ///
/// @@ -11235,15 +11943,17 @@ pub struct ServerSkill { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ServerSkillList { - /// Messages for skills that failed to load (e.g. malformed SKILL.md). Empty when host skills are excluded so host-local paths are not disclosed to multitenant callers. +pub struct RemoteSessionRepository { + /// Optional branch associated with the remote session. #[serde(skip_serializing_if = "Option::is_none")] - pub errors: Option>, - /// All discovered skills across all sources - pub skills: Vec, + pub branch: Option, + /// Repository name. + pub name: String, + /// Repository owner or organization login. + pub owner: String, } -/// Current activity flags for the session. +/// macOS seatbelt experimental options. /// ///
/// @@ -11253,14 +11963,13 @@ pub struct ServerSkillList { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionActivity { - /// Whether an in-flight operation can currently be aborted. - pub abortable: bool, - /// Whether the session currently has active work, including running turns or tasks. - pub has_active_work: bool, +pub struct SandboxConfigUserPolicyExperimentalSeatbelt { + /// Whether the macOS seatbelt profile may access the keychain. + #[serde(skip_serializing_if = "Option::is_none")] + pub keychain_access: Option, } -/// Authentication status and account metadata for the session. +/// Platform-specific experimental policy fields. /// ///
/// @@ -11270,27 +11979,13 @@ pub struct SessionActivity { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionAuthStatus { - /// Authentication type - #[serde(skip_serializing_if = "Option::is_none")] - pub auth_type: Option, - /// Copilot plan tier (e.g., individual_pro, business) - #[serde(skip_serializing_if = "Option::is_none")] - pub copilot_plan: Option, - /// Authentication host URL - #[serde(skip_serializing_if = "Option::is_none")] - pub host: Option, - /// Whether the session has resolved authentication - pub is_authenticated: bool, - /// Authenticated login/username, if available - #[serde(skip_serializing_if = "Option::is_none")] - pub login: Option, - /// Human-readable authentication status description +pub struct SandboxConfigUserPolicyExperimental { + /// macOS seatbelt experimental options. #[serde(skip_serializing_if = "Option::is_none")] - pub status_message: Option, + pub seatbelt: Option, } -/// Map of sessionId -> bytes freed by removing the session's workspace directory. +/// Filesystem rules to merge into the base policy. /// ///
/// @@ -11300,39 +11995,65 @@ pub struct SessionAuthStatus { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionBulkDeleteResult { - /// Map of sessionId -> bytes freed by removing the session's workspace directory. Sessions whose deletion failed are omitted from this map (failures are logged on the server but not surfaced per-id; check the map for absent IDs to detect them). - pub freed_bytes: HashMap, +pub struct SandboxConfigUserPolicyFilesystem { + /// Whether to clear the policy when the session exits. + #[serde(skip_serializing_if = "Option::is_none")] + pub clear_policy_on_exit: Option, + /// Paths explicitly denied. + #[serde(skip_serializing_if = "Option::is_none")] + pub denied_paths: Option>, + /// Paths granted read-only access. + #[serde(skip_serializing_if = "Option::is_none")] + pub readonly_paths: Option>, + /// Paths granted read/write access. + #[serde(skip_serializing_if = "Option::is_none")] + pub readwrite_paths: Option>, } -/// Successful compaction history for the session. +/// HTTP proxy configuration for sandboxed traffic. +/// +///
+/// +/// **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 SessionContextAttributionCompactions { - /// Number of successful compactions in this session. - pub count: i64, +pub struct SandboxConfigUserPolicyNetworkProxy { + /// Optional password for proxy authentication, combined with the URL at spawn time. The persisted value may be a literal password, a `${secret:…}` reference resolved from the OS keychain, or a `${VAR}`/`$VAR` environment reference; it is resolved just before the sandboxed process routes through the proxy. The /sandbox dialog stores a real password in the OS keychain and persists only a `${secret:…}` placeholder (never plaintext in settings.json); the field is masked in the dialog and redacted by /settings show. + #[serde(skip_serializing_if = "Option::is_none")] + pub password: Option, + /// Proxy URL (e.g. http://proxy.example.com:8080). The port is optional and defaults to the scheme's standard port when omitted. Credentials must not be embedded here — a `user:pass@` authority is rejected; put them in the separate `username`/`password` fields. A credential-free http:// loopback URL is routed through the localhost proxy automatically; loopback covers localhost and any *.localhost subdomain, the whole 127.0.0.0/8 range, ::1, and IPv4-mapped loopback (::ffff:127.0.0.1). An https:// URL, or one with a username/password set, is used as-is. + pub url: String, + /// Optional username for proxy authentication. Combined with the URL (and `password`) into `user:pass@host` when the sandboxed process routes through the proxy. + #[serde(skip_serializing_if = "Option::is_none")] + pub username: Option, } +/// Network rules to merge into the base policy. +/// +///
+/// +/// **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 SessionContextAttributionEntriesItem { - /// Supplementary per-entry metadata (e.g. `messageCount`, `role`, `evictable`, `pluginSource`). Values are stringified; parse as needed and ignore unrecognized keys. +pub struct SandboxConfigUserPolicyNetwork { + /// Whether traffic to local/loopback addresses is allowed. #[serde(skip_serializing_if = "Option::is_none")] - pub attributes: Option>, - /// Identifier for this entry, formed by joining its `kind` and source name (e.g. `tool:bash`, `skill:tmux`, `toolDefinition:bash`); unique within the snapshot. Use it to match the same entry across snapshots, to correlate with other APIs (skill/agent/MCP registries), and as the `parentId` target for nesting. Distinct from the human-facing `label`. - pub id: String, - /// Source category for this entry. Not a closed set — tolerate unknown values. Known values today: `skill`, `subagent`, `mcpServer`, `tool`, `system`, `toolDefinition`, `plugin`. - pub kind: String, - /// Human-readable display label, e.g. `bash` or `skill: tmux`. Presentation-only; may be localized/reformatted without notice — do not key off it. - pub label: String, - /// Optional `id` of the parent entry: e.g. a `plugin` entry parenting its `skill`/`mcpServer` entries, or the `system` entry parenting `toolDefinition` entries. Omitted for top-level entries. + pub allow_local_network: Option, + /// Whether outbound network traffic is allowed at all. #[serde(skip_serializing_if = "Option::is_none")] - pub parent_id: Option, - /// Token count currently in context attributable to this entry. - pub tokens: i64, + pub allow_outbound: Option, + /// HTTP proxy the sandboxed process routes traffic through. Enforced on Windows and cooperative (honored by well-behaved tools, not strictly enforced) on Linux and macOS. Credentials go in the separate `username`/`password` fields. A credential-free http:// loopback proxy URL is routed through the localhost proxy automatically; an https:// or authenticated loopback URL is used as-is. + #[serde(skip_serializing_if = "Option::is_none")] + pub proxy: Option, } -/// Per-source context-window attribution, or null if the session has not yet been initialized (no system prompt or tool metadata cached). +/// macOS seatbelt-specific options. /// ///
/// @@ -11342,16 +12063,13 @@ pub struct SessionContextAttributionEntriesItem { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionContextAttribution { - /// Successful compaction history for the session. - pub compactions: SessionContextAttributionCompactions, - /// Flat list of per-source attribution entries. Group by `kind` and render unrecognized kinds generically. Nesting and rollups are expressed via `parentId`. - pub entries: Vec, - /// Total token count of the current context window the entries are measured against (system message + conversation messages + tool definitions — the same total reported by /context). Divide an entry's `tokens` by this to derive its share. - pub total_tokens: i64, +pub struct SandboxConfigUserPolicySeatbelt { + /// Whether the macOS seatbelt profile may access the keychain. + #[serde(skip_serializing_if = "Option::is_none")] + pub keychain_access: Option, } -/// Token breakdown for the current context window, or null if the session has not yet been initialized (no system prompt or tool metadata cached). +/// User-managed sandbox policy fragment merged into the auto-discovered base policy. /// ///
/// @@ -11361,30 +12079,22 @@ pub struct SessionContextAttribution { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionContextInfo { - /// Output reserve plus tokens after the buffer-exhaustion blocking threshold (default 95%) - pub buffer_tokens: i64, - /// Token count at which background compaction starts (configurable percentage of promptTokenLimit) - pub compaction_threshold: i64, - /// Tokens consumed by user/assistant/tool messages - pub conversation_tokens: i64, - /// Prompt token limit plus the model's full output token limit. - pub limit: i64, - /// Tokens consumed by MCP tool definitions (subset of toolDefinitionsTokens, excludes deferred tools) - pub mcp_tools_tokens: i64, - /// The model used for token counting - pub model_name: String, - /// Maximum prompt tokens allowed by the model (or DEFAULT_TOKEN_LIMIT if unspecified) - pub prompt_token_limit: i64, - /// Tokens consumed by the system prompt - pub system_tokens: i64, - /// Tokens consumed by tool definitions sent to the model (excludes deferred tools) - pub tool_definitions_tokens: i64, - /// Sum of system, conversation and tool-definition tokens - pub total_tokens: i64, +pub struct SandboxConfigUserPolicy { + /// Deprecated legacy location for `seatbelt`; read only when the top-level `seatbelt` is absent. + #[serde(skip_serializing_if = "Option::is_none")] + pub experimental: Option, + /// Filesystem rules to merge into the base policy. + #[serde(skip_serializing_if = "Option::is_none")] + pub filesystem: Option, + /// Network rules to merge into the base policy. + #[serde(skip_serializing_if = "Option::is_none")] + pub network: Option, + /// macOS seatbelt options to merge into the base policy. + #[serde(skip_serializing_if = "Option::is_none")] + pub seatbelt: Option, } -/// The enriched metadata records, with summary and context fields backfilled where available. Sessions confirmed empty and unnamed are omitted. +/// Resolved sandbox configuration. /// ///
/// @@ -11394,12 +12104,24 @@ pub struct SessionContextInfo { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionEnrichMetadataResult { - /// Enriched records, with summary and context backfilled. Sessions confirmed empty and unnamed may be omitted. - pub sessions: Vec, +pub struct SandboxConfig { + /// Whether to auto-add the current working directory to readwritePaths. Default: true. + #[serde(skip_serializing_if = "Option::is_none")] + pub add_current_working_directory: Option, + /// Whether sandboxing is enabled for the session. + pub enabled: bool, + /// Whether to export `GH_TOKEN` so the `gh` CLI authenticates inside the sandbox without the OS keyring the sandbox blocks. Default: false (opt-in). + #[serde(skip_serializing_if = "Option::is_none")] + pub gh_auth: Option, + /// Whether to inject the Copilot GitHub token as an `http..extraheader` so authenticated HTTPS git works inside the sandbox without the shell-based credential helper the sandbox blocks. Default: false (opt-in). + #[serde(skip_serializing_if = "Option::is_none")] + pub git_auth: Option, + /// User-managed sandbox policy fragment merged into the auto-discovered base policy. + #[serde(skip_serializing_if = "Option::is_none")] + pub user_policy: Option, } -/// File path, content to append, and optional mode for the client-provided session filesystem. +/// Register an absolute-time scheduled prompt. /// ///
/// @@ -11409,19 +12131,20 @@ pub struct SessionEnrichMetadataResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsAppendFileRequest { - /// Target session identifier - pub session_id: SessionId, - /// Path using SessionFs conventions - pub path: String, - /// Content to append - pub content: String, - /// Optional POSIX-style mode for newly created files +pub struct ScheduleAddAtRequest { + /// Epoch milliseconds when the prompt should fire. + pub at: i64, + /// Optional display-only prompt label. #[serde(skip_serializing_if = "Option::is_none")] - pub mode: Option, + pub display_prompt: Option, + /// Prompt text to enqueue when the schedule fires. + pub prompt: String, + /// Whether the schedule should re-arm after each tick. Defaults to false. + #[serde(skip_serializing_if = "Option::is_none")] + pub recurring: Option, } -/// Describes a filesystem error. +/// Register a cron scheduled prompt. /// ///
/// @@ -11431,15 +12154,23 @@ pub struct SessionFsAppendFileRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsError { - /// Error classification - pub code: SessionFsErrorCode, - /// Free-form detail about the error, for logging/diagnostics +pub struct ScheduleAddCronRequest { + /// 5-field cron expression. + pub cron: String, + /// Optional display-only prompt label. #[serde(skip_serializing_if = "Option::is_none")] - pub message: Option, + pub display_prompt: Option, + /// Prompt text to enqueue when the schedule fires. + pub prompt: String, + /// Whether the schedule should re-arm after each tick. Defaults to true. + #[serde(skip_serializing_if = "Option::is_none")] + pub recurring: Option, + /// IANA timezone for evaluating the cron expression. + #[serde(skip_serializing_if = "Option::is_none")] + pub tz: Option, } -/// Path to test for existence in the client-provided session filesystem. +/// Register a relative-interval scheduled prompt. /// ///
/// @@ -11449,14 +12180,20 @@ pub struct SessionFsError { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsExistsRequest { - /// Target session identifier - pub session_id: SessionId, - /// Path using SessionFs conventions - pub path: String, +pub struct ScheduleAddRequest { + /// Optional display-only prompt label. + #[serde(skip_serializing_if = "Option::is_none")] + pub display_prompt: Option, + /// Human-readable interval such as `30s`, `5m`, or `2h`. + pub interval: String, + /// Prompt text to enqueue when the schedule fires. + pub prompt: String, + /// Whether the schedule should re-arm after each tick. Defaults to true. + #[serde(skip_serializing_if = "Option::is_none")] + pub recurring: Option, } -/// Indicates whether the requested path exists in the client-provided session filesystem. +/// Scheduled prompt entry with ID, timing (`intervalMs`, `cron`, or `at`), prompt text, recurrence, and next run time. /// ///
/// @@ -11466,12 +12203,36 @@ pub struct SessionFsExistsRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsExistsResult { - /// Whether the path exists - pub exists: bool, +pub struct ScheduleEntry { + /// Absolute fire time (epoch milliseconds) for a one-shot calendar schedule. + #[serde(skip_serializing_if = "Option::is_none")] + pub at: Option, + /// 5-field cron expression for a recurring calendar schedule, evaluated in `tz`. + #[serde(skip_serializing_if = "Option::is_none")] + pub cron: Option, + /// Display-only label for the prompt as shown in the UI (e.g. `/skill-name` for a skill-invocation schedule). The actual enqueued prompt is `prompt`. + #[serde(skip_serializing_if = "Option::is_none")] + pub display_prompt: Option, + /// Sequential id assigned by the runtime within the session. Stable across resumes (rebuilt from the event log). + pub id: i64, + /// Interval between scheduled ticks, in milliseconds (relative-interval schedules). + #[serde(skip_serializing_if = "Option::is_none")] + pub interval_ms: Option, + /// ISO 8601 timestamp when the next tick is scheduled to fire. + pub next_run_at: String, + /// Prompt text that gets enqueued on every tick. + pub prompt: String, + /// Whether the schedule re-arms after each tick (`/every`) or fires once (`/after`). + pub recurring: bool, + /// True for a self-paced (`dynamic`) schedule: no fixed cadence; the model arms each next run via the `manage_schedule` `wakeup` action. `nextRunAt` is model-controlled. + #[serde(skip_serializing_if = "Option::is_none")] + pub self_paced: Option, + /// IANA timezone the `cron` expression is evaluated in. + #[serde(skip_serializing_if = "Option::is_none")] + pub tz: Option, } -/// Directory path to create in the client-provided session filesystem, with options for recursive creation and POSIX mode. +/// Result of registering or re-arming a scheduled prompt. /// ///
/// @@ -11481,20 +12242,16 @@ pub struct SessionFsExistsResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsMkdirRequest { - /// Target session identifier - pub session_id: SessionId, - /// Path using SessionFs conventions - pub path: String, - /// Create parent directories as needed +pub struct ScheduleAddResult { + /// The registered or updated schedule entry. #[serde(skip_serializing_if = "Option::is_none")] - pub recursive: Option, - /// Optional POSIX-style mode for newly created directories + pub entry: Option, + /// User-facing validation error, when registration failed. #[serde(skip_serializing_if = "Option::is_none")] - pub mode: Option, + pub error: Option, } -/// Directory path whose entries should be listed from the client-provided session filesystem. +/// Register a self-paced scheduled prompt. /// ///
/// @@ -11504,14 +12261,15 @@ pub struct SessionFsMkdirRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsReaddirRequest { - /// Target session identifier - pub session_id: SessionId, - /// Path using SessionFs conventions - pub path: String, +pub struct ScheduleAddSelfPacedRequest { + /// Optional display-only prompt label. + #[serde(skip_serializing_if = "Option::is_none")] + pub display_prompt: Option, + /// Prompt text to enqueue when the schedule fires. + pub prompt: String, } -/// Names of entries in the requested directory, or a filesystem error if the read failed. +/// Whether the session currently has an active self-paced schedule. /// ///
/// @@ -11521,15 +12279,12 @@ pub struct SessionFsReaddirRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsReaddirResult { - /// Entry names in the directory - pub entries: Vec, - /// Describes a filesystem error. - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, +pub struct ScheduleHasSelfPacedResult { + /// True when at least one active schedule is self-paced. + pub has_self_paced: bool, } -/// Directory entry returned by session filesystem `readdirWithTypes`, with name and entry type. +/// Snapshot of the currently active recurring prompts for this session. /// ///
/// @@ -11539,14 +12294,12 @@ pub struct SessionFsReaddirResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsReaddirWithTypesEntry { - /// Entry name - pub name: String, - /// Entry type - pub r#type: SessionFsReaddirWithTypesEntryType, +pub struct ScheduleList { + /// Active scheduled prompts, ordered by id. + pub entries: Vec, } -/// Directory path whose entries (with type information) should be listed from the client-provided session filesystem. +/// Re-arm a self-paced scheduled prompt. /// ///
/// @@ -11556,14 +12309,14 @@ pub struct SessionFsReaddirWithTypesEntry { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsReaddirWithTypesRequest { - /// Target session identifier - pub session_id: SessionId, - /// Path using SessionFs conventions - pub path: String, +pub struct ScheduleRearmSelfPacedRequest { + /// Epoch milliseconds when the prompt should next fire. + pub at: i64, + /// Id of the self-paced scheduled prompt. + pub id: i64, } -/// Entries in the requested directory paired with file/directory type information, or a filesystem error if the read failed. +/// Identifier of the scheduled prompt to remove. /// ///
/// @@ -11573,15 +12326,12 @@ pub struct SessionFsReaddirWithTypesRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsReaddirWithTypesResult { - /// Directory entries with type information - pub entries: Vec, - /// Describes a filesystem error. - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, +pub struct ScheduleStopRequest { + /// Id of the scheduled prompt to remove. + pub id: i64, } -/// Path of the file to read from the client-provided session filesystem. +/// Remove a scheduled prompt by id. The result entry is omitted if the id was unknown. /// ///
/// @@ -11591,14 +12341,13 @@ pub struct SessionFsReaddirWithTypesResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsReadFileRequest { - /// Target session identifier - pub session_id: SessionId, - /// Path using SessionFs conventions - pub path: String, +pub struct ScheduleStopResult { + /// The removed entry, or omitted if no entry matched. + #[serde(skip_serializing_if = "Option::is_none")] + pub entry: Option, } -/// File content as a UTF-8 string, or a filesystem error if the read failed. +/// Secret values to add to the redaction filter. /// ///
/// @@ -11608,15 +12357,12 @@ pub struct SessionFsReadFileRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsReadFileResult { - /// File content as UTF-8 string - pub content: String, - /// Describes a filesystem error. - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, +pub struct SecretsAddFilterValuesRequest { + /// Raw secret values to register for redaction + pub values: Vec, } -/// Source and destination paths for renaming or moving an entry in the client-provided session filesystem. +/// Confirmation that the secret values were registered. /// ///
/// @@ -11626,16 +12372,12 @@ pub struct SessionFsReadFileResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsRenameRequest { - /// Target session identifier - pub session_id: SessionId, - /// Source path using SessionFs conventions - pub src: String, - /// Destination path using SessionFs conventions - pub dest: String, +pub struct SecretsAddFilterValuesResult { + /// Whether the values were successfully registered + pub ok: bool, } -/// Path to remove from the client-provided session filesystem, with options for recursive removal and force. +/// Parameters for session.extensions.sendAttachmentsToMessage. /// ///
/// @@ -11645,20 +12387,15 @@ pub struct SessionFsRenameRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsRmRequest { - /// Target session identifier - pub session_id: SessionId, - /// Path using SessionFs conventions - pub path: String, - /// Remove directories and their contents recursively - #[serde(skip_serializing_if = "Option::is_none")] - pub recursive: Option, - /// Ignore errors if the path does not exist +pub struct SendAttachmentsToMessageParams { + /// Attachments to push into the next user-message turn. extension_context entries take the slim shape; standard variants take their full AttachmentSchema shape. + pub attachments: Vec, + /// Optional canvas instance binding the push for provenance. When supplied, the runtime resolves the canvas, verifies it is owned by the calling extension, and stamps canvasId/instanceId onto each extension_context entry. When omitted, no resolution runs and those fields stay unset on the attachment. #[serde(skip_serializing_if = "Option::is_none")] - pub force: Option, + pub instance_id: Option, } -/// Optional capabilities declared by the provider +/// A single user message to append to the session as part of a `session.sendMessages` turn /// ///
/// @@ -11668,13 +12405,29 @@ pub struct SessionFsRmRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsSetProviderCapabilities { - /// Whether the provider supports SQLite query/exists operations +pub struct SendMessageItem { + /// Optional attachments (files, directories, selections, blobs, GitHub references) to include with this message #[serde(skip_serializing_if = "Option::is_none")] - pub sqlite: Option, + pub attachments: Option>, + /// If false, this message will not trigger a Premium Request Unit charge. User messages default to billable. + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) billable: Option, + /// If provided, this is shown in the timeline instead of `prompt` + #[serde(skip_serializing_if = "Option::is_none")] + pub display_prompt: Option, + /// The user message text + pub prompt: String, + /// If set, the request will fail if the named tool is not available when this message is among the user messages at the start of the current exchange + #[serde(skip_serializing_if = "Option::is_none")] + pub required_tool: Option, + /// Optional provenance tag copied to the resulting user.message event. Must be `user`, `system`, `command-` for command-originated messages, `schedule-` for scheduled prompts, or `agent-` for prompts sent by another agent. + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) source: Option, } -/// Initial working directory, session-state path layout, and path conventions used to register the calling SDK client as the session filesystem provider. +/// Parameters for sending zero or more user messages to the session in a single turn. Remote-backed (Mission Control) sessions do not support this method and will return an error. /// ///
/// @@ -11684,19 +12437,33 @@ pub struct SessionFsSetProviderCapabilities { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsSetProviderRequest { - /// Optional capabilities declared by the provider +pub struct SendMessagesRequest { + /// The UI mode the agent was in when these messages were sent. Defaults to the session's current mode. #[serde(skip_serializing_if = "Option::is_none")] - pub capabilities: Option, - /// Path conventions used by this filesystem - pub conventions: SessionFsSetProviderConventions, - /// Initial working directory for sessions - pub initial_cwd: String, - /// Path within each session's SessionFs where the runtime stores files for that session - pub session_state_path: String, + pub agent_mode: Option, + /// The user messages to append to the conversation, in order. May be empty, in which case a single turn runs over the existing history with no new user message. + pub messages: Vec, + /// How to deliver the messages. `enqueue` (default) appends to the message queue. `immediate` interjects during an in-progress turn. + #[serde(skip_serializing_if = "Option::is_none")] + pub mode: Option, + /// If true, adds the messages to the front of the queue instead of the end + #[serde(skip_serializing_if = "Option::is_none")] + pub prepend: Option, + /// 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. + #[serde(skip_serializing_if = "Option::is_none")] + pub request_headers: Option>, + /// W3C Trace Context traceparent header for distributed tracing of this agent turn + #[serde(skip_serializing_if = "Option::is_none")] + pub traceparent: Option, + /// W3C Trace Context tracestate header for distributed tracing + #[serde(skip_serializing_if = "Option::is_none")] + pub tracestate: Option, + /// If true, await completion of the agentic loop for this turn before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageIds`; the caller can rely on the agent having processed the messages before the call resolves. Transport-dependent tail semantics: on a LOCAL (in-process) session the wait additionally blocks until the completed turn's event tail has been dispatched to this session's in-process subscribers, so a subsequent read of subscriber state already reflects the turn; on a REMOTE session the wait resolves once the loop completes and mirrored delivery follows over the wire. Callers that need the stronger local guarantee on remote sessions should await the event stream explicitly. + #[serde(skip_serializing_if = "Option::is_none")] + pub wait: Option, } -/// Indicates whether the calling client was registered as the session filesystem provider. +/// Result of sending zero or more user messages /// ///
/// @@ -11706,12 +12473,12 @@ pub struct SessionFsSetProviderRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsSetProviderResult { - /// Whether the provider was set successfully - pub success: bool, +pub struct SendMessagesResult { + /// Unique identifiers assigned to the messages, one per provided message in order. Empty when no messages were provided. + pub message_ids: Vec, } -/// Indicates whether the per-session SQLite database already exists. +/// Parameters for sending a user message to the session /// ///
/// @@ -11721,12 +12488,49 @@ pub struct SessionFsSetProviderResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsSqliteExistsResult { - /// Whether the session database already exists - pub exists: bool, +pub struct SendRequest { + /// The UI mode the agent was in when this message was sent. Defaults to the session's current mode. + #[serde(skip_serializing_if = "Option::is_none")] + pub agent_mode: Option, + /// Optional attachments (files, directories, selections, blobs, GitHub references) to include with the message + #[serde(skip_serializing_if = "Option::is_none")] + pub attachments: Option>, + /// If false, this message will not trigger a Premium Request Unit charge. User messages default to billable. + #[serde(skip_serializing_if = "Option::is_none")] + pub billable: Option, + /// If provided, this is shown in the timeline instead of `prompt` + #[serde(skip_serializing_if = "Option::is_none")] + pub display_prompt: Option, + /// How to deliver the message. `enqueue` (default) appends to the message queue. `immediate` interjects during an in-progress turn. + #[serde(skip_serializing_if = "Option::is_none")] + pub mode: Option, + /// If true, adds the message to the front of the queue instead of the end + #[serde(skip_serializing_if = "Option::is_none")] + pub prepend: Option, + /// The user message text + pub prompt: String, + /// 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. + #[serde(skip_serializing_if = "Option::is_none")] + pub request_headers: Option>, + /// If set, the request will fail if the named tool is not available when this message is among the user messages at the start of the current exchange + #[serde(skip_serializing_if = "Option::is_none")] + pub required_tool: Option, + /// Optional provenance tag copied to the resulting user.message event. Must be `user`, `system`, `command-` for command-originated messages, `schedule-` for scheduled prompts, or `agent-` for prompts sent by another agent. + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) source: Option, + /// W3C Trace Context traceparent header for distributed tracing of this agent turn + #[serde(skip_serializing_if = "Option::is_none")] + pub traceparent: Option, + /// W3C Trace Context tracestate header for distributed tracing + #[serde(skip_serializing_if = "Option::is_none")] + pub tracestate: Option, + /// If true, await completion of the agentic loop for this message before returning. Defaults to false (fire-and-forget). When true, the result still contains the same `messageId`; the caller can rely on the agent having processed the message before the call resolves. Transport-dependent tail semantics: on a LOCAL (in-process) session the wait additionally blocks until the completed turn's event tail has been dispatched to this session's in-process subscribers, so a subsequent read of subscriber state already reflects the turn; on a REMOTE session the wait resolves once the loop completes and mirrored delivery follows over the wire. Callers that need the stronger local guarantee on remote sessions should await the event stream explicitly. + #[serde(skip_serializing_if = "Option::is_none")] + pub wait: Option, } -/// SQL query, query type, and optional bind parameters for executing a SQLite query against the per-session database. +/// Result of sending a user message /// ///
/// @@ -11736,19 +12540,12 @@ pub struct SessionFsSqliteExistsResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsSqliteQueryRequest { - /// Target session identifier - pub session_id: SessionId, - /// SQL query to execute - pub query: String, - /// How to execute the query: 'exec' for DDL/multi-statement (no results), 'query' for SELECT (returns rows), 'run' for INSERT/UPDATE/DELETE (returns rowsAffected) - pub query_type: SessionFsSqliteQueryType, - /// Optional named bind parameters - #[serde(skip_serializing_if = "Option::is_none")] - pub params: Option>, +pub struct SendResult { + /// Unique identifier assigned to the message + pub message_id: String, } -/// Query results including rows, columns, and rows affected, or a filesystem error if execution failed. +/// Internal request for sending a system notification. /// ///
/// @@ -11758,22 +12555,18 @@ pub struct SessionFsSqliteQueryRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsSqliteQueryResult { - /// Column names from the result set - pub columns: Vec, - /// Describes a filesystem error. +pub struct SendSystemNotificationRequest { + /// Optional structured notification kind. #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - /// SQLite last_insert_rowid() value for INSERT. + pub kind: Option, + /// Notification text to deliver to the model. + pub message: String, + /// Internal delivery options, including passive policy. #[serde(skip_serializing_if = "Option::is_none")] - pub last_insert_rowid: Option, - /// For SELECT: array of row objects. For others: empty array. - pub rows: Vec>, - /// Number of rows affected (for INSERT/UPDATE/DELETE) - pub rows_affected: i64, + pub options: Option, } -/// Path whose metadata should be returned from the client-provided session filesystem. +/// Agents discovered across user, project, plugin, and remote sources. /// ///
/// @@ -11783,14 +12576,12 @@ pub struct SessionFsSqliteQueryResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsStatRequest { - /// Target session identifier - pub session_id: SessionId, - /// Path using SessionFs conventions - pub path: String, +pub struct ServerAgentList { + /// All discovered agents across all sources + pub agents: Vec, } -/// Filesystem metadata for the requested path, or a filesystem error if the stat failed. +/// Instruction sources discovered across user, repository, and plugin sources. /// ///
/// @@ -11800,23 +12591,12 @@ pub struct SessionFsStatRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsStatResult { - /// ISO 8601 timestamp of creation - pub birthtime: String, - /// Describes a filesystem error. - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - /// Whether the path is a directory - pub is_directory: bool, - /// Whether the path is a file - pub is_file: bool, - /// ISO 8601 timestamp of last modification - pub mtime: String, - /// File size in bytes - pub size: i64, +pub struct ServerInstructionSourceList { + /// All discovered instruction sources + pub sources: Vec, } -/// File path, content to write, and optional mode for the client-provided session filesystem. +/// Server-side skill metadata, including name, description, source, enabled/invocable state, path, project path, and argument hint. /// ///
/// @@ -11826,50 +12606,29 @@ pub struct SessionFsStatResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFsWriteFileRequest { - /// Target session identifier - pub session_id: SessionId, - /// Path using SessionFs conventions - pub path: String, - /// Content to write - pub content: String, - /// Optional POSIX-style mode for newly created files +pub struct ServerSkill { + /// Optional freeform hint describing the skill's expected arguments, from the `argument-hint` frontmatter field #[serde(skip_serializing_if = "Option::is_none")] - pub mode: Option, -} - -/// Installed plugin record for a session, with marketplace, version, install time, enabled state, cache path, and source. -/// -///
-/// -/// **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 SessionInstalledPlugin { - /// Path where the plugin is cached locally - #[serde(rename = "cache_path", skip_serializing_if = "Option::is_none")] - pub cache_path: Option, - /// Whether the plugin is currently enabled + pub argument_hint: Option, + /// Description of what the skill does + pub description: String, + /// Whether the skill is currently enabled (based on global config) pub enabled: bool, - /// Installation timestamp (ISO-8601) - #[serde(rename = "installed_at")] - pub installed_at: String, - /// Marketplace the plugin came from (empty string for direct repo installs) - pub marketplace: String, - /// Plugin name + /// Unique identifier for the skill pub name: String, - /// Source descriptor for direct repo installs (when marketplace is empty) + /// Absolute path to the skill file #[serde(skip_serializing_if = "Option::is_none")] - pub source: Option, - /// Installed version, if known + pub path: Option, + /// The project path this skill belongs to (only for project/inherited skills) #[serde(skip_serializing_if = "Option::is_none")] - pub version: Option, + pub project_path: Option, + /// Source location type (e.g., project, personal-copilot, plugin, builtin) + pub source: SkillSource, + /// Whether the skill can be invoked by the user as a slash command + pub user_invocable: bool, } -/// Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref, and optional subpath. +/// Skills discovered across global and project sources. /// ///
/// @@ -11879,17 +12638,15 @@ pub struct SessionInstalledPlugin { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionInstalledPluginSourceGitHub { - #[serde(skip_serializing_if = "Option::is_none")] - pub path: Option, +pub struct ServerSkillList { + /// Messages for skills that failed to load (e.g. malformed SKILL.md). Empty when host skills are excluded so host-local paths are not disclosed to multitenant callers. #[serde(skip_serializing_if = "Option::is_none")] - pub r#ref: Option, - pub repo: String, - /// Constant value. Always "github". - pub source: SessionInstalledPluginSourceGitHubSource, + pub errors: Option>, + /// All discovered skills across all sources + pub skills: Vec, } -/// Source descriptor for a direct local plugin install, with a local filesystem path. +/// Current activity flags for the session. /// ///
/// @@ -11899,13 +12656,14 @@ pub struct SessionInstalledPluginSourceGitHub { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionInstalledPluginSourceLocal { - pub path: String, - /// Constant value. Always "local". - pub source: SessionInstalledPluginSourceLocalSource, +pub struct SessionActivity { + /// Whether an in-flight operation can currently be aborted. + pub abortable: bool, + /// Whether the session currently has active work, including running turns or tasks. + pub has_active_work: bool, } -/// Source descriptor for a direct URL plugin install, with URL, optional ref, and optional subpath. +/// Authentication status and account metadata for the session. /// ///
/// @@ -11915,17 +12673,27 @@ pub struct SessionInstalledPluginSourceLocal { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionInstalledPluginSourceUrl { +pub struct SessionAuthStatus { + /// Authentication type #[serde(skip_serializing_if = "Option::is_none")] - pub path: Option, + pub auth_type: Option, + /// Copilot plan tier (e.g., individual_pro, business) #[serde(skip_serializing_if = "Option::is_none")] - pub r#ref: Option, - /// Constant value. Always "url". - pub source: SessionInstalledPluginSourceUrlSource, - pub url: String, + pub copilot_plan: Option, + /// Authentication host URL + #[serde(skip_serializing_if = "Option::is_none")] + pub host: Option, + /// Whether the session has resolved authentication + pub is_authenticated: bool, + /// Authenticated login/username, if available + #[serde(skip_serializing_if = "Option::is_none")] + pub login: Option, + /// Human-readable authentication status description + #[serde(skip_serializing_if = "Option::is_none")] + pub status_message: Option, } -/// Sessions matching the filter, ordered most-recently-modified first. +/// Map of sessionId -> bytes freed by removing the session's workspace directory. /// ///
/// @@ -11935,37 +12703,39 @@ pub struct SessionInstalledPluginSourceUrl { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionList { - /// Sessions ordered most-recently-modified first. Discriminated by `isRemote`. - pub sessions: Vec, +pub struct SessionBulkDeleteResult { + /// Map of sessionId -> bytes freed by removing the session's workspace directory. Sessions whose deletion failed are omitted from this map (failures are logged on the server but not surfaced per-id; check the map for absent IDs to detect them). + pub freed_bytes: HashMap, } -/// Optional filter applied to the returned sessions -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
+/// Successful compaction history for the session. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionListFilter { - /// Match sessions whose context.branch equals this value +pub struct SessionContextAttributionCompactions { + /// Number of successful compactions in this session. + pub count: i64, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionContextAttributionEntriesItem { + /// Supplementary per-entry metadata (e.g. `messageCount`, `role`, `evictable`, `pluginSource`). Values are stringified; parse as needed and ignore unrecognized keys. #[serde(skip_serializing_if = "Option::is_none")] - pub branch: Option, - /// Match sessions whose context.cwd equals this value - #[serde(skip_serializing_if = "Option::is_none")] - pub cwd: Option, - /// Match sessions whose context.gitRoot equals this value - #[serde(skip_serializing_if = "Option::is_none")] - pub git_root: Option, - /// Match sessions whose context.repository equals this value + pub attributes: Option>, + /// Identifier for this entry, formed by joining its `kind` and source name (e.g. `tool:bash`, `skill:tmux`, `toolDefinition:bash`); unique within the snapshot. Use it to match the same entry across snapshots, to correlate with other APIs (skill/agent/MCP registries), and as the `parentId` target for nesting. Distinct from the human-facing `label`. + pub id: String, + /// Source category for this entry. Not a closed set — tolerate unknown values. Known values today: `skill`, `subagent`, `mcpServer`, `tool`, `system`, `toolDefinition`, `plugin`. + pub kind: String, + /// Human-readable display label, e.g. `bash` or `skill: tmux`. Presentation-only; may be localized/reformatted without notice — do not key off it. + pub label: String, + /// Optional `id` of the parent entry: e.g. a `plugin` entry parenting its `skill`/`mcpServer` entries, or the `system` entry parenting `toolDefinition` entries. Omitted for top-level entries. #[serde(skip_serializing_if = "Option::is_none")] - pub repository: Option, + pub parent_id: Option, + /// Token count currently in context attributable to this entry. + pub tokens: i64, } -/// Queued repo-level startup prompts and the total hook command count after loading. +/// Per-source context-window attribution, or null if the session has not yet been initialized (no system prompt or tool metadata cached). /// ///
/// @@ -11975,49 +12745,49 @@ pub struct SessionListFilter { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionLoadDeferredRepoHooksResult { - /// Total hook command count (user + plugin + repo) loaded for the session by this call. Captured atomically with startupPrompts so callers don't need to read a separate counter. - pub hook_count: i64, - /// Repo-level startup prompts queued from repo hook configs. Empty on resume, when no repo configs were pending, or when disableAllHooks is set. - pub startup_prompts: Vec, +pub struct SessionContextAttribution { + /// Successful compaction history for the session. + pub compactions: SessionContextAttributionCompactions, + /// Flat list of per-source attribution entries. Group by `kind` and render unrecognized kinds generically. Nesting and rollups are expressed via `parentId`. + pub entries: Vec, + /// Total token count of the current context window the entries are measured against (system message + conversation messages + tool definitions — the same total reported by /context). Divide an entry's `tokens` by this to derive its share. + pub total_tokens: i64, } -/// Public-facing projection of workspace metadata for SDK / TUI consumers +/// Token breakdown for the current context window, or null if the session has not yet been initialized (no system prompt or tool metadata cached). +/// +///
+/// +/// **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 SessionMetadataSnapshotWorkspace { - /// Branch checked out at session start, if any - #[serde(skip_serializing_if = "Option::is_none")] - pub branch: Option, - /// ISO 8601 timestamp when the workspace was created - #[serde(rename = "created_at", skip_serializing_if = "Option::is_none")] - pub created_at: Option, - /// Current working directory at session start - #[serde(skip_serializing_if = "Option::is_none")] - pub cwd: Option, - /// Resolved git root for cwd, if any - #[serde(rename = "git_root", skip_serializing_if = "Option::is_none")] - pub git_root: Option, - /// Repository host type, if known - #[serde(rename = "host_type", skip_serializing_if = "Option::is_none")] - pub host_type: Option, - /// Workspace identifier (1:1 with sessionId) - pub id: String, - /// Display name for the session, if set - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - /// Repository identifier in 'owner/repo' or 'org/project/repo' format, if any - #[serde(skip_serializing_if = "Option::is_none")] - pub repository: Option, - /// ISO 8601 timestamp when the workspace was last updated - #[serde(rename = "updated_at", skip_serializing_if = "Option::is_none")] - pub updated_at: Option, - /// Whether the display name was explicitly set by the user - #[serde(rename = "user_named", skip_serializing_if = "Option::is_none")] - pub user_named: Option, +pub struct SessionContextInfo { + /// Output reserve plus tokens after the buffer-exhaustion blocking threshold (default 95%) + pub buffer_tokens: i64, + /// Token count at which background compaction starts (configurable percentage of promptTokenLimit) + pub compaction_threshold: i64, + /// Tokens consumed by user/assistant/tool messages + pub conversation_tokens: i64, + /// Prompt token limit plus the model's full output token limit. + pub limit: i64, + /// Tokens consumed by MCP tool definitions (subset of toolDefinitionsTokens, excludes deferred tools) + pub mcp_tools_tokens: i64, + /// The model used for token counting + pub model_name: String, + /// Maximum prompt tokens allowed by the model (or DEFAULT_TOKEN_LIMIT if unspecified) + pub prompt_token_limit: i64, + /// Tokens consumed by the system prompt + pub system_tokens: i64, + /// Tokens consumed by tool definitions sent to the model (excludes deferred tools) + pub tool_definitions_tokens: i64, + /// Sum of system, conversation and tool-definition tokens + pub total_tokens: i64, } -/// Point-in-time snapshot of slow-changing session identifier and state fields +/// The enriched metadata records, with summary and context fields backfilled where available. Sessions confirmed empty and unnamed are omitted. /// ///
/// @@ -12027,45 +12797,69 @@ pub struct SessionMetadataSnapshotWorkspace { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMetadataSnapshot { - /// True when the session was detected to be in use by another process at construction time. Local consumers may surface a confirmation prompt before fully attaching. Always false for new sessions. - pub already_in_use: bool, - /// Runtime client name associated with the session (telemetry identifier). - #[serde(skip_serializing_if = "Option::is_none")] - pub client_name: Option, - /// The current agent mode for this session (e.g., 'interactive', 'plan', 'autopilot') - pub current_mode: MetadataSnapshotCurrentMode, - /// User-provided name supplied at session construction (via `--name`), if any. Immutable after construction. - #[serde(skip_serializing_if = "Option::is_none")] - pub initial_name: Option, - /// Whether this is a remote session (i.e., one whose runtime executes elsewhere and is steered through this process) - pub is_remote: bool, - /// ISO 8601 timestamp of when the session's persisted state was last modified on disk. For new sessions, equals startTime. For resumed sessions, reflects the previous modification time at construction. - pub modified_time: String, - /// Remote-session-specific metadata. Populated only when `isRemote` is true. Fields are immutable for the lifetime of the session. +pub struct SessionEnrichMetadataResult { + /// Enriched records, with summary and context backfilled. Sessions confirmed empty and unnamed may be omitted. + pub sessions: Vec, +} + +/// File path, content to append, and optional mode for the client-provided session filesystem. +/// +///
+/// +/// **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 SessionFsAppendFileRequest { + /// Target session identifier + pub session_id: SessionId, + /// Path using SessionFs conventions + pub path: String, + /// Content to append + pub content: String, + /// Optional POSIX-style mode for newly created files #[serde(skip_serializing_if = "Option::is_none")] - pub remote_metadata: Option, - /// Currently selected model identifier, if any + pub mode: Option, +} + +/// Describes a filesystem error. +/// +///
+/// +/// **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 SessionFsError { + /// Error classification + pub code: SessionFsErrorCode, + /// Free-form detail about the error, for logging/diagnostics #[serde(skip_serializing_if = "Option::is_none")] - pub selected_model: Option, - /// The unique identifier of the session + pub message: Option, +} + +/// Path to test for existence in the client-provided session filesystem. +/// +///
+/// +/// **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 SessionFsExistsRequest { + /// Target session identifier pub session_id: SessionId, - /// Current session limits, or null when no limits are active - pub session_limits: Option, - /// ISO 8601 timestamp of when the session started - pub start_time: String, - /// Short human-readable summary of the session, if known. Omitted when no summary has been generated. - #[serde(skip_serializing_if = "Option::is_none")] - pub summary: Option, - /// Absolute path to the session's current working directory - pub working_directory: String, - /// 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). - pub workspace: Option, - /// Absolute path to the session's workspace directory on disk, or null if the session has no associated workspace - pub workspace_path: Option, + /// Path using SessionFs conventions + pub path: String, } -/// Cost-category metadata for a CAPI model. +/// Indicates whether the requested path exists in the client-provided session filesystem. /// ///
/// @@ -12075,12 +12869,12 @@ pub struct SessionMetadataSnapshot { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionModelPriceCategory { - pub id: String, - pub price_category: ModelPickerPriceCategory, +pub struct SessionFsExistsResult { + /// Whether the path exists + pub exists: bool, } -/// The list of models available to this session. +/// Directory path to create in the client-provided session filesystem, with options for recursive creation and POSIX mode. /// ///
/// @@ -12090,18 +12884,20 @@ pub struct SessionModelPriceCategory { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionModelList { - /// Available models, ordered with the most preferred default first. Includes both Copilot (CAPI) models and any registry BYOK models; a BYOK model appears under its provider-qualified selection id (`provider/id`). - pub list: Vec, - /// Cost categories for the full CAPI catalog, including picker-disabled models that Auto may select. Metadata only; entries absent from `list` are not manually selectable. +pub struct SessionFsMkdirRequest { + /// Target session identifier + pub session_id: SessionId, + /// Path using SessionFs conventions + pub path: String, + /// Create parent directories as needed #[serde(skip_serializing_if = "Option::is_none")] - pub model_price_categories: Option>, - /// Per-quota snapshots returned alongside the model list, keyed by quota type. + pub recursive: Option, + /// Optional POSIX-style mode for newly created directories #[serde(skip_serializing_if = "Option::is_none")] - pub quota_snapshots: Option>, + pub mode: Option, } -/// Source descriptor for a `sessions.open` content-exclusion rule, with source name and type. +/// Directory path whose entries should be listed from the client-provided session filesystem. /// ///
/// @@ -12111,12 +12907,14 @@ pub struct SessionModelList { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource { - pub name: String, - pub r#type: String, +pub struct SessionFsReaddirRequest { + /// Target session identifier + pub session_id: SessionId, + /// Path using SessionFs conventions + pub path: String, } -/// Single content-exclusion rule supplied to `sessions.open` options, with paths, match conditions, and source. +/// Names of entries in the requested directory, or a filesystem error if the read failed. /// ///
/// @@ -12126,17 +12924,15 @@ pub struct SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionOpenOptionsAdditionalContentExclusionPolicyRule { - #[serde(skip_serializing_if = "Option::is_none")] - pub if_any_match: Option>, +pub struct SessionFsReaddirResult { + /// Entry names in the directory + pub entries: Vec, + /// Describes a filesystem error. #[serde(skip_serializing_if = "Option::is_none")] - pub if_none_match: Option>, - pub paths: Vec, - /// Source descriptor for a `sessions.open` content-exclusion rule, with source name and type. - pub source: SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource, + pub error: Option, } -/// Content-exclusion policy supplied to `sessions.open` options, with rules, last-updated data, and scope. +/// Directory entry returned by session filesystem `readdirWithTypes`, with name and entry type. /// ///
/// @@ -12146,15 +12942,14 @@ pub struct SessionOpenOptionsAdditionalContentExclusionPolicyRule { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionOpenOptionsAdditionalContentExclusionPolicy { - #[serde(rename = "last_updated_at")] - pub last_updated_at: serde_json::Value, - pub rules: Vec, - /// Allowed values for the `SessionOpenOptionsAdditionalContentExclusionPolicyScope` enumeration. - pub scope: SessionOpenOptionsAdditionalContentExclusionPolicyScope, +pub struct SessionFsReaddirWithTypesEntry { + /// Entry name + pub name: String, + /// Entry type + pub r#type: SessionFsReaddirWithTypesEntryType, } -/// Session construction options. +/// Directory path whose entries (with type information) should be listed from the client-provided session filesystem. /// ///
/// @@ -12164,120 +12959,2330 @@ pub struct SessionOpenOptionsAdditionalContentExclusionPolicy { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionOpenOptions { - /// Additional content-exclusion policies to merge into the session policy set. - /// - ///
- /// - /// **Experimental.** This type is part of an experimental wire-protocol surface +pub struct SessionFsReaddirWithTypesRequest { + /// Target session identifier + pub session_id: SessionId, + /// Path using SessionFs conventions + pub path: String, +} + +/// Entries in the requested directory paired with file/directory type information, or a filesystem error if the read failed. +/// +///
+/// +/// **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 SessionFsReaddirWithTypesResult { + /// Directory entries with type information + pub entries: Vec, + /// Describes a filesystem error. + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +/// Path of the file to read from the client-provided session filesystem. +/// +///
+/// +/// **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 SessionFsReadFileRequest { + /// Target session identifier + pub session_id: SessionId, + /// Path using SessionFs conventions + pub path: String, +} + +/// File content as a UTF-8 string, or a filesystem error if the read failed. +/// +///
+/// +/// **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 SessionFsReadFileResult { + /// File content as UTF-8 string + pub content: String, + /// Describes a filesystem error. + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +/// Source and destination paths for renaming or moving an entry in the client-provided session filesystem. +/// +///
+/// +/// **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 SessionFsRenameRequest { + /// Target session identifier + pub session_id: SessionId, + /// Source path using SessionFs conventions + pub src: String, + /// Destination path using SessionFs conventions + pub dest: String, +} + +/// Path to remove from the client-provided session filesystem, with options for recursive removal and force. +/// +///
+/// +/// **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 SessionFsRmRequest { + /// Target session identifier + pub session_id: SessionId, + /// Path using SessionFs conventions + pub path: String, + /// Remove directories and their contents recursively + #[serde(skip_serializing_if = "Option::is_none")] + pub recursive: Option, + /// Ignore errors if the path does not exist + #[serde(skip_serializing_if = "Option::is_none")] + pub force: Option, +} + +/// Optional capabilities declared by the provider +/// +///
+/// +/// **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 SessionFsSetProviderCapabilities { + /// Whether the provider supports SQLite query/exists operations + #[serde(skip_serializing_if = "Option::is_none")] + pub sqlite: Option, +} + +/// Initial working directory, session-state path layout, and path conventions used to register the calling SDK client as the session filesystem provider. +/// +///
+/// +/// **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 SessionFsSetProviderRequest { + /// Optional capabilities declared by the provider + #[serde(skip_serializing_if = "Option::is_none")] + pub capabilities: Option, + /// Path conventions used by this filesystem + pub conventions: SessionFsSetProviderConventions, + /// Initial working directory for sessions + pub initial_cwd: String, + /// Path within each session's SessionFs where the runtime stores files for that session + pub session_state_path: String, +} + +/// Indicates whether the calling client was registered as the session filesystem provider. +/// +///
+/// +/// **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 SessionFsSetProviderResult { + /// Whether the provider was set successfully + pub success: bool, +} + +/// Indicates whether the per-session SQLite database already exists. +/// +///
+/// +/// **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 SessionFsSqliteExistsResult { + /// Whether the session database already exists + pub exists: bool, +} + +/// SQL query, query type, and optional bind parameters for executing a SQLite query against the per-session database. The provider applies its SQLite busy timeout for every call. +/// +///
+/// +/// **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 SessionFsSqliteQueryRequest { + /// Target session identifier + pub session_id: SessionId, + /// SQL query to execute + pub query: String, + /// How to execute the query: 'exec' for DDL/multi-statement (no results), 'query' for SELECT (returns rows), 'run' for INSERT/UPDATE/DELETE (returns rowsAffected) + pub query_type: SessionFsSqliteQueryType, + /// Optional named bind parameters + #[serde(skip_serializing_if = "Option::is_none")] + pub params: Option>, +} + +/// Query results including rows, columns, and rows affected, or a filesystem error if execution failed. +/// +///
+/// +/// **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 SessionFsSqliteQueryResult { + /// Column names from the result set + pub columns: Vec, + /// Describes a filesystem error. + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, + /// SQLite last_insert_rowid() value for INSERT. + #[serde(skip_serializing_if = "Option::is_none")] + pub last_insert_rowid: Option, + /// For SELECT: array of row objects. For others: empty array. + pub rows: Vec>, + /// Number of rows affected (for INSERT/UPDATE/DELETE) + pub rows_affected: i64, +} + +/// Classified SQLite transaction failure. busyOrLocked guarantees rollback; postCommitAmbiguous must never be retried. +/// +///
+/// +/// **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 SessionFsSqliteTransactionError { + pub error_class: SessionFsSqliteTransactionErrorClass, + pub message: String, +} + +/// One statement in an atomic SQLite transaction. +/// +///
+/// +/// **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 SessionFsSqliteTransactionStatement { + /// Optional named bind parameters. + #[serde(skip_serializing_if = "Option::is_none")] + pub params: Option>, + /// SQL statement to execute. + pub query: String, + /// How to execute the statement. + pub query_type: SessionFsSqliteQueryType, +} + +/// Statements to execute atomically. Providers apply busy handling for every call. +/// +///
+/// +/// **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 SessionFsSqliteTransactionRequest { + /// Target session identifier + pub session_id: SessionId, + pub statements: Vec, +} + +/// Per-statement results, or a classified transaction error. +/// +///
+/// +/// **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 SessionFsSqliteTransactionResult { + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, + pub results: Vec, +} + +/// Path whose metadata should be returned from the client-provided session filesystem. +/// +///
+/// +/// **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 SessionFsStatRequest { + /// Target session identifier + pub session_id: SessionId, + /// Path using SessionFs conventions + pub path: String, +} + +/// Filesystem metadata for the requested path, or a filesystem error if the stat failed. +/// +///
+/// +/// **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 SessionFsStatResult { + /// ISO 8601 timestamp of creation + pub birthtime: String, + /// Describes a filesystem error. + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, + /// Whether the path is a directory + pub is_directory: bool, + /// Whether the path is a file + pub is_file: bool, + /// ISO 8601 timestamp of last modification + pub mtime: String, + /// File size in bytes + pub size: i64, +} + +/// File path, content to write, and optional mode for the client-provided session filesystem. +/// +///
+/// +/// **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 SessionFsWriteFileRequest { + /// Target session identifier + pub session_id: SessionId, + /// Path using SessionFs conventions + pub path: String, + /// Content to write + pub content: String, + /// Optional POSIX-style mode for newly created files + #[serde(skip_serializing_if = "Option::is_none")] + pub mode: Option, +} + +/// Installed plugin record for a session, with marketplace, version, install time, enabled state, cache path, and source. +/// +///
+/// +/// **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 SessionInstalledPlugin { + /// Path where the plugin is cached locally + #[serde(rename = "cache_path", skip_serializing_if = "Option::is_none")] + pub cache_path: Option, + /// Whether the plugin is currently enabled + pub enabled: bool, + /// Installation timestamp (ISO-8601) + #[serde(rename = "installed_at")] + pub installed_at: String, + /// Marketplace the plugin came from (empty string for direct repo installs) + pub marketplace: String, + /// Plugin name + pub name: String, + /// Source descriptor for direct repo installs (when marketplace is empty) + #[serde(skip_serializing_if = "Option::is_none")] + pub source: Option, + /// Installed version, if known + #[serde(skip_serializing_if = "Option::is_none")] + pub version: Option, +} + +/// Source descriptor for a direct GitHub plugin install, with `owner/repo`, optional ref or full commit SHA, and optional subpath. +/// +///
+/// +/// **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 SessionInstalledPluginSourceGitHub { + #[serde(skip_serializing_if = "Option::is_none")] + pub path: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub r#ref: Option, + pub repo: String, + /// Optional full 40-character hexadecimal commit SHA. + #[serde(skip_serializing_if = "Option::is_none")] + pub sha: Option, + /// Constant value. Always "github". + pub source: SessionInstalledPluginSourceGitHubSource, +} + +/// Source descriptor for a direct local plugin install, with a local filesystem path. +/// +///
+/// +/// **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 SessionInstalledPluginSourceLocal { + pub path: String, + /// Constant value. Always "local". + pub source: SessionInstalledPluginSourceLocalSource, +} + +/// Source descriptor for a direct URL plugin install, with URL, optional ref or full commit SHA, and optional subpath. +/// +///
+/// +/// **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 SessionInstalledPluginSourceUrl { + #[serde(skip_serializing_if = "Option::is_none")] + pub path: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub r#ref: Option, + /// Optional full 40-character hexadecimal commit SHA. + #[serde(skip_serializing_if = "Option::is_none")] + pub sha: Option, + /// Constant value. Always "url". + pub source: SessionInstalledPluginSourceUrlSource, + pub url: String, +} + +/// Baseline data provenance for a prediction. +/// +///
+/// +/// **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 SessionLimitPredictionBaselineData { + /// End of the baseline data slice. + pub window_end: String, + /// Start of the baseline data slice. + pub window_start: String, +} + +/// Semantic usage tier and its AI-credit cap. +/// +///
+/// +/// **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 SessionLimitPredictionTierOption { + /// AI-credit cap for this tier. + pub cap: f64, + pub tier: SessionLimitPredictionTier, +} + +/// Explainable AI-credit session-limit prediction. +/// +///
+/// +/// **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 SessionLimitPredictionDetails { + /// Baseline data provenance. + pub baseline_data: SessionLimitPredictionBaselineData, + /// Client population used for the prediction. + pub client_type: SessionLimitPredictionClientType, + /// Resolved model family when known. + #[serde(skip_serializing_if = "Option::is_none")] + pub family: Option, + /// Model identifier used for lookup. + pub model_id: String, + /// Recommended maximum AI credits for this session. + pub recommended_cap: f64, + /// Tier chosen as the recommended cap. + pub recommended_tier: SessionLimitPredictionTier, + /// Baseline fallback level used to create the prediction. + pub source: SessionLimitPredictionSource, + /// Key matched at the source level, such as a model id, family id, or `global`. + pub source_key: String, + /// Ordered usage tiers and their AI-credit caps. + pub tiers: Vec, +} + +/// Parameters for predicting an AI-credit session limit. Omitting `modelId` uses the session's currently selected model. +/// +///
+/// +/// **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 SessionLimitPredictionRequest { + /// Client type to size for. Defaults to `cli-interactive`. + #[serde(skip_serializing_if = "Option::is_none")] + pub client_type: Option, + /// Optional model identifier override. If omitted, the session's current model is used. + #[serde(skip_serializing_if = "Option::is_none")] + pub model_id: Option, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionLimitPredictionResultAvailable { + pub kind: SessionLimitPredictionResultAvailableKind, + /// Predicted session limit details. + pub prediction: SessionLimitPredictionDetails, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionLimitPredictionResultUnavailable { + pub kind: SessionLimitPredictionResultUnavailableKind, + /// Reason no prediction is available. + pub reason: SessionLimitPredictionUnavailableReason, +} + +/// Sessions matching the filter, ordered most-recently-modified first. +/// +///
+/// +/// **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 SessionList { + /// Sessions ordered most-recently-modified first. Discriminated by `isRemote`. + pub sessions: Vec, +} + +/// Optional filter applied to the returned sessions +/// +///
+/// +/// **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 SessionListFilter { + /// Match sessions whose context.branch equals this value + #[serde(skip_serializing_if = "Option::is_none")] + pub branch: Option, + /// Match sessions whose context.cwd equals this value + #[serde(skip_serializing_if = "Option::is_none")] + pub cwd: Option, + /// Match sessions whose context.gitRoot equals this value + #[serde(skip_serializing_if = "Option::is_none")] + pub git_root: Option, + /// Match sessions whose context.repository equals this value + #[serde(skip_serializing_if = "Option::is_none")] + pub repository: Option, +} + +/// Queued repo-level startup prompts and the total hook command count after loading. +/// +///
+/// +/// **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 SessionLoadDeferredRepoHooksResult { + /// Total hook command count (user + plugin + repo) loaded for the session by this call. Captured atomically with startupPrompts so callers don't need to read a separate counter. + pub hook_count: i64, + /// Repo-level startup prompts queued from repo hook configs. Empty on resume, when no repo configs were pending, or when disableAllHooks is set. + pub startup_prompts: Vec, +} + +/// Public-facing projection of workspace metadata for SDK / TUI consumers +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionMetadataSnapshotWorkspace { + /// Branch checked out at session start, if any + #[serde(skip_serializing_if = "Option::is_none")] + pub branch: Option, + /// ISO 8601 timestamp when the workspace was created + #[serde(rename = "created_at", skip_serializing_if = "Option::is_none")] + pub created_at: Option, + /// Current working directory at session start + #[serde(skip_serializing_if = "Option::is_none")] + pub cwd: Option, + /// Resolved git root for cwd, if any + #[serde(rename = "git_root", skip_serializing_if = "Option::is_none")] + pub git_root: Option, + /// Repository host type, if known + #[serde(rename = "host_type", skip_serializing_if = "Option::is_none")] + pub host_type: Option, + /// Workspace identifier (1:1 with sessionId) + pub id: String, + /// Display name for the session, if set + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + /// Repository identifier in 'owner/repo' or 'org/project/repo' format, if any + #[serde(skip_serializing_if = "Option::is_none")] + pub repository: Option, + /// ISO 8601 timestamp when the workspace was last updated + #[serde(rename = "updated_at", skip_serializing_if = "Option::is_none")] + pub updated_at: Option, + /// Whether the display name was explicitly set by the user + #[serde(rename = "user_named", skip_serializing_if = "Option::is_none")] + pub user_named: Option, +} + +/// Point-in-time snapshot of slow-changing session identifier and state fields +/// +///
+/// +/// **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 SessionMetadataSnapshot { + /// True when the session was detected to be in use by another process at construction time. Local consumers may surface a confirmation prompt before fully attaching. Always false for new sessions. + pub already_in_use: bool, + /// Runtime client name associated with the session (telemetry identifier). + #[serde(skip_serializing_if = "Option::is_none")] + pub client_name: Option, + /// The current agent mode for this session (e.g., 'interactive', 'plan', 'autopilot') + pub current_mode: MetadataSnapshotCurrentMode, + /// User-provided name supplied at session construction (via `--name`), if any. Immutable after construction. + #[serde(skip_serializing_if = "Option::is_none")] + pub initial_name: Option, + /// Whether this is a remote session (i.e., one whose runtime executes elsewhere and is steered through this process) + pub is_remote: bool, + /// ISO 8601 timestamp of when the session's persisted state was last modified on disk. For new sessions, equals startTime. For resumed sessions, reflects the previous modification time at construction. + pub modified_time: String, + /// Remote-session-specific metadata. Populated only when `isRemote` is true. Fields are immutable for the lifetime of the session. + #[serde(skip_serializing_if = "Option::is_none")] + pub remote_metadata: Option, + /// Currently selected model identifier, if any + #[serde(skip_serializing_if = "Option::is_none")] + pub selected_model: Option, + /// The unique identifier of the session + pub session_id: SessionId, + /// Current session limits, or null when no limits are active + pub session_limits: Option, + /// ISO 8601 timestamp of when the session started + pub start_time: String, + /// Short human-readable summary of the session, if known. Omitted when no summary has been generated. + #[serde(skip_serializing_if = "Option::is_none")] + pub summary: Option, + /// Absolute path to the session's current working directory + pub working_directory: String, + /// 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). + pub workspace: Option, + /// Absolute path to the session's workspace directory on disk, or null if the session has no associated workspace + pub workspace_path: Option, +} + +/// Cost-category metadata for a CAPI model. +/// +///
+/// +/// **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 SessionModelPriceCategory { + pub id: String, + pub price_category: ModelPickerPriceCategory, +} + +/// The list of models available to this 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 SessionModelList { + /// Available models, ordered with the most preferred default first. Includes both Copilot (CAPI) models and any registry BYOK models; a BYOK model appears under its provider-qualified selection id (`provider/id`). + pub list: Vec, + /// Cost categories for the full CAPI catalog, including picker-disabled models that Auto may select. Metadata only; entries absent from `list` are not manually selectable. + #[serde(skip_serializing_if = "Option::is_none")] + pub model_price_categories: Option>, + /// Per-quota snapshots returned alongside the model list, keyed by quota type. + #[serde(skip_serializing_if = "Option::is_none")] + pub quota_snapshots: Option>, +} + +/// Source descriptor for a `sessions.open` content-exclusion rule, with source name and 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 SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource { + pub name: String, + pub r#type: String, +} + +/// Single content-exclusion rule supplied to `sessions.open` options, with paths, match conditions, and source. +/// +///
+/// +/// **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 SessionOpenOptionsAdditionalContentExclusionPolicyRule { + #[serde(skip_serializing_if = "Option::is_none")] + pub if_any_match: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub if_none_match: Option>, + pub paths: Vec, + /// Source descriptor for a `sessions.open` content-exclusion rule, with source name and type. + pub source: SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource, +} + +/// Content-exclusion policy supplied to `sessions.open` options, with rules, last-updated data, and scope. +/// +///
+/// +/// **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 SessionOpenOptionsAdditionalContentExclusionPolicy { + #[serde(rename = "last_updated_at")] + pub last_updated_at: serde_json::Value, + pub rules: Vec, + /// Allowed values for the `SessionOpenOptionsAdditionalContentExclusionPolicyScope` enumeration. + pub scope: SessionOpenOptionsAdditionalContentExclusionPolicyScope, +} + +/// A host-provided script sourced before each built-in shell command when its shell target matches the active shell. +/// +///
+/// +/// **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 ShellInitScript { + /// Path to the script to source. + pub path: String, + /// Built-in shell that may source this script. + pub shell: ShellInitScriptShell, +} + +/// Per-session settings for built-in shell tools. +/// +///
+/// +/// **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 ShellOptions { + /// Controls automatic non-interactive profile loading where supported. Explicit initScripts are unaffected. + #[serde(skip_serializing_if = "Option::is_none")] + pub init_profile: Option, + /// Ordered host-provided script paths sourced before each built-in shell command when the + /// entry's shell target matches the active shell. Use these for rc files, environment setup scripts, + /// or other custom scripts. A script that returns a nonzero status is reported, and later scripts + /// and the user command continue while the shell remains running. Because scripts are sourced into + /// the command shell, `exit`, `exec`, failures under `set -e`, or other shell-terminating behavior + /// can prevent continuation. Script standard output is preserved; Bash script stderr is discarded, + /// PowerShell exception messages are replaced, and runtime-generated failure notices omit + /// configured script paths. When sandboxing is enabled, each script must already be readable under + /// the active sandbox filesystem policy. Pass an empty array to clear the list. + #[serde(skip_serializing_if = "Option::is_none")] + pub init_scripts: Option>, + /// Flags passed to the active built-in shell process on startup, replacing its default flags. + /// When omitted, the built-in Bash shell uses `--norc --noprofile`, + /// and the built-in PowerShell shell uses `-NoProfile -NoLogo`. + #[serde(skip_serializing_if = "Option::is_none")] + pub process_flags: Option>, +} + +/// Session construction options. +/// +///
+/// +/// **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 SessionOpenOptions { + /// Additional content-exclusion policies to merge into the session policy set. + /// + ///
+ /// + /// **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 additional_content_exclusion_policies: + Option>, + /// Additional directories the agent may access beyond the working directory. Each entry is granted to the session's file-access allow-list and surfaced to the model (system prompt context and `@`-mention completion). Absolute paths are recommended; a relative path is resolved against the session's working directory. Nonexistent or unresolvable entries are skipped with a warning. This is applied on both session creation and resume, and is not persisted: a resumed session that omits this option does not retain previously supplied directories (re-supply them, exactly as the CLI re-passes `--add-dir`). + #[serde(skip_serializing_if = "Option::is_none")] + pub additional_directories: Option>, + /// Runtime context discriminator for agent filtering. + #[serde(skip_serializing_if = "Option::is_none")] + pub agent_context: Option, + /// Whether to include instructions from every MCP server in the system prompt instead of only allowlisted servers. + #[serde(skip_serializing_if = "Option::is_none")] + pub allow_all_mcp_server_instructions: Option, + /// Whether ask_user is explicitly disabled. + #[serde(skip_serializing_if = "Option::is_none")] + pub ask_user_disabled: Option, + /// Initial authentication info for the session. + #[serde(skip_serializing_if = "Option::is_none")] + pub auth_info: Option, + /// Allowlist of available tool names. + #[serde(skip_serializing_if = "Option::is_none")] + pub available_tools: Option>, + /// Options scoped to the built-in CAPI (Copilot API) provider. + #[serde(skip_serializing_if = "Option::is_none")] + pub capi: Option, + /// Structured client kind used for runtime behavior gates. + #[serde(skip_serializing_if = "Option::is_none")] + pub client_kind: Option, + /// Identifier of the client driving the session. + #[serde(skip_serializing_if = "Option::is_none")] + pub client_name: Option, + /// Whether commit-message coauthor trailers are enabled. + #[serde(skip_serializing_if = "Option::is_none")] + pub coauthor_enabled: Option, + /// Override Copilot configuration directory. + #[serde(skip_serializing_if = "Option::is_none")] + pub config_dir: Option, + /// Whether auto-mode continuation is enabled. + #[serde(skip_serializing_if = "Option::is_none")] + pub continue_on_auto_mode: Option, + /// Override URL for the Copilot API endpoint. + #[serde(skip_serializing_if = "Option::is_none")] + pub copilot_url: Option, + /// Whether custom agents default to local-only execution. + #[serde(skip_serializing_if = "Option::is_none")] + pub custom_agents_local_only: Option, + /// Parent engagement ID for detached child telemetry rollup. + #[serde(skip_serializing_if = "Option::is_none")] + pub detached_from_spawning_parent_engagement_id: Option, + /// Parent session ID for detached child telemetry rollup. + #[serde(skip_serializing_if = "Option::is_none")] + pub detached_from_spawning_parent_session_id: Option, + /// Instruction source IDs disabled for this session. + #[serde(skip_serializing_if = "Option::is_none")] + pub disabled_instruction_sources: Option>, + /// Skill IDs disabled for this session. + #[serde(skip_serializing_if = "Option::is_none")] + pub disabled_skills: Option>, + /// Experimental: enable native model citations (Anthropic models today), normalized onto the `assistant.message` event. Off by default; may change or be removed while the citations surface is experimental. + /// + ///
+ /// + /// **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 enable_citations: Option, + /// Opt in to capturing file changes for session rewind and session diff. Capture cannot reconstruct changes made before it was enabled. On create it starts capture from the first turn. It is also honored on resume: for a session that already has tracked prior turns, tracking continues automatically even if this is omitted; passing it on resume additionally enables tracking for an eligible session that has no prior root turn yet. Resuming a session whose prior root turns were never tracked has no restorable baseline, so tracking stays disabled for it and rewind reports file change tracking as unavailable; the resume itself still succeeds, so sessions that predate tracking remain loadable. The opt-in is only rejected when the session can never track (a subagent session, or one without local session storage). It is intentionally absent from the mutable options update because enabling it after edits have occurred would create an incomplete, misleading baseline. Subagents share the parent session's capture store and are not tracked as separate rewind points: a file a subagent writes is attributed to whichever root user turn was open when the capture was staged, just before the tool body ran. A turn cannot open while a staged capture is still in flight, so a subagent tool that staged under the spawning turn stays attributed to it however late the write lands, while a capture it stages after the user's next message belongs to that later turn. Attribution decides which turn's rewind point counts and file preview include that write; it does not narrow which rewinds revert it, because a rewind restores every capture from the selected turn onward, so the earlier spawning turn reverts it as well. + #[serde(skip_serializing_if = "Option::is_none")] + pub enable_file_change_tracking: Option, + /// Opt-in: self-fetch and enforce enterprise managed settings at session bootstrap. + #[serde(skip_serializing_if = "Option::is_none")] + pub enable_managed_settings: Option, + /// Whether on-demand custom instruction discovery is enabled. + #[serde(skip_serializing_if = "Option::is_none")] + pub enable_on_demand_instruction_discovery: Option, + /// Whether shell-script safety heuristics are enabled. + #[serde(skip_serializing_if = "Option::is_none")] + pub enable_script_safety: Option, + /// Whether model responses stream as delta events. + #[serde(skip_serializing_if = "Option::is_none")] + pub enable_streaming: Option, + /// How MCP server environment values are interpreted. + #[serde(skip_serializing_if = "Option::is_none")] + pub env_value_mode: Option, + /// Override directory for session event logs. + #[serde(skip_serializing_if = "Option::is_none")] + pub events_log_directory: Option, + /// Whether subagent callback events should be forwarded into the session event log sink. + #[serde(skip_serializing_if = "Option::is_none")] + pub events_log_includes_subagents: Option, + /// Built-in subagent names to exclude from this session. Excluded built-ins are hidden from agent discovery and cannot be dispatched unless a custom agent with the same name is available. + #[serde(skip_serializing_if = "Option::is_none")] + pub excluded_builtin_agents: Option>, + /// Denylist of tool names. + #[serde(skip_serializing_if = "Option::is_none")] + pub excluded_tools: Option>, + /// ExP assignment ('flight') data injected by an SDK integrator, in the same JSON shape the Copilot CLI fetches from the experimentation service (CopilotExpAssignmentResponse). When supplied this is fed into the FeatureFlagService exactly like CLI-fetched assignments and ExP-backed flags wait for it. When absent the session does not block on ExP. + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) exp_assignments: Option, + /// Feature-flag values resolved by the host. + #[serde(skip_serializing_if = "Option::is_none")] + pub feature_flags: Option>, + /// Built-in subagent names to include in this session. When specified, only these built-ins are available, subject to runtime availability and exclusions. Custom agents with the same name remain available. + #[serde(skip_serializing_if = "Option::is_none")] + pub included_builtin_agents: Option>, + /// Installed plugins visible to the session. + #[serde(skip_serializing_if = "Option::is_none")] + pub installed_plugins: Option>, + /// Stable integration identifier for analytics. + #[serde(skip_serializing_if = "Option::is_none")] + pub integration_id: Option, + /// Whether experimental behavior is enabled. + #[serde(skip_serializing_if = "Option::is_none")] + pub is_experimental_mode: Option, + /// Whether interactive shell sessions are logged. + #[serde(skip_serializing_if = "Option::is_none")] + pub log_interactive_shells: Option, + /// Identifier sent to LSP-style integrations. + #[serde(skip_serializing_if = "Option::is_none")] + pub lsp_client_name: Option, + /// Maximum decoded byte size of a single inline model-facing binary tool result persisted in session events (default 10 MB). + #[serde(skip_serializing_if = "Option::is_none")] + pub max_inline_binary_bytes: Option, + /// Memory configuration for this session. + #[serde(skip_serializing_if = "Option::is_none")] + pub memory: Option, + /// Initial model identifier. + #[serde(skip_serializing_if = "Option::is_none")] + pub model: Option, + /// Initial model capability overrides. + #[serde(skip_serializing_if = "Option::is_none")] + pub model_capabilities_overrides: Option, + /// BYOK model definitions added to the selectable model list, each referencing a provider name. + /// + ///
+ /// + /// **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 models: Option>, + /// Optional human-friendly session name. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + /// Custom model-provider configuration (BYOK). + #[serde(skip_serializing_if = "Option::is_none")] + pub provider: Option, + /// Named BYOK provider connections, additive to CAPI auth. Combining with `provider` is rejected. + /// + ///
+ /// + /// **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 providers: Option>, + /// Initial reasoning effort level. + #[serde(skip_serializing_if = "Option::is_none")] + pub reasoning_effort: Option, + /// Initial reasoning summary mode for supported model clients. + #[serde(skip_serializing_if = "Option::is_none")] + pub reasoning_summary: Option, + /// Telemetry-only remote-defaulted flag. + #[serde(skip_serializing_if = "Option::is_none")] + pub remote_defaulted_on: Option, + /// Telemetry-only remote exporting flag. + #[serde(skip_serializing_if = "Option::is_none")] + pub remote_exporting: Option, + /// Whether this session supports remote steering. + #[serde(skip_serializing_if = "Option::is_none")] + pub remote_steerable: Option, + /// Whether the host is an interactive UI. + #[serde(skip_serializing_if = "Option::is_none")] + pub running_in_interactive_mode: Option, + /// Resolved sandbox configuration. + #[serde(skip_serializing_if = "Option::is_none")] + pub sandbox_config: Option, + /// Capabilities enabled for this session. + #[serde(skip_serializing_if = "Option::is_none")] + pub session_capabilities: Option>, + /// Optional stable session identifier to use for a new session. + #[serde(skip_serializing_if = "Option::is_none")] + pub session_id: Option, + /// Initial session limits. + #[serde(skip_serializing_if = "Option::is_none")] + pub session_limits: Option, + /// Per-session settings for built-in shell tools. + #[serde(skip_serializing_if = "Option::is_none")] + pub shell: Option, + /// Use shell.initProfile instead. Shell init profile. + #[doc(hidden)] + #[deprecated] + #[serde(skip_serializing_if = "Option::is_none")] + pub shell_init_profile: Option, + /// PowerShell process flags applied to built-in and user-requested shell commands. + #[serde(skip_serializing_if = "Option::is_none")] + pub shell_process_flags: Option>, + /// Additional directories to search for skills. + #[serde(skip_serializing_if = "Option::is_none")] + pub skill_directories: Option>, + /// Whether to skip custom instruction sources. + #[serde(skip_serializing_if = "Option::is_none")] + pub skip_custom_instructions: Option, + /// Optional trajectory output file path. + #[serde(skip_serializing_if = "Option::is_none")] + pub trajectory_file: Option, + /// Initial output verbosity level for supported models. + #[serde(skip_serializing_if = "Option::is_none")] + pub verbosity: Option, + /// Working directory to anchor the session. + #[serde(skip_serializing_if = "Option::is_none")] + pub working_directory: Option, + /// Pre-resolved working-directory context for session startup. + #[serde(skip_serializing_if = "Option::is_none")] + pub working_directory_context: Option, +} + +/// Parameters for creating a new local 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 SessionsOpenCreate { + /// Whether to emit session.start during creation. Defaults to true. + #[serde(skip_serializing_if = "Option::is_none")] + pub emit_start: Option, + /// Create a new local session. + pub kind: SessionsOpenCreateKind, + /// Session construction options. + #[serde(skip_serializing_if = "Option::is_none")] + pub options: Option, +} + +/// Parameters for resuming a specific local 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 SessionsOpenResume { + /// Resume a specific local session by ID or prefix. + pub kind: SessionsOpenResumeKind, + /// Session resume options. + #[serde(skip_serializing_if = "Option::is_none")] + pub options: Option, + /// Whether to emit session.resume after loading. Defaults to true. + #[serde(skip_serializing_if = "Option::is_none")] + pub resume: Option, + /// Session ID or unique prefix to resume. + pub session_id: SessionId, + /// Suppress workspace.yaml metadata writeback when resuming from an incidental cwd. + #[serde(skip_serializing_if = "Option::is_none")] + pub suppress_resume_workspace_metadata_writeback: Option, +} + +/// Parameters for resuming the most relevant local 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 SessionsOpenResumeLast { + /// Working-directory context used to choose the most relevant session. + #[serde(skip_serializing_if = "Option::is_none")] + pub context: Option, + /// Resume the most relevant existing local session. + pub kind: SessionsOpenResumeLastKind, + /// Session resume options. + #[serde(skip_serializing_if = "Option::is_none")] + pub options: Option, + /// Suppress workspace.yaml metadata writeback when resuming from an incidental cwd. + #[serde(skip_serializing_if = "Option::is_none")] + pub suppress_resume_workspace_metadata_writeback: Option, +} + +/// Parameters for attaching to an already-active session by ID. +/// +///
+/// +/// **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 SessionsOpenAttach { + /// Attach to an already-active in-process session by ID. Unlike `resume`, this does NOT re-load from disk; the session must already be loaded by an earlier `create`/`resume` call. Returns `status: 'not_found'` when no active session matches the id. Useful for in-process consumers that need a fresh API handle to a session opened elsewhere (e.g., a peer foreground-session switch). + pub kind: SessionsOpenAttachKind, + /// Session ID to attach to. + pub session_id: SessionId, +} + +/// Parameters for connecting to a live remote 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 SessionsOpenRemote { + /// Connect to a live remote session. + pub kind: SessionsOpenRemoteKind, + /// Session options for the connection. + #[serde(skip_serializing_if = "Option::is_none")] + pub options: Option, + /// Remote session identifier to connect to. + pub remote_session_id: SessionId, + /// Repository context for the remote session. + #[serde(skip_serializing_if = "Option::is_none")] + pub repository: Option, +} + +/// Parameters for creating a new cloud 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 SessionsOpenCloud { + /// Create a new cloud (coding-agent) session. + pub kind: SessionsOpenCloudKind, + /// In-process callback invoked when the cloud task is created (before connection). Marked internal because a function reference cannot cross the JSON-RPC boundary. Disappears in the SDK migration: the field is purely cosmetic (it flips a single CLI phase label from 'creating' to 'connecting') and the wire-clean version just drops the intermediate phase. + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) on_task_created: Option, + /// Session options for cloud session creation. + #[serde(skip_serializing_if = "Option::is_none")] + pub options: Option, + /// Optional owner (user or organization login) to associate with the cloud session when no repository is provided. Ignored when `repository` is set (the repo's owner takes precedence). + #[serde(skip_serializing_if = "Option::is_none")] + pub owner: Option, + /// Repository for the cloud session. + #[serde(skip_serializing_if = "Option::is_none")] + pub repository: Option, +} + +/// Parameters for fetching a remote session and handing it off to a new local 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 SessionsOpenHandoff { + /// Fetch a remote session and hand it off to a new local session. + pub kind: SessionsOpenHandoffKind, + /// Remote session metadata for the session to hand off (typically obtained from `sessions.list` with `source: "remote"`). + pub metadata: RemoteSessionMetadataValue, + /// In-process confirmation callback `(request) => boolean | Promise` invoked when the handoff needs the caller to confirm a non-fatal blocker (e.g. a repository mismatch between the current working directory and the remote session). Returning `true` proceeds with the handoff; returning `false` (or omitting the callback) aborts it. Marked internal because a function reference cannot cross the JSON-RPC boundary, for the same reasons as `onProgress`. + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) on_confirm: Option, + /// In-process progress callback `(update) => void` invoked for each handoff step. Marked internal because a function reference cannot cross the JSON-RPC boundary. The host-side `handoffSession` is already declared as `AsyncGenerator`; the schema layer flattens it because it does not yet support streaming methods. The wire-clean replacement is to expose the AsyncGenerator directly (or use vscode-jsonrpc `$/progress` notifications) once the schema/transport layer supports it. + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) on_progress: Option, + /// Session construction options for the new local session. + #[serde(skip_serializing_if = "Option::is_none")] + pub options: Option, + /// Task type determines the handoff strategy (CCA fetches events; CLI prepares a transient session). + #[serde(skip_serializing_if = "Option::is_none")] + pub task_type: Option, +} + +/// `sessions.open` handoff progress update with step, status, and optional message. +/// +///
+/// +/// **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 SessionsOpenProgress { + /// Optional step message. + #[serde(skip_serializing_if = "Option::is_none")] + pub message: Option, + /// Step status. + pub status: SessionsOpenProgressStatus, + /// Handoff step. + pub step: SessionsOpenProgressStep, +} + +/// Result of opening a 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 SessionOpenResult { + /// Remote session metadata, present when status is `connected`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + /// Handoff progress steps, present when status is `handed_off`. + #[serde(skip_serializing_if = "Option::is_none")] + pub progress: Option>, + /// Remote session ID, present when status is `connected`. + #[serde(skip_serializing_if = "Option::is_none")] + pub remote_session_id: Option, + /// In-process SessionClientApi handle for the opened session, returned to CLI callers as a transitional shortcut. Marked internal so the public SDK surface does not expose it; SDK consumers should construct per-session clients from `sessionId` instead. + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) session_api: Option, + /// Opened session ID. Omitted when status is `not_found`. + #[serde(skip_serializing_if = "Option::is_none")] + pub session_id: Option, + /// Startup prompts queued by user-level hook configs at session creation. Only populated when status is `created`; resumed sessions return an empty array. + #[serde(skip_serializing_if = "Option::is_none")] + pub startup_prompts: Option>, + /// Outcome of the open request. + pub status: SessionsOpenStatus, +} + +/// Outcome of the prune operation: deleted IDs, dry-run candidates, skipped IDs, total bytes freed, and the dry-run flag. +/// +///
+/// +/// **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 SessionPruneResult { + /// Session IDs that would be deleted in dry-run mode (always empty otherwise) + pub candidates: Vec, + /// Session IDs that were deleted (always empty in dry-run mode) + pub deleted: Vec, + /// True when no deletions were actually performed + pub dry_run: bool, + /// Total bytes freed (actual when not dry-run, projected when dry-run) + pub freed_bytes: i64, + /// Session IDs that were skipped (e.g., named sessions) + pub skipped: Vec, +} + +/// Session IDs to close, deactivate, and delete from disk. +/// +///
+/// +/// **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 SessionsBulkDeleteRequest { + /// Session IDs to close, deactivate, and delete from disk + pub session_ids: Vec, +} + +/// Session IDs to test for live in-use locks. +/// +///
+/// +/// **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 SessionsCheckInUseRequest { + /// Session IDs to test for live in-use locks + pub session_ids: Vec, +} + +/// Session IDs from the input set that are currently in use by another process. +/// +///
+/// +/// **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 SessionsCheckInUseResult { + /// Session IDs from the input set that are currently held by another running process via an alive lock file + pub in_use: Vec, +} + +/// Session ID to close. +/// +///
+/// +/// **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 SessionsCloseRequest { + /// Session ID to close + pub session_id: SessionId, +} + +/// Closes a session: emits shutdown, flushes pending events to disk, releases the in-use lock, disposes the active session. Idempotent: succeeds even if the session is not currently active. +/// +///
+/// +/// **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 SessionsCloseResult {} + +/// Session ID to delete from disk. +/// +///
+/// +/// **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 SessionsDeleteRequest { + /// Session ID to delete + pub session_id: SessionId, + /// Internal resolved session directory path to delete + #[serde(skip_serializing_if = "Option::is_none")] + pub session_path: Option, +} + +/// Session metadata records to enrich with summary and context information. +/// +///
+/// +/// **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 SessionsEnrichMetadataRequest { + /// Session metadata records to enrich. Records that already have summary and context are returned unchanged. + pub sessions: Vec, +} + +/// New auth credentials to install on the session. Omit to leave credentials unchanged. +/// +///
+/// +/// **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 SessionSetCredentialsParams { + /// 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 installs the supplied value immediately for outbound model/API requests. When the credential carries a raw token (`token`, `env`, or `gh-cli`) but no `copilotUser`, the runtime additionally re-resolves `copilotUser` server-side (best-effort, asynchronously, after the synchronous install) so plan/quota/billing metadata regains fidelity; on resolution failure the verbatim credential remains installed. It does NOT otherwise validate the credential. Several variants carry secret material; treat this method's params as containing secrets at rest and in transit. + #[serde(skip_serializing_if = "Option::is_none")] + pub credentials: Option, +} + +/// Indicates whether the credential update succeeded. +/// +///
+/// +/// **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 SessionSetCredentialsResult { + /// Whether the session ended up with a populated `copilotUser` for the installed credentials. `true` when the supplied credential already carried `copilotUser` or it was successfully re-resolved server-side. `false` when the credential is installed without `copilotUser` — either re-resolution failed, or the variant cannot be re-resolved from the credential alone (only the raw-token variants `token`, `env`, and `gh-cli` can). In both `false` cases the token swap still applied, but plan/quota/billing metadata is degraded. Present whenever a credential was supplied; omitted only when no credential was supplied (no-op call). + #[serde(skip_serializing_if = "Option::is_none")] + pub copilot_user_resolved: Option, + /// Whether the operation succeeded + pub success: bool, +} + +/// Availability of built-in job tools surfaced to boundary consumers. +/// +///
+/// +/// **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 SessionSettingsBuiltInToolAvailabilitySnapshot { + #[serde(skip_serializing_if = "Option::is_none")] + pub create_pull_request: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub report_progress: Option, +} + +/// Named Rust-owned settings predicate to evaluate for this 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 SessionSettingsEvaluatePredicateRequest { + /// Predicate name. The runtime owns the raw feature-flag names and composition logic. + pub name: SessionSettingsPredicateName, + /// Tool name for tool-scoped predicates such as trivial-change handling. + #[serde(skip_serializing_if = "Option::is_none")] + pub tool_name: Option, +} + +/// Result of evaluating a Rust-owned settings predicate. +/// +///
+/// +/// **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 SessionSettingsEvaluatePredicateResult { + pub enabled: bool, +} + +/// Redacted job settings for a session. The job nonce is excluded. +/// +///
+/// +/// **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 SessionSettingsJobSnapshot { + #[serde(skip_serializing_if = "Option::is_none")] + pub built_in_tool_availability: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub event_type: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub is_trigger_job: Option, +} + +/// Redacted model routing settings for a 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 SessionSettingsModelSnapshot { + #[serde(skip_serializing_if = "Option::is_none")] + pub callback_url: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub default_reasoning_effort: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub instance_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub model: Option, +} + +/// Online-evaluation settings safe to expose across the SDK boundary. +/// +///
+/// +/// **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 SessionSettingsOnlineEvaluationSnapshot { + #[serde(skip_serializing_if = "Option::is_none")] + pub disable_online_evaluation: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub enable_online_evaluation_output_file: Option, +} + +/// Redacted repository and GitHub host settings for a 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 SessionSettingsRepoSnapshot { + #[serde(skip_serializing_if = "Option::is_none")] + pub branch: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub commit: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub host: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub host_protocol: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub owner_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub owner_name: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub pr_commit_count: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub read_write: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub secret_scanning_url: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub server_url: Option, +} + +/// Redacted validation and memory-tool settings for a 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 SessionSettingsValidationSnapshot { + #[serde(skip_serializing_if = "Option::is_none")] + pub advisory_enabled: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub codeql_enabled: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub code_review_enabled: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub code_review_model: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub dependabot_timeout: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub memory_store_enabled: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub memory_vote_enabled: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub secret_scanning_enabled: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub timeout: Option, +} + +/// Redacted, serializable view of session runtime settings for SDK boundary consumers. Secrets and raw feature flags are intentionally excluded. +/// +///
+/// +/// **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 SessionSettingsSnapshot { + #[serde(skip_serializing_if = "Option::is_none")] + pub client_name: Option, + pub job: SessionSettingsJobSnapshot, + pub model: SessionSettingsModelSnapshot, + pub online_evaluation: SessionSettingsOnlineEvaluationSnapshot, + pub repo: SessionSettingsRepoSnapshot, + #[serde(skip_serializing_if = "Option::is_none")] + pub start_time_ms: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub timeout_ms: Option, + pub validation: SessionSettingsValidationSnapshot, + #[serde(skip_serializing_if = "Option::is_none")] + pub version: Option, +} + +/// UUID prefix to resolve to a unique session ID. +/// +///
+/// +/// **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 SessionsFindByPrefixRequest { + /// UUID prefix (>=7 hex chars, <36 chars). Returns the unique session ID, or undefined when there is no match or the prefix matches multiple sessions. + pub prefix: String, +} + +/// Session ID matching the prefix, omitted when no unique match exists. +/// +///
+/// +/// **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 SessionsFindByPrefixResult { + /// Omitted when no unique session matches the prefix (no match or ambiguous) + #[serde(skip_serializing_if = "Option::is_none")] + pub session_id: Option, +} + +/// GitHub task ID to look up. +/// +///
+/// +/// **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 SessionsFindByTaskIDRequest { + /// GitHub task ID to look up + pub task_id: String, +} + +/// ID of the local session bound to the given GitHub task, or omitted when none. +/// +///
+/// +/// **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 SessionsFindByTaskIDResult { + /// Omitted when no local session is bound to that GitHub task + #[serde(skip_serializing_if = "Option::is_none")] + pub session_id: Option, +} + +/// Source session identifier to fork from, optional event-ID boundary, and optional friendly name for the new 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 SessionsForkRequest { + /// Optional friendly name to assign to the forked session. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + /// Source session ID to fork from + pub session_id: SessionId, + /// Optional event ID boundary. When provided, the fork includes only events before this ID (exclusive). When omitted, all events are included. + #[serde(skip_serializing_if = "Option::is_none")] + pub to_event_id: Option, +} + +/// Identifier and optional friendly name assigned to the newly forked 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 SessionsForkResult { + /// Friendly name assigned to the forked session, if any. + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + /// The new forked session's ID + pub session_id: SessionId, +} + +/// Session ID whose board entry count should be returned. +/// +///
+/// +/// **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 SessionsGetBoardEntryCountRequest { + /// Session ID whose board entry count should be returned. + pub session_id: SessionId, +} + +/// Dynamic-context board entry count, when available. +/// +///
+/// +/// **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 SessionsGetBoardEntryCountResult { + /// Board entry count, when available. + #[serde(skip_serializing_if = "Option::is_none")] + pub count: Option, +} + +/// Session ID whose event-log file path to compute. +/// +///
+/// +/// **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 SessionsGetEventFilePathRequest { + /// Session ID whose event-log file path to compute + pub session_id: SessionId, +} + +/// Absolute path to the session's events.jsonl file on disk. +/// +///
+/// +/// **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 SessionsGetEventFilePathResult { + /// Absolute path to the session's events.jsonl file + pub file_path: String, +} + +/// Optional working-directory context used to score session relevance. +/// +///
+/// +/// **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 SessionsGetLastForContextRequest { + /// Optional working-directory context used to score session relevance. When omitted the most-recently-modified session wins. + #[serde(skip_serializing_if = "Option::is_none")] + pub context: Option, +} + +/// Most-relevant session ID for the supplied context, or omitted when no sessions exist. +/// +///
+/// +/// **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 SessionsGetLastForContextResult { + /// Most-relevant session ID for the supplied context, or omitted when no sessions exist + #[serde(skip_serializing_if = "Option::is_none")] + pub session_id: Option, +} + +/// Session ID whose persisted metadata should be read. +/// +///
+/// +/// **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 SessionsGetMetadataRequest { + /// Session ID to inspect + pub session_id: SessionId, +} + +/// Persisted local session metadata when the session exists. +/// +///
+/// +/// **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 SessionsGetMetadataResult { + /// Local session metadata, omitted when the session does not exist. + #[serde(skip_serializing_if = "Option::is_none")] + pub session: Option, +} + +/// Session ID to look up the persisted remote-steerable flag for. +/// +///
+/// +/// **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 SessionsGetPersistedRemoteSteerableRequest { + /// Session ID to look up the persisted remote-steerable flag for + pub session_id: SessionId, +} + +/// The session's persisted remote-steerable flag, or omitted when no value has been persisted. +/// +///
+/// +/// **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 SessionsGetPersistedRemoteSteerableResult { + /// The session's persisted remote-steerable flag if recorded; omitted when no value has been persisted + #[serde(skip_serializing_if = "Option::is_none")] + pub remote_steerable: Option, +} + +/// Map of sessionId -> on-disk size in bytes for each session's workspace directory. +/// +///
+/// +/// **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 SessionSizes { + /// Map of sessionId -> on-disk size in bytes for the session's workspace directory + pub sizes: HashMap, +} + +/// Limit for non-empty local session IDs. +/// +///
+/// +/// **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 SessionsListNonEmptySessionIdsRequest { + /// Maximum number of session IDs to return. + #[serde(skip_serializing_if = "Option::is_none")] + pub limit: Option, +} + +/// Recent local session IDs that contain user-visible history. +/// +///
+/// +/// **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 SessionsListNonEmptySessionIdsResult { + /// Session IDs ordered newest-first. + pub session_ids: Vec, +} + +/// Optional source filter, metadata-load limit, and context filter applied to the returned sessions. +/// +///
+/// +/// **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 SessionsListRequest { + /// Optional filter applied to the returned sessions + #[serde(skip_serializing_if = "Option::is_none")] + pub filter: Option, + /// When true, include detached maintenance sessions. Defaults to false for user-facing session lists. + #[serde(skip_serializing_if = "Option::is_none")] + pub include_detached: Option, + /// When provided, only the first N local sessions (sorted by modification time, newest first) load full metadata; remaining sessions return basic info only. Use 0 to return only basic info for every local session. Has no effect on remote entries (which always carry their full shape). + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata_limit: Option, + /// Which session sources to include. Defaults to `local` for backward compatibility. + #[serde(skip_serializing_if = "Option::is_none")] + pub source: Option, + /// Only meaningful when `source` includes remote. When true, propagates errors from the remote service instead of silently returning an empty remote list. Defaults to false. + #[serde(skip_serializing_if = "Option::is_none")] + pub throw_on_error: Option, +} + +/// Active session ID whose deferred repo-level hooks should be loaded. +/// +///
+/// +/// **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 SessionsLoadDeferredRepoHooksRequest { + /// Active session ID whose deferred repo-level hooks should be loaded + pub session_id: SessionId, +} + +/// Age threshold and optional flags controlling which old sessions are pruned (or simulated when dryRun is true). +/// +///
+/// +/// **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 SessionsPruneOldRequest { + /// When true, only report what would be deleted without performing any deletion + #[serde(skip_serializing_if = "Option::is_none")] + pub dry_run: Option, + /// Session IDs that should never be considered for pruning + #[serde(skip_serializing_if = "Option::is_none")] + pub exclude_session_ids: Option>, + /// When true, named sessions (set via /rename) are also eligible for pruning + #[serde(skip_serializing_if = "Option::is_none")] + pub include_named: Option, + /// Delete sessions whose modifiedTime is at least this many days old + pub older_than_days: i64, +} + +/// Session ID whose in-use lock should be released. +/// +///
+/// +/// **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 SessionsReleaseLockRequest { + /// Session ID whose in-use lock should be released + pub session_id: SessionId, +} + +/// Release the in-use lock held by this process for the given session. No-op when this process does not currently hold a lock for the 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 SessionsReleaseLockResult {} + +/// Active session ID and an optional flag for deferring repo-level hooks until folder trust. +/// +///
+/// +/// **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 SessionsReloadPluginHooksRequest { + /// When true, skip repo-level hooks. Use before folder trust is confirmed; loadDeferredRepoHooks loads them post-trust. + #[serde(skip_serializing_if = "Option::is_none")] + pub defer_repo_hooks: Option, + /// Active session ID to reload hooks for + pub session_id: SessionId, +} + +/// Reload all hooks (user, plugin, optionally repo) and apply them to the active session. Call after installing or removing plugins so their hooks take effect immediately. No-op when no active session matches the given sessionId. +/// +///
+/// +/// **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 SessionsReloadPluginHooksResult {} + +/// Session ID whose pending events should be flushed to disk. +/// +///
+/// +/// **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 SessionsSaveRequest { + /// Session ID whose pending events should be flushed to disk + pub session_id: SessionId, +} + +/// Flush a session's pending events to disk. No-op when no writer exists for the session (e.g., already closed). +/// +///
+/// +/// **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 SessionsSaveResult {} + +/// Manager-wide additional plugins to register; replaces any previously-configured set. +/// +///
+/// +/// **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 SessionsSetAdditionalPluginsRequest { + /// Manager-wide additional plugins to register. Replaces any previously-configured set. Pass an empty array to clear. + pub plugins: Vec, +} + +/// Replace the manager-wide additional plugins. New session creations and subsequent hook reloads see the new set; already-running sessions keep their existing hook installation until the next reload. +/// +///
+/// +/// **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 SessionsSetAdditionalPluginsResult {} + +/// Patch for the singleton's steering state. +/// +///
+/// +/// **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 SessionsSetRemoteControlSteeringRequest { + /// Target steering state. Today only `true` is actionable on the underlying exporter; `false` is reserved for future use. + pub enabled: bool, +} + +/// Parameters for attaching the remote-control singleton to a 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 SessionsStartRemoteControlRequest { + /// Configuration for the runtime-managed remote-control singleton. + pub config: RemoteControlConfig, + /// Local session id to attach remote control to. + pub session_id: SessionId, +} + +/// Parameters for stopping the remote-control singleton. +/// +///
+/// +/// **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 SessionsStopRemoteControlRequest { + /// When provided, the stop is rejected unless the singleton currently points at this session id (compare-and-swap semantics). + #[serde(skip_serializing_if = "Option::is_none")] + pub expected_session_id: Option, + /// When true, the singleton is unconditionally torn down regardless of `expectedSessionId`. Use during shutdown or explicit `/remote off`. + #[serde(skip_serializing_if = "Option::is_none")] + pub force: Option, +} + +/// Parameters for atomically rebinding the remote-control singleton. +/// +///
+/// +/// **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 SessionsTransferRemoteControlRequest { + /// When provided, the transfer is rejected unless the singleton currently points at this session id (compare-and-swap semantics to avoid clobbering newer state). + #[serde(skip_serializing_if = "Option::is_none")] + pub expected_from_session_id: Option, + /// Local session id to point remote control at. + pub to_session_id: String, +} + +/// Telemetry engagement ID for the session, when available. +/// +///
+/// +/// **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 SessionTelemetryEngagement { + /// Current telemetry engagement ID, when available. + #[serde(skip_serializing_if = "Option::is_none")] + pub engagement_id: Option, +} + +/// Patch of mutable session options to apply to the running 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 SessionUpdateOptionsParams { + /// Additional content-exclusion policies to merge into the session's policy set. + /// + ///
+ /// + /// **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 additional_content_exclusion_policies: - Option>, - /// Runtime context discriminator for agent filtering. + Option>, + /// Runtime context discriminator (e.g., `cli`, `actions`). #[serde(skip_serializing_if = "Option::is_none")] pub agent_context: Option, /// Whether to include instructions from every MCP server in the system prompt instead of only allowlisted servers. #[serde(skip_serializing_if = "Option::is_none")] pub allow_all_mcp_server_instructions: Option, - /// Whether ask_user is explicitly disabled. + /// Whether to disable the `ask_user` tool (encourages autonomous behavior). #[serde(skip_serializing_if = "Option::is_none")] pub ask_user_disabled: Option, - /// Initial authentication info for the session. - #[serde(skip_serializing_if = "Option::is_none")] - pub auth_info: Option, - /// Allowlist of available tool names. + /// Allowlist of tool names available to this session. #[serde(skip_serializing_if = "Option::is_none")] pub available_tools: Option>, /// Options scoped to the built-in CAPI (Copilot API) provider. #[serde(skip_serializing_if = "Option::is_none")] pub capi: Option, - /// Structured client kind used for runtime behavior gates. - #[serde(skip_serializing_if = "Option::is_none")] - pub client_kind: Option, /// Identifier of the client driving the session. #[serde(skip_serializing_if = "Option::is_none")] pub client_name: Option, - /// Whether commit-message coauthor trailers are enabled. + /// Whether to include the `Co-authored-by` trailer in commit messages. #[serde(skip_serializing_if = "Option::is_none")] pub coauthor_enabled: Option, - /// Override Copilot configuration directory. + /// Context tier for models with tiered pricing. The session uses this to derive effective `modelCapabilitiesOverrides` so compaction, truncation, token display, and request limits honor the selected tier. #[serde(skip_serializing_if = "Option::is_none")] - pub config_dir: Option, - /// Whether auto-mode continuation is enabled. + pub context_tier: Option, + /// Whether to allow auto-mode continuation across turns. #[serde(skip_serializing_if = "Option::is_none")] pub continue_on_auto_mode: Option, /// Override URL for the Copilot API endpoint. #[serde(skip_serializing_if = "Option::is_none")] pub copilot_url: Option, - /// Whether custom agents default to local-only execution. + /// Whether to default custom agents to local-only execution. #[serde(skip_serializing_if = "Option::is_none")] pub custom_agents_local_only: Option, - /// Parent engagement ID for detached child telemetry rollup. - #[serde(skip_serializing_if = "Option::is_none")] - pub detached_from_spawning_parent_engagement_id: Option, - /// Parent session ID for detached child telemetry rollup. - #[serde(skip_serializing_if = "Option::is_none")] - pub detached_from_spawning_parent_session_id: Option, - /// Instruction source IDs disabled for this session. + /// Instruction source IDs to exclude from the system prompt. #[serde(skip_serializing_if = "Option::is_none")] pub disabled_instruction_sources: Option>, - /// Skill IDs disabled for this session. + /// Skill IDs that should be excluded from this session. #[serde(skip_serializing_if = "Option::is_none")] pub disabled_skills: Option>, - /// Experimental: enable native model citations (Anthropic models today), normalized onto the `assistant.message` event. Off by default; may change or be removed while the citations surface is experimental. - /// - ///
- /// - /// **Experimental.** This type is part of an experimental wire-protocol surface - /// and may change or be removed in future SDK or CLI releases. - /// - ///
+ /// Whether to enable loading of `.github/hooks/` filesystem hooks. Separate from the SDK callback hook mechanism. #[serde(skip_serializing_if = "Option::is_none")] - pub enable_citations: Option, - /// Opt-in: self-fetch and enforce enterprise managed settings at session bootstrap. + pub enable_file_hooks: Option, + /// Whether to enable host git operations (context resolution, child repo scanning, git info in system prompt). #[serde(skip_serializing_if = "Option::is_none")] - pub enable_managed_settings: Option, - /// Whether on-demand custom instruction discovery is enabled. + pub enable_host_git_operations: Option, + /// Whether to discover custom instructions on demand after successful file views (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md surfacing). Combined with `skipCustomInstructions`. #[serde(skip_serializing_if = "Option::is_none")] pub enable_on_demand_instruction_discovery: Option, + /// Whether to surface reasoning-summary events from the model. + #[serde(skip_serializing_if = "Option::is_none")] + pub enable_reasoning_summaries: Option, /// Whether shell-script safety heuristics are enabled. #[serde(skip_serializing_if = "Option::is_none")] pub enable_script_safety: Option, - /// Whether model responses stream as delta events. + /// Whether to enable cross-session store writes and reads. + #[serde(skip_serializing_if = "Option::is_none")] + pub enable_session_store: Option, + /// Whether to enable skill directory scanning and loading. Falls back to enableConfigDiscovery when unset. + #[serde(skip_serializing_if = "Option::is_none")] + pub enable_skills: Option, + /// Whether to stream model responses. #[serde(skip_serializing_if = "Option::is_none")] pub enable_streaming: Option, - /// How MCP server environment values are interpreted. + /// How env values are passed to MCP servers (`direct` inlines literal values; `indirect` resolves at launch). #[serde(skip_serializing_if = "Option::is_none")] - pub env_value_mode: Option, - /// Override directory for session event logs. + pub env_value_mode: Option, + /// Override directory for the session-events log. When unset, the runtime's default events log directory is used. #[serde(skip_serializing_if = "Option::is_none")] pub events_log_directory: Option, + /// Whether subagent callback events should be forwarded into the session event log sink. + #[serde(skip_serializing_if = "Option::is_none")] + pub events_log_includes_subagents: Option, /// Built-in subagent names to exclude from this session. Excluded built-ins are hidden from agent discovery and cannot be dispatched unless a custom agent with the same name is available. #[serde(skip_serializing_if = "Option::is_none")] pub excluded_builtin_agents: Option>, - /// Denylist of tool names. + /// Denylist of tool names for this session. #[serde(skip_serializing_if = "Option::is_none")] pub excluded_tools: Option>, - /// ExP assignment ('flight') data injected by an SDK integrator, in the same JSON shape the Copilot CLI fetches from the experimentation service (CopilotExpAssignmentResponse). When supplied this is fed into the FeatureFlagService exactly like CLI-fetched assignments and ExP-backed flags wait for it. When absent the session does not block on ExP. - #[doc(hidden)] - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) exp_assignments: Option, - /// Feature-flag values resolved by the host. + /// Map of feature-flag IDs to their boolean enabled state. #[serde(skip_serializing_if = "Option::is_none")] pub feature_flags: Option>, - /// Built-in subagent names to include in this session. When specified, only these built-ins are available, subject to runtime availability and exclusions. Custom agents with the same name remain available. + /// Built-in subagent names to include in this session. When specified, only these built-ins are available, subject to runtime availability and exclusions. Custom agents with the same name remain available. Set to null to remove the allowlist restriction. #[serde(skip_serializing_if = "Option::is_none")] pub included_builtin_agents: Option>, - /// Installed plugins visible to the session. + /// Full set of installed plugins for the session. Replaces the existing list; the runtime invalidates the skills cache only when the list materially changes. #[serde(skip_serializing_if = "Option::is_none")] - pub installed_plugins: Option>, - /// Stable integration identifier for analytics. + pub installed_plugins: Option>, + /// Stable integration identifier used for analytics and rate-limit attribution. #[serde(skip_serializing_if = "Option::is_none")] pub integration_id: Option, - /// Whether experimental behavior is enabled. + /// Whether experimental capabilities are enabled. #[serde(skip_serializing_if = "Option::is_none")] pub is_experimental_mode: Option, /// Whether interactive shell sessions are logged. @@ -12286,101 +15291,80 @@ pub struct SessionOpenOptions { /// Identifier sent to LSP-style integrations. #[serde(skip_serializing_if = "Option::is_none")] pub lsp_client_name: Option, - /// Maximum decoded byte size of a single inline model-facing binary tool result persisted in session events (default 10 MB). + /// 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). #[serde(skip_serializing_if = "Option::is_none")] - pub max_inline_binary_bytes: Option, - /// Memory configuration for this session. + pub manage_schedule_enabled: Option, + /// Maximum decoded byte size of a single model-facing binary tool result (e.g. an image) persisted inline in session events and re-presented to the model on later turns / resume. Larger results are persisted as a metadata-only marker and shown to the model as a short text note. Defaults to 10 MB. #[serde(skip_serializing_if = "Option::is_none")] - pub memory: Option, - /// Initial model identifier. + pub max_inline_binary_bytes: Option, + /// The model ID to use for assistant turns. #[serde(skip_serializing_if = "Option::is_none")] pub model: Option, - /// Initial model capability overrides. + /// Per-property model capability overrides for the selected model. #[serde(skip_serializing_if = "Option::is_none")] pub model_capabilities_overrides: Option, - /// BYOK model definitions added to the selectable model list, each referencing a provider name. - /// - ///
- /// - /// **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 models: Option>, - /// Optional human-friendly session name. + /// Organization-level custom instructions to inject into the system prompt. #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, + pub organization_custom_instructions: Option, /// Custom model-provider configuration (BYOK). #[serde(skip_serializing_if = "Option::is_none")] pub provider: Option, - /// Named BYOK provider connections, additive to CAPI auth. Combining with `provider` is rejected. - /// - ///
- /// - /// **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 providers: Option>, - /// Initial reasoning effort level. + /// Reasoning effort for the selected model (model-defined enum). #[serde(skip_serializing_if = "Option::is_none")] pub reasoning_effort: Option, - /// Initial reasoning summary mode for supported model clients. - #[serde(skip_serializing_if = "Option::is_none")] - pub reasoning_summary: Option, - /// Telemetry-only remote-defaulted flag. - #[serde(skip_serializing_if = "Option::is_none")] - pub remote_defaulted_on: Option, - /// Telemetry-only remote exporting flag. - #[serde(skip_serializing_if = "Option::is_none")] - pub remote_exporting: Option, - /// Whether this session supports remote steering. + /// Reasoning summary mode for supported model clients. #[serde(skip_serializing_if = "Option::is_none")] - pub remote_steerable: Option, - /// Whether the host is an interactive UI. + pub reasoning_summary: Option, + /// Whether the session is running in an interactive UI. #[serde(skip_serializing_if = "Option::is_none")] pub running_in_interactive_mode: Option, /// Resolved sandbox configuration. #[serde(skip_serializing_if = "Option::is_none")] pub sandbox_config: Option, - /// Capabilities enabled for this session. + /// Replaces the session's capability set with the given list. Use to enable or disable capabilities mid-session (e.g., remove `memory` for reproducible scripted runs). Omit the field to leave the existing capability set unchanged. #[serde(skip_serializing_if = "Option::is_none")] pub session_capabilities: Option>, - /// Optional stable session identifier to use for a new session. - #[serde(skip_serializing_if = "Option::is_none")] - pub session_id: Option, - /// Initial session limits. + /// Optional session limits. Pass null to clear the session limits. #[serde(skip_serializing_if = "Option::is_none")] pub session_limits: Option, - /// Shell init profile. + /// Per-session settings for built-in shell tools. + #[serde(skip_serializing_if = "Option::is_none")] + pub shell: Option, + /// Use shell.initProfile instead. Shell init profile (`None` or `NonInteractive`). + #[doc(hidden)] + #[deprecated] #[serde(skip_serializing_if = "Option::is_none")] pub shell_init_profile: Option, - /// Per-shell process flags. + /// PowerShell process flags applied to built-in and user-requested shell commands. #[serde(skip_serializing_if = "Option::is_none")] pub shell_process_flags: Option>, /// Additional directories to search for skills. #[serde(skip_serializing_if = "Option::is_none")] pub skill_directories: Option>, - /// Whether to skip custom instruction sources. + /// Whether to skip loading custom instruction sources. #[serde(skip_serializing_if = "Option::is_none")] pub skip_custom_instructions: Option, - /// Optional trajectory output file path. + /// Whether to skip embedding retrieval pipeline initialization and execution. + #[serde(skip_serializing_if = "Option::is_none")] + pub skip_embedding_retrieval: Option, + /// When true, the selected custom agent's prompt is not injected into the user message (skill context is still injected). Used by automation triggers where the agent prompt is already in the problem statement. + #[serde(skip_serializing_if = "Option::is_none")] + pub suppress_custom_agent_prompt: Option, + /// Controls how availableTools (allowlist) and excludedTools (denylist) combine when both are set. + #[serde(skip_serializing_if = "Option::is_none")] + pub tool_filter_precedence: Option, + /// Optional path for trajectory output. #[serde(skip_serializing_if = "Option::is_none")] pub trajectory_file: Option, - /// Initial output verbosity level for supported models. + /// Output verbosity level for supported models. #[serde(skip_serializing_if = "Option::is_none")] pub verbosity: Option, - /// Working directory to anchor the session. + /// Absolute working-directory path for shell tools. #[serde(skip_serializing_if = "Option::is_none")] pub working_directory: Option, - /// Pre-resolved working-directory context for session startup. - #[serde(skip_serializing_if = "Option::is_none")] - pub working_directory_context: Option, } -/// Parameters for creating a new local session. +/// Indicates whether the session options patch was applied successfully. /// ///
/// @@ -12390,18 +15374,15 @@ pub struct SessionOpenOptions { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsOpenCreate { - /// Whether to emit session.start during creation. Defaults to true. - #[serde(skip_serializing_if = "Option::is_none")] - pub emit_start: Option, - /// Create a new local session. - pub kind: SessionsOpenCreateKind, - /// Session construction options. +pub struct SessionUpdateOptionsResult { + /// Number of hooks loaded from installed plugins, returned when installedPlugins is updated #[serde(skip_serializing_if = "Option::is_none")] - pub options: Option, + pub plugin_hook_count: Option, + /// Whether the operation succeeded + pub success: bool, } -/// Parameters for resuming a specific local session. +/// User-requested shell execution cancellation handle. /// ///
/// @@ -12411,23 +15392,12 @@ pub struct SessionsOpenCreate { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsOpenResume { - /// Resume a specific local session by ID or prefix. - pub kind: SessionsOpenResumeKind, - /// Session resume options. - #[serde(skip_serializing_if = "Option::is_none")] - pub options: Option, - /// Whether to emit session.resume after loading. Defaults to true. - #[serde(skip_serializing_if = "Option::is_none")] - pub resume: Option, - /// Session ID or unique prefix to resume. - pub session_id: SessionId, - /// Suppress workspace.yaml metadata writeback when resuming from an incidental cwd. - #[serde(skip_serializing_if = "Option::is_none")] - pub suppress_resume_workspace_metadata_writeback: Option, +pub struct ShellCancelUserRequestedRequest { + /// Request ID previously passed to executeUserRequested + pub request_id: RequestId, } -/// Parameters for resuming the most relevant local session. +/// Shell command to run, with optional working directory and timeout in milliseconds. /// ///
/// @@ -12437,21 +15407,33 @@ pub struct SessionsOpenResume { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsOpenResumeLast { - /// Working-directory context used to choose the most relevant session. - #[serde(skip_serializing_if = "Option::is_none")] - pub context: Option, - /// Resume the most relevant existing local session. - pub kind: SessionsOpenResumeLastKind, - /// Session resume options. +pub struct ShellExecRequest { + /// Shell command to execute + pub command: String, + /// Working directory (defaults to session working directory) #[serde(skip_serializing_if = "Option::is_none")] - pub options: Option, - /// Suppress workspace.yaml metadata writeback when resuming from an incidental cwd. + pub cwd: Option, + /// Timeout in milliseconds (default: 30000) #[serde(skip_serializing_if = "Option::is_none")] - pub suppress_resume_workspace_metadata_writeback: Option, + pub timeout: Option, +} + +/// Identifier of the spawned process, used to correlate streamed output and exit notifications. +/// +///
+/// +/// **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 ShellExecResult { + /// Unique identifier for tracking streamed output + pub process_id: String, } -/// Parameters for attaching to an already-active session by ID. +/// User-requested shell command and cancellation handle. /// ///
/// @@ -12461,14 +15443,14 @@ pub struct SessionsOpenResumeLast { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsOpenAttach { - /// Attach to an already-active in-process session by ID. Unlike `resume`, this does NOT re-load from disk; the session must already be loaded by an earlier `create`/`resume` call. Returns `status: 'not_found'` when no active session matches the id. Useful for in-process consumers that need a fresh API handle to a session opened elsewhere (e.g., a peer foreground-session switch). - pub kind: SessionsOpenAttachKind, - /// Session ID to attach to. - pub session_id: SessionId, +pub struct ShellExecuteUserRequestedRequest { + /// Shell command to execute + pub command: String, + /// Caller-provided cancellation handle for this execution + pub request_id: RequestId, } -/// Parameters for connecting to a live remote session. +/// Identifier of a process previously returned by "shell.exec" and the signal to send. /// ///
/// @@ -12478,20 +15460,15 @@ pub struct SessionsOpenAttach { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsOpenRemote { - /// Connect to a live remote session. - pub kind: SessionsOpenRemoteKind, - /// Session options for the connection. - #[serde(skip_serializing_if = "Option::is_none")] - pub options: Option, - /// Remote session identifier to connect to. - pub remote_session_id: SessionId, - /// Repository context for the remote session. +pub struct ShellKillRequest { + /// Process identifier returned by shell.exec + pub process_id: String, + /// Signal to send (default: SIGTERM) #[serde(skip_serializing_if = "Option::is_none")] - pub repository: Option, + pub signal: Option, } -/// Parameters for creating a new cloud session. +/// Indicates whether the signal was delivered; false if the process was unknown or already exited. /// ///
/// @@ -12501,25 +15478,12 @@ pub struct SessionsOpenRemote { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsOpenCloud { - /// Create a new cloud (coding-agent) session. - pub kind: SessionsOpenCloudKind, - /// In-process callback invoked when the cloud task is created (before connection). Marked internal because a function reference cannot cross the JSON-RPC boundary. Disappears in the SDK migration: the field is purely cosmetic (it flips a single CLI phase label from 'creating' to 'connecting') and the wire-clean version just drops the intermediate phase. - #[doc(hidden)] - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) on_task_created: Option, - /// Session options for cloud session creation. - #[serde(skip_serializing_if = "Option::is_none")] - pub options: Option, - /// Optional owner (user or organization login) to associate with the cloud session when no repository is provided. Ignored when `repository` is set (the repo's owner takes precedence). - #[serde(skip_serializing_if = "Option::is_none")] - pub owner: Option, - /// Repository for the cloud session. - #[serde(skip_serializing_if = "Option::is_none")] - pub repository: Option, +pub struct ShellKillResult { + /// Whether the signal was sent successfully + pub killed: bool, } -/// Parameters for fetching a remote session and handing it off to a new local session. +/// Parameters for shutting down the session /// ///
/// @@ -12529,28 +15493,16 @@ pub struct SessionsOpenCloud { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsOpenHandoff { - /// Fetch a remote session and hand it off to a new local session. - pub kind: SessionsOpenHandoffKind, - /// Remote session metadata for the session to hand off (typically obtained from `sessions.list` with `source: "remote"`). - pub metadata: RemoteSessionMetadataValue, - /// In-process confirmation callback `(request) => boolean | Promise` invoked when the handoff needs the caller to confirm a non-fatal blocker (e.g. a repository mismatch between the current working directory and the remote session). Returning `true` proceeds with the handoff; returning `false` (or omitting the callback) aborts it. Marked internal because a function reference cannot cross the JSON-RPC boundary, for the same reasons as `onProgress`. - #[doc(hidden)] - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) on_confirm: Option, - /// In-process progress callback `(update) => void` invoked for each handoff step. Marked internal because a function reference cannot cross the JSON-RPC boundary. The host-side `handoffSession` is already declared as `AsyncGenerator`; the schema layer flattens it because it does not yet support streaming methods. The wire-clean replacement is to expose the AsyncGenerator directly (or use vscode-jsonrpc `$/progress` notifications) once the schema/transport layer supports it. - #[doc(hidden)] - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) on_progress: Option, - /// Session construction options for the new local session. +pub struct ShutdownRequest { + /// Optional human-readable reason. Typically the message of the error that triggered shutdown when type is 'error'. #[serde(skip_serializing_if = "Option::is_none")] - pub options: Option, - /// Task type determines the handoff strategy (CCA fetches events; CLI prepares a transient session). + pub reason: Option, + /// Why the session is being shut down. Defaults to "routine" when omitted. #[serde(skip_serializing_if = "Option::is_none")] - pub task_type: Option, + pub r#type: Option, } -/// `sessions.open` handoff progress update with step, status, and optional message. +/// Skill metadata available to a session, with name, description, source, enabled/invocable state, path, plugin, and argument hint. /// ///
/// @@ -12560,17 +15512,29 @@ pub struct SessionsOpenHandoff { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsOpenProgress { - /// Optional step message. +pub struct Skill { + /// Optional freeform hint describing the skill's expected arguments, from the `argument-hint` frontmatter field #[serde(skip_serializing_if = "Option::is_none")] - pub message: Option, - /// Step status. - pub status: SessionsOpenProgressStatus, - /// Handoff step. - pub step: SessionsOpenProgressStep, + pub argument_hint: Option, + /// Description of what the skill does + pub description: String, + /// Whether the skill is currently enabled + pub enabled: bool, + /// Unique identifier for the skill + pub name: String, + /// Absolute path to the skill file + #[serde(skip_serializing_if = "Option::is_none")] + pub path: Option, + /// Name of the plugin that provides the skill, when source is 'plugin' + #[serde(skip_serializing_if = "Option::is_none")] + pub plugin_name: Option, + /// Source location type (e.g., project, personal-copilot, plugin, builtin) + pub source: SkillSource, + /// Whether the skill can be invoked by the user as a slash command + pub user_invocable: bool, } -/// Result of opening a session. +/// Canonical directory where skills can be discovered or created, with scope, preference, and optional project path. /// ///
/// @@ -12580,31 +15544,19 @@ pub struct SessionsOpenProgress { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionOpenResult { - /// Remote session metadata, present when status is `connected`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - /// Handoff progress steps, present when status is `handed_off`. - #[serde(skip_serializing_if = "Option::is_none")] - pub progress: Option>, - /// Remote session ID, present when status is `connected`. - #[serde(skip_serializing_if = "Option::is_none")] - pub remote_session_id: Option, - /// In-process SessionClientApi handle for the opened session, returned to CLI callers as a transitional shortcut. Marked internal so the public SDK surface does not expose it; SDK consumers should construct per-session clients from `sessionId` instead. - #[doc(hidden)] - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) session_api: Option, - /// Opened session ID. Omitted when status is `not_found`. - #[serde(skip_serializing_if = "Option::is_none")] - pub session_id: Option, - /// Startup prompts queued by user-level hook configs at session creation. Only populated when status is `created`; resumed sessions return an empty array. +pub struct SkillDiscoveryPath { + /// Absolute path of the create/discovery target (may not exist on disk yet) + pub path: String, + /// Whether this is the canonical directory to create a new skill in its tier. At most one entry per tier is preferred; the `personal-agents` and `custom` scopes are never preferred. + pub preferred_for_creation: bool, + /// The input project path this directory was derived from (only for project scope) #[serde(skip_serializing_if = "Option::is_none")] - pub startup_prompts: Option>, - /// Outcome of the open request. - pub status: SessionsOpenStatus, + pub project_path: Option, + /// Which tier this directory belongs to + pub scope: SkillDiscoveryScope, } -/// Outcome of the prune operation: deleted IDs, dry-run candidates, skipped IDs, total bytes freed, and the dry-run flag. +/// Canonical locations where skills can be created so the runtime will recognize them. /// ///
/// @@ -12614,20 +15566,12 @@ pub struct SessionOpenResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPruneResult { - /// Session IDs that would be deleted in dry-run mode (always empty otherwise) - pub candidates: Vec, - /// Session IDs that were deleted (always empty in dry-run mode) - pub deleted: Vec, - /// True when no deletions were actually performed - pub dry_run: bool, - /// Total bytes freed (actual when not dry-run, projected when dry-run) - pub freed_bytes: i64, - /// Session IDs that were skipped (e.g., named sessions) - pub skipped: Vec, +pub struct SkillDiscoveryPathList { + /// Canonical skill create/discovery directories, in priority order + pub paths: Vec, } -/// Session IDs to close, deactivate, and delete from disk. +/// Skills available to the session, with their enabled state. /// ///
/// @@ -12637,12 +15581,12 @@ pub struct SessionPruneResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsBulkDeleteRequest { - /// Session IDs to close, deactivate, and delete from disk - pub session_ids: Vec, +pub struct SkillList { + /// Available skills + pub skills: Vec, } -/// Session IDs to test for live in-use locks. +/// Skill names to mark as disabled in global configuration, replacing any previous list. /// ///
/// @@ -12652,12 +15596,12 @@ pub struct SessionsBulkDeleteRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsCheckInUseRequest { - /// Session IDs to test for live in-use locks - pub session_ids: Vec, +pub struct SkillsConfigSetDisabledSkillsRequest { + /// List of skill names to disable + pub disabled_skills: Vec, } -/// Session IDs from the input set that are currently in use by another process. +/// Name of the skill to disable for the session. /// ///
/// @@ -12667,12 +15611,12 @@ pub struct SessionsCheckInUseRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsCheckInUseResult { - /// Session IDs from the input set that are currently held by another running process via an alive lock file - pub in_use: Vec, +pub struct SkillsDisableRequest { + /// Name of the skill to disable + pub name: String, } -/// Session ID to close. +/// Optional project paths and additional skill directories to include in discovery. /// ///
/// @@ -12682,12 +15626,19 @@ pub struct SessionsCheckInUseResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsCloseRequest { - /// Session ID to close - pub session_id: SessionId, +pub struct SkillsDiscoverRequest { + /// When true, omit skills from the host's global sources (personal, custom, plugin, and built-in), returning only project-scoped skills. For multitenant deployments. + #[serde(skip_serializing_if = "Option::is_none")] + pub exclude_host_skills: Option, + /// Optional list of project directory paths to scan for project-scoped skills + #[serde(skip_serializing_if = "Option::is_none")] + pub project_paths: Option>, + /// Optional list of additional skill directory paths to include + #[serde(skip_serializing_if = "Option::is_none")] + pub skill_directories: Option>, } -/// Closes a session: emits shutdown, flushes pending events to disk, releases the in-use lock, disposes the active session. Idempotent: succeeds even if the session is not currently active. +/// Name of the skill to enable for the session. /// ///
/// @@ -12697,9 +15648,12 @@ pub struct SessionsCloseRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsCloseResult {} +pub struct SkillsEnableRequest { + /// Name of the skill to enable + pub name: String, +} -/// Session metadata records to enrich with summary and context information. +/// Optional project paths to enumerate. /// ///
/// @@ -12709,12 +15663,16 @@ pub struct SessionsCloseResult {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsEnrichMetadataRequest { - /// Session metadata records to enrich. Records that already have summary and context are returned unchanged. - pub sessions: Vec, +pub struct SkillsGetDiscoveryPathsRequest { + /// When true, omit the host's personal and custom skill directories, leaving only project directories. For multitenant deployments. + #[serde(skip_serializing_if = "Option::is_none")] + pub exclude_host_skills: Option, + /// Optional list of project directory paths. When omitted or empty, only personal and custom directories are returned. + #[serde(skip_serializing_if = "Option::is_none")] + pub project_paths: Option>, } -/// New auth credentials to install on the session. Omit to leave credentials unchanged. +/// Skill invocation record with name, path, content, allowed tools, and turn number. /// ///
/// @@ -12724,13 +15682,21 @@ pub struct SessionsEnrichMetadataRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSetCredentialsParams { - /// 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 installs the supplied value immediately for outbound model/API requests. When the credential carries a raw token (`token`, `env`, or `gh-cli`) but no `copilotUser`, the runtime additionally re-resolves `copilotUser` server-side (best-effort, asynchronously, after the synchronous install) so plan/quota/billing metadata regains fidelity; on resolution failure the verbatim credential remains installed. It does NOT otherwise validate the credential. Several variants carry secret material; treat this method's params as containing secrets at rest and in transit. +pub struct SkillsInvokedSkill { + /// Tools that should be auto-approved when this skill is active, captured at invocation time #[serde(skip_serializing_if = "Option::is_none")] - pub credentials: Option, + pub allowed_tools: Option>, + /// Full content of the skill file + pub content: String, + /// Turn number when the skill was invoked + pub invoked_at_turn: i64, + /// Unique identifier for the skill + pub name: String, + /// Path to the SKILL.md file + pub path: String, } -/// Indicates whether the credential update succeeded. +/// Skills invoked during this session, ordered by invocation time (most recent last). /// ///
/// @@ -12740,15 +15706,12 @@ pub struct SessionSetCredentialsParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSetCredentialsResult { - /// Whether the session ended up with a populated `copilotUser` for the installed credentials. `true` when the supplied credential already carried `copilotUser` or it was successfully re-resolved server-side. `false` when the credential is installed without `copilotUser` — either re-resolution failed, or the variant cannot be re-resolved from the credential alone (only the raw-token variants `token`, `env`, and `gh-cli` can). In both `false` cases the token swap still applied, but plan/quota/billing metadata is degraded. Present whenever a credential was supplied; omitted only when no credential was supplied (no-op call). - #[serde(skip_serializing_if = "Option::is_none")] - pub copilot_user_resolved: Option, - /// Whether the operation succeeded - pub success: bool, +pub struct SkillsGetInvokedResult { + /// Skills invoked during this session, ordered by invocation time (most recent last) + pub skills: Vec, } -/// Availability of built-in job tools surfaced to boundary consumers. +/// Diagnostics from reloading skill definitions, with warnings and errors as separate lists. /// ///
/// @@ -12758,14 +15721,14 @@ pub struct SessionSetCredentialsResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSettingsBuiltInToolAvailabilitySnapshot { - #[serde(skip_serializing_if = "Option::is_none")] - pub create_pull_request: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub report_progress: Option, +pub struct SkillsLoadDiagnostics { + /// Errors emitted while loading skills (e.g. skills that failed to load entirely) + pub errors: Vec, + /// Warnings emitted while loading skills (e.g. skills that loaded but had issues) + pub warnings: Vec, } -/// Named Rust-owned settings predicate to evaluate for this session. +/// Slash-command invocation result that submits an agent prompt, with display prompt, optional mode, optional user-facing notice, and settings-change flag. /// ///
/// @@ -12775,15 +15738,25 @@ pub struct SessionSettingsBuiltInToolAvailabilitySnapshot { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSettingsEvaluatePredicateRequest { - /// Predicate name. The runtime owns the raw feature-flag names and composition logic. - pub name: SessionSettingsPredicateName, - /// Tool name for tool-scoped predicates such as trivial-change handling. +pub struct SlashCommandAgentPromptResult { + /// Prompt text to display to the user + pub display_prompt: String, + /// Agent prompt result discriminator + pub kind: SlashCommandAgentPromptResultKind, + /// Optional target session mode for the agent prompt #[serde(skip_serializing_if = "Option::is_none")] - pub tool_name: Option, + pub mode: Option, + /// Optional user-facing notice to show before the prompt is submitted + #[serde(skip_serializing_if = "Option::is_none")] + pub notice: Option, + /// Prompt to submit to the agent + pub prompt: String, + /// True when the invocation mutated user runtime settings; consumers caching settings should refresh + #[serde(skip_serializing_if = "Option::is_none")] + pub runtime_settings_changed: Option, } -/// Result of evaluating a Rust-owned settings predicate. +/// Slash-command invocation result indicating completion, with optional message and settings-change flag. /// ///
/// @@ -12793,11 +15766,18 @@ pub struct SessionSettingsEvaluatePredicateRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSettingsEvaluatePredicateResult { - pub enabled: bool, +pub struct SlashCommandCompletedResult { + /// Completed result discriminator + pub kind: SlashCommandCompletedResultKind, + /// Optional user-facing message describing the completed command + #[serde(skip_serializing_if = "Option::is_none")] + pub message: Option, + /// True when the invocation mutated user runtime settings; consumers caching settings should refresh + #[serde(skip_serializing_if = "Option::is_none")] + pub runtime_settings_changed: Option, } -/// Redacted job settings for a session. The job nonce is excluded. +/// Slash-command invocation result containing text output plus Markdown/ANSI rendering flags. /// ///
/// @@ -12807,16 +15787,23 @@ pub struct SessionSettingsEvaluatePredicateResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSettingsJobSnapshot { +pub struct SlashCommandTextResult { + /// Text result discriminator + pub kind: SlashCommandTextResultKind, + /// Whether text contains Markdown #[serde(skip_serializing_if = "Option::is_none")] - pub built_in_tool_availability: Option, + pub markdown: Option, + /// Whether ANSI sequences should be preserved #[serde(skip_serializing_if = "Option::is_none")] - pub event_type: Option, + pub preserve_ansi: Option, + /// True when the invocation mutated user runtime settings; consumers caching settings should refresh #[serde(skip_serializing_if = "Option::is_none")] - pub is_trigger_job: Option, + pub runtime_settings_changed: Option, + /// Text output for the client to render + pub text: String, } -/// Redacted model routing settings for a session. +/// Selectable slash-command subcommand option with name, description, and optional group label. /// ///
/// @@ -12826,18 +15813,17 @@ pub struct SessionSettingsJobSnapshot { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSettingsModelSnapshot { - #[serde(skip_serializing_if = "Option::is_none")] - pub callback_url: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub default_reasoning_effort: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub instance_id: Option, +pub struct SlashCommandSelectSubcommandOption { + /// Human-readable description of the subcommand + pub description: String, + /// Optional group label for organizing options #[serde(skip_serializing_if = "Option::is_none")] - pub model: Option, + pub group: Option, + /// Subcommand name to invoke + pub name: String, } -/// Online-evaluation settings safe to expose across the SDK boundary. +/// Slash-command invocation result asking the client to present subcommand options for a parent command. /// ///
/// @@ -12847,14 +15833,21 @@ pub struct SessionSettingsModelSnapshot { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSettingsOnlineEvaluationSnapshot { - #[serde(skip_serializing_if = "Option::is_none")] - pub disable_online_evaluation: Option, +pub struct SlashCommandSelectSubcommandResult { + /// Parent command name that requires subcommand selection + pub command: String, + /// Select subcommand result discriminator + pub kind: SlashCommandSelectSubcommandResultKind, + /// Available subcommand options for the client to present + pub options: Vec, + /// True when the invocation mutated user runtime settings; consumers caching settings should refresh #[serde(skip_serializing_if = "Option::is_none")] - pub enable_online_evaluation_output_file: Option, + pub runtime_settings_changed: Option, + /// Human-readable title for the selection UI + pub title: String, } -/// Redacted repository and GitHub host settings for a session. +/// Subagent model, reasoning effort, and context tier settings /// ///
/// @@ -12864,34 +15857,19 @@ pub struct SessionSettingsOnlineEvaluationSnapshot { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSettingsRepoSnapshot { - #[serde(skip_serializing_if = "Option::is_none")] - pub branch: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub commit: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub host: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub host_protocol: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub id: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub owner_id: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub owner_name: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub pr_commit_count: Option, +pub struct SubagentSettingsEntry { + /// Context tier override for matching subagents #[serde(skip_serializing_if = "Option::is_none")] - pub read_write: Option, + pub context_tier: Option, + /// Reasoning effort override for matching subagents #[serde(skip_serializing_if = "Option::is_none")] - pub secret_scanning_url: Option, + pub effort_level: Option, + /// Model override for matching subagents #[serde(skip_serializing_if = "Option::is_none")] - pub server_url: Option, + pub model: Option, } -/// Redacted validation and memory-tool settings for a session. +/// Subagent settings to apply, or null to clear the live session override /// ///
/// @@ -12901,28 +15879,22 @@ pub struct SessionSettingsRepoSnapshot { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSettingsValidationSnapshot { - #[serde(skip_serializing_if = "Option::is_none")] - pub advisory_enabled: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub codeql_enabled: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub code_review_enabled: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub code_review_model: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub dependabot_timeout: Option, +pub struct SubagentSettings { + /// Per-agent settings keyed by subagent agent_type #[serde(skip_serializing_if = "Option::is_none")] - pub memory_store_enabled: Option, + pub agents: Option>, + /// Names of subagents the user has turned off; they cannot be dispatched #[serde(skip_serializing_if = "Option::is_none")] - pub memory_vote_enabled: Option, + pub disabled_subagents: Option>, + /// Maximum number of subagents that can run concurrently; applies to usage-based billing users only #[serde(skip_serializing_if = "Option::is_none")] - pub secret_scanning_enabled: Option, + pub max_concurrency: Option, + /// Maximum subagent nesting depth; applies to usage-based billing users only #[serde(skip_serializing_if = "Option::is_none")] - pub timeout: Option, + pub max_depth: Option, } -/// Redacted, serializable view of session runtime settings for SDK boundary consumers. Secrets and raw feature flags are intentionally excluded. +/// Tracked background agent task metadata, including IDs, status, timing, agent type, prompt, model, result, and latest response. /// ///
/// @@ -12932,23 +15904,59 @@ pub struct SessionSettingsValidationSnapshot { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSettingsSnapshot { +pub struct TaskAgentInfo { + /// ISO 8601 timestamp when the current active period began #[serde(skip_serializing_if = "Option::is_none")] - pub client_name: Option, - pub job: SessionSettingsJobSnapshot, - pub model: SessionSettingsModelSnapshot, - pub online_evaluation: SessionSettingsOnlineEvaluationSnapshot, - pub repo: SessionSettingsRepoSnapshot, + pub active_started_at: Option, + /// Accumulated active execution time in milliseconds #[serde(skip_serializing_if = "Option::is_none")] - pub start_time_ms: Option, + pub active_time_ms: Option, + /// Type of agent running this task + pub agent_type: String, + /// Whether the task is currently in the original sync wait and can be moved to background mode. False once it is already backgrounded, idle, finished, or no longer has a promotable sync waiter. #[serde(skip_serializing_if = "Option::is_none")] - pub timeout_ms: Option, - pub validation: SessionSettingsValidationSnapshot, + pub can_promote_to_background: Option, + /// ISO 8601 timestamp when the task finished #[serde(skip_serializing_if = "Option::is_none")] - pub version: Option, + pub completed_at: Option, + /// Short description of the task + pub description: String, + /// Error message when the task failed + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, + /// Whether task execution is synchronously awaited or managed in the background + #[serde(skip_serializing_if = "Option::is_none")] + pub execution_mode: Option, + /// Unique task identifier + pub id: String, + /// ISO 8601 timestamp when the agent entered idle state + #[serde(skip_serializing_if = "Option::is_none")] + pub idle_since: Option, + /// Most recent response text from the agent + #[serde(skip_serializing_if = "Option::is_none")] + pub latest_response: Option, + /// Requested model override for the task when specified + #[serde(skip_serializing_if = "Option::is_none")] + pub model: Option, + /// Most recent prompt delivered to the agent. Updated whenever the agent receives a follow-up message. + pub prompt: String, + /// Runtime model resolved for the task when available + #[serde(skip_serializing_if = "Option::is_none")] + pub resolved_model: Option, + /// Result text from the task when available + #[serde(skip_serializing_if = "Option::is_none")] + pub result: Option, + /// ISO 8601 timestamp when the task was started + pub started_at: String, + /// Current lifecycle status of the task + pub status: TaskStatus, + /// Tool call ID associated with this agent task + pub tool_call_id: String, + /// Task kind + pub r#type: TaskAgentInfoType, } -/// UUID prefix to resolve to a unique session ID. +/// Timestamped display line for task progress output or recent agent activity. /// ///
/// @@ -12958,12 +15966,14 @@ pub struct SessionSettingsSnapshot { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsFindByPrefixRequest { - /// UUID prefix (>=7 hex chars, <36 chars). Returns the unique session ID, or undefined when there is no match or the prefix matches multiple sessions. - pub prefix: String, +pub struct TaskProgressLine { + /// Display message, e.g., "▸ bash", "✓ edit src/foo.ts" + pub message: String, + /// ISO 8601 timestamp when this event occurred + pub timestamp: String, } -/// Session ID matching the prefix, omitted when no unique match exists. +/// Progress snapshot for an agent task, with recent activity lines and optional latest intent. /// ///
/// @@ -12973,13 +15983,17 @@ pub struct SessionsFindByPrefixRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsFindByPrefixResult { - /// Omitted when no unique session matches the prefix (no match or ambiguous) +pub struct TaskAgentProgress { + /// The most recent intent reported by the agent #[serde(skip_serializing_if = "Option::is_none")] - pub session_id: Option, + pub latest_intent: Option, + /// Recent tool execution events converted to display lines + pub recent_activity: Vec, + /// Progress kind + pub r#type: TaskAgentProgressType, } -/// GitHub task ID to look up. +/// Background tasks currently tracked by the session. /// ///
/// @@ -12989,12 +16003,12 @@ pub struct SessionsFindByPrefixResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsFindByTaskIDRequest { - /// GitHub task ID to look up - pub task_id: String, +pub struct TaskList { + /// Currently tracked tasks + pub tasks: Vec, } -/// ID of the local session bound to the given GitHub task, or omitted when none. +/// Identifier of the background task to cancel. /// ///
/// @@ -13004,34 +16018,27 @@ pub struct SessionsFindByTaskIDRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsFindByTaskIDResult { - /// Omitted when no local session is bound to that GitHub task - #[serde(skip_serializing_if = "Option::is_none")] - pub session_id: Option, +pub struct TasksCancelRequest { + /// Task identifier + pub id: String, } -/// Source session identifier to fork from, optional event-ID boundary, and optional friendly name for the new session. +/// Indicates whether the background task was successfully cancelled. /// ///
/// /// **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 SessionsForkRequest { - /// Optional friendly name to assign to the forked session. - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - /// Source session ID to fork from - pub session_id: SessionId, - /// Optional event ID boundary. When provided, the fork includes only events before this ID (exclusive). When omitted, all events are included. - #[serde(skip_serializing_if = "Option::is_none")] - pub to_event_id: Option, +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TasksCancelResult { + /// Whether the task was successfully cancelled + pub cancelled: bool, } -/// Identifier and optional friendly name assigned to the newly forked session. +/// The first sync-waiting task that can currently be promoted to background mode. /// ///
/// @@ -13041,15 +16048,13 @@ pub struct SessionsForkRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsForkResult { - /// Friendly name assigned to the forked session, if any. +pub struct TasksGetCurrentPromotableResult { + /// The first sync-waiting task (agent first, then shell) that can currently be promoted to background mode. Omitted if no such task exists. The returned task is guaranteed to have executionMode='sync' and canPromoteToBackground=true at the time of the call. #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - /// The new forked session's ID - pub session_id: SessionId, + pub task: Option, } -/// Session ID whose board entry count should be returned. +/// Identifier of the background task to fetch progress for. /// ///
/// @@ -13059,12 +16064,12 @@ pub struct SessionsForkResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsGetBoardEntryCountRequest { - /// Session ID whose board entry count should be returned. - pub session_id: SessionId, +pub struct TasksGetProgressRequest { + /// Task identifier (agent ID or shell ID) + pub id: String, } -/// Dynamic-context board entry count, when available. +/// Progress information for the task, or null when no task with that ID is tracked. /// ///
/// @@ -13074,13 +16079,12 @@ pub struct SessionsGetBoardEntryCountRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsGetBoardEntryCountResult { - /// Board entry count, when available. - #[serde(skip_serializing_if = "Option::is_none")] - pub count: Option, +pub struct TasksGetProgressResult { + /// Progress information for the task, discriminated by type. Returns null when no task with this ID is currently tracked. + pub progress: Option, } -/// Session ID whose event-log file path to compute. +/// Tracked shell task metadata, including ID, command, status, timing, attachment/execution mode, log path, and PID. /// ///
/// @@ -13090,12 +16094,39 @@ pub struct SessionsGetBoardEntryCountResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsGetEventFilePathRequest { - /// Session ID whose event-log file path to compute - pub session_id: SessionId, +pub struct TaskShellInfo { + /// Whether the shell runs inside a managed PTY session or as an independent background process + pub attachment_mode: TaskShellInfoAttachmentMode, + /// Whether this shell task can be promoted to background mode + #[serde(skip_serializing_if = "Option::is_none")] + pub can_promote_to_background: Option, + /// Command being executed + pub command: String, + /// ISO 8601 timestamp when the task finished + #[serde(skip_serializing_if = "Option::is_none")] + pub completed_at: Option, + /// Short description of the task + pub description: String, + /// Whether task execution is synchronously awaited or managed in the background + #[serde(skip_serializing_if = "Option::is_none")] + pub execution_mode: Option, + /// Unique task identifier + pub id: String, + /// Path to the detached shell log, when available + #[serde(skip_serializing_if = "Option::is_none")] + pub log_path: Option, + /// Process ID when available + #[serde(skip_serializing_if = "Option::is_none")] + pub pid: Option, + /// ISO 8601 timestamp when the task was started + pub started_at: String, + /// Current lifecycle status of the task + pub status: TaskStatus, + /// Task kind + pub r#type: TaskShellInfoType, } -/// Absolute path to the session's events.jsonl file on disk. +/// Progress snapshot for a shell task, with recent stdout/stderr output and optional process ID. /// ///
/// @@ -13105,12 +16136,17 @@ pub struct SessionsGetEventFilePathRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsGetEventFilePathResult { - /// Absolute path to the session's events.jsonl file - pub file_path: String, +pub struct TaskShellProgress { + /// Process ID when available + #[serde(skip_serializing_if = "Option::is_none")] + pub pid: Option, + /// Recent stdout/stderr lines from the running shell command + pub recent_output: String, + /// Progress kind + pub r#type: TaskShellProgressType, } -/// Optional working-directory context used to score session relevance. +/// The promoted task as it now exists in background mode, omitted if no promotable task was waiting. /// ///
/// @@ -13120,13 +16156,13 @@ pub struct SessionsGetEventFilePathResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsGetLastForContextRequest { - /// Optional working-directory context used to score session relevance. When omitted the most-recently-modified session wins. +pub struct TasksPromoteCurrentToBackgroundResult { + /// The promoted task as it now exists in background mode, omitted if no promotable task was waiting. Atomic operation: avoids the race window of getCurrentPromotable + promoteToBackground. #[serde(skip_serializing_if = "Option::is_none")] - pub context: Option, + pub task: Option, } -/// Most-relevant session ID for the supplied context, or omitted when no sessions exist. +/// Identifier of the task to promote to background mode. /// ///
/// @@ -13136,13 +16172,12 @@ pub struct SessionsGetLastForContextRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsGetLastForContextResult { - /// Most-relevant session ID for the supplied context, or omitted when no sessions exist - #[serde(skip_serializing_if = "Option::is_none")] - pub session_id: Option, +pub struct TasksPromoteToBackgroundRequest { + /// Task identifier + pub id: String, } -/// Session ID to look up the persisted remote-steerable flag for. +/// Indicates whether the task was successfully promoted to background mode. /// ///
/// @@ -13152,12 +16187,12 @@ pub struct SessionsGetLastForContextResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsGetPersistedRemoteSteerableRequest { - /// Session ID to look up the persisted remote-steerable flag for - pub session_id: SessionId, +pub struct TasksPromoteToBackgroundResult { + /// Whether the task was successfully promoted to background mode + pub promoted: bool, } -/// The session's persisted remote-steerable flag, or omitted when no value has been persisted. +/// Refresh metadata for any detached background shells the runtime knows about. Use after a long pause to pick up exit/output state for shells running outside the agent loop. /// ///
/// @@ -13167,13 +16202,9 @@ pub struct SessionsGetPersistedRemoteSteerableRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsGetPersistedRemoteSteerableResult { - /// The session's persisted remote-steerable flag if recorded; omitted when no value has been persisted - #[serde(skip_serializing_if = "Option::is_none")] - pub remote_steerable: Option, -} +pub struct TasksRefreshResult {} -/// Map of sessionId -> on-disk size in bytes for each session's workspace directory. +/// Identifier of the completed or cancelled task to remove from tracking. /// ///
/// @@ -13183,12 +16214,12 @@ pub struct SessionsGetPersistedRemoteSteerableResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSizes { - /// Map of sessionId -> on-disk size in bytes for the session's workspace directory - pub sizes: HashMap, +pub struct TasksRemoveRequest { + /// Task identifier + pub id: String, } -/// Optional source filter, metadata-load limit, and context filter applied to the returned sessions. +/// Indicates whether the task was removed. False when the task does not exist or is still running/idle. /// ///
/// @@ -13198,25 +16229,12 @@ pub struct SessionSizes { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsListRequest { - /// Optional filter applied to the returned sessions - #[serde(skip_serializing_if = "Option::is_none")] - pub filter: Option, - /// When true, include detached maintenance sessions. Defaults to false for user-facing session lists. - #[serde(skip_serializing_if = "Option::is_none")] - pub include_detached: Option, - /// When provided, only the first N local sessions (sorted by modification time, newest first) load full metadata; remaining sessions return basic info only. Use 0 to return only basic info for every local session. Has no effect on remote entries (which always carry their full shape). - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata_limit: Option, - /// Which session sources to include. Defaults to `local` for backward compatibility. - #[serde(skip_serializing_if = "Option::is_none")] - pub source: Option, - /// Only meaningful when `source` includes remote. When true, propagates errors from the remote service instead of silently returning an empty remote list. Defaults to false. - #[serde(skip_serializing_if = "Option::is_none")] - pub throw_on_error: Option, +pub struct TasksRemoveResult { + /// Whether the task was removed. Returns false if the task does not exist or is still running/idle (cancel it first). + pub removed: bool, } -/// Active session ID whose deferred repo-level hooks should be loaded. +/// Identifier of the target agent task, message content, and optional sender agent ID. /// ///
/// @@ -13226,12 +16244,17 @@ pub struct SessionsListRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsLoadDeferredRepoHooksRequest { - /// Active session ID whose deferred repo-level hooks should be loaded - pub session_id: SessionId, +pub struct TasksSendMessageRequest { + /// Agent ID of the sender, if sent on behalf of another agent + #[serde(skip_serializing_if = "Option::is_none")] + pub from_agent_id: Option, + /// Agent task identifier + pub id: String, + /// Message content to send to the agent + pub message: String, } -/// Age threshold and optional flags controlling which old sessions are pruned (or simulated when dryRun is true). +/// Indicates whether the message was delivered, with an error message when delivery failed. /// ///
/// @@ -13241,21 +16264,15 @@ pub struct SessionsLoadDeferredRepoHooksRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsPruneOldRequest { - /// When true, only report what would be deleted without performing any deletion - #[serde(skip_serializing_if = "Option::is_none")] - pub dry_run: Option, - /// Session IDs that should never be considered for pruning - #[serde(skip_serializing_if = "Option::is_none")] - pub exclude_session_ids: Option>, - /// When true, named sessions (set via /rename) are also eligible for pruning +pub struct TasksSendMessageResult { + /// Error message if delivery failed #[serde(skip_serializing_if = "Option::is_none")] - pub include_named: Option, - /// Delete sessions whose modifiedTime is at least this many days old - pub older_than_days: i64, + pub error: Option, + /// Whether the message was successfully delivered or steered + pub sent: bool, } -/// Session ID whose in-use lock should be released. +/// Agent type, prompt, name, and optional description and model override for the new task. /// ///
/// @@ -13265,12 +16282,22 @@ pub struct SessionsPruneOldRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsReleaseLockRequest { - /// Session ID whose in-use lock should be released - pub session_id: SessionId, +pub struct TasksStartAgentRequest { + /// Type of agent to start (e.g., 'explore', 'task', 'general-purpose') + pub agent_type: String, + /// Short description of the task + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + /// Optional model override + #[serde(skip_serializing_if = "Option::is_none")] + pub model: Option, + /// Short name for the agent, used to generate a human-readable ID + pub name: String, + /// Task prompt for the agent + pub prompt: String, } -/// Release the in-use lock held by this process for the given session. No-op when this process does not currently hold a lock for the session. +/// Identifier assigned to the newly started background agent task. /// ///
/// @@ -13280,9 +16307,12 @@ pub struct SessionsReleaseLockRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsReleaseLockResult {} +pub struct TasksStartAgentResult { + /// Generated agent ID for the background task + pub agent_id: String, +} -/// Active session ID and an optional flag for deferring repo-level hooks until folder trust. +/// Wait until all in-flight background tasks (agents + shells) and any follow-up turns scheduled by their completions have settled. Returns when the runtime is fully drained or after an internal timeout (default 10 minutes; configurable via COPILOT_TASK_WAIT_TIMEOUT_SECONDS). /// ///
/// @@ -13292,15 +16322,9 @@ pub struct SessionsReleaseLockResult {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsReloadPluginHooksRequest { - /// When true, skip repo-level hooks. Use before folder trust is confirmed; loadDeferredRepoHooks loads them post-trust. - #[serde(skip_serializing_if = "Option::is_none")] - pub defer_repo_hooks: Option, - /// Active session ID to reload hooks for - pub session_id: SessionId, -} +pub struct TasksWaitForPendingResult {} -/// Reload all hooks (user, plugin, optionally repo) and apply them to the active session. Call after installing or removing plugins so their hooks take effect immediately. No-op when no active session matches the given sessionId. +/// Feature override key/value pairs to attach to subsequent telemetry events from this session. /// ///
/// @@ -13310,9 +16334,12 @@ pub struct SessionsReloadPluginHooksRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsReloadPluginHooksResult {} +pub struct TelemetrySetFeatureOverridesRequest { + /// Override key/value pairs to attach to subsequent telemetry events from this session. Replaces any previously-set overrides. + pub features: HashMap, +} -/// Session ID whose pending events should be flushed to disk. +/// Authentication-info variant for SDK-configured token authentication, carrying host and the secret token value. /// ///
/// @@ -13322,12 +16349,19 @@ pub struct SessionsReloadPluginHooksResult {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsSaveRequest { - /// Session ID whose pending events should be flushed to disk - pub session_id: SessionId, +pub struct TokenAuthInfo { + /// 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. + #[serde(skip_serializing_if = "Option::is_none")] + pub copilot_user: Option, + /// Authentication host. + pub host: String, + /// The token value itself. Treat as a secret. + pub token: String, + /// SDK-side token authentication; the host configured the token directly via the SDK. + pub r#type: TokenAuthInfoType, } -/// Flush a session's pending events to disk. No-op when no writer exists for the session (e.g., already closed). +/// Built-in tool metadata with identifier, optional namespaced name, description, input-parameter schema, and usage instructions. /// ///
/// @@ -13337,9 +16371,23 @@ pub struct SessionsSaveRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsSaveResult {} +pub struct Tool { + /// Description of what the tool does + pub description: String, + /// Optional instructions for how to use this tool effectively + #[serde(skip_serializing_if = "Option::is_none")] + pub instructions: Option, + /// Tool identifier (e.g., "bash", "grep", "str_replace_editor") + pub name: String, + /// Optional namespaced name for declarative filtering (e.g., "playwright/navigate" for MCP tools) + #[serde(skip_serializing_if = "Option::is_none")] + pub namespaced_name: Option, + /// JSON Schema for the tool's input parameters + #[serde(skip_serializing_if = "Option::is_none")] + pub parameters: Option>, +} -/// Manager-wide additional plugins to register; replaces any previously-configured set. +/// Built-in tools available for the requested model, with their parameters and instructions. /// ///
/// @@ -13349,12 +16397,12 @@ pub struct SessionsSaveResult {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsSetAdditionalPluginsRequest { - /// Manager-wide additional plugins to register. Replaces any previously-configured set. Pass an empty array to clear. - pub plugins: Vec, +pub struct ToolList { + /// List of available built-in tools with metadata + pub tools: Vec, } -/// Replace the manager-wide additional plugins. New session creations and subsequent hook reloads see the new set; already-running sessions keep their existing hook installation until the next reload. +/// Current lightweight tool metadata snapshot for the session. /// ///
/// @@ -13364,9 +16412,12 @@ pub struct SessionsSetAdditionalPluginsRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsSetAdditionalPluginsResult {} +pub struct ToolsGetCurrentMetadataResult { + /// Current tool metadata, or null when tools have not been initialized yet + pub tools: Option>, +} -/// Patch for the singleton's steering state. +/// Resolve, build, and validate the runtime tool list for this session. Subagent sessions and consumer flows that need an initialized tool set before `send` invoke this. Default base-class implementation is a no-op for sessions that don't support tool validation. /// ///
/// @@ -13376,12 +16427,9 @@ pub struct SessionsSetAdditionalPluginsResult {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsSetRemoteControlSteeringRequest { - /// Target steering state. Today only `true` is actionable on the underlying exporter; `false` is reserved for future use. - pub enabled: bool, -} +pub struct ToolsInitializeAndValidateResult {} -/// Parameters for attaching the remote-control singleton to a session. +/// Optional model identifier whose tool overrides should be applied to the listing. /// ///
/// @@ -13391,14 +16439,13 @@ pub struct SessionsSetRemoteControlSteeringRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsStartRemoteControlRequest { - /// Configuration for the runtime-managed remote-control singleton. - pub config: RemoteControlConfig, - /// Local session id to attach remote control to. - pub session_id: SessionId, +pub struct ToolsListRequest { + /// Optional model ID — when provided, the returned tool list reflects model-specific overrides + #[serde(skip_serializing_if = "Option::is_none")] + pub model: Option, } -/// Parameters for stopping the remote-control singleton. +/// Empty result after applying subagent settings /// ///
/// @@ -13408,16 +16455,9 @@ pub struct SessionsStartRemoteControlRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsStopRemoteControlRequest { - /// When provided, the stop is rejected unless the singleton currently points at this session id (compare-and-swap semantics). - #[serde(skip_serializing_if = "Option::is_none")] - pub expected_session_id: Option, - /// When true, the singleton is unconditionally torn down regardless of `expectedSessionId`. Use during shutdown or explicit `/remote off`. - #[serde(skip_serializing_if = "Option::is_none")] - pub force: Option, -} +pub struct ToolsUpdateSubagentSettingsResult {} -/// Parameters for atomically rebinding the remote-control singleton. +/// Selectable option for a UI elicitation multi-select array item, with submitted value and display label. /// ///
/// @@ -13427,15 +16467,14 @@ pub struct SessionsStopRemoteControlRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsTransferRemoteControlRequest { - /// When provided, the transfer is rejected unless the singleton currently points at this session id (compare-and-swap semantics to avoid clobbering newer state). - #[serde(skip_serializing_if = "Option::is_none")] - pub expected_from_session_id: Option, - /// Local session id to point remote control at. - pub to_session_id: String, +pub struct UIElicitationArrayAnyOfFieldItemsAnyOf { + /// Value submitted when this option is selected. + pub r#const: String, + /// Display label for this option. + pub title: String, } -/// Telemetry engagement ID for the session, when available. +/// Schema applied to each item in the array. /// ///
/// @@ -13445,13 +16484,12 @@ pub struct SessionsTransferRemoteControlRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionTelemetryEngagement { - /// Current telemetry engagement ID, when available. - #[serde(skip_serializing_if = "Option::is_none")] - pub engagement_id: Option, +pub struct UIElicitationArrayAnyOfFieldItems { + /// Selectable options, each with a value and a display label. + pub any_of: Vec, } -/// Patch of mutable session options to apply to the running session. +/// Multi-select string field where each option pairs a value with a display label. /// ///
/// @@ -13461,201 +16499,46 @@ pub struct SessionTelemetryEngagement { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionUpdateOptionsParams { - /// Additional content-exclusion policies to merge into the session's policy set. - /// - ///
- /// - /// **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 additional_content_exclusion_policies: - Option>, - /// Runtime context discriminator (e.g., `cli`, `actions`). - #[serde(skip_serializing_if = "Option::is_none")] - pub agent_context: Option, - /// Whether to include instructions from every MCP server in the system prompt instead of only allowlisted servers. - #[serde(skip_serializing_if = "Option::is_none")] - pub allow_all_mcp_server_instructions: Option, - /// Whether to disable the `ask_user` tool (encourages autonomous behavior). - #[serde(skip_serializing_if = "Option::is_none")] - pub ask_user_disabled: Option, - /// Allowlist of tool names available to this session. - #[serde(skip_serializing_if = "Option::is_none")] - pub available_tools: Option>, - /// Options scoped to the built-in CAPI (Copilot API) provider. - #[serde(skip_serializing_if = "Option::is_none")] - pub capi: Option, - /// Identifier of the client driving the session. - #[serde(skip_serializing_if = "Option::is_none")] - pub client_name: Option, - /// Whether to include the `Co-authored-by` trailer in commit messages. - #[serde(skip_serializing_if = "Option::is_none")] - pub coauthor_enabled: Option, - /// Context tier for models with tiered pricing. The session uses this to derive effective `modelCapabilitiesOverrides` so compaction, truncation, token display, and request limits honor the selected tier. - #[serde(skip_serializing_if = "Option::is_none")] - pub context_tier: Option, - /// Whether to allow auto-mode continuation across turns. - #[serde(skip_serializing_if = "Option::is_none")] - pub continue_on_auto_mode: Option, - /// Override URL for the Copilot API endpoint. - #[serde(skip_serializing_if = "Option::is_none")] - pub copilot_url: Option, - /// Whether to default custom agents to local-only execution. - #[serde(skip_serializing_if = "Option::is_none")] - pub custom_agents_local_only: Option, - /// Instruction source IDs to exclude from the system prompt. - #[serde(skip_serializing_if = "Option::is_none")] - pub disabled_instruction_sources: Option>, - /// Skill IDs that should be excluded from this session. - #[serde(skip_serializing_if = "Option::is_none")] - pub disabled_skills: Option>, - /// Whether to enable loading of `.github/hooks/` filesystem hooks. Separate from the SDK callback hook mechanism. - #[serde(skip_serializing_if = "Option::is_none")] - pub enable_file_hooks: Option, - /// Whether to enable host git operations (context resolution, child repo scanning, git info in system prompt). - #[serde(skip_serializing_if = "Option::is_none")] - pub enable_host_git_operations: Option, - /// Whether to discover custom instructions on demand after successful file views (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md surfacing). Combined with `skipCustomInstructions` and the runtime-side `ON_DEMAND_INSTRUCTIONS` feature flag. - #[serde(skip_serializing_if = "Option::is_none")] - pub enable_on_demand_instruction_discovery: Option, - /// Whether to surface reasoning-summary events from the model. - #[serde(skip_serializing_if = "Option::is_none")] - pub enable_reasoning_summaries: Option, - /// Whether shell-script safety heuristics are enabled. - #[serde(skip_serializing_if = "Option::is_none")] - pub enable_script_safety: Option, - /// Whether to enable cross-session store writes and reads. - #[serde(skip_serializing_if = "Option::is_none")] - pub enable_session_store: Option, - /// Whether to enable skill directory scanning and loading. Falls back to enableConfigDiscovery when unset. - #[serde(skip_serializing_if = "Option::is_none")] - pub enable_skills: Option, - /// Whether to stream model responses. - #[serde(skip_serializing_if = "Option::is_none")] - pub enable_streaming: Option, - /// How env values are passed to MCP servers (`direct` inlines literal values; `indirect` resolves at launch). - #[serde(skip_serializing_if = "Option::is_none")] - pub env_value_mode: Option, - /// Override directory for the session-events log. When unset, the runtime's default events log directory is used. - #[serde(skip_serializing_if = "Option::is_none")] - pub events_log_directory: Option, - /// Built-in subagent names to exclude from this session. Excluded built-ins are hidden from agent discovery and cannot be dispatched unless a custom agent with the same name is available. - #[serde(skip_serializing_if = "Option::is_none")] - pub excluded_builtin_agents: Option>, - /// Denylist of tool names for this session. - #[serde(skip_serializing_if = "Option::is_none")] - pub excluded_tools: Option>, - /// Map of feature-flag IDs to their boolean enabled state. - #[serde(skip_serializing_if = "Option::is_none")] - pub feature_flags: Option>, - /// Built-in subagent names to include in this session. When specified, only these built-ins are available, subject to runtime availability and exclusions. Custom agents with the same name remain available. Set to null to remove the allowlist restriction. - #[serde(skip_serializing_if = "Option::is_none")] - pub included_builtin_agents: Option>, - /// Full set of installed plugins for the session. Replaces the existing list; the runtime invalidates the skills cache only when the list materially changes. - #[serde(skip_serializing_if = "Option::is_none")] - pub installed_plugins: Option>, - /// Stable integration identifier used for analytics and rate-limit attribution. - #[serde(skip_serializing_if = "Option::is_none")] - pub integration_id: Option, - /// Whether experimental capabilities are enabled. - #[serde(skip_serializing_if = "Option::is_none")] - pub is_experimental_mode: Option, - /// Whether interactive shell sessions are logged. - #[serde(skip_serializing_if = "Option::is_none")] - pub log_interactive_shells: Option, - /// Identifier sent to LSP-style integrations. - #[serde(skip_serializing_if = "Option::is_none")] - pub lsp_client_name: Option, - /// 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). - #[serde(skip_serializing_if = "Option::is_none")] - pub manage_schedule_enabled: Option, - /// Maximum decoded byte size of a single model-facing binary tool result (e.g. an image) persisted inline in session events and re-presented to the model on later turns / resume. Larger results are persisted as a metadata-only marker and shown to the model as a short text note. Defaults to 10 MB. - #[serde(skip_serializing_if = "Option::is_none")] - pub max_inline_binary_bytes: Option, - /// The model ID to use for assistant turns. - #[serde(skip_serializing_if = "Option::is_none")] - pub model: Option, - /// Per-property model capability overrides for the selected model. - #[serde(skip_serializing_if = "Option::is_none")] - pub model_capabilities_overrides: Option, - /// Organization-level custom instructions to inject into the system prompt. - #[serde(skip_serializing_if = "Option::is_none")] - pub organization_custom_instructions: Option, - /// Custom model-provider configuration (BYOK). - #[serde(skip_serializing_if = "Option::is_none")] - pub provider: Option, - /// Reasoning effort for the selected model (model-defined enum). - #[serde(skip_serializing_if = "Option::is_none")] - pub reasoning_effort: Option, - /// Reasoning summary mode for supported model clients. - #[serde(skip_serializing_if = "Option::is_none")] - pub reasoning_summary: Option, - /// Whether the session is running in an interactive UI. - #[serde(skip_serializing_if = "Option::is_none")] - pub running_in_interactive_mode: Option, - /// Resolved sandbox configuration. - #[serde(skip_serializing_if = "Option::is_none")] - pub sandbox_config: Option, - /// Replaces the session's capability set with the given list. Use to enable or disable capabilities mid-session (e.g., remove `memory` for reproducible scripted runs). Omit the field to leave the existing capability set unchanged. - #[serde(skip_serializing_if = "Option::is_none")] - pub session_capabilities: Option>, - /// Optional session limits. Pass null to clear the session limits. - #[serde(skip_serializing_if = "Option::is_none")] - pub session_limits: Option, - /// Shell init profile (`None` or `NonInteractive`). - #[serde(skip_serializing_if = "Option::is_none")] - pub shell_init_profile: Option, - /// Per-shell process flags (e.g., `pwsh` arguments). - #[serde(skip_serializing_if = "Option::is_none")] - pub shell_process_flags: Option>, - /// Additional directories to search for skills. - #[serde(skip_serializing_if = "Option::is_none")] - pub skill_directories: Option>, - /// Whether to skip loading custom instruction sources. - #[serde(skip_serializing_if = "Option::is_none")] - pub skip_custom_instructions: Option, - /// Whether to skip embedding retrieval pipeline initialization and execution. - #[serde(skip_serializing_if = "Option::is_none")] - pub skip_embedding_retrieval: Option, - /// When true, the selected custom agent's prompt is not injected into the user message (skill context is still injected). Used by automation triggers where the agent prompt is already in the problem statement. +pub struct UIElicitationArrayAnyOfField { + /// Default values selected when the form is first shown. #[serde(skip_serializing_if = "Option::is_none")] - pub suppress_custom_agent_prompt: Option, - /// Controls how availableTools (allowlist) and excludedTools (denylist) combine when both are set. + pub default: Option>, + /// Help text describing the field. #[serde(skip_serializing_if = "Option::is_none")] - pub tool_filter_precedence: Option, - /// Optional path for trajectory output. + pub description: Option, + /// Schema applied to each item in the array. + pub items: UIElicitationArrayAnyOfFieldItems, + /// Maximum number of items the user may select. #[serde(skip_serializing_if = "Option::is_none")] - pub trajectory_file: Option, - /// Output verbosity level for supported models. + pub max_items: Option, + /// Minimum number of items the user must select. #[serde(skip_serializing_if = "Option::is_none")] - pub verbosity: Option, - /// Absolute working-directory path for shell tools. + pub min_items: Option, + /// Human-readable label for the field. #[serde(skip_serializing_if = "Option::is_none")] - pub working_directory: Option, + pub title: Option, + /// Type discriminator. Always "array". + pub r#type: UIElicitationArrayAnyOfFieldType, } -/// Indicates whether the session options patch was applied successfully. +/// Schema applied to each item in the array. /// ///
/// /// **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 SessionUpdateOptionsResult { - /// Number of hooks loaded from installed plugins, returned when installedPlugins is updated - #[serde(skip_serializing_if = "Option::is_none")] - pub plugin_hook_count: Option, - /// Whether the operation succeeded - pub success: bool, +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UIElicitationArrayEnumFieldItems { + /// Allowed string values for each selected item. + pub r#enum: Vec, + /// Type discriminator. Always "string". + pub r#type: UIElicitationArrayEnumFieldItemsType, } -/// User-requested shell execution cancellation handle. +/// Multi-select string field whose allowed values are defined inline. /// ///
/// @@ -13665,12 +16548,29 @@ pub struct SessionUpdateOptionsResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ShellCancelUserRequestedRequest { - /// Request ID previously passed to executeUserRequested - pub request_id: RequestId, +pub struct UIElicitationArrayEnumField { + /// Default values selected when the form is first shown. + #[serde(skip_serializing_if = "Option::is_none")] + pub default: Option>, + /// Help text describing the field. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + /// Schema applied to each item in the array. + pub items: UIElicitationArrayEnumFieldItems, + /// Maximum number of items the user may select. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_items: Option, + /// Minimum number of items the user must select. + #[serde(skip_serializing_if = "Option::is_none")] + pub min_items: Option, + /// Human-readable label for the field. + #[serde(skip_serializing_if = "Option::is_none")] + pub title: Option, + /// Type discriminator. Always "array". + pub r#type: UIElicitationArrayEnumFieldType, } -/// Shell command to run, with optional working directory and timeout in milliseconds. +/// JSON Schema describing the form fields to present to the user /// ///
/// @@ -13680,18 +16580,17 @@ pub struct ShellCancelUserRequestedRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ShellExecRequest { - /// Shell command to execute - pub command: String, - /// Working directory (defaults to session working directory) - #[serde(skip_serializing_if = "Option::is_none")] - pub cwd: Option, - /// Timeout in milliseconds (default: 30000) +pub struct UIElicitationSchema { + /// Form field definitions, keyed by field name + pub properties: HashMap, + /// List of required field names #[serde(skip_serializing_if = "Option::is_none")] - pub timeout: Option, + pub required: Option>, + /// Schema type indicator (always 'object') + pub r#type: UIElicitationSchemaType, } -/// Identifier of the spawned process, used to correlate streamed output and exit notifications. +/// Prompt message and JSON schema describing the form fields to elicit from the user. /// ///
/// @@ -13701,12 +16600,14 @@ pub struct ShellExecRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ShellExecResult { - /// Unique identifier for tracking streamed output - pub process_id: String, +pub struct UIElicitationRequest { + /// Message describing what information is needed from the user + pub message: String, + /// JSON Schema describing the form fields to present to the user + pub requested_schema: UIElicitationSchema, } -/// User-requested shell command and cancellation handle. +/// The elicitation response (accept with form values, decline, or cancel) /// ///
/// @@ -13716,14 +16617,15 @@ pub struct ShellExecResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ShellExecuteUserRequestedRequest { - /// Shell command to execute - pub command: String, - /// Caller-provided cancellation handle for this execution - pub request_id: RequestId, +pub struct UIElicitationResponse { + /// The user's response: accept (submitted), decline (rejected), or cancel (dismissed) + pub action: UIElicitationResponseAction, + /// The form values submitted by the user (present when action is 'accept') + #[serde(skip_serializing_if = "Option::is_none")] + pub content: Option>, } -/// Identifier of a process previously returned by "shell.exec" and the signal to send. +/// Indicates whether the elicitation response was accepted; false if it was already resolved by another client. /// ///
/// @@ -13733,15 +16635,12 @@ pub struct ShellExecuteUserRequestedRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ShellKillRequest { - /// Process identifier returned by shell.exec - pub process_id: String, - /// Signal to send (default: SIGTERM) - #[serde(skip_serializing_if = "Option::is_none")] - pub signal: Option, +pub struct UIElicitationResult { + /// Whether the response was accepted. False if the request was already resolved by another client. + pub success: bool, } -/// Indicates whether the signal was delivered; false if the process was unknown or already exited. +/// Boolean field rendered as a yes/no toggle. /// ///
/// @@ -13751,12 +16650,21 @@ pub struct ShellKillRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ShellKillResult { - /// Whether the signal was sent successfully - pub killed: bool, +pub struct UIElicitationSchemaPropertyBoolean { + /// Default value selected when the form is first shown. + #[serde(skip_serializing_if = "Option::is_none")] + pub default: Option, + /// Help text describing the field. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + /// Human-readable label for the field. + #[serde(skip_serializing_if = "Option::is_none")] + pub title: Option, + /// Type discriminator. Always "boolean". + pub r#type: UIElicitationSchemaPropertyBooleanType, } -/// Parameters for shutting down the session +/// Numeric field accepting either a number or an integer. /// ///
/// @@ -13766,16 +16674,27 @@ pub struct ShellKillResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ShutdownRequest { - /// Optional human-readable reason. Typically the message of the error that triggered shutdown when type is 'error'. +pub struct UIElicitationSchemaPropertyNumber { + /// Default value populated in the input when the form is first shown. #[serde(skip_serializing_if = "Option::is_none")] - pub reason: Option, - /// Why the session is being shut down. Defaults to "routine" when omitted. + pub default: Option, + /// Help text describing the field. #[serde(skip_serializing_if = "Option::is_none")] - pub r#type: Option, + pub description: Option, + /// Maximum allowed value (inclusive). + #[serde(skip_serializing_if = "Option::is_none")] + pub maximum: Option, + /// Minimum allowed value (inclusive). + #[serde(skip_serializing_if = "Option::is_none")] + pub minimum: Option, + /// Human-readable label for the field. + #[serde(skip_serializing_if = "Option::is_none")] + pub title: Option, + /// Numeric type accepted by the field. + pub r#type: UIElicitationSchemaPropertyNumberType, } -/// Skill metadata available to a session, with name, description, source, enabled/invocable state, path, plugin, and argument hint. +/// Free-text string field with optional length and format constraints. /// ///
/// @@ -13785,29 +16704,30 @@ pub struct ShutdownRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct Skill { - /// Optional freeform hint describing the skill's expected arguments, from the `argument-hint` frontmatter field +pub struct UIElicitationSchemaPropertyString { + /// Default value populated in the input when the form is first shown. #[serde(skip_serializing_if = "Option::is_none")] - pub argument_hint: Option, - /// Description of what the skill does - pub description: String, - /// Whether the skill is currently enabled - pub enabled: bool, - /// Unique identifier for the skill - pub name: String, - /// Absolute path to the skill file + pub default: Option, + /// Help text describing the field. #[serde(skip_serializing_if = "Option::is_none")] - pub path: Option, - /// Name of the plugin that provides the skill, when source is 'plugin' + pub description: Option, + /// Optional format hint that constrains the accepted input. #[serde(skip_serializing_if = "Option::is_none")] - pub plugin_name: Option, - /// Source location type (e.g., project, personal-copilot, plugin, builtin) - pub source: SkillSource, - /// Whether the skill can be invoked by the user as a slash command - pub user_invocable: bool, + pub format: Option, + /// Maximum number of characters allowed. + #[serde(skip_serializing_if = "Option::is_none")] + pub max_length: Option, + /// Minimum number of characters required. + #[serde(skip_serializing_if = "Option::is_none")] + pub min_length: Option, + /// Human-readable label for the field. + #[serde(skip_serializing_if = "Option::is_none")] + pub title: Option, + /// Type discriminator. Always "string". + pub r#type: UIElicitationSchemaPropertyStringType, } -/// Canonical directory where skills can be discovered or created, with scope, preference, and optional project path. +/// Single-select string field whose allowed values are defined inline. /// ///
/// @@ -13817,19 +16737,26 @@ pub struct Skill { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SkillDiscoveryPath { - /// Absolute path of the create/discovery target (may not exist on disk yet) - pub path: String, - /// Whether this is the canonical directory to create a new skill in its tier. At most one entry per tier is preferred; the `personal-agents` and `custom` scopes are never preferred. - pub preferred_for_creation: bool, - /// The input project path this directory was derived from (only for project scope) +pub struct UIElicitationStringEnumField { + /// Default value selected when the form is first shown. #[serde(skip_serializing_if = "Option::is_none")] - pub project_path: Option, - /// Which tier this directory belongs to - pub scope: SkillDiscoveryScope, + pub default: Option, + /// Help text describing the field. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + /// Allowed string values. + pub r#enum: Vec, + /// Optional display labels for each enum value, in the same order as `enum`. + #[serde(skip_serializing_if = "Option::is_none")] + pub enum_names: Option>, + /// Human-readable label for the field. + #[serde(skip_serializing_if = "Option::is_none")] + pub title: Option, + /// Type discriminator. Always "string". + pub r#type: UIElicitationStringEnumFieldType, } -/// Canonical locations where skills can be created so the runtime will recognize them. +/// Selectable option for a UI elicitation single-select string field, with submitted value and display label. /// ///
/// @@ -13839,12 +16766,14 @@ pub struct SkillDiscoveryPath { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SkillDiscoveryPathList { - /// Canonical skill create/discovery directories, in priority order - pub paths: Vec, +pub struct UIElicitationStringOneOfFieldOneOf { + /// Value submitted when this option is selected. + pub r#const: String, + /// Display label for this option. + pub title: String, } -/// Skills available to the session, with their enabled state. +/// Single-select string field where each option pairs a value with a display label. /// ///
/// @@ -13854,12 +16783,23 @@ pub struct SkillDiscoveryPathList { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SkillList { - /// Available skills - pub skills: Vec, +pub struct UIElicitationStringOneOfField { + /// Default value selected when the form is first shown. + #[serde(skip_serializing_if = "Option::is_none")] + pub default: Option, + /// Help text describing the field. + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + /// Selectable options, each with a value and a display label. + pub one_of: Vec, + /// Human-readable label for the field. + #[serde(skip_serializing_if = "Option::is_none")] + pub title: Option, + /// Type discriminator. Always "string". + pub r#type: UIElicitationStringOneOfFieldType, } -/// Skill names to mark as disabled in global configuration, replacing any previous list. +/// Transient question to answer without adding it to conversation history. /// ///
/// @@ -13869,12 +16809,20 @@ pub struct SkillList { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SkillsConfigSetDisabledSkillsRequest { - /// List of skill names to disable - pub disabled_skills: Vec, +pub struct UIEphemeralQueryRequest { + /// In-process `AbortSignal` forwarded to the model client to cancel an in-flight request. Marked internal: excluded from the public SDK surface. Replaced by an explicit cancellation token + cancel RPC in the SDK migration. + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) abort_signal: Option, + /// In-process streaming callback `(text) => void` invoked with each token as the model emits it. Marked internal: excluded from the public SDK surface. In a process-separated SDK this is replaced by a streaming RPC that yields chunks and a final answer. + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) on_chunk: Option, + /// Question to answer from the current conversation context. + pub question: String, } -/// Name of the skill to disable for the session. +/// Transient answer generated from current conversation context. /// ///
/// @@ -13884,12 +16832,12 @@ pub struct SkillsConfigSetDisabledSkillsRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SkillsDisableRequest { - /// Name of the skill to disable - pub name: String, +pub struct UIEphemeralQueryResult { + /// Full assistant response text. + pub answer: String, } -/// Optional project paths and additional skill directories to include in discovery. +/// User response for a pending exit-plan-mode request, with approval state, selected action, auto-approve flag, and feedback. /// ///
/// @@ -13899,19 +16847,24 @@ pub struct SkillsDisableRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SkillsDiscoverRequest { - /// When true, omit skills from the host's global sources (personal, custom, plugin, and built-in), returning only project-scoped skills. For multitenant deployments. +pub struct UIExitPlanModeResponse { + /// Whether the plan was approved. + pub approved: bool, + /// Whether subsequent edits should be auto-approved without confirmation. #[serde(skip_serializing_if = "Option::is_none")] - pub exclude_host_skills: Option, - /// Optional list of project directory paths to scan for project-scoped skills + pub auto_approve_edits: Option, + /// When true, the agent is instructed to end its turn without starting implementation so the client can restore the session model and auto-submit a fresh implementation turn on it. Set only when a distinct plan configuration (a different model, reasoning effort, or context tier) actually ran the planning turn. + #[serde(skip_serializing_if = "Option::is_none")] + pub defer_implementation: Option, + /// Feedback from the user when they declined the plan or requested changes. #[serde(skip_serializing_if = "Option::is_none")] - pub project_paths: Option>, - /// Optional list of additional skill directory paths to include + pub feedback: Option, + /// The action the user selected. Defaults to 'autopilot' when autoApproveEdits is true, otherwise 'interactive'. #[serde(skip_serializing_if = "Option::is_none")] - pub skill_directories: Option>, + pub selected_action: Option, } -/// Name of the skill to enable for the session. +/// Request ID of a pending `auto_mode_switch.requested` event and the user's response. /// ///
/// @@ -13921,12 +16874,14 @@ pub struct SkillsDiscoverRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SkillsEnableRequest { - /// Name of the skill to enable - pub name: String, +pub struct UIHandlePendingAutoModeSwitchRequest { + /// The unique request ID from the auto_mode_switch.requested event + pub request_id: RequestId, + /// User's choice for auto-mode switching: yes (allow this turn), yes_always (allow + persist as setting), or no (decline). + pub response: UIAutoModeSwitchResponse, } -/// Optional project paths to enumerate. +/// Pending elicitation request ID and the user's response (accept/decline/cancel + form values). /// ///
/// @@ -13936,16 +16891,14 @@ pub struct SkillsEnableRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SkillsGetDiscoveryPathsRequest { - /// When true, omit the host's personal and custom skill directories, leaving only project directories. For multitenant deployments. - #[serde(skip_serializing_if = "Option::is_none")] - pub exclude_host_skills: Option, - /// Optional list of project directory paths. When omitted or empty, only personal and custom directories are returned. - #[serde(skip_serializing_if = "Option::is_none")] - pub project_paths: Option>, +pub struct UIHandlePendingElicitationRequest { + /// The unique request ID from the elicitation.requested event + pub request_id: RequestId, + /// The elicitation response (accept with form values, decline, or cancel) + pub result: UIElicitationResponse, } -/// Skill invocation record with name, path, content, allowed tools, and turn number. +/// Request ID of a pending `exit_plan_mode.requested` event and the user's response. /// ///
/// @@ -13955,21 +16908,14 @@ pub struct SkillsGetDiscoveryPathsRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SkillsInvokedSkill { - /// Tools that should be auto-approved when this skill is active, captured at invocation time - #[serde(skip_serializing_if = "Option::is_none")] - pub allowed_tools: Option>, - /// Full content of the skill file - pub content: String, - /// Turn number when the skill was invoked - pub invoked_at_turn: i64, - /// Unique identifier for the skill - pub name: String, - /// Path to the SKILL.md file - pub path: String, +pub struct UIHandlePendingExitPlanModeRequest { + /// The unique request ID from the exit_plan_mode.requested event + pub request_id: RequestId, + /// User response for a pending exit-plan-mode request, with approval state, selected action, auto-approve flag, and feedback. + pub response: UIExitPlanModeResponse, } -/// Skills invoked during this session, ordered by invocation time (most recent last). +/// Indicates whether the pending UI request was resolved by this call. /// ///
/// @@ -13979,12 +16925,12 @@ pub struct SkillsInvokedSkill { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SkillsGetInvokedResult { - /// Skills invoked during this session, ordered by invocation time (most recent last) - pub skills: Vec, +pub struct UIHandlePendingResult { + /// True if the request was still pending and was resolved by this call. False if the request ID was unknown, already resolved by another client (e.g. GitHub), expired, or otherwise no longer pending. + pub success: bool, } -/// Diagnostics from reloading skill definitions, with warnings and errors as separate lists. +/// Optional sampling result payload. Omit to reject/cancel the sampling request without providing a result. /// ///
/// @@ -13994,14 +16940,9 @@ pub struct SkillsGetInvokedResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SkillsLoadDiagnostics { - /// Errors emitted while loading skills (e.g. skills that failed to load entirely) - pub errors: Vec, - /// Warnings emitted while loading skills (e.g. skills that loaded but had issues) - pub warnings: Vec, -} +pub struct UIHandlePendingSamplingResponse {} -/// Slash-command invocation result that submits an agent prompt, with display prompt, optional mode, optional user-facing notice, and settings-change flag. +/// Request ID of a pending `sampling.requested` event and an optional sampling result payload (omit to reject). /// ///
/// @@ -14011,25 +16952,15 @@ pub struct SkillsLoadDiagnostics { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SlashCommandAgentPromptResult { - /// Prompt text to display to the user - pub display_prompt: String, - /// Agent prompt result discriminator - pub kind: SlashCommandAgentPromptResultKind, - /// Optional target session mode for the agent prompt - #[serde(skip_serializing_if = "Option::is_none")] - pub mode: Option, - /// Optional user-facing notice to show before the prompt is submitted - #[serde(skip_serializing_if = "Option::is_none")] - pub notice: Option, - /// Prompt to submit to the agent - pub prompt: String, - /// True when the invocation mutated user runtime settings; consumers caching settings should refresh +pub struct UIHandlePendingSamplingRequest { + /// The unique request ID from the sampling.requested event + pub request_id: RequestId, + /// Optional sampling result payload. Omit to reject/cancel the sampling request without providing a result. #[serde(skip_serializing_if = "Option::is_none")] - pub runtime_settings_changed: Option, + pub response: Option, } -/// Slash-command invocation result indicating completion, with optional message and settings-change flag. +/// The user's selected action for an exhausted session limit. /// ///
/// @@ -14039,18 +16970,18 @@ pub struct SlashCommandAgentPromptResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SlashCommandCompletedResult { - /// Completed result discriminator - pub kind: SlashCommandCompletedResultKind, - /// Optional user-facing message describing the completed command +pub struct UISessionLimitsExhaustedResponse { + /// Action selected by the user. + pub action: UISessionLimitsExhaustedResponseAction, + /// AI Credits to add to the current max when action is 'add'. #[serde(skip_serializing_if = "Option::is_none")] - pub message: Option, - /// True when the invocation mutated user runtime settings; consumers caching settings should refresh + pub additional_ai_credits: Option, + /// New absolute max AI Credits when action is 'set'. #[serde(skip_serializing_if = "Option::is_none")] - pub runtime_settings_changed: Option, + pub max_ai_credits: Option, } -/// Slash-command invocation result containing text output plus Markdown/ANSI rendering flags. +/// Request ID of a pending `session_limits_exhausted.requested` event and the user's selected limit action. /// ///
/// @@ -14060,23 +16991,14 @@ pub struct SlashCommandCompletedResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SlashCommandTextResult { - /// Text result discriminator - pub kind: SlashCommandTextResultKind, - /// Whether text contains Markdown - #[serde(skip_serializing_if = "Option::is_none")] - pub markdown: Option, - /// Whether ANSI sequences should be preserved - #[serde(skip_serializing_if = "Option::is_none")] - pub preserve_ansi: Option, - /// True when the invocation mutated user runtime settings; consumers caching settings should refresh - #[serde(skip_serializing_if = "Option::is_none")] - pub runtime_settings_changed: Option, - /// Text output for the client to render - pub text: String, +pub struct UIHandlePendingSessionLimitsExhaustedRequest { + /// The unique request ID from the session_limits_exhausted.requested event + pub request_id: RequestId, + /// The selected session-limit action. + pub response: UISessionLimitsExhaustedResponse, } -/// Selectable slash-command subcommand option with name, description, and optional group label. +/// User response for a pending user-input request, with answer text and whether it was typed freeform. /// ///
/// @@ -14086,17 +17008,14 @@ pub struct SlashCommandTextResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SlashCommandSelectSubcommandOption { - /// Human-readable description of the subcommand - pub description: String, - /// Optional group label for organizing options - #[serde(skip_serializing_if = "Option::is_none")] - pub group: Option, - /// Subcommand name to invoke - pub name: String, +pub struct UIUserInputResponse { + /// The user's answer text + pub answer: String, + /// True if the user typed a freeform response, false if they selected a presented choice. Used by telemetry to differentiate between free text input and choice selection. + pub was_freeform: bool, } -/// Slash-command invocation result asking the client to present subcommand options for a parent command. +/// Request ID of a pending `user_input.requested` event and the user's response. /// ///
/// @@ -14106,21 +17025,14 @@ pub struct SlashCommandSelectSubcommandOption { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SlashCommandSelectSubcommandResult { - /// Parent command name that requires subcommand selection - pub command: String, - /// Select subcommand result discriminator - pub kind: SlashCommandSelectSubcommandResultKind, - /// Available subcommand options for the client to present - pub options: Vec, - /// True when the invocation mutated user runtime settings; consumers caching settings should refresh - #[serde(skip_serializing_if = "Option::is_none")] - pub runtime_settings_changed: Option, - /// Human-readable title for the selection UI - pub title: String, +pub struct UIHandlePendingUserInputRequest { + /// The unique request ID from the user_input.requested event + pub request_id: RequestId, + /// User response for a pending user-input request, with answer text and whether it was typed freeform. + pub response: UIUserInputResponse, } -/// Subagent model, reasoning effort, and context tier settings +/// Register an in-process handler for `auto_mode_switch.requested` events. The caller still attaches the actual listener via the standard event-subscription mechanism; this registration solely tells the server bridge to skip its own dispatch (so a remote client doesn't race the in-process handler for the same requestId). /// ///
/// @@ -14130,19 +17042,12 @@ pub struct SlashCommandSelectSubcommandResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SubagentSettingsEntry { - /// Context tier override for matching subagents - #[serde(skip_serializing_if = "Option::is_none")] - pub context_tier: Option, - /// Reasoning effort override for matching subagents - #[serde(skip_serializing_if = "Option::is_none")] - pub effort_level: Option, - /// Model override for matching subagents - #[serde(skip_serializing_if = "Option::is_none")] - pub model: Option, +pub struct UIRegisterDirectAutoModeSwitchHandlerResult { + /// Opaque handle representing the registration. Pass this same handle to `unregisterDirectAutoModeSwitchHandler` when the in-process handler is no longer active. Multiple registrations are reference-counted; the server bridge will only dispatch auto-mode-switch requests when no handles are active. + pub handle: String, } -/// Subagent settings to apply, or null to clear the live session override +/// Opaque handle previously returned by `registerDirectAutoModeSwitchHandler` to release. /// ///
/// @@ -14152,22 +17057,12 @@ pub struct SubagentSettingsEntry { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SubagentSettings { - /// Per-agent settings keyed by subagent agent_type - #[serde(skip_serializing_if = "Option::is_none")] - pub agents: Option>, - /// Names of subagents the user has turned off; they cannot be dispatched - #[serde(skip_serializing_if = "Option::is_none")] - pub disabled_subagents: Option>, - /// Maximum number of subagents that can run concurrently; applies to usage-based billing users only - #[serde(skip_serializing_if = "Option::is_none")] - pub max_concurrency: Option, - /// Maximum subagent nesting depth; applies to usage-based billing users only - #[serde(skip_serializing_if = "Option::is_none")] - pub max_depth: Option, +pub struct UIUnregisterDirectAutoModeSwitchHandlerRequest { + /// Handle previously returned by `registerDirectAutoModeSwitchHandler` + pub handle: String, } -/// Tracked background agent task metadata, including IDs, status, timing, agent type, prompt, model, result, and latest response. +/// Indicates whether the handle was active and the registration count was decremented. /// ///
/// @@ -14177,59 +17072,30 @@ pub struct SubagentSettings { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TaskAgentInfo { - /// ISO 8601 timestamp when the current active period began - #[serde(skip_serializing_if = "Option::is_none")] - pub active_started_at: Option, - /// Accumulated active execution time in milliseconds - #[serde(skip_serializing_if = "Option::is_none")] - pub active_time_ms: Option, - /// Type of agent running this task - pub agent_type: String, - /// Whether the task is currently in the original sync wait and can be moved to background mode. False once it is already backgrounded, idle, finished, or no longer has a promotable sync waiter. - #[serde(skip_serializing_if = "Option::is_none")] - pub can_promote_to_background: Option, - /// ISO 8601 timestamp when the task finished - #[serde(skip_serializing_if = "Option::is_none")] - pub completed_at: Option, - /// Short description of the task - pub description: String, - /// Error message when the task failed - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - /// Whether task execution is synchronously awaited or managed in the background - #[serde(skip_serializing_if = "Option::is_none")] - pub execution_mode: Option, - /// Unique task identifier - pub id: String, - /// ISO 8601 timestamp when the agent entered idle state - #[serde(skip_serializing_if = "Option::is_none")] - pub idle_since: Option, - /// Most recent response text from the agent - #[serde(skip_serializing_if = "Option::is_none")] - pub latest_response: Option, - /// Requested model override for the task when specified - #[serde(skip_serializing_if = "Option::is_none")] - pub model: Option, - /// Most recent prompt delivered to the agent. Updated whenever the agent receives a follow-up message. - pub prompt: String, - /// Runtime model resolved for the task when available +pub struct UIUnregisterDirectAutoModeSwitchHandlerResult { + /// True if the handle was active and decremented the counter; false if the handle was unknown. + pub unregistered: bool, +} + +/// Configured per-agent subagent overrides +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct UpdateSubagentSettingsRequestSubagents { + /// Per-agent settings keyed by subagent agent_type #[serde(skip_serializing_if = "Option::is_none")] - pub resolved_model: Option, - /// Result text from the task when available + pub agents: Option>, + /// Names of subagents the user has turned off; they cannot be dispatched #[serde(skip_serializing_if = "Option::is_none")] - pub result: Option, - /// ISO 8601 timestamp when the task was started - pub started_at: String, - /// Current lifecycle status of the task - pub status: TaskStatus, - /// Tool call ID associated with this agent task - pub tool_call_id: String, - /// Task kind - pub r#type: TaskAgentInfoType, + pub disabled_subagents: Option>, + /// Maximum number of subagents that can run concurrently; applies to usage-based billing users only + #[serde(skip_serializing_if = "Option::is_none")] + pub max_concurrency: Option, + /// Maximum subagent nesting depth; applies to usage-based billing users only + #[serde(skip_serializing_if = "Option::is_none")] + pub max_depth: Option, } -/// Timestamped display line for task progress output or recent agent activity. +/// Subagent settings to apply to the current session /// ///
/// @@ -14239,14 +17105,12 @@ pub struct TaskAgentInfo { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TaskProgressLine { - /// Display message, e.g., "▸ bash", "✓ edit src/foo.ts" - pub message: String, - /// ISO 8601 timestamp when this event occurred - pub timestamp: String, +pub struct UpdateSubagentSettingsRequest { + /// Subagent settings to apply, or null to clear the live session override + pub subagents: Option, } -/// Progress snapshot for an agent task, with recent activity lines and optional latest intent. +/// Aggregated code change metrics /// ///
/// @@ -14256,17 +17120,18 @@ pub struct TaskProgressLine { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TaskAgentProgress { - /// The most recent intent reported by the agent - #[serde(skip_serializing_if = "Option::is_none")] - pub latest_intent: Option, - /// Recent tool execution events converted to display lines - pub recent_activity: Vec, - /// Progress kind - pub r#type: TaskAgentProgressType, +pub struct UsageMetricsCodeChanges { + /// Distinct file paths modified during the session + pub files_modified: Vec, + /// Number of distinct files modified + pub files_modified_count: i64, + /// Total lines of code added + pub lines_added: i64, + /// Total lines of code removed + pub lines_removed: i64, } -/// Background tasks currently tracked by the session. +/// Request count and cost metrics for this model /// ///
/// @@ -14276,12 +17141,14 @@ pub struct TaskAgentProgress { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TaskList { - /// Currently tracked tasks - pub tasks: Vec, +pub struct UsageMetricsModelMetricRequests { + /// User-initiated premium request cost (with multiplier applied) + pub cost: f64, + /// Number of API requests made with this model + pub count: i64, } -/// Identifier of the background task to cancel. +/// Per-model token-detail entry containing the accumulated token count for one token type. /// ///
/// @@ -14291,12 +17158,12 @@ pub struct TaskList { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TasksCancelRequest { - /// Task identifier - pub id: String, +pub struct UsageMetricsModelMetricTokenDetail { + /// Accumulated token count for this token type + pub token_count: i64, } -/// Indicates whether the background task was successfully cancelled. +/// Token usage metrics for this model /// ///
/// @@ -14306,12 +17173,21 @@ pub struct TasksCancelRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TasksCancelResult { - /// Whether the task was successfully cancelled - pub cancelled: bool, +pub struct UsageMetricsModelMetricUsage { + /// Total tokens read from prompt cache + pub cache_read_tokens: i64, + /// Total tokens written to prompt cache + pub cache_write_tokens: i64, + /// Total input tokens consumed + pub input_tokens: i64, + /// Total output tokens produced + pub output_tokens: i64, + /// Total output tokens used for reasoning + #[serde(skip_serializing_if = "Option::is_none")] + pub reasoning_tokens: Option, } -/// The first sync-waiting task that can currently be promoted to background mode. +/// Per-model usage metrics, including request counts/costs, token usage, nano-AI units, and per-token-type details. /// ///
/// @@ -14321,13 +17197,23 @@ pub struct TasksCancelResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TasksGetCurrentPromotableResult { - /// The first sync-waiting task (agent first, then shell) that can currently be promoted to background mode. Omitted if no such task exists. The returned task is guaranteed to have executionMode='sync' and canPromoteToBackground=true at the time of the call. +pub struct UsageMetricsModelMetric { + /// Latest known prompt-cache expiration for this model. A timestamp in the past indicates that the observed cache has expired. #[serde(skip_serializing_if = "Option::is_none")] - pub task: Option, + pub cache_expires_at: Option, + /// Request count and cost metrics for this model + pub requests: UsageMetricsModelMetricRequests, + /// Token count details per type + #[serde(skip_serializing_if = "Option::is_none")] + pub token_details: Option>, + /// Accumulated nano-AI units cost for this model + #[serde(skip_serializing_if = "Option::is_none")] + pub total_nano_aiu: Option, + /// Token usage metrics for this model + pub usage: UsageMetricsModelMetricUsage, } -/// Identifier of the background task to fetch progress for. +/// Session-wide token-detail entry containing the accumulated token count for one token type. /// ///
/// @@ -14337,12 +17223,12 @@ pub struct TasksGetCurrentPromotableResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TasksGetProgressRequest { - /// Task identifier (agent ID or shell ID) - pub id: String, +pub struct UsageMetricsTokenDetail { + /// Accumulated token count for this token type + pub token_count: i64, } -/// Progress information for the task, or null when no task with that ID is tracked. +/// Accumulated session usage metrics, including premium request cost, token counts, model breakdown, and code-change totals. /// ///
/// @@ -14352,12 +17238,35 @@ pub struct TasksGetProgressRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TasksGetProgressResult { - /// Progress information for the task, discriminated by type. Returns null when no task with this ID is currently tracked. - pub progress: Option, +pub struct UsageGetMetricsResult { + /// Aggregated code change metrics + pub code_changes: UsageMetricsCodeChanges, + /// Currently active model identifier + #[serde(skip_serializing_if = "Option::is_none")] + pub current_model: Option, + /// Input tokens from the most recent main-agent API call + pub last_call_input_tokens: i64, + /// Output tokens from the most recent main-agent API call + pub last_call_output_tokens: i64, + /// Per-model token and request metrics, keyed by model identifier + pub model_metrics: HashMap, + /// ISO 8601 timestamp when the session started + pub session_start_time: String, + /// Session-wide per-token-type accumulated token counts + #[serde(skip_serializing_if = "Option::is_none")] + pub token_details: Option>, + /// Total time spent in model API calls (milliseconds) + pub total_api_duration_ms: i64, + /// Session-wide accumulated nano-AI units cost + #[serde(skip_serializing_if = "Option::is_none")] + pub total_nano_aiu: Option, + /// Total user-initiated premium request cost across all models (may be fractional due to multipliers) + pub total_premium_request_cost: f64, + /// Raw count of user-initiated API requests + pub total_user_requests: i64, } -/// Tracked shell task metadata, including ID, command, status, timing, attachment/execution mode, log path, and PID. +/// Authentication-info variant for OAuth user auth, with host and login; the token remains in the runtime secret store. /// ///
/// @@ -14367,39 +17276,19 @@ pub struct TasksGetProgressResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TaskShellInfo { - /// Whether the shell runs inside a managed PTY session or as an independent background process - pub attachment_mode: TaskShellInfoAttachmentMode, - /// Whether this shell task can be promoted to background mode - #[serde(skip_serializing_if = "Option::is_none")] - pub can_promote_to_background: Option, - /// Command being executed - pub command: String, - /// ISO 8601 timestamp when the task finished - #[serde(skip_serializing_if = "Option::is_none")] - pub completed_at: Option, - /// Short description of the task - pub description: String, - /// Whether task execution is synchronously awaited or managed in the background - #[serde(skip_serializing_if = "Option::is_none")] - pub execution_mode: Option, - /// Unique task identifier - pub id: String, - /// Path to the detached shell log, when available - #[serde(skip_serializing_if = "Option::is_none")] - pub log_path: Option, - /// Process ID when available +pub struct UserAuthInfo { + /// 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. #[serde(skip_serializing_if = "Option::is_none")] - pub pid: Option, - /// ISO 8601 timestamp when the task was started - pub started_at: String, - /// Current lifecycle status of the task - pub status: TaskStatus, - /// Task kind - pub r#type: TaskShellInfoType, + pub copilot_user: Option, + /// Authentication host. + pub host: String, + /// OAuth user login. + pub login: String, + /// 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. + pub r#type: UserAuthInfoType, } -/// Progress snapshot for a shell task, with recent stdout/stderr output and optional process ID. +/// Result of a user-requested shell command. /// ///
/// @@ -14409,17 +17298,22 @@ pub struct TaskShellInfo { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TaskShellProgress { - /// Process ID when available +pub struct UserRequestedShellCommandResult { + /// Error output when the execution failed #[serde(skip_serializing_if = "Option::is_none")] - pub pid: Option, - /// Recent stdout/stderr lines from the running shell command - pub recent_output: String, - /// Progress kind - pub r#type: TaskShellProgressType, + pub error: Option, + /// Process exit code, when available + #[serde(skip_serializing_if = "Option::is_none")] + pub exit_code: Option, + /// Captured command output + pub output: String, + /// Whether the command completed successfully + pub success: bool, + /// Tool call id emitted for the shell execution + pub tool_call_id: String, } -/// The promoted task as it now exists in background mode, omitted if no promotable task was waiting. +/// A single user setting's effective value alongside its default, so consumers can render settings left at their default. /// ///
/// @@ -14429,13 +17323,16 @@ pub struct TaskShellProgress { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TasksPromoteCurrentToBackgroundResult { - /// The promoted task as it now exists in background mode, omitted if no promotable task was waiting. Atomic operation: avoids the race window of getCurrentPromotable + promoteToBackground. - #[serde(skip_serializing_if = "Option::is_none")] - pub task: Option, +pub struct UserSettingMetadata { + /// The centrally-known default for this setting (null when no default is registered). + pub default: serde_json::Value, + /// True when the user has not set an explicit value for this setting (i.e. it is left at its default). Reflects whether the user has overridden the key, not whether the effective value happens to equal the default — a key explicitly set to a value identical to the default still reports false. + pub is_default: bool, + /// The effective value: the user's value if set, otherwise the default. + pub value: serde_json::Value, } -/// Identifier of the task to promote to background mode. +/// Per-key metadata for every known user setting (settings.json overlaid with the legacy config.json, config.json wins), including settings left at their default. Excludes repository- and enterprise-managed overrides. /// ///
/// @@ -14445,12 +17342,12 @@ pub struct TasksPromoteCurrentToBackgroundResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TasksPromoteToBackgroundRequest { - /// Task identifier - pub id: String, +pub struct UserSettingsGetResult { + /// Every known user setting keyed by setting name, each with its effective value, default, and whether it is at the default. + pub settings: HashMap, } -/// Indicates whether the task was successfully promoted to background mode. +/// Partial user settings to write to settings.json. Each top-level key is written individually, replacing the existing value; a key whose value is null is removed. /// ///
/// @@ -14460,12 +17357,12 @@ pub struct TasksPromoteToBackgroundRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TasksPromoteToBackgroundResult { - /// Whether the task was successfully promoted to background mode - pub promoted: bool, +pub struct UserSettingsSetRequest { + /// Partial user settings to write, as a free-form object keyed by setting name + pub settings: serde_json::Value, } -/// Refresh metadata for any detached background shells the runtime knows about. Use after a long pause to pick up exit/output state for shells running outside the agent loop. +/// Outcome of writing user settings. /// ///
/// @@ -14475,9 +17372,12 @@ pub struct TasksPromoteToBackgroundResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TasksRefreshResult {} +pub struct UserSettingsSetResult { + /// Top-level keys whose write landed in settings.json but is shadowed by a value still present in the legacy config.json (config.json wins on read). The write does not take effect until the legacy value is removed. + pub shadowed_keys: Vec, +} -/// Identifier of the completed or cancelled task to remove from tracking. +/// Current sharing status and shareable GitHub URL for a session. /// ///
/// @@ -14487,12 +17387,18 @@ pub struct TasksRefreshResult {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TasksRemoveRequest { - /// Task identifier - pub id: String, +pub struct VisibilityGetResult { + /// Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. + #[serde(skip_serializing_if = "Option::is_none")] + pub share_url: Option, + /// Current sharing status. Absent when the session is not synced or the status could not be retrieved (e.g. the user is not authenticated). + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, + /// Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the session cannot be shared and `status`/`shareUrl` are absent. + pub synced: bool, } -/// Indicates whether the task was removed. False when the task does not exist or is still running/idle. +/// Desired sharing status for the session. /// ///
/// @@ -14502,12 +17408,12 @@ pub struct TasksRemoveRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TasksRemoveResult { - /// Whether the task was removed. Returns false if the task does not exist or is still running/idle (cancel it first). - pub removed: bool, +pub struct VisibilitySetRequest { + /// Sharing status to apply. "repo" makes the session visible to repository readers; "unshared" restricts it to the creator and collaborators. + pub status: SessionVisibilityStatus, } -/// Identifier of the target agent task, message content, and optional sender agent ID. +/// Effective sharing status and shareable GitHub URL after updating session visibility. /// ///
/// @@ -14517,17 +17423,18 @@ pub struct TasksRemoveResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TasksSendMessageRequest { - /// Agent ID of the sender, if sent on behalf of another agent +pub struct VisibilitySetResult { + /// Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. #[serde(skip_serializing_if = "Option::is_none")] - pub from_agent_id: Option, - /// Agent task identifier - pub id: String, - /// Message content to send to the agent - pub message: String, + pub share_url: Option, + /// Effective sharing status after the update. May differ from the requested status for task types that are already visible to repository readers by default. Absent when the update could not be applied (e.g. the session is not synced or the user is not authenticated). + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, + /// Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the visibility change could not be applied and `status`/`shareUrl` are absent. + pub synced: bool, } -/// Indicates whether the message was delivered, with an error message when delivery failed. +/// A single changed file and its unified diff. /// ///
/// @@ -14537,15 +17444,22 @@ pub struct TasksSendMessageRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TasksSendMessageResult { - /// Error message if delivery failed +pub struct WorkspaceDiffFileChange { + /// Type of change represented by this file diff. + pub change_type: WorkspaceDiffFileChangeType, + /// Unified diff content for the file. Empty when the diff was truncated. + pub diff: String, + /// Whether the diff content was omitted because it exceeded the per-file size limit. #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - /// Whether the message was successfully delivered or steered - pub sent: bool, + pub is_truncated: Option, + /// Original file path for renamed files. + #[serde(skip_serializing_if = "Option::is_none")] + pub old_path: Option, + /// Path to the changed file, relative to the workspace root when the file lives under it. A file changed outside the workspace root keeps a `../`-relative path, or an absolute path when no relative path exists (for example a different Windows drive). + pub path: String, } -/// Agent type, prompt, name, and optional description and model override for the new task. +/// Workspace diff result for the requested mode. /// ///
/// @@ -14555,22 +17469,24 @@ pub struct TasksSendMessageResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TasksStartAgentRequest { - /// Type of agent to start (e.g., 'explore', 'task', 'general-purpose') - pub agent_type: String, - /// Short description of the task +pub struct WorkspaceDiffResult { + /// Default branch used for a branch diff, when branch mode was requested. #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - /// Optional model override + pub base_branch: Option, + /// Changed files and their unified diffs. + pub changes: Vec, + /// Whether the requested diff fell back to unstaged changes, either because branch diff failed or session diff was unavailable. + pub is_fallback: bool, + /// Effective mode used for the returned changes. + pub mode: WorkspaceDiffMode, + /// Diff mode requested by the client. + pub requested_mode: WorkspaceDiffMode, + /// Why the session diff could not be produced, when applicable. Set only when `session` mode was requested and `isFallback` is true, so a client can tell the permanent `file-change-tracking-disabled` apart from the transient `session-busy`, which the same request answers once the session settles. Never set for `unstaged` or `branch` mode, and never `unsupported-remote-session`: a remote session's captures live on its own host, so a `session`-mode diff is rejected for one rather than answered with a controller-side fallback. #[serde(skip_serializing_if = "Option::is_none")] - pub model: Option, - /// Short name for the agent, used to generate a human-readable ID - pub name: String, - /// Task prompt for the agent - pub prompt: String, + pub unavailable_reason: Option, } -/// Identifier assigned to the newly started background agent task. +/// Compaction summary checkpoint to persist. /// ///
/// @@ -14580,12 +17496,14 @@ pub struct TasksStartAgentRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TasksStartAgentResult { - /// Generated agent ID for the background task - pub agent_id: String, +pub struct WorkspacesAddSummaryRequest { + /// Markdown summary content to persist. + pub content: String, + /// Summary title shown in checkpoint listings. + pub title: String, } -/// Wait until all in-flight background tasks (agents + shells) and any follow-up turns scheduled by their completions have settled. Returns when the runtime is fully drained or after an internal timeout (default 10 minutes; configurable via COPILOT_TASK_WAIT_TIMEOUT_SECONDS). +/// Persisted summary metadata and refreshed workspace metadata. /// ///
/// @@ -14595,9 +17513,14 @@ pub struct TasksStartAgentResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TasksWaitForPendingResult {} +pub struct WorkspacesAddSummaryResult { + #[serde(skip_serializing_if = "Option::is_none")] + pub summary: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub workspace: Option, +} -/// Feature override key/value pairs to attach to subsequent telemetry events from this session. +/// Whether the autopilot objective file exists. /// ///
/// @@ -14607,12 +17530,12 @@ pub struct TasksWaitForPendingResult {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TelemetrySetFeatureOverridesRequest { - /// Override key/value pairs to attach to subsequent telemetry events from this session. Replaces any previously-set overrides. - pub features: HashMap, +pub struct WorkspacesAutopilotObjectiveExistsResult { + /// True when the objective file exists. + pub exists: bool, } -/// Authentication-info variant for SDK-configured token authentication, carrying host and the secret token value. +/// Workspace checkpoint metadata with assigned number, human-readable title, and checkpoint filename. /// ///
/// @@ -14622,19 +17545,16 @@ pub struct TelemetrySetFeatureOverridesRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct TokenAuthInfo { - /// 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. - #[serde(skip_serializing_if = "Option::is_none")] - pub copilot_user: Option, - /// Authentication host. - pub host: String, - /// The token value itself. Treat as a secret. - pub token: String, - /// SDK-side token authentication; the host configured the token directly via the SDK. - pub r#type: TokenAuthInfoType, +pub struct WorkspacesCheckpoints { + /// Filename of the checkpoint within the workspace checkpoints directory + pub filename: String, + /// Checkpoint number assigned by the workspace manager + pub number: i64, + /// Human-readable checkpoint title + pub title: String, } -/// Built-in tool metadata with identifier, optional namespaced name, description, input-parameter schema, and usage instructions. +/// Relative path and UTF-8 content for the workspace file to create or overwrite. /// ///
/// @@ -14644,23 +17564,14 @@ pub struct TokenAuthInfo { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct Tool { - /// Description of what the tool does - pub description: String, - /// Optional instructions for how to use this tool effectively - #[serde(skip_serializing_if = "Option::is_none")] - pub instructions: Option, - /// Tool identifier (e.g., "bash", "grep", "str_replace_editor") - pub name: String, - /// Optional namespaced name for declarative filtering (e.g., "playwright/navigate" for MCP tools) - #[serde(skip_serializing_if = "Option::is_none")] - pub namespaced_name: Option, - /// JSON Schema for the tool's input parameters - #[serde(skip_serializing_if = "Option::is_none")] - pub parameters: Option>, +pub struct WorkspacesCreateFileRequest { + /// File content to write as a UTF-8 string + pub content: String, + /// Relative path within the workspace files directory + pub path: String, } -/// Built-in tools available for the requested model, with their parameters and instructions. +/// Result of deleting the autopilot objective file. /// ///
/// @@ -14670,12 +17581,12 @@ pub struct Tool { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ToolList { - /// List of available built-in tools with metadata - pub tools: Vec, +pub struct WorkspacesDeleteAutopilotObjectiveResult { + /// True when a file was deleted. + pub deleted: bool, } -/// Current lightweight tool metadata snapshot for the session. +/// Parameters for computing a workspace diff. /// ///
/// @@ -14685,12 +17596,15 @@ pub struct ToolList { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ToolsGetCurrentMetadataResult { - /// Current tool metadata, or null when tools have not been initialized yet - pub tools: Option>, +pub struct WorkspacesDiffRequest { + /// When true, ignore whitespace-only changes (git `--ignore-all-space`). Defaults to false. + #[serde(skip_serializing_if = "Option::is_none")] + pub ignore_whitespace: Option, + /// Diff mode requested by the client. + pub mode: WorkspaceDiffMode, } -/// Resolve, build, and validate the runtime tool list for this session. Subagent sessions and consumer flows that need an initialized tool set before `send` invoke this. Default base-class implementation is a no-op for sessions that don't support tool validation. +/// Optional session context used when creating a local workspace. /// ///
/// @@ -14700,9 +17614,55 @@ pub struct ToolsGetCurrentMetadataResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ToolsInitializeAndValidateResult {} +pub struct WorkspacesEnsureRequest { + /// Opaque workspace context supplied by the session host. + #[serde(skip_serializing_if = "Option::is_none")] + pub context: Option, +} -/// Optional model identifier whose tool overrides should be applied to the listing. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WorkspacesGetWorkspaceResultWorkspace { + #[serde(skip_serializing_if = "Option::is_none")] + pub branch: Option, + #[serde( + rename = "chronicle_sync_dismissed", + skip_serializing_if = "Option::is_none" + )] + pub chronicle_sync_dismissed: Option, + #[serde(rename = "client_name", skip_serializing_if = "Option::is_none")] + pub client_name: Option, + #[serde(rename = "created_at", skip_serializing_if = "Option::is_none")] + pub created_at: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub cwd: Option, + #[serde(rename = "git_root", skip_serializing_if = "Option::is_none")] + pub git_root: Option, + /// Allowed values for the `WorkspacesWorkspaceDetailsHostType` enumeration. + #[serde(rename = "host_type", skip_serializing_if = "Option::is_none")] + pub host_type: Option, + pub id: String, + #[serde(rename = "mc_last_event_id", skip_serializing_if = "Option::is_none")] + pub mc_last_event_id: Option, + #[serde(rename = "mc_session_id", skip_serializing_if = "Option::is_none")] + pub mc_session_id: Option, + #[serde(rename = "mc_task_id", skip_serializing_if = "Option::is_none")] + pub mc_task_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(rename = "remote_steerable", skip_serializing_if = "Option::is_none")] + pub remote_steerable: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub repository: Option, + #[serde(rename = "summary_count", skip_serializing_if = "Option::is_none")] + pub summary_count: Option, + #[serde(rename = "updated_at", skip_serializing_if = "Option::is_none")] + pub updated_at: Option, + #[serde(rename = "user_named", skip_serializing_if = "Option::is_none")] + pub user_named: Option, +} + +/// Current workspace metadata for the session, including its absolute filesystem path when available. /// ///
/// @@ -14712,13 +17672,15 @@ pub struct ToolsInitializeAndValidateResult {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ToolsListRequest { - /// Optional model ID — when provided, the returned tool list reflects model-specific overrides +pub struct WorkspacesGetWorkspaceResult { + /// Absolute filesystem path to the workspace directory. Omitted when the session has no workspace (e.g. remote sessions). #[serde(skip_serializing_if = "Option::is_none")] - pub model: Option, + pub path: Option, + /// Current workspace metadata, or null if not available + pub workspace: Option, } -/// Empty result after applying subagent settings +/// Workspace checkpoints in chronological order; empty when the workspace is not enabled. /// ///
/// @@ -14728,9 +17690,12 @@ pub struct ToolsListRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ToolsUpdateSubagentSettingsResult {} +pub struct WorkspacesListCheckpointsResult { + /// Workspace checkpoints in chronological order. Empty when workspace is not enabled. + pub checkpoints: Vec, +} -/// Selectable option for a UI elicitation multi-select array item, with submitted value and display label. +/// Relative paths of files stored in the session workspace files directory. /// ///
/// @@ -14740,14 +17705,12 @@ pub struct ToolsUpdateSubagentSettingsResult {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIElicitationArrayAnyOfFieldItemsAnyOf { - /// Value submitted when this option is selected. - pub r#const: String, - /// Display label for this option. - pub title: String, +pub struct WorkspacesListFilesResult { + /// Relative file paths in the workspace files directory + pub files: Vec, } -/// Schema applied to each item in the array. +/// Autopilot objective file content, or null when missing. /// ///
/// @@ -14757,12 +17720,12 @@ pub struct UIElicitationArrayAnyOfFieldItemsAnyOf { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIElicitationArrayAnyOfFieldItems { - /// Selectable options, each with a value and a display label. - pub any_of: Vec, +pub struct WorkspacesReadAutopilotObjectiveResult { + /// Autopilot objective file content, or null when missing. + pub content: Option, } -/// Multi-select string field where each option pairs a value with a display label. +/// Checkpoint number to read. /// ///
/// @@ -14772,29 +17735,12 @@ pub struct UIElicitationArrayAnyOfFieldItems { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIElicitationArrayAnyOfField { - /// Default values selected when the form is first shown. - #[serde(skip_serializing_if = "Option::is_none")] - pub default: Option>, - /// Help text describing the field. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - /// Schema applied to each item in the array. - pub items: UIElicitationArrayAnyOfFieldItems, - /// Maximum number of items the user may select. - #[serde(skip_serializing_if = "Option::is_none")] - pub max_items: Option, - /// Minimum number of items the user must select. - #[serde(skip_serializing_if = "Option::is_none")] - pub min_items: Option, - /// Human-readable label for the field. - #[serde(skip_serializing_if = "Option::is_none")] - pub title: Option, - /// Type discriminator. Always "array". - pub r#type: UIElicitationArrayAnyOfFieldType, +pub struct WorkspacesReadCheckpointRequest { + /// Checkpoint number to read + pub number: i64, } -/// Schema applied to each item in the array. +/// Checkpoint content as a UTF-8 string, or null when the checkpoint or workspace is missing. /// ///
/// @@ -14804,14 +17750,12 @@ pub struct UIElicitationArrayAnyOfField { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIElicitationArrayEnumFieldItems { - /// Allowed string values for each selected item. - pub r#enum: Vec, - /// Type discriminator. Always "string". - pub r#type: UIElicitationArrayEnumFieldItemsType, +pub struct WorkspacesReadCheckpointResult { + /// Checkpoint content as a UTF-8 string, or null when the checkpoint or workspace is missing + pub content: Option, } -/// Multi-select string field whose allowed values are defined inline. +/// Relative path of the workspace file to read. /// ///
/// @@ -14821,29 +17765,12 @@ pub struct UIElicitationArrayEnumFieldItems { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIElicitationArrayEnumField { - /// Default values selected when the form is first shown. - #[serde(skip_serializing_if = "Option::is_none")] - pub default: Option>, - /// Help text describing the field. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - /// Schema applied to each item in the array. - pub items: UIElicitationArrayEnumFieldItems, - /// Maximum number of items the user may select. - #[serde(skip_serializing_if = "Option::is_none")] - pub max_items: Option, - /// Minimum number of items the user must select. - #[serde(skip_serializing_if = "Option::is_none")] - pub min_items: Option, - /// Human-readable label for the field. - #[serde(skip_serializing_if = "Option::is_none")] - pub title: Option, - /// Type discriminator. Always "array". - pub r#type: UIElicitationArrayEnumFieldType, +pub struct WorkspacesReadFileRequest { + /// Relative path within the workspace files directory + pub path: String, } -/// JSON Schema describing the form fields to present to the user +/// Contents of the requested workspace file as a UTF-8 string. /// ///
/// @@ -14853,17 +17780,12 @@ pub struct UIElicitationArrayEnumField { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIElicitationSchema { - /// Form field definitions, keyed by field name - pub properties: HashMap, - /// List of required field names - #[serde(skip_serializing_if = "Option::is_none")] - pub required: Option>, - /// Schema type indicator (always 'object') - pub r#type: UIElicitationSchemaType, +pub struct WorkspacesReadFileResult { + /// File content as a UTF-8 string + pub content: String, } -/// Prompt message and JSON schema describing the form fields to elicit from the user. +/// Pasted content to save as a UTF-8 file in the session workspace. /// ///
/// @@ -14873,14 +17795,23 @@ pub struct UIElicitationSchema { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIElicitationRequest { - /// Message describing what information is needed from the user - pub message: String, - /// JSON Schema describing the form fields to present to the user - pub requested_schema: UIElicitationSchema, +pub struct WorkspacesSaveLargePasteRequest { + /// Pasted content to save as a UTF-8 file + pub content: String, } -/// The elicitation response (accept with form values, decline, or cancel) +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WorkspacesSaveLargePasteResultSaved { + /// Filename within the workspace files directory + pub filename: String, + /// Absolute filesystem path to the saved paste file + pub file_path: String, + /// Size of the saved file in bytes + pub size_bytes: i64, +} + +/// Descriptor for the saved paste file, or null when the workspace is unavailable. /// ///
/// @@ -14890,15 +17821,12 @@ pub struct UIElicitationRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIElicitationResponse { - /// The user's response: accept (submitted), decline (rejected), or cancel (dismissed) - pub action: UIElicitationResponseAction, - /// The form values submitted by the user (present when action is 'accept') - #[serde(skip_serializing_if = "Option::is_none")] - pub content: Option>, +pub struct WorkspacesSaveLargePasteResult { + /// Saved-paste descriptor, or null when the workspace is unavailable (e.g. CCA runtime, non-infinite sessions, remote sessions) + pub saved: Option, } -/// Indicates whether the elicitation response was accepted; false if it was already resolved by another client. +/// Rollback point for local workspace summaries. /// ///
/// @@ -14908,12 +17836,12 @@ pub struct UIElicitationResponse { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIElicitationResult { - /// Whether the response was accepted. False if the request was already resolved by another client. - pub success: bool, +pub struct WorkspacesTruncateSummariesRequest { + /// Number of newest summaries to keep. + pub keep_count: i64, } -/// Boolean field rendered as a yes/no toggle. +/// 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). /// ///
/// @@ -14923,21 +17851,39 @@ pub struct UIElicitationResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIElicitationSchemaPropertyBoolean { - /// Default value selected when the form is first shown. +pub struct WorkspaceSummary { + /// Branch checked out at session start, if any #[serde(skip_serializing_if = "Option::is_none")] - pub default: Option, - /// Help text describing the field. + pub branch: Option, + /// ISO 8601 timestamp when the workspace was created + #[serde(rename = "created_at", skip_serializing_if = "Option::is_none")] + pub created_at: Option, + /// Current working directory at session start #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - /// Human-readable label for the field. + pub cwd: Option, + /// Resolved git root for cwd, if any + #[serde(rename = "git_root", skip_serializing_if = "Option::is_none")] + pub git_root: Option, + /// Repository host type, if known + #[serde(rename = "host_type", skip_serializing_if = "Option::is_none")] + pub host_type: Option, + /// Workspace identifier (1:1 with sessionId) + pub id: String, + /// Display name for the session, if set #[serde(skip_serializing_if = "Option::is_none")] - pub title: Option, - /// Type discriminator. Always "boolean". - pub r#type: UIElicitationSchemaPropertyBooleanType, + pub name: Option, + /// Repository identifier in 'owner/repo' or 'org/project/repo' format, if any + #[serde(skip_serializing_if = "Option::is_none")] + pub repository: Option, + /// ISO 8601 timestamp when the workspace was last updated + #[serde(rename = "updated_at", skip_serializing_if = "Option::is_none")] + pub updated_at: Option, + /// Whether the display name was explicitly set by the user + #[serde(rename = "user_named", skip_serializing_if = "Option::is_none")] + pub user_named: Option, } -/// Numeric field accepting either a number or an integer. +/// Workspace metadata fields to update. /// ///
/// @@ -14947,27 +17893,16 @@ pub struct UIElicitationSchemaPropertyBoolean { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIElicitationSchemaPropertyNumber { - /// Default value populated in the input when the form is first shown. - #[serde(skip_serializing_if = "Option::is_none")] - pub default: Option, - /// Help text describing the field. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - /// Maximum allowed value (inclusive). +pub struct WorkspacesUpdateMetadataRequest { + /// Opaque workspace context supplied by the session host. #[serde(skip_serializing_if = "Option::is_none")] - pub maximum: Option, - /// Minimum allowed value (inclusive). - #[serde(skip_serializing_if = "Option::is_none")] - pub minimum: Option, - /// Human-readable label for the field. + pub context: Option, + /// Optional workspace display name override. #[serde(skip_serializing_if = "Option::is_none")] - pub title: Option, - /// Numeric type accepted by the field. - pub r#type: UIElicitationSchemaPropertyNumberType, + pub name: Option, } -/// Free-text string field with optional length and format constraints. +/// Autopilot objective file content to persist. /// ///
/// @@ -14977,30 +17912,12 @@ pub struct UIElicitationSchemaPropertyNumber { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIElicitationSchemaPropertyString { - /// Default value populated in the input when the form is first shown. - #[serde(skip_serializing_if = "Option::is_none")] - pub default: Option, - /// Help text describing the field. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - /// Optional format hint that constrains the accepted input. - #[serde(skip_serializing_if = "Option::is_none")] - pub format: Option, - /// Maximum number of characters allowed. - #[serde(skip_serializing_if = "Option::is_none")] - pub max_length: Option, - /// Minimum number of characters required. - #[serde(skip_serializing_if = "Option::is_none")] - pub min_length: Option, - /// Human-readable label for the field. - #[serde(skip_serializing_if = "Option::is_none")] - pub title: Option, - /// Type discriminator. Always "string". - pub r#type: UIElicitationSchemaPropertyStringType, +pub struct WorkspacesWriteAutopilotObjectiveRequest { + /// Autopilot objective file content. + pub content: String, } -/// Single-select string field whose allowed values are defined inline. +/// Result of writing the autopilot objective file. /// ///
/// @@ -15010,26 +17927,12 @@ pub struct UIElicitationSchemaPropertyString { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIElicitationStringEnumField { - /// Default value selected when the form is first shown. - #[serde(skip_serializing_if = "Option::is_none")] - pub default: Option, - /// Help text describing the field. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - /// Allowed string values. - pub r#enum: Vec, - /// Optional display labels for each enum value, in the same order as `enum`. - #[serde(skip_serializing_if = "Option::is_none")] - pub enum_names: Option>, - /// Human-readable label for the field. - #[serde(skip_serializing_if = "Option::is_none")] - pub title: Option, - /// Type discriminator. Always "string". - pub r#type: UIElicitationStringEnumFieldType, +pub struct WorkspacesWriteAutopilotObjectiveResult { + /// Filesystem operation performed. + pub operation: String, } -/// Selectable option for a UI elicitation single-select string field, with submitted value and display label. +/// List of Copilot models available to the resolved user, including capabilities and billing metadata. /// ///
/// @@ -15039,14 +17942,12 @@ pub struct UIElicitationStringEnumField { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIElicitationStringOneOfFieldOneOf { - /// Value submitted when this option is selected. - pub r#const: String, - /// Display label for this option. - pub title: String, +pub struct ModelsListResult { + /// List of available models with full metadata + pub models: Vec, } -/// Single-select string field where each option pairs a value with a display label. +/// The running runtime's complete catalog of well-known built-in model IDs, including supported models and additional IDs with built-in metadata. /// ///
/// @@ -15056,23 +17957,12 @@ pub struct UIElicitationStringOneOfFieldOneOf { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIElicitationStringOneOfField { - /// Default value selected when the form is first shown. - #[serde(skip_serializing_if = "Option::is_none")] - pub default: Option, - /// Help text describing the field. - #[serde(skip_serializing_if = "Option::is_none")] - pub description: Option, - /// Selectable options, each with a value and a display label. - pub one_of: Vec, - /// Human-readable label for the field. - #[serde(skip_serializing_if = "Option::is_none")] - pub title: Option, - /// Type discriminator. Always "string". - pub r#type: UIElicitationStringOneOfFieldType, +pub struct ModelsGetBuiltInCatalogResult { + /// Built-in model entries. + pub models: Vec, } -/// Transient question to answer without adding it to conversation history. +/// Built-in tools available for the requested model, with their parameters and instructions. /// ///
/// @@ -15082,20 +17972,12 @@ pub struct UIElicitationStringOneOfField { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIEphemeralQueryRequest { - /// In-process `AbortSignal` forwarded to the model client to cancel an in-flight request. Marked internal: excluded from the public SDK surface. Replaced by an explicit cancellation token + cancel RPC in the SDK migration. - #[doc(hidden)] - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) abort_signal: Option, - /// In-process streaming callback `(text) => void` invoked with each token as the model emits it. Marked internal: excluded from the public SDK surface. In a process-separated SDK this is replaced by a streaming RPC that yields chunks and a final answer. - #[doc(hidden)] - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) on_chunk: Option, - /// Question to answer from the current conversation context. - pub question: String, +pub struct ToolsListResult { + /// List of available built-in tools with metadata + pub tools: Vec, } -/// Transient answer generated from current conversation context. +/// User-configured MCP servers, keyed by server name. /// ///
/// @@ -15105,12 +17987,12 @@ pub struct UIEphemeralQueryRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIEphemeralQueryResult { - /// Full assistant response text. - pub answer: String, +pub struct McpConfigListResult { + /// All MCP servers from user config, keyed by name + pub servers: HashMap, } -/// User response for a pending exit-plan-mode request, with approval state, selected action, auto-approve flag, and feedback. +/// Plugins installed in user/global state. /// ///
/// @@ -15120,21 +18002,35 @@ pub struct UIEphemeralQueryResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIExitPlanModeResponse { - /// Whether the plan was approved. - pub approved: bool, - /// Whether subsequent edits should be auto-approved without confirmation. - #[serde(skip_serializing_if = "Option::is_none")] - pub auto_approve_edits: Option, - /// Feedback from the user when they declined the plan or requested changes. +pub struct PluginsListResult { + /// Installed plugins + pub plugins: Vec, +} + +/// Result of installing a plugin. +/// +///
+/// +/// **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 PluginsInstallResult { + /// Set when the install path is deprecated (e.g. direct repo / URL / local installs). Callers should surface this to end users. #[serde(skip_serializing_if = "Option::is_none")] - pub feedback: Option, - /// The action the user selected. Defaults to 'autopilot' when autoApproveEdits is true, otherwise 'interactive'. + pub deprecation_warning: Option, + /// The newly installed plugin's metadata + pub plugin: InstalledPluginInfo, + /// Optional post-install message provided by the plugin (e.g. setup instructions) #[serde(skip_serializing_if = "Option::is_none")] - pub selected_action: Option, + pub post_install_message: Option, + /// Number of skills discovered and installed from the plugin + pub skills_installed: i64, } -/// Request ID of a pending `auto_mode_switch.requested` event and the user's response. +/// Result of updating a single plugin. /// ///
/// @@ -15144,14 +18040,33 @@ pub struct UIExitPlanModeResponse { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIHandlePendingAutoModeSwitchRequest { - /// The unique request ID from the auto_mode_switch.requested event - pub request_id: RequestId, - /// User's choice for auto-mode switching: yes (allow this turn), yes_always (allow + persist as setting), or no (decline). - pub response: UIAutoModeSwitchResponse, +pub struct PluginsUpdateResult { + /// Version after the update, when reported by the plugin manifest + #[serde(skip_serializing_if = "Option::is_none")] + pub new_version: Option, + /// Version that was previously installed, when available + #[serde(skip_serializing_if = "Option::is_none")] + pub previous_version: Option, + /// Number of skills discovered and installed after the update + pub skills_installed: i64, +} + +/// Result of updating all installed plugins. +/// +///
+/// +/// **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 PluginsUpdateAllResult { + /// Per-plugin update results in deterministic order. + pub results: Vec, } -/// Pending elicitation request ID and the user's response (accept/decline/cancel + form values). +/// All registered marketplaces, including built-in defaults. /// ///
/// @@ -15161,14 +18076,12 @@ pub struct UIHandlePendingAutoModeSwitchRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIHandlePendingElicitationRequest { - /// The unique request ID from the elicitation.requested event - pub request_id: RequestId, - /// The elicitation response (accept with form values, decline, or cancel) - pub result: UIElicitationResponse, +pub struct PluginsMarketplacesListResult { + /// Registered marketplaces + pub marketplaces: Vec, } -/// Request ID of a pending `exit_plan_mode.requested` event and the user's response. +/// Result of registering a new marketplace. /// ///
/// @@ -15178,14 +18091,12 @@ pub struct UIHandlePendingElicitationRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIHandlePendingExitPlanModeRequest { - /// The unique request ID from the exit_plan_mode.requested event - pub request_id: RequestId, - /// User response for a pending exit-plan-mode request, with approval state, selected action, auto-approve flag, and feedback. - pub response: UIExitPlanModeResponse, +pub struct PluginsMarketplacesAddResult { + /// Final name of the marketplace as resolved from its manifest + pub name: String, } -/// Indicates whether the pending UI request was resolved by this call. +/// Outcome of the remove attempt, including dependent-plugin info when applicable. /// ///
/// @@ -15195,12 +18106,15 @@ pub struct UIHandlePendingExitPlanModeRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIHandlePendingResult { - /// True if the request was still pending and was resolved by this call. False if the request ID was unknown, already resolved by another client (e.g. GitHub), expired, or otherwise no longer pending. - pub success: bool, +pub struct PluginsMarketplacesRemoveResult { + /// Names of installed plugins that prevented removal. Populated only when `removed=false`. + #[serde(skip_serializing_if = "Option::is_none")] + pub dependent_plugins: Option>, + /// True when the marketplace was actually removed. False when removal was skipped because the marketplace has dependent plugins and `force` was not set. + pub removed: bool, } -/// Optional sampling result payload. Omit to reject/cancel the sampling request without providing a result. +/// Plugins advertised by the marketplace. /// ///
/// @@ -15210,9 +18124,12 @@ pub struct UIHandlePendingResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIHandlePendingSamplingResponse {} +pub struct PluginsMarketplacesBrowseResult { + /// Plugins advertised by the marketplace + pub plugins: Vec, +} -/// Request ID of a pending `sampling.requested` event and an optional sampling result payload (omit to reject). +/// Result of refreshing one or more marketplace catalogs. /// ///
/// @@ -15222,15 +18139,12 @@ pub struct UIHandlePendingSamplingResponse {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIHandlePendingSamplingRequest { - /// The unique request ID from the sampling.requested event - pub request_id: RequestId, - /// Optional sampling result payload. Omit to reject/cancel the sampling request without providing a result. - #[serde(skip_serializing_if = "Option::is_none")] - pub response: Option, +pub struct PluginsMarketplacesRefreshResult { + /// Per-marketplace refresh results in deterministic order. + pub results: Vec, } -/// The user's selected action for an exhausted session limit. +/// Skills discovered across global and project sources. /// ///
/// @@ -15240,18 +18154,15 @@ pub struct UIHandlePendingSamplingRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UISessionLimitsExhaustedResponse { - /// Action selected by the user. - pub action: UISessionLimitsExhaustedResponseAction, - /// AI Credits to add to the current max when action is 'add'. - #[serde(skip_serializing_if = "Option::is_none")] - pub additional_ai_credits: Option, - /// New absolute max AI Credits when action is 'set'. +pub struct SkillsDiscoverResult { + /// Messages for skills that failed to load (e.g. malformed SKILL.md). Empty when host skills are excluded so host-local paths are not disclosed to multitenant callers. #[serde(skip_serializing_if = "Option::is_none")] - pub max_ai_credits: Option, + pub errors: Option>, + /// All discovered skills across all sources + pub skills: Vec, } -/// Request ID of a pending `session_limits_exhausted.requested` event and the user's selected limit action. +/// Canonical locations where skills can be created so the runtime will recognize them. /// ///
/// @@ -15261,14 +18172,12 @@ pub struct UISessionLimitsExhaustedResponse { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIHandlePendingSessionLimitsExhaustedRequest { - /// The unique request ID from the session_limits_exhausted.requested event - pub request_id: RequestId, - /// The selected session-limit action. - pub response: UISessionLimitsExhaustedResponse, +pub struct SkillsGetDiscoveryPathsResult { + /// Canonical skill create/discovery directories, in priority order + pub paths: Vec, } -/// User response for a pending user-input request, with answer text and whether it was typed freeform. +/// Agents discovered across user, project, plugin, and remote sources. /// ///
/// @@ -15278,14 +18187,12 @@ pub struct UIHandlePendingSessionLimitsExhaustedRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIUserInputResponse { - /// The user's answer text - pub answer: String, - /// True if the user typed a freeform response, false if they selected a presented choice. Used by telemetry to differentiate between free text input and choice selection. - pub was_freeform: bool, +pub struct AgentsDiscoverResult { + /// All discovered agents across all sources + pub agents: Vec, } -/// Request ID of a pending `user_input.requested` event and the user's response. +/// Canonical locations where custom agents can be created so the runtime will recognize them. /// ///
/// @@ -15295,14 +18202,12 @@ pub struct UIUserInputResponse { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIHandlePendingUserInputRequest { - /// The unique request ID from the user_input.requested event - pub request_id: RequestId, - /// User response for a pending user-input request, with answer text and whether it was typed freeform. - pub response: UIUserInputResponse, +pub struct AgentsGetDiscoveryPathsResult { + /// Canonical agent create/discovery directories, in priority order + pub paths: Vec, } -/// Register an in-process handler for `auto_mode_switch.requested` events. The caller still attaches the actual listener via the standard event-subscription mechanism; this registration solely tells the server bridge to skip its own dispatch (so a remote client doesn't race the in-process handler for the same requestId). +/// Instruction sources discovered across user, repository, and plugin sources. /// ///
/// @@ -15312,12 +18217,12 @@ pub struct UIHandlePendingUserInputRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIRegisterDirectAutoModeSwitchHandlerResult { - /// Opaque handle representing the registration. Pass this same handle to `unregisterDirectAutoModeSwitchHandler` when the in-process handler is no longer active. Multiple registrations are reference-counted; the server bridge will only dispatch auto-mode-switch requests when no handles are active. - pub handle: String, +pub struct InstructionsDiscoverResult { + /// All discovered instruction sources + pub sources: Vec, } -/// Opaque handle previously returned by `registerDirectAutoModeSwitchHandler` to release. +/// Canonical files and directories where custom instructions can be created so the runtime will recognize them. /// ///
/// @@ -15327,12 +18232,12 @@ pub struct UIRegisterDirectAutoModeSwitchHandlerResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIUnregisterDirectAutoModeSwitchHandlerRequest { - /// Handle previously returned by `registerDirectAutoModeSwitchHandler` - pub handle: String, +pub struct InstructionsGetDiscoveryPathsResult { + /// Canonical instruction create/discovery files and directories, in priority order + pub paths: Vec, } -/// Indicates whether the handle was active and the registration count was decremented. +/// Slash commands available in the session, after applying any include/exclude filters. /// ///
/// @@ -15342,30 +18247,12 @@ pub struct UIUnregisterDirectAutoModeSwitchHandlerRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UIUnregisterDirectAutoModeSwitchHandlerResult { - /// True if the handle was active and decremented the counter; false if the handle was unknown. - pub unregistered: bool, -} - -/// Configured per-agent subagent overrides -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct UpdateSubagentSettingsRequestSubagents { - /// Per-agent settings keyed by subagent agent_type - #[serde(skip_serializing_if = "Option::is_none")] - pub agents: Option>, - /// Names of subagents the user has turned off; they cannot be dispatched - #[serde(skip_serializing_if = "Option::is_none")] - pub disabled_subagents: Option>, - /// Maximum number of subagents that can run concurrently; applies to usage-based billing users only - #[serde(skip_serializing_if = "Option::is_none")] - pub max_concurrency: Option, - /// Maximum subagent nesting depth; applies to usage-based billing users only - #[serde(skip_serializing_if = "Option::is_none")] - pub max_depth: Option, +pub struct CommandsListResult { + /// Commands available in this session + pub commands: Vec, } -/// Subagent settings to apply to the current session +/// Result of opening a session. /// ///
/// @@ -15375,12 +18262,31 @@ pub struct UpdateSubagentSettingsRequestSubagents { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UpdateSubagentSettingsRequest { - /// Subagent settings to apply, or null to clear the live session override - pub subagents: Option, +pub struct SessionsOpenResult { + /// Remote session metadata, present when status is `connected`. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + /// Handoff progress steps, present when status is `handed_off`. + #[serde(skip_serializing_if = "Option::is_none")] + pub progress: Option>, + /// Remote session ID, present when status is `connected`. + #[serde(skip_serializing_if = "Option::is_none")] + pub remote_session_id: Option, + /// In-process SessionClientApi handle for the opened session, returned to CLI callers as a transitional shortcut. Marked internal so the public SDK surface does not expose it; SDK consumers should construct per-session clients from `sessionId` instead. + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) session_api: Option, + /// Opened session ID. Omitted when status is `not_found`. + #[serde(skip_serializing_if = "Option::is_none")] + pub session_id: Option, + /// Startup prompts queued by user-level hook configs at session creation. Only populated when status is `created`; resumed sessions return an empty array. + #[serde(skip_serializing_if = "Option::is_none")] + pub startup_prompts: Option>, + /// Outcome of the open request. + pub status: SessionsOpenStatus, } -/// Aggregated code change metrics +/// Remote session connection result. /// ///
/// @@ -15390,18 +18296,14 @@ pub struct UpdateSubagentSettingsRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UsageMetricsCodeChanges { - /// Distinct file paths modified during the session - pub files_modified: Vec, - /// Number of distinct files modified - pub files_modified_count: i64, - /// Total lines of code added - pub lines_added: i64, - /// Total lines of code removed - pub lines_removed: i64, +pub struct SessionsConnectResult { + /// Metadata for a connected remote session. + pub metadata: ConnectedRemoteSessionMetadata, + /// SDK session ID for the connected remote session. + pub session_id: SessionId, } -/// Request count and cost metrics for this model +/// Sessions matching the filter, ordered most-recently-modified first. /// ///
/// @@ -15411,14 +18313,12 @@ pub struct UsageMetricsCodeChanges { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UsageMetricsModelMetricRequests { - /// User-initiated premium request cost (with multiplier applied) - pub cost: f64, - /// Number of API requests made with this model - pub count: i64, +pub struct SessionsListResult { + /// Sessions ordered most-recently-modified first. Discriminated by `isRemote`. + pub sessions: Vec, } -/// Per-model token-detail entry containing the accumulated token count for one token type. +/// ID of the local session bound to the given GitHub task, or omitted when none. /// ///
/// @@ -15428,12 +18328,13 @@ pub struct UsageMetricsModelMetricRequests { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UsageMetricsModelMetricTokenDetail { - /// Accumulated token count for this token type - pub token_count: i64, +pub struct SessionsFindByTaskIdResult { + /// Omitted when no local session is bound to that GitHub task + #[serde(skip_serializing_if = "Option::is_none")] + pub session_id: Option, } -/// Token usage metrics for this model +/// Map of sessionId -> on-disk size in bytes for each session's workspace directory. /// ///
/// @@ -15443,21 +18344,12 @@ pub struct UsageMetricsModelMetricTokenDetail { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UsageMetricsModelMetricUsage { - /// Total tokens read from prompt cache - pub cache_read_tokens: i64, - /// Total tokens written to prompt cache - pub cache_write_tokens: i64, - /// Total input tokens consumed - pub input_tokens: i64, - /// Total output tokens produced - pub output_tokens: i64, - /// Total output tokens used for reasoning - #[serde(skip_serializing_if = "Option::is_none")] - pub reasoning_tokens: Option, +pub struct SessionsGetSizesResult { + /// Map of sessionId -> on-disk size in bytes for the session's workspace directory + pub sizes: HashMap, } -/// Per-model usage metrics, including request counts/costs, token usage, nano-AI units, and per-token-type details. +/// Map of sessionId -> bytes freed by removing the session's workspace directory. /// ///
/// @@ -15467,23 +18359,12 @@ pub struct UsageMetricsModelMetricUsage { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UsageMetricsModelMetric { - /// Latest known prompt-cache expiration for this model. A timestamp in the past indicates that the observed cache has expired. - #[serde(skip_serializing_if = "Option::is_none")] - pub cache_expires_at: Option, - /// Request count and cost metrics for this model - pub requests: UsageMetricsModelMetricRequests, - /// Token count details per type - #[serde(skip_serializing_if = "Option::is_none")] - pub token_details: Option>, - /// Accumulated nano-AI units cost for this model - #[serde(skip_serializing_if = "Option::is_none")] - pub total_nano_aiu: Option, - /// Token usage metrics for this model - pub usage: UsageMetricsModelMetricUsage, +pub struct SessionsBulkDeleteResult { + /// Map of sessionId -> bytes freed by removing the session's workspace directory. Sessions whose deletion failed are omitted from this map (failures are logged on the server but not surfaced per-id; check the map for absent IDs to detect them). + pub freed_bytes: HashMap, } -/// Session-wide token-detail entry containing the accumulated token count for one token type. +/// Outcome of the prune operation: deleted IDs, dry-run candidates, skipped IDs, total bytes freed, and the dry-run flag. /// ///
/// @@ -15493,12 +18374,20 @@ pub struct UsageMetricsModelMetric { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UsageMetricsTokenDetail { - /// Accumulated token count for this token type - pub token_count: i64, +pub struct SessionsPruneOldResult { + /// Session IDs that would be deleted in dry-run mode (always empty otherwise) + pub candidates: Vec, + /// Session IDs that were deleted (always empty in dry-run mode) + pub deleted: Vec, + /// True when no deletions were actually performed + pub dry_run: bool, + /// Total bytes freed (actual when not dry-run, projected when dry-run) + pub freed_bytes: i64, + /// Session IDs that were skipped (e.g., named sessions) + pub skipped: Vec, } -/// Accumulated session usage metrics, including premium request cost, token counts, model breakdown, and code-change totals. +/// The enriched metadata records, with summary and context fields backfilled where available. Sessions confirmed empty and unnamed are omitted. /// ///
/// @@ -15508,35 +18397,12 @@ pub struct UsageMetricsTokenDetail { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UsageGetMetricsResult { - /// Aggregated code change metrics - pub code_changes: UsageMetricsCodeChanges, - /// Currently active model identifier - #[serde(skip_serializing_if = "Option::is_none")] - pub current_model: Option, - /// Input tokens from the most recent main-agent API call - pub last_call_input_tokens: i64, - /// Output tokens from the most recent main-agent API call - pub last_call_output_tokens: i64, - /// Per-model token and request metrics, keyed by model identifier - pub model_metrics: HashMap, - /// ISO 8601 timestamp when the session started - pub session_start_time: String, - /// Session-wide per-token-type accumulated token counts - #[serde(skip_serializing_if = "Option::is_none")] - pub token_details: Option>, - /// Total time spent in model API calls (milliseconds) - pub total_api_duration_ms: i64, - /// Session-wide accumulated nano-AI units cost - #[serde(skip_serializing_if = "Option::is_none")] - pub total_nano_aiu: Option, - /// Total user-initiated premium request cost across all models (may be fractional due to multipliers) - pub total_premium_request_cost: f64, - /// Raw count of user-initiated API requests - pub total_user_requests: i64, +pub struct SessionsEnrichMetadataResult { + /// Enriched records, with summary and context backfilled. Sessions confirmed empty and unnamed may be omitted. + pub sessions: Vec, } -/// Authentication-info variant for OAuth user auth, with host and login; the token remains in the runtime secret store. +/// Queued repo-level startup prompts and the total hook command count after loading. /// ///
/// @@ -15546,19 +18412,14 @@ pub struct UsageGetMetricsResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UserAuthInfo { - /// 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. - #[serde(skip_serializing_if = "Option::is_none")] - pub copilot_user: Option, - /// Authentication host. - pub host: String, - /// OAuth user login. - pub login: String, - /// 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. - pub r#type: UserAuthInfoType, +pub struct SessionsLoadDeferredRepoHooksResult { + /// Total hook command count (user + plugin + repo) loaded for the session by this call. Captured atomically with startupPrompts so callers don't need to read a separate counter. + pub hook_count: i64, + /// Repo-level startup prompts queued from repo hook configs. Empty on resume, when no repo configs were pending, or when disableAllHooks is set. + pub startup_prompts: Vec, } -/// Result of a user-requested shell command. +/// Wrapper for the singleton's current status. /// ///
/// @@ -15568,22 +18429,12 @@ pub struct UserAuthInfo { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UserRequestedShellCommandResult { - /// Error output when the execution failed - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - /// Process exit code, when available - #[serde(skip_serializing_if = "Option::is_none")] - pub exit_code: Option, - /// Captured command output - pub output: String, - /// Whether the command completed successfully - pub success: bool, - /// Tool call id emitted for the shell execution - pub tool_call_id: String, +pub struct SessionsStartRemoteControlResult { + /// State of the runtime-managed remote-control singleton. + pub status: serde_json::Value, } -/// A single user setting's effective value alongside its default, so consumers can render settings left at their default. +/// Outcome of a transferRemoteControl call. /// ///
/// @@ -15593,16 +18444,14 @@ pub struct UserRequestedShellCommandResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UserSettingMetadata { - /// The centrally-known default for this setting (null when no default is registered). - pub default: serde_json::Value, - /// True when the user has not set an explicit value for this setting (i.e. it is left at its default). Reflects whether the user has overridden the key, not whether the effective value happens to equal the default — a key explicitly set to a value identical to the default still reports false. - pub is_default: bool, - /// The effective value: the user's value if set, otherwise the default. - pub value: serde_json::Value, +pub struct SessionsTransferRemoteControlResult { + /// State of the runtime-managed remote-control singleton. + pub status: serde_json::Value, + /// Whether the rebinding actually happened. + pub transferred: bool, } -/// Per-key metadata for every known user setting (settings.json overlaid with the legacy config.json, config.json wins), including settings left at their default. Excludes repository- and enterprise-managed overrides. +/// Wrapper for the singleton's current status. /// ///
/// @@ -15612,12 +18461,12 @@ pub struct UserSettingMetadata { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UserSettingsGetResult { - /// Every known user setting keyed by setting name, each with its effective value, default, and whether it is at the default. - pub settings: HashMap, +pub struct SessionsSetRemoteControlSteeringResult { + /// State of the runtime-managed remote-control singleton. + pub status: serde_json::Value, } -/// Partial user settings to write to settings.json. Each top-level key is written individually, replacing the existing value; a key whose value is null is removed. +/// Outcome of a stopRemoteControl call. /// ///
/// @@ -15627,12 +18476,14 @@ pub struct UserSettingsGetResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UserSettingsSetRequest { - /// Partial user settings to write, as a free-form object keyed by setting name - pub settings: serde_json::Value, +pub struct SessionsStopRemoteControlResult { + /// State of the runtime-managed remote-control singleton. + pub status: serde_json::Value, + /// Whether the singleton was actually torn down by this call. + pub stopped: bool, } -/// Outcome of writing user settings. +/// Wrapper for the singleton's current status. /// ///
/// @@ -15642,12 +18493,12 @@ pub struct UserSettingsSetRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UserSettingsSetResult { - /// Top-level keys whose write landed in settings.json but is shadowed by a value still present in the legacy config.json (config.json wins on read). The write does not take effect until the legacy value is removed. - pub shadowed_keys: Vec, +pub struct SessionsGetRemoteControlStatusResult { + /// State of the runtime-managed remote-control singleton. + pub status: serde_json::Value, } -/// Current sharing status and shareable GitHub URL for a session. +/// Handle for releasing the extension tool registration. /// ///
/// @@ -15657,18 +18508,13 @@ pub struct UserSettingsSetResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct VisibilityGetResult { - /// Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. - #[serde(skip_serializing_if = "Option::is_none")] - pub share_url: Option, - /// Current sharing status. Absent when the session is not synced or the status could not be retrieved (e.g. the user is not authenticated). - #[serde(skip_serializing_if = "Option::is_none")] - pub status: Option, - /// Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the session cannot be shared and `status`/`shareUrl` are absent. - pub synced: bool, +pub(crate) struct SessionsRegisterExtensionToolsOnSessionResult { + /// In-process unsubscribe function (CLI-only optimization). Marked internal: replaced by an explicit `extensions.unregister` RPC in the SDK migration. + #[doc(hidden)] + pub(crate) unsubscribe: serde_json::Value, } -/// Desired sharing status for the session. +/// Identifies the target session. /// ///
/// @@ -15678,12 +18524,12 @@ pub struct VisibilityGetResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct VisibilitySetRequest { - /// Sharing status to apply. "repo" makes the session visible to repository readers; "unshared" restricts it to the creator and collaborators. - pub status: SessionVisibilityStatus, +pub struct SessionSuspendParams { + /// Target session identifier + pub session_id: SessionId, } -/// Effective sharing status and shareable GitHub URL after updating session visibility. +/// Result of sending a user message /// ///
/// @@ -15693,18 +18539,12 @@ pub struct VisibilitySetRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct VisibilitySetResult { - /// Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. - #[serde(skip_serializing_if = "Option::is_none")] - pub share_url: Option, - /// Effective sharing status after the update. May differ from the requested status for task types that are already visible to repository readers by default. Absent when the update could not be applied (e.g. the session is not synced or the user is not authenticated). - #[serde(skip_serializing_if = "Option::is_none")] - pub status: Option, - /// Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the visibility change could not be applied and `status`/`shareUrl` are absent. - pub synced: bool, +pub struct SessionSendResult { + /// Unique identifier assigned to the message + pub message_id: String, } -/// A single changed file and its unified diff. +/// Result of sending zero or more user messages /// ///
/// @@ -15714,22 +18554,12 @@ pub struct VisibilitySetResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct WorkspaceDiffFileChange { - /// Type of change represented by this file diff. - pub change_type: WorkspaceDiffFileChangeType, - /// Unified diff content for the file. Empty when the diff was truncated. - pub diff: String, - /// Whether the diff content was omitted because it exceeded the per-file size limit. - #[serde(skip_serializing_if = "Option::is_none")] - pub is_truncated: Option, - /// Original file path for renamed files. - #[serde(skip_serializing_if = "Option::is_none")] - pub old_path: Option, - /// Path to the changed file, relative to the workspace root. - pub path: String, +pub struct SessionSendMessagesResult { + /// Unique identifiers assigned to the messages, one per provided message in order. Empty when no messages were provided. + pub message_ids: Vec, } -/// Workspace diff result for the requested mode. +/// Result of aborting the current turn /// ///
/// @@ -15739,21 +18569,15 @@ pub struct WorkspaceDiffFileChange { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct WorkspaceDiffResult { - /// Default branch used for a branch diff, when branch mode was requested. +pub struct SessionAbortResult { + /// Error message if the abort failed #[serde(skip_serializing_if = "Option::is_none")] - pub base_branch: Option, - /// Changed files and their unified diffs. - pub changes: Vec, - /// Whether a requested branch diff fell back to unstaged changes because branch diff failed. - pub is_fallback: bool, - /// Effective mode used for the returned changes. - pub mode: WorkspaceDiffMode, - /// Diff mode requested by the client. - pub requested_mode: WorkspaceDiffMode, + pub error: Option, + /// Whether the abort completed successfully + pub success: bool, } -/// Workspace checkpoint metadata with assigned number, human-readable title, and checkpoint filename. +/// Result of interrupting the main agent turn. /// ///
/// @@ -15763,16 +18587,12 @@ pub struct WorkspaceDiffResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct WorkspacesCheckpoints { - /// Filename of the checkpoint within the workspace checkpoints directory - pub filename: String, - /// Checkpoint number assigned by the workspace manager - pub number: i64, - /// Human-readable checkpoint title - pub title: String, +pub struct SessionInterruptMainTurnResult { + /// Whether an in-flight main agent turn was interrupted. False when the main loop was not processing. + pub interrupted: bool, } -/// Relative path and UTF-8 content for the workspace file to create or overwrite. +/// Identifies the target session. /// ///
/// @@ -15782,14 +18602,12 @@ pub struct WorkspacesCheckpoints { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct WorkspacesCreateFileRequest { - /// File content to write as a UTF-8 string - pub content: String, - /// Relative path within the workspace files directory - pub path: String, +pub struct SessionCancelAllBackgroundAgentsParams { + /// Target session identifier + pub session_id: SessionId, } -/// Parameters for computing a workspace diff. +/// Identifies the target session. /// ///
/// @@ -15799,57 +18617,12 @@ pub struct WorkspacesCreateFileRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct WorkspacesDiffRequest { - /// When true, ignore whitespace-only changes (git `--ignore-all-space`). Defaults to false. - #[serde(skip_serializing_if = "Option::is_none")] - pub ignore_whitespace: Option, - /// Diff mode requested by the client. - pub mode: WorkspaceDiffMode, -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct WorkspacesGetWorkspaceResultWorkspace { - #[serde(skip_serializing_if = "Option::is_none")] - pub branch: Option, - #[serde( - rename = "chronicle_sync_dismissed", - skip_serializing_if = "Option::is_none" - )] - pub chronicle_sync_dismissed: Option, - #[serde(rename = "client_name", skip_serializing_if = "Option::is_none")] - pub client_name: Option, - #[serde(rename = "created_at", skip_serializing_if = "Option::is_none")] - pub created_at: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub cwd: Option, - #[serde(rename = "git_root", skip_serializing_if = "Option::is_none")] - pub git_root: Option, - /// Allowed values for the `WorkspacesWorkspaceDetailsHostType` enumeration. - #[serde(rename = "host_type", skip_serializing_if = "Option::is_none")] - pub host_type: Option, - pub id: String, - #[serde(rename = "mc_last_event_id", skip_serializing_if = "Option::is_none")] - pub mc_last_event_id: Option, - #[serde(rename = "mc_session_id", skip_serializing_if = "Option::is_none")] - pub mc_session_id: Option, - #[serde(rename = "mc_task_id", skip_serializing_if = "Option::is_none")] - pub mc_task_id: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - #[serde(rename = "remote_steerable", skip_serializing_if = "Option::is_none")] - pub remote_steerable: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub repository: Option, - #[serde(rename = "summary_count", skip_serializing_if = "Option::is_none")] - pub summary_count: Option, - #[serde(rename = "updated_at", skip_serializing_if = "Option::is_none")] - pub updated_at: Option, - #[serde(rename = "user_named", skip_serializing_if = "Option::is_none")] - pub user_named: Option, +pub struct SessionGitHubAuthGetStatusParams { + /// Target session identifier + pub session_id: SessionId, } -/// Current workspace metadata for the session, including its absolute filesystem path when available. +/// Authentication status and account metadata for the session. /// ///
/// @@ -15859,15 +18632,27 @@ pub struct WorkspacesGetWorkspaceResultWorkspace { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct WorkspacesGetWorkspaceResult { - /// Absolute filesystem path to the workspace directory. Omitted when the session has no workspace (e.g. remote sessions). +pub struct SessionGitHubAuthGetStatusResult { + /// Authentication type + #[serde(skip_serializing_if = "Option::is_none")] + pub auth_type: Option, + /// Copilot plan tier (e.g., individual_pro, business) #[serde(skip_serializing_if = "Option::is_none")] - pub path: Option, - /// Current workspace metadata, or null if not available - pub workspace: Option, + pub copilot_plan: Option, + /// Authentication host URL + #[serde(skip_serializing_if = "Option::is_none")] + pub host: Option, + /// Whether the session has resolved authentication + pub is_authenticated: bool, + /// Authenticated login/username, if available + #[serde(skip_serializing_if = "Option::is_none")] + pub login: Option, + /// Human-readable authentication status description + #[serde(skip_serializing_if = "Option::is_none")] + pub status_message: Option, } -/// Workspace checkpoints in chronological order; empty when the workspace is not enabled. +/// Indicates whether the credential update succeeded. /// ///
/// @@ -15877,12 +18662,15 @@ pub struct WorkspacesGetWorkspaceResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct WorkspacesListCheckpointsResult { - /// Workspace checkpoints in chronological order. Empty when workspace is not enabled. - pub checkpoints: Vec, +pub struct SessionGitHubAuthSetCredentialsResult { + /// Whether the session ended up with a populated `copilotUser` for the installed credentials. `true` when the supplied credential already carried `copilotUser` or it was successfully re-resolved server-side. `false` when the credential is installed without `copilotUser` — either re-resolution failed, or the variant cannot be re-resolved from the credential alone (only the raw-token variants `token`, `env`, and `gh-cli` can). In both `false` cases the token swap still applied, but plan/quota/billing metadata is degraded. Present whenever a credential was supplied; omitted only when no credential was supplied (no-op call). + #[serde(skip_serializing_if = "Option::is_none")] + pub copilot_user_resolved: Option, + /// Whether the operation succeeded + pub success: bool, } -/// Relative paths of files stored in the session workspace files directory. +/// Result of collecting a redacted debug bundle. /// ///
/// @@ -15892,12 +18680,19 @@ pub struct WorkspacesListCheckpointsResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct WorkspacesListFilesResult { - /// Relative file paths in the workspace files directory - pub files: Vec, +pub struct SessionDebugCollectLogsResult { + /// Files included in the redacted bundle. + pub entries: Vec, + /// Destination kind that was written. + pub kind: DebugCollectLogsResultKind, + /// Actual archive path or staging directory path written. This may differ from the requested path when no-overwrite suffixing or fallback-to-temp-directory was needed. + pub path: String, + /// Optional files or directories that could not be included. + #[serde(skip_serializing_if = "Option::is_none")] + pub skipped_entries: Option>, } -/// Checkpoint number to read. +/// Identifies the target session. /// ///
/// @@ -15907,12 +18702,12 @@ pub struct WorkspacesListFilesResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct WorkspacesReadCheckpointRequest { - /// Checkpoint number to read - pub number: i64, +pub struct SessionCanvasListParams { + /// Target session identifier + pub session_id: SessionId, } -/// Checkpoint content as a UTF-8 string, or null when the checkpoint or workspace is missing. +/// Declared canvases available in this session. /// ///
/// @@ -15922,12 +18717,12 @@ pub struct WorkspacesReadCheckpointRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct WorkspacesReadCheckpointResult { - /// Checkpoint content as a UTF-8 string, or null when the checkpoint or workspace is missing - pub content: Option, +pub struct SessionCanvasListResult { + /// Declared canvases available in this session + pub canvases: Vec, } -/// Relative path of the workspace file to read. +/// Identifies the target session. /// ///
/// @@ -15937,12 +18732,12 @@ pub struct WorkspacesReadCheckpointResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct WorkspacesReadFileRequest { - /// Relative path within the workspace files directory - pub path: String, +pub struct SessionCanvasListOpenParams { + /// Target session identifier + pub session_id: SessionId, } -/// Contents of the requested workspace file as a UTF-8 string. +/// Live open-canvas snapshot. /// ///
/// @@ -15952,12 +18747,12 @@ pub struct WorkspacesReadFileRequest { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct WorkspacesReadFileResult { - /// File content as a UTF-8 string - pub content: String, +pub struct SessionCanvasListOpenResult { + /// Currently open canvas instances + pub open_canvases: Vec, } -/// Pasted content to save as a UTF-8 file in the session workspace. +/// Open canvas instance snapshot. /// ///
/// @@ -15967,23 +18762,34 @@ pub struct WorkspacesReadFileResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct WorkspacesSaveLargePasteRequest { - /// Pasted content to save as a UTF-8 file - pub content: String, -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct WorkspacesSaveLargePasteResultSaved { - /// Filename within the workspace files directory - pub filename: String, - /// Absolute filesystem path to the saved paste file - pub file_path: String, - /// Size of the saved file in bytes - pub size_bytes: i64, +pub struct SessionCanvasOpenResult { + /// Provider-local canvas identifier + pub canvas_id: String, + /// Owning provider identifier + pub extension_id: String, + /// Owning extension display name, when available + #[serde(skip_serializing_if = "Option::is_none")] + pub extension_name: Option, + /// Host-local PNG path for the canvas icon, when supplied + #[serde(skip_serializing_if = "Option::is_none")] + pub icon: Option, + /// Input supplied when the instance was opened + #[serde(skip_serializing_if = "Option::is_none")] + pub input: Option, + /// Stable caller-supplied canvas instance identifier + pub instance_id: String, + /// Provider-supplied status text + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, + /// Rendered title + #[serde(skip_serializing_if = "Option::is_none")] + pub title: Option, + /// URL for web-rendered canvases + #[serde(skip_serializing_if = "Option::is_none")] + pub url: Option, } -/// Descriptor for the saved paste file, or null when the workspace is unavailable. +/// Canvas action invocation result. /// ///
/// @@ -15993,12 +18799,13 @@ pub struct WorkspacesSaveLargePasteResultSaved { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct WorkspacesSaveLargePasteResult { - /// Saved-paste descriptor, or null when the workspace is unavailable (e.g. CCA runtime, non-infinite sessions, remote sessions) - pub saved: Option, +pub struct SessionCanvasActionInvokeResult { + /// Provider-supplied action result + #[serde(skip_serializing_if = "Option::is_none")] + pub result: Option, } -/// 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). +/// Complete current or terminal factory run envelope. /// ///
/// @@ -16008,39 +18815,29 @@ pub struct WorkspacesSaveLargePasteResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct WorkspaceSummary { - /// Branch checked out at session start, if any +pub struct SessionFactoryRunResult { + /// Error message for an errored run. #[serde(skip_serializing_if = "Option::is_none")] - pub branch: Option, - /// ISO 8601 timestamp when the workspace was created - #[serde(rename = "created_at", skip_serializing_if = "Option::is_none")] - pub created_at: Option, - /// Current working directory at session start + pub error: Option, + /// Machine-readable failure details for an errored run. #[serde(skip_serializing_if = "Option::is_none")] - pub cwd: Option, - /// Resolved git root for cwd, if any - #[serde(rename = "git_root", skip_serializing_if = "Option::is_none")] - pub git_root: Option, - /// Repository host type, if known - #[serde(rename = "host_type", skip_serializing_if = "Option::is_none")] - pub host_type: Option, - /// Workspace identifier (1:1 with sessionId) - pub id: String, - /// Display name for the session, if set + pub failure: Option, + /// Reason for a halted or cancelled run. #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - /// Repository identifier in 'owner/repo' or 'org/project/repo' format, if any + pub reason: Option, + /// Completed factory result. #[serde(skip_serializing_if = "Option::is_none")] - pub repository: Option, - /// ISO 8601 timestamp when the workspace was last updated - #[serde(rename = "updated_at", skip_serializing_if = "Option::is_none")] - pub updated_at: Option, - /// Whether the display name was explicitly set by the user - #[serde(rename = "user_named", skip_serializing_if = "Option::is_none")] - pub user_named: Option, + pub result: Option, + /// Factory run identifier. + pub run_id: String, + /// Partial journal and progress snapshot for a halted, cancelled, or errored run. + #[serde(skip_serializing_if = "Option::is_none")] + pub snapshot: Option, + /// Current or terminal factory run status. + pub status: FactoryRunStatus, } -/// List of Copilot models available to the resolved user, including capabilities and billing metadata. +/// Resolved persisted factory identity and resumed run envelope. /// ///
/// @@ -16050,12 +18847,14 @@ pub struct WorkspaceSummary { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ModelsListResult { - /// List of available models with full metadata - pub models: Vec, +pub struct SessionFactoryResumeResult { + /// Persisted factory name resolved for the resumed run. + pub factory_name: String, + /// Terminal resumed run envelope. + pub run: FactoryRunResult, } -/// Built-in tools available for the requested model, with their parameters and instructions. +/// Complete current or terminal factory run envelope. /// ///
/// @@ -16065,12 +18864,29 @@ pub struct ModelsListResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct ToolsListResult { - /// List of available built-in tools with metadata - pub tools: Vec, +pub struct SessionFactoryGetRunResult { + /// Error message for an errored run. + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, + /// Machine-readable failure details for an errored run. + #[serde(skip_serializing_if = "Option::is_none")] + pub failure: Option, + /// Reason for a halted or cancelled run. + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, + /// Completed factory result. + #[serde(skip_serializing_if = "Option::is_none")] + pub result: Option, + /// Factory run identifier. + pub run_id: String, + /// Partial journal and progress snapshot for a halted, cancelled, or errored run. + #[serde(skip_serializing_if = "Option::is_none")] + pub snapshot: Option, + /// Current or terminal factory run status. + pub status: FactoryRunStatus, } -/// User-configured MCP servers, keyed by server name. +/// Factory runs in durable creation order. /// ///
/// @@ -16080,12 +18896,11 @@ pub struct ToolsListResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct McpConfigListResult { - /// All MCP servers from user config, keyed by name - pub servers: HashMap, +pub struct SessionFactoryListRunsResult { + pub runs: Vec, } -/// Plugins installed in user/global state. +/// Full factory run observability detail. /// ///
/// @@ -16095,12 +18910,32 @@ pub struct McpConfigListResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct PluginsListResult { - /// Installed plugins - pub plugins: Vec, +pub struct SessionFactoryGetRunDetailResult { + pub active_segment_started_at: Option, + pub agents: Vec, + pub approved: Option, + pub completed_at: Option, + pub consumed: FactoryRunConsumed, + pub created_at: i64, + pub current_phase: Option, + pub declared_limits: FactoryDeclaredLimits, + pub declared_phase_count: i64, + pub description: String, + pub factory_name: String, + pub live_agent_count: i64, + pub observed_at: i64, + pub phases: Vec, + pub progress: FactoryProgressPage, + pub revision: i64, + pub run_id: String, + pub started_at: Option, + pub status: FactoryRunStatus, + pub terminal: Option, + pub total_spawned_agent_count: i64, + pub updated_at: i64, } -/// Result of installing a plugin. +/// A bidirectional page of factory progress. /// ///
/// @@ -16110,20 +18945,17 @@ pub struct PluginsListResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct PluginsInstallResult { - /// Set when the install path is deprecated (e.g. direct repo / URL / local installs). Callers should surface this to end users. - #[serde(skip_serializing_if = "Option::is_none")] - pub deprecation_warning: Option, - /// The newly installed plugin's metadata - pub plugin: InstalledPluginInfo, - /// Optional post-install message provided by the plugin (e.g. setup instructions) - #[serde(skip_serializing_if = "Option::is_none")] - pub post_install_message: Option, - /// Number of skills discovered and installed from the plugin - pub skills_installed: i64, +pub struct SessionFactoryGetRunProgressResult { + pub has_more_newer: bool, + pub has_more_older: bool, + pub newest_seq: Option, + pub oldest_seq: Option, + pub records: Vec, + /// Run revision reflected by this page. + pub revision: i64, } -/// Result of updating a single plugin. +/// Complete current or terminal factory run envelope. /// ///
/// @@ -16133,33 +18965,29 @@ pub struct PluginsInstallResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct PluginsUpdateResult { - /// Version after the update, when reported by the plugin manifest +pub struct SessionFactoryCancelResult { + /// Error message for an errored run. #[serde(skip_serializing_if = "Option::is_none")] - pub new_version: Option, - /// Version that was previously installed, when available + pub error: Option, + /// Machine-readable failure details for an errored run. #[serde(skip_serializing_if = "Option::is_none")] - pub previous_version: Option, - /// Number of skills discovered and installed after the update - pub skills_installed: i64, -} - -/// Result of updating all installed plugins. -/// -///
-/// -/// **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 PluginsUpdateAllResult { - /// Per-plugin update results in deterministic order. - pub results: Vec, + pub failure: Option, + /// Reason for a halted or cancelled run. + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, + /// Completed factory result. + #[serde(skip_serializing_if = "Option::is_none")] + pub result: Option, + /// Factory run identifier. + pub run_id: String, + /// Partial journal and progress snapshot for a halted, cancelled, or errored run. + #[serde(skip_serializing_if = "Option::is_none")] + pub snapshot: Option, + /// Current or terminal factory run status. + pub status: FactoryRunStatus, } -/// All registered marketplaces, including built-in defaults. +/// Acknowledgement that a factory request was accepted. /// ///
/// @@ -16169,12 +18997,9 @@ pub struct PluginsUpdateAllResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct PluginsMarketplacesListResult { - /// Registered marketplaces - pub marketplaces: Vec, -} +pub struct SessionFactoryLogResult {} -/// Result of registering a new marketplace. +/// Result of one factory-scoped subagent call. /// ///
/// @@ -16184,12 +19009,13 @@ pub struct PluginsMarketplacesListResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct PluginsMarketplacesAddResult { - /// Final name of the marketplace as resolved from its manifest - pub name: String, +pub struct SessionFactoryAgentResult { + /// Agent result, omitted when the agent produced no result. + #[serde(skip_serializing_if = "Option::is_none")] + pub result: Option, } -/// Outcome of the remove attempt, including dependent-plugin info when applicable. +/// Result of reading a factory journal entry. /// ///
/// @@ -16199,15 +19025,15 @@ pub struct PluginsMarketplacesAddResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct PluginsMarketplacesRemoveResult { - /// Names of installed plugins that prevented removal. Populated only when `removed=false`. +pub struct SessionFactoryJournalGetResult { + /// Whether the journal contained the requested key. + pub hit: bool, + /// Cached JSON result. The hit field distinguishes a cached JSON null from a miss. #[serde(skip_serializing_if = "Option::is_none")] - pub dependent_plugins: Option>, - /// True when the marketplace was actually removed. False when removal was skipped because the marketplace has dependent plugins and `force` was not set. - pub removed: bool, + pub result_json: Option, } -/// Plugins advertised by the marketplace. +/// Acknowledgement that a factory request was accepted. /// ///
/// @@ -16217,12 +19043,9 @@ pub struct PluginsMarketplacesRemoveResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct PluginsMarketplacesBrowseResult { - /// Plugins advertised by the marketplace - pub plugins: Vec, -} +pub struct SessionFactoryJournalPutResult {} -/// Result of refreshing one or more marketplace catalogs. +/// Identifies the target session. /// ///
/// @@ -16232,12 +19055,12 @@ pub struct PluginsMarketplacesBrowseResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct PluginsMarketplacesRefreshResult { - /// Per-marketplace refresh results in deterministic order. - pub results: Vec, +pub struct SessionModelGetCurrentParams { + /// Target session identifier + pub session_id: SessionId, } -/// Skills discovered across global and project sources. +/// The currently selected model, reasoning effort, and context tier for the session. The context tier reflects `Session.getContextTier()`, restored from the session journal on resume. /// ///
/// @@ -16247,15 +19070,19 @@ pub struct PluginsMarketplacesRefreshResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SkillsDiscoverResult { - /// Messages for skills that failed to load (e.g. malformed SKILL.md). Empty when host skills are excluded so host-local paths are not disclosed to multitenant callers. +pub struct SessionModelGetCurrentResult { + /// Context tier for models that support multiple context-window sizes. #[serde(skip_serializing_if = "Option::is_none")] - pub errors: Option>, - /// All discovered skills across all sources - pub skills: Vec, + pub context_tier: Option, + /// Currently active model identifier + #[serde(skip_serializing_if = "Option::is_none")] + pub model_id: Option, + /// Reasoning effort level currently applied to the active model, when one is set. Reads `Session.getReasoningEffort()` synchronously after `getSelectedModel()` resolves so the two values are reported as a snapshot. + #[serde(skip_serializing_if = "Option::is_none")] + pub reasoning_effort: Option, } -/// Canonical locations where skills can be created so the runtime will recognize them. +/// The model identifier active on the session after the switch. /// ///
/// @@ -16265,12 +19092,16 @@ pub struct SkillsDiscoverResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SkillsGetDiscoveryPathsResult { - /// Canonical skill create/discovery directories, in priority order - pub paths: Vec, +pub struct SessionModelSwitchToResult { + /// True when the switch was deferred (enqueued as a cancellable `/model` command) because a turn was active or another model change was already queued, rather than applied immediately. When true, the session's live model is unchanged until the queued change drains. + #[serde(skip_serializing_if = "Option::is_none")] + pub deferred: Option, + /// Currently active model identifier after the switch + #[serde(skip_serializing_if = "Option::is_none")] + pub model_id: Option, } -/// Agents discovered across user, project, plugin, and remote sources. +/// Update the session's reasoning effort without changing the selected model. Use `switchTo` instead when you also need to change the model. The runtime stores the effort on the session and applies it to subsequent turns. /// ///
/// @@ -16280,12 +19111,12 @@ pub struct SkillsGetDiscoveryPathsResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct AgentsDiscoverResult { - /// All discovered agents across all sources - pub agents: Vec, +pub struct SessionModelSetReasoningEffortResult { + /// Reasoning effort level recorded on the session after the update + pub reasoning_effort: String, } -/// Canonical locations where custom agents can be created so the runtime will recognize them. +/// The list of models available to this session. /// ///
/// @@ -16295,12 +19126,18 @@ pub struct AgentsDiscoverResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct AgentsGetDiscoveryPathsResult { - /// Canonical agent create/discovery directories, in priority order - pub paths: Vec, +pub struct SessionModelListResult { + /// Available models, ordered with the most preferred default first. Includes both Copilot (CAPI) models and any registry BYOK models; a BYOK model appears under its provider-qualified selection id (`provider/id`). + pub list: Vec, + /// Cost categories for the full CAPI catalog, including picker-disabled models that Auto may select. Metadata only; entries absent from `list` are not manually selectable. + #[serde(skip_serializing_if = "Option::is_none")] + pub model_price_categories: Option>, + /// Per-quota snapshots returned alongside the model list, keyed by quota type. + #[serde(skip_serializing_if = "Option::is_none")] + pub quota_snapshots: Option>, } -/// Instruction sources discovered across user, repository, and plugin sources. +/// Identifies the target session. /// ///
/// @@ -16310,12 +19147,12 @@ pub struct AgentsGetDiscoveryPathsResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct InstructionsDiscoverResult { - /// All discovered instruction sources - pub sources: Vec, +pub struct SessionModeGetParams { + /// Target session identifier + pub session_id: SessionId, } -/// Canonical files and directories where custom instructions can be created so the runtime will recognize them. +/// Identifies the target session. /// ///
/// @@ -16325,12 +19162,12 @@ pub struct InstructionsDiscoverResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct InstructionsGetDiscoveryPathsResult { - /// Canonical instruction create/discovery files and directories, in priority order - pub paths: Vec, +pub struct SessionNameGetParams { + /// Target session identifier + pub session_id: SessionId, } -/// Slash commands available in the session, after applying any include/exclude filters. +/// The session's friendly name, or null when not yet set. /// ///
/// @@ -16340,12 +19177,12 @@ pub struct InstructionsGetDiscoveryPathsResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct CommandsListResult { - /// Commands available in this session - pub commands: Vec, +pub struct SessionNameGetResult { + /// The session name (user-set or auto-generated), or null if not yet set + pub name: Option, } -/// Result of opening a session. +/// Indicates whether the auto-generated summary was applied as the session's name. /// ///
/// @@ -16355,31 +19192,12 @@ pub struct CommandsListResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsOpenResult { - /// Remote session metadata, present when status is `connected`. - #[serde(skip_serializing_if = "Option::is_none")] - pub metadata: Option, - /// Handoff progress steps, present when status is `handed_off`. - #[serde(skip_serializing_if = "Option::is_none")] - pub progress: Option>, - /// Remote session ID, present when status is `connected`. - #[serde(skip_serializing_if = "Option::is_none")] - pub remote_session_id: Option, - /// In-process SessionClientApi handle for the opened session, returned to CLI callers as a transitional shortcut. Marked internal so the public SDK surface does not expose it; SDK consumers should construct per-session clients from `sessionId` instead. - #[doc(hidden)] - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) session_api: Option, - /// Opened session ID. Omitted when status is `not_found`. - #[serde(skip_serializing_if = "Option::is_none")] - pub session_id: Option, - /// Startup prompts queued by user-level hook configs at session creation. Only populated when status is `created`; resumed sessions return an empty array. - #[serde(skip_serializing_if = "Option::is_none")] - pub startup_prompts: Option>, - /// Outcome of the open request. - pub status: SessionsOpenStatus, +pub struct SessionNameSetAutoResult { + /// Whether the auto-generated summary was persisted. False if the session already has a user-set name, the summary normalized to empty, or the session does not have a workspace. + pub applied: bool, } -/// Remote session connection result. +/// Identifies the target session. /// ///
/// @@ -16389,14 +19207,12 @@ pub struct SessionsOpenResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsConnectResult { - /// Metadata for a connected remote session. - pub metadata: ConnectedRemoteSessionMetadata, - /// SDK session ID for the connected remote session. +pub struct SessionPlanReadParams { + /// Target session identifier pub session_id: SessionId, } -/// Sessions matching the filter, ordered most-recently-modified first. +/// Existence, contents, and resolved path of the session plan file. /// ///
/// @@ -16406,12 +19222,16 @@ pub struct SessionsConnectResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsListResult { - /// Sessions ordered most-recently-modified first. Discriminated by `isRemote`. - pub sessions: Vec, +pub struct SessionPlanReadResult { + /// The content of the plan file, or null if it does not exist + pub content: Option, + /// Whether the plan file exists in the workspace + pub exists: bool, + /// Absolute file path of the plan file, or null if workspace is not enabled + pub path: Option, } -/// ID of the local session bound to the given GitHub task, or omitted when none. +/// Identifies the target session. /// ///
/// @@ -16421,13 +19241,12 @@ pub struct SessionsListResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsFindByTaskIdResult { - /// Omitted when no local session is bound to that GitHub task - #[serde(skip_serializing_if = "Option::is_none")] - pub session_id: Option, +pub struct SessionPlanDeleteParams { + /// Target session identifier + pub session_id: SessionId, } -/// Map of sessionId -> on-disk size in bytes for each session's workspace directory. +/// Identifies the target session. /// ///
/// @@ -16437,12 +19256,12 @@ pub struct SessionsFindByTaskIdResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsGetSizesResult { - /// Map of sessionId -> on-disk size in bytes for the session's workspace directory - pub sizes: HashMap, +pub struct SessionPlanReadSqlTodosParams { + /// Target session identifier + pub session_id: SessionId, } -/// Map of sessionId -> bytes freed by removing the session's workspace directory. +/// Todo rows read from the session SQL database. Empty when no session database is available. /// ///
/// @@ -16452,12 +19271,12 @@ pub struct SessionsGetSizesResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsBulkDeleteResult { - /// Map of sessionId -> bytes freed by removing the session's workspace directory. Sessions whose deletion failed are omitted from this map (failures are logged on the server but not surfaced per-id; check the map for absent IDs to detect them). - pub freed_bytes: HashMap, +pub struct SessionPlanReadSqlTodosResult { + /// Rows from the session SQL todos table, ordered by creation time and id. + pub rows: Vec, } -/// Outcome of the prune operation: deleted IDs, dry-run candidates, skipped IDs, total bytes freed, and the dry-run flag. +/// Identifies the target session. /// ///
/// @@ -16467,20 +19286,12 @@ pub struct SessionsBulkDeleteResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsPruneOldResult { - /// Session IDs that would be deleted in dry-run mode (always empty otherwise) - pub candidates: Vec, - /// Session IDs that were deleted (always empty in dry-run mode) - pub deleted: Vec, - /// True when no deletions were actually performed - pub dry_run: bool, - /// Total bytes freed (actual when not dry-run, projected when dry-run) - pub freed_bytes: i64, - /// Session IDs that were skipped (e.g., named sessions) - pub skipped: Vec, +pub struct SessionPlanReadSqlTodosWithDependenciesParams { + /// Target session identifier + pub session_id: SessionId, } -/// The enriched metadata records, with summary and context fields backfilled where available. Sessions confirmed empty and unnamed are omitted. +/// Todo rows + dependency edges read from the session SQL database. /// ///
/// @@ -16490,12 +19301,14 @@ pub struct SessionsPruneOldResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsEnrichMetadataResult { - /// Enriched records, with summary and context backfilled. Sessions confirmed empty and unnamed may be omitted. - pub sessions: Vec, +pub struct SessionPlanReadSqlTodosWithDependenciesResult { + /// Edges from the session SQL todo_deps table. Empty when no database, no todo_deps table, or the SELECT failed. Read independently from `rows`, so a broken todo_deps table does not affect the rows result and vice versa. + pub dependencies: Vec, + /// Rows from the session SQL todos table, ordered by creation time and id. Empty when no database, no todos table, or the SELECT failed. + pub rows: Vec, } -/// Queued repo-level startup prompts and the total hook command count after loading. +/// Identifies the target session. /// ///
/// @@ -16505,14 +19318,54 @@ pub struct SessionsEnrichMetadataResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsLoadDeferredRepoHooksResult { - /// Total hook command count (user + plugin + repo) loaded for the session by this call. Captured atomically with startupPrompts so callers don't need to read a separate counter. - pub hook_count: i64, - /// Repo-level startup prompts queued from repo hook configs. Empty on resume, when no repo configs were pending, or when disableAllHooks is set. - pub startup_prompts: Vec, +pub struct SessionWorkspacesGetWorkspaceParams { + /// Target session identifier + pub session_id: SessionId, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionWorkspacesGetWorkspaceResultWorkspace { + #[serde(skip_serializing_if = "Option::is_none")] + pub branch: Option, + #[serde( + rename = "chronicle_sync_dismissed", + skip_serializing_if = "Option::is_none" + )] + pub chronicle_sync_dismissed: Option, + #[serde(rename = "client_name", skip_serializing_if = "Option::is_none")] + pub client_name: Option, + #[serde(rename = "created_at", skip_serializing_if = "Option::is_none")] + pub created_at: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub cwd: Option, + #[serde(rename = "git_root", skip_serializing_if = "Option::is_none")] + pub git_root: Option, + /// Allowed values for the `WorkspacesWorkspaceDetailsHostType` enumeration. + #[serde(rename = "host_type", skip_serializing_if = "Option::is_none")] + pub host_type: Option, + pub id: String, + #[serde(rename = "mc_last_event_id", skip_serializing_if = "Option::is_none")] + pub mc_last_event_id: Option, + #[serde(rename = "mc_session_id", skip_serializing_if = "Option::is_none")] + pub mc_session_id: Option, + #[serde(rename = "mc_task_id", skip_serializing_if = "Option::is_none")] + pub mc_task_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(rename = "remote_steerable", skip_serializing_if = "Option::is_none")] + pub remote_steerable: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub repository: Option, + #[serde(rename = "summary_count", skip_serializing_if = "Option::is_none")] + pub summary_count: Option, + #[serde(rename = "updated_at", skip_serializing_if = "Option::is_none")] + pub updated_at: Option, + #[serde(rename = "user_named", skip_serializing_if = "Option::is_none")] + pub user_named: Option, } -/// Wrapper for the singleton's current status. +/// Current workspace metadata for the session, including its absolute filesystem path when available. /// ///
/// @@ -16522,29 +19375,57 @@ pub struct SessionsLoadDeferredRepoHooksResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsStartRemoteControlResult { - /// State of the runtime-managed remote-control singleton. - pub status: serde_json::Value, +pub struct SessionWorkspacesGetWorkspaceResult { + /// Absolute filesystem path to the workspace directory. Omitted when the session has no workspace (e.g. remote sessions). + #[serde(skip_serializing_if = "Option::is_none")] + pub path: Option, + /// Current workspace metadata, or null if not available + pub workspace: Option, } -/// Outcome of a transferRemoteControl call. -/// -///
-/// -/// **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 SessionsTransferRemoteControlResult { - /// State of the runtime-managed remote-control singleton. - pub status: serde_json::Value, - /// Whether the rebinding actually happened. - pub transferred: bool, +pub struct SessionWorkspacesUpdateMetadataResultWorkspace { + #[serde(skip_serializing_if = "Option::is_none")] + pub branch: Option, + #[serde( + rename = "chronicle_sync_dismissed", + skip_serializing_if = "Option::is_none" + )] + pub chronicle_sync_dismissed: Option, + #[serde(rename = "client_name", skip_serializing_if = "Option::is_none")] + pub client_name: Option, + #[serde(rename = "created_at", skip_serializing_if = "Option::is_none")] + pub created_at: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub cwd: Option, + #[serde(rename = "git_root", skip_serializing_if = "Option::is_none")] + pub git_root: Option, + /// Allowed values for the `WorkspacesWorkspaceDetailsHostType` enumeration. + #[serde(rename = "host_type", skip_serializing_if = "Option::is_none")] + pub host_type: Option, + pub id: String, + #[serde(rename = "mc_last_event_id", skip_serializing_if = "Option::is_none")] + pub mc_last_event_id: Option, + #[serde(rename = "mc_session_id", skip_serializing_if = "Option::is_none")] + pub mc_session_id: Option, + #[serde(rename = "mc_task_id", skip_serializing_if = "Option::is_none")] + pub mc_task_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(rename = "remote_steerable", skip_serializing_if = "Option::is_none")] + pub remote_steerable: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub repository: Option, + #[serde(rename = "summary_count", skip_serializing_if = "Option::is_none")] + pub summary_count: Option, + #[serde(rename = "updated_at", skip_serializing_if = "Option::is_none")] + pub updated_at: Option, + #[serde(rename = "user_named", skip_serializing_if = "Option::is_none")] + pub user_named: Option, } -/// Wrapper for the singleton's current status. +/// Current workspace metadata for the session, including its absolute filesystem path when available. /// ///
/// @@ -16554,29 +19435,57 @@ pub struct SessionsTransferRemoteControlResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsSetRemoteControlSteeringResult { - /// State of the runtime-managed remote-control singleton. - pub status: serde_json::Value, +pub struct SessionWorkspacesUpdateMetadataResult { + /// Absolute filesystem path to the workspace directory. Omitted when the session has no workspace (e.g. remote sessions). + #[serde(skip_serializing_if = "Option::is_none")] + pub path: Option, + /// Current workspace metadata, or null if not available + pub workspace: Option, } -/// Outcome of a stopRemoteControl call. -/// -///
-/// -/// **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 SessionsStopRemoteControlResult { - /// State of the runtime-managed remote-control singleton. - pub status: serde_json::Value, - /// Whether the singleton was actually torn down by this call. - pub stopped: bool, +pub struct SessionWorkspacesEnsureResultWorkspace { + #[serde(skip_serializing_if = "Option::is_none")] + pub branch: Option, + #[serde( + rename = "chronicle_sync_dismissed", + skip_serializing_if = "Option::is_none" + )] + pub chronicle_sync_dismissed: Option, + #[serde(rename = "client_name", skip_serializing_if = "Option::is_none")] + pub client_name: Option, + #[serde(rename = "created_at", skip_serializing_if = "Option::is_none")] + pub created_at: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub cwd: Option, + #[serde(rename = "git_root", skip_serializing_if = "Option::is_none")] + pub git_root: Option, + /// Allowed values for the `WorkspacesWorkspaceDetailsHostType` enumeration. + #[serde(rename = "host_type", skip_serializing_if = "Option::is_none")] + pub host_type: Option, + pub id: String, + #[serde(rename = "mc_last_event_id", skip_serializing_if = "Option::is_none")] + pub mc_last_event_id: Option, + #[serde(rename = "mc_session_id", skip_serializing_if = "Option::is_none")] + pub mc_session_id: Option, + #[serde(rename = "mc_task_id", skip_serializing_if = "Option::is_none")] + pub mc_task_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(rename = "remote_steerable", skip_serializing_if = "Option::is_none")] + pub remote_steerable: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub repository: Option, + #[serde(rename = "summary_count", skip_serializing_if = "Option::is_none")] + pub summary_count: Option, + #[serde(rename = "updated_at", skip_serializing_if = "Option::is_none")] + pub updated_at: Option, + #[serde(rename = "user_named", skip_serializing_if = "Option::is_none")] + pub user_named: Option, } -/// Wrapper for the singleton's current status. +/// Current workspace metadata for the session, including its absolute filesystem path when available. /// ///
/// @@ -16586,12 +19495,15 @@ pub struct SessionsStopRemoteControlResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionsGetRemoteControlStatusResult { - /// State of the runtime-managed remote-control singleton. - pub status: serde_json::Value, +pub struct SessionWorkspacesEnsureResult { + /// Absolute filesystem path to the workspace directory. Omitted when the session has no workspace (e.g. remote sessions). + #[serde(skip_serializing_if = "Option::is_none")] + pub path: Option, + /// Current workspace metadata, or null if not available + pub workspace: Option, } -/// Handle for releasing the extension tool registration. +/// Identifies the target session. /// ///
/// @@ -16601,13 +19513,12 @@ pub struct SessionsGetRemoteControlStatusResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub(crate) struct SessionsRegisterExtensionToolsOnSessionResult { - /// In-process unsubscribe function (CLI-only optimization). Marked internal: replaced by an explicit `extensions.unregister` RPC in the SDK migration. - #[doc(hidden)] - pub(crate) unsubscribe: serde_json::Value, +pub struct SessionWorkspacesListFilesParams { + /// Target session identifier + pub session_id: SessionId, } -/// Identifies the target session. +/// Relative paths of files stored in the session workspace files directory. /// ///
/// @@ -16617,12 +19528,12 @@ pub(crate) struct SessionsRegisterExtensionToolsOnSessionResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSuspendParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionWorkspacesListFilesResult { + /// Relative file paths in the workspace files directory + pub files: Vec, } -/// Result of sending a user message +/// Contents of the requested workspace file as a UTF-8 string. /// ///
/// @@ -16632,12 +19543,12 @@ pub struct SessionSuspendParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSendResult { - /// Unique identifier assigned to the message - pub message_id: String, +pub struct SessionWorkspacesReadFileResult { + /// File content as a UTF-8 string + pub content: String, } -/// Result of sending zero or more user messages +/// Identifies the target session. /// ///
/// @@ -16647,12 +19558,12 @@ pub struct SessionSendResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSendMessagesResult { - /// Unique identifiers assigned to the messages, one per provided message in order. Empty when no messages were provided. - pub message_ids: Vec, +pub struct SessionWorkspacesListCheckpointsParams { + /// Target session identifier + pub session_id: SessionId, } -/// Result of aborting the current turn +/// Workspace checkpoints in chronological order; empty when the workspace is not enabled. /// ///
/// @@ -16662,15 +19573,12 @@ pub struct SessionSendMessagesResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionAbortResult { - /// Error message if the abort failed - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - /// Whether the abort completed successfully - pub success: bool, +pub struct SessionWorkspacesListCheckpointsResult { + /// Workspace checkpoints in chronological order. Empty when workspace is not enabled. + pub checkpoints: Vec, } -/// Identifies the target session. +/// Checkpoint content as a UTF-8 string, or null when the checkpoint or workspace is missing. /// ///
/// @@ -16680,12 +19588,12 @@ pub struct SessionAbortResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionGitHubAuthGetStatusParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionWorkspacesReadCheckpointResult { + /// Checkpoint content as a UTF-8 string, or null when the checkpoint or workspace is missing + pub content: Option, } -/// Authentication status and account metadata for the session. +/// Persisted summary metadata and refreshed workspace metadata. /// ///
/// @@ -16695,45 +19603,56 @@ pub struct SessionGitHubAuthGetStatusParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionGitHubAuthGetStatusResult { - /// Authentication type - #[serde(skip_serializing_if = "Option::is_none")] - pub auth_type: Option, - /// Copilot plan tier (e.g., individual_pro, business) - #[serde(skip_serializing_if = "Option::is_none")] - pub copilot_plan: Option, - /// Authentication host URL - #[serde(skip_serializing_if = "Option::is_none")] - pub host: Option, - /// Whether the session has resolved authentication - pub is_authenticated: bool, - /// Authenticated login/username, if available +pub struct SessionWorkspacesAddSummaryResult { #[serde(skip_serializing_if = "Option::is_none")] - pub login: Option, - /// Human-readable authentication status description + pub summary: Option, #[serde(skip_serializing_if = "Option::is_none")] - pub status_message: Option, + pub workspace: Option, } -/// Indicates whether the credential update succeeded. -/// -///
-/// -/// **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 SessionGitHubAuthSetCredentialsResult { - /// Whether the session ended up with a populated `copilotUser` for the installed credentials. `true` when the supplied credential already carried `copilotUser` or it was successfully re-resolved server-side. `false` when the credential is installed without `copilotUser` — either re-resolution failed, or the variant cannot be re-resolved from the credential alone (only the raw-token variants `token`, `env`, and `gh-cli` can). In both `false` cases the token swap still applied, but plan/quota/billing metadata is degraded. Present whenever a credential was supplied; omitted only when no credential was supplied (no-op call). +pub struct SessionWorkspacesTruncateSummariesResultWorkspace { #[serde(skip_serializing_if = "Option::is_none")] - pub copilot_user_resolved: Option, - /// Whether the operation succeeded - pub success: bool, + pub branch: Option, + #[serde( + rename = "chronicle_sync_dismissed", + skip_serializing_if = "Option::is_none" + )] + pub chronicle_sync_dismissed: Option, + #[serde(rename = "client_name", skip_serializing_if = "Option::is_none")] + pub client_name: Option, + #[serde(rename = "created_at", skip_serializing_if = "Option::is_none")] + pub created_at: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub cwd: Option, + #[serde(rename = "git_root", skip_serializing_if = "Option::is_none")] + pub git_root: Option, + /// Allowed values for the `WorkspacesWorkspaceDetailsHostType` enumeration. + #[serde(rename = "host_type", skip_serializing_if = "Option::is_none")] + pub host_type: Option, + pub id: String, + #[serde(rename = "mc_last_event_id", skip_serializing_if = "Option::is_none")] + pub mc_last_event_id: Option, + #[serde(rename = "mc_session_id", skip_serializing_if = "Option::is_none")] + pub mc_session_id: Option, + #[serde(rename = "mc_task_id", skip_serializing_if = "Option::is_none")] + pub mc_task_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + #[serde(rename = "remote_steerable", skip_serializing_if = "Option::is_none")] + pub remote_steerable: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub repository: Option, + #[serde(rename = "summary_count", skip_serializing_if = "Option::is_none")] + pub summary_count: Option, + #[serde(rename = "updated_at", skip_serializing_if = "Option::is_none")] + pub updated_at: Option, + #[serde(rename = "user_named", skip_serializing_if = "Option::is_none")] + pub user_named: Option, } -/// Result of collecting a redacted debug bundle. +/// Current workspace metadata for the session, including its absolute filesystem path when available. /// ///
/// @@ -16743,16 +19662,12 @@ pub struct SessionGitHubAuthSetCredentialsResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionDebugCollectLogsResult { - /// Files included in the redacted bundle. - pub entries: Vec, - /// Destination kind that was written. - pub kind: DebugCollectLogsResultKind, - /// Actual archive path or staging directory path written. This may differ from the requested path when no-overwrite suffixing or fallback-to-temp-directory was needed. - pub path: String, - /// Optional files or directories that could not be included. +pub struct SessionWorkspacesTruncateSummariesResult { + /// Absolute filesystem path to the workspace directory. Omitted when the session has no workspace (e.g. remote sessions). #[serde(skip_serializing_if = "Option::is_none")] - pub skipped_entries: Option>, + pub path: Option, + /// Current workspace metadata, or null if not available + pub workspace: Option, } /// Identifies the target session. @@ -16765,12 +19680,12 @@ pub struct SessionDebugCollectLogsResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionCanvasListParams { +pub struct SessionWorkspacesReadAutopilotObjectiveParams { /// Target session identifier pub session_id: SessionId, } -/// Declared canvases available in this session. +/// Autopilot objective file content, or null when missing. /// ///
/// @@ -16780,12 +19695,12 @@ pub struct SessionCanvasListParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionCanvasListResult { - /// Declared canvases available in this session - pub canvases: Vec, +pub struct SessionWorkspacesReadAutopilotObjectiveResult { + /// Autopilot objective file content, or null when missing. + pub content: Option, } -/// Identifies the target session. +/// Result of writing the autopilot objective file. /// ///
/// @@ -16795,12 +19710,12 @@ pub struct SessionCanvasListResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionCanvasListOpenParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionWorkspacesWriteAutopilotObjectiveResult { + /// Filesystem operation performed. + pub operation: String, } -/// Live open-canvas snapshot. +/// Identifies the target session. /// ///
/// @@ -16810,12 +19725,12 @@ pub struct SessionCanvasListOpenParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionCanvasListOpenResult { - /// Currently open canvas instances - pub open_canvases: Vec, +pub struct SessionWorkspacesDeleteAutopilotObjectiveParams { + /// Target session identifier + pub session_id: SessionId, } -/// Open canvas instance snapshot. +/// Result of deleting the autopilot objective file. /// ///
/// @@ -16825,34 +19740,12 @@ pub struct SessionCanvasListOpenResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionCanvasOpenResult { - /// Provider-local canvas identifier - pub canvas_id: String, - /// Owning provider identifier - pub extension_id: String, - /// Owning extension display name, when available - #[serde(skip_serializing_if = "Option::is_none")] - pub extension_name: Option, - /// Host-local PNG path for the canvas icon, when supplied - #[serde(skip_serializing_if = "Option::is_none")] - pub icon: Option, - /// Input supplied when the instance was opened - #[serde(skip_serializing_if = "Option::is_none")] - pub input: Option, - /// Stable caller-supplied canvas instance identifier - pub instance_id: String, - /// Provider-supplied status text - #[serde(skip_serializing_if = "Option::is_none")] - pub status: Option, - /// Rendered title - #[serde(skip_serializing_if = "Option::is_none")] - pub title: Option, - /// URL for web-rendered canvases - #[serde(skip_serializing_if = "Option::is_none")] - pub url: Option, +pub struct SessionWorkspacesDeleteAutopilotObjectiveResult { + /// True when a file was deleted. + pub deleted: bool, } -/// Canvas action invocation result. +/// Identifies the target session. /// ///
/// @@ -16862,13 +19755,12 @@ pub struct SessionCanvasOpenResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionCanvasActionInvokeResult { - /// Provider-supplied action result - #[serde(skip_serializing_if = "Option::is_none")] - pub result: Option, +pub struct SessionWorkspacesAutopilotObjectiveExistsParams { + /// Target session identifier + pub session_id: SessionId, } -/// Complete current or terminal factory run envelope. +/// Whether the autopilot objective file exists. /// ///
/// @@ -16878,61 +19770,23 @@ pub struct SessionCanvasActionInvokeResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFactoryRunResult { - /// Error message for an errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - /// Machine-readable failure details for an errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub failure: Option, - /// Reason for a halted or cancelled run. - #[serde(skip_serializing_if = "Option::is_none")] - pub reason: Option, - /// Completed factory result. - #[serde(skip_serializing_if = "Option::is_none")] - pub result: Option, - /// Factory run identifier. - pub run_id: String, - /// Partial journal and progress snapshot for a halted, cancelled, or errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub snapshot: Option, - /// Current or terminal factory run status. - pub status: FactoryRunStatus, +pub struct SessionWorkspacesAutopilotObjectiveExistsResult { + /// True when the objective file exists. + pub exists: bool, } -/// Complete current or terminal factory run envelope. -/// -///
-/// -/// **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 SessionFactoryGetRunResult { - /// Error message for an errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - /// Machine-readable failure details for an errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub failure: Option, - /// Reason for a halted or cancelled run. - #[serde(skip_serializing_if = "Option::is_none")] - pub reason: Option, - /// Completed factory result. - #[serde(skip_serializing_if = "Option::is_none")] - pub result: Option, - /// Factory run identifier. - pub run_id: String, - /// Partial journal and progress snapshot for a halted, cancelled, or errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub snapshot: Option, - /// Current or terminal factory run status. - pub status: FactoryRunStatus, +pub struct SessionWorkspacesSaveLargePasteResultSaved { + /// Filename within the workspace files directory + pub filename: String, + /// Absolute filesystem path to the saved paste file + pub file_path: String, + /// Size of the saved file in bytes + pub size_bytes: i64, } -/// Complete current or terminal factory run envelope. +/// Descriptor for the saved paste file, or null when the workspace is unavailable. /// ///
/// @@ -16942,29 +19796,12 @@ pub struct SessionFactoryGetRunResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFactoryCancelResult { - /// Error message for an errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - /// Machine-readable failure details for an errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub failure: Option, - /// Reason for a halted or cancelled run. - #[serde(skip_serializing_if = "Option::is_none")] - pub reason: Option, - /// Completed factory result. - #[serde(skip_serializing_if = "Option::is_none")] - pub result: Option, - /// Factory run identifier. - pub run_id: String, - /// Partial journal and progress snapshot for a halted, cancelled, or errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub snapshot: Option, - /// Current or terminal factory run status. - pub status: FactoryRunStatus, +pub struct SessionWorkspacesSaveLargePasteResult { + /// Saved-paste descriptor, or null when the workspace is unavailable (e.g. CCA runtime, non-infinite sessions, remote sessions) + pub saved: Option, } -/// Acknowledgement that a factory request was accepted. +/// Workspace diff result for the requested mode. /// ///
/// @@ -16974,9 +19811,24 @@ pub struct SessionFactoryCancelResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFactoryLogResult {} +pub struct SessionWorkspacesDiffResult { + /// Default branch used for a branch diff, when branch mode was requested. + #[serde(skip_serializing_if = "Option::is_none")] + pub base_branch: Option, + /// Changed files and their unified diffs. + pub changes: Vec, + /// Whether the requested diff fell back to unstaged changes, either because branch diff failed or session diff was unavailable. + pub is_fallback: bool, + /// Effective mode used for the returned changes. + pub mode: WorkspaceDiffMode, + /// Diff mode requested by the client. + pub requested_mode: WorkspaceDiffMode, + /// Why the session diff could not be produced, when applicable. Set only when `session` mode was requested and `isFallback` is true, so a client can tell the permanent `file-change-tracking-disabled` apart from the transient `session-busy`, which the same request answers once the session settles. Never set for `unstaged` or `branch` mode, and never `unsupported-remote-session`: a remote session's captures live on its own host, so a `session`-mode diff is rejected for one rather than answered with a controller-side fallback. + #[serde(skip_serializing_if = "Option::is_none")] + pub unavailable_reason: Option, +} -/// Result of one factory-scoped subagent call. +/// Identifies the target session. /// ///
/// @@ -16986,13 +19838,12 @@ pub struct SessionFactoryLogResult {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFactoryAgentResult { - /// Agent result, omitted when the agent produced no result. - #[serde(skip_serializing_if = "Option::is_none")] - pub result: Option, +pub struct SessionCompletionsGetTriggerCharactersParams { + /// Target session identifier + pub session_id: SessionId, } -/// Result of reading a factory journal entry. +/// Characters that, when typed in the composer, should trigger a `completions.request`. Empty when the session has no host-driven completions (e.g. local sessions, or a relay host that does not advertise `completionTriggerCharacters`). /// ///
/// @@ -17002,15 +19853,12 @@ pub struct SessionFactoryAgentResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFactoryJournalGetResult { - /// Whether the journal contained the requested key. - pub hit: bool, - /// Cached JSON result. The hit field distinguishes a cached JSON null from a miss. - #[serde(skip_serializing_if = "Option::is_none")] - pub result_json: Option, +pub struct SessionCompletionsGetTriggerCharactersResult { + /// Trigger characters advertised by the host (e.g. `["@", "#"]`). Empty disables host-driven completions for the session. + pub trigger_characters: Vec, } -/// Acknowledgement that a factory request was accepted. +/// Host-driven completion items for the current composer input. Empty when the host returns no items or does not support completions. /// ///
/// @@ -17020,7 +19868,10 @@ pub struct SessionFactoryJournalGetResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFactoryJournalPutResult {} +pub struct SessionCompletionsRequestResult { + /// Completion items in host-ranked order. + pub items: Vec, +} /// Identifies the target session. /// @@ -17032,34 +19883,12 @@ pub struct SessionFactoryJournalPutResult {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionModelGetCurrentParams { +pub struct SessionInstructionsGetSourcesParams { /// Target session identifier pub session_id: SessionId, } -/// The currently selected model, reasoning effort, and context tier for the session. The context tier reflects `Session.getContextTier()`, restored from the session journal on resume. -/// -///
-/// -/// **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 SessionModelGetCurrentResult { - /// Context tier for models that support multiple context-window sizes. - #[serde(skip_serializing_if = "Option::is_none")] - pub context_tier: Option, - /// Currently active model identifier - #[serde(skip_serializing_if = "Option::is_none")] - pub model_id: Option, - /// Reasoning effort level currently applied to the active model, when one is set. Reads `Session.getReasoningEffort()` synchronously after `getSelectedModel()` resolves so the two values are reported as a snapshot. - #[serde(skip_serializing_if = "Option::is_none")] - pub reasoning_effort: Option, -} - -/// The model identifier active on the session after the switch. +/// Instruction sources loaded for the session, in merge order. /// ///
/// @@ -17069,13 +19898,12 @@ pub struct SessionModelGetCurrentResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionModelSwitchToResult { - /// Currently active model identifier after the switch - #[serde(skip_serializing_if = "Option::is_none")] - pub model_id: Option, +pub struct SessionInstructionsGetSourcesResult { + /// Instruction sources for the session + pub sources: Vec, } -/// Update the session's reasoning effort without changing the selected model. Use `switchTo` instead when you also need to change the model. The runtime stores the effort on the session and applies it to subsequent turns. +/// Indicates whether fleet mode was successfully activated. /// ///
/// @@ -17085,12 +19913,12 @@ pub struct SessionModelSwitchToResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionModelSetReasoningEffortResult { - /// Reasoning effort level recorded on the session after the update - pub reasoning_effort: String, +pub struct SessionFleetStartResult { + /// Whether fleet mode was successfully activated + pub started: bool, } -/// The list of models available to this session. +/// Agents available to the session. /// ///
/// @@ -17100,15 +19928,9 @@ pub struct SessionModelSetReasoningEffortResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionModelListResult { - /// Available models, ordered with the most preferred default first. Includes both Copilot (CAPI) models and any registry BYOK models; a BYOK model appears under its provider-qualified selection id (`provider/id`). - pub list: Vec, - /// Cost categories for the full CAPI catalog, including picker-disabled models that Auto may select. Metadata only; entries absent from `list` are not manually selectable. - #[serde(skip_serializing_if = "Option::is_none")] - pub model_price_categories: Option>, - /// Per-quota snapshots returned alongside the model list, keyed by quota type. - #[serde(skip_serializing_if = "Option::is_none")] - pub quota_snapshots: Option>, +pub struct SessionAgentListResult { + /// Available agents + pub agents: Vec, } /// Identifies the target session. @@ -17121,12 +19943,12 @@ pub struct SessionModelListResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionModeGetParams { +pub struct SessionAgentGetCurrentParams { /// Target session identifier pub session_id: SessionId, } -/// Identifies the target session. +/// The currently selected custom agent, or null when using the default agent. /// ///
/// @@ -17135,13 +19957,13 @@ pub struct SessionModeGetParams { /// ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionNameGetParams { - /// Target session identifier - pub session_id: SessionId, +#[serde(rename_all = "camelCase")] +pub struct SessionAgentGetCurrentResult { + /// Currently selected custom agent, or null if using the default agent + pub agent: AgentInfo, } -/// The session's friendly name, or null when not yet set. +/// The newly selected custom agent. /// ///
/// @@ -17151,12 +19973,12 @@ pub struct SessionNameGetParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionNameGetResult { - /// The session name (user-set or auto-generated), or null if not yet set - pub name: Option, +pub struct SessionAgentSelectResult { + /// The newly selected custom agent + pub agent: AgentInfo, } -/// Indicates whether the auto-generated summary was applied as the session's name. +/// Identifies the target session. /// ///
/// @@ -17166,9 +19988,9 @@ pub struct SessionNameGetResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionNameSetAutoResult { - /// Whether the auto-generated summary was persisted. False if the session already has a user-set name, the summary normalized to empty, or the session does not have a workspace. - pub applied: bool, +pub struct SessionAgentDeselectParams { + /// Target session identifier + pub session_id: SessionId, } /// Identifies the target session. @@ -17181,12 +20003,12 @@ pub struct SessionNameSetAutoResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPlanReadParams { +pub struct SessionAgentReloadParams { /// Target session identifier pub session_id: SessionId, } -/// Existence, contents, and resolved path of the session plan file. +/// Custom agents available to the session after reloading definitions from disk. /// ///
/// @@ -17196,16 +20018,12 @@ pub struct SessionPlanReadParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPlanReadResult { - /// The content of the plan file, or null if it does not exist - pub content: Option, - /// Whether the plan file exists in the workspace - pub exists: bool, - /// Absolute file path of the plan file, or null if workspace is not enabled - pub path: Option, +pub struct SessionAgentReloadResult { + /// Reloaded custom agents + pub agents: Vec, } -/// Identifies the target session. +/// Identifier assigned to the newly started background agent task. /// ///
/// @@ -17215,9 +20033,9 @@ pub struct SessionPlanReadResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPlanDeleteParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionTasksStartAgentResult { + /// Generated agent ID for the background task + pub agent_id: String, } /// Identifies the target session. @@ -17230,12 +20048,12 @@ pub struct SessionPlanDeleteParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPlanReadSqlTodosParams { +pub struct SessionTasksListParams { /// Target session identifier pub session_id: SessionId, } -/// Todo rows read from the session SQL database. Empty when no session database is available. +/// Background tasks currently tracked by the session. /// ///
/// @@ -17245,9 +20063,9 @@ pub struct SessionPlanReadSqlTodosParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPlanReadSqlTodosResult { - /// Rows from the session SQL todos table, ordered by creation time and id. - pub rows: Vec, +pub struct SessionTasksListResult { + /// Currently tracked tasks + pub tasks: Vec, } /// Identifies the target session. @@ -17260,12 +20078,12 @@ pub struct SessionPlanReadSqlTodosResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPlanReadSqlTodosWithDependenciesParams { +pub struct SessionTasksRefreshParams { /// Target session identifier pub session_id: SessionId, } -/// Todo rows + dependency edges read from the session SQL database. +/// Refresh metadata for any detached background shells the runtime knows about. Use after a long pause to pick up exit/output state for shells running outside the agent loop. /// ///
/// @@ -17275,12 +20093,7 @@ pub struct SessionPlanReadSqlTodosWithDependenciesParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPlanReadSqlTodosWithDependenciesResult { - /// Edges from the session SQL todo_deps table. Empty when no database, no todo_deps table, or the SELECT failed. Read independently from `rows`, so a broken todo_deps table does not affect the rows result and vice versa. - pub dependencies: Vec, - /// Rows from the session SQL todos table, ordered by creation time and id. Empty when no database, no todos table, or the SELECT failed. - pub rows: Vec, -} +pub struct SessionTasksRefreshResult {} /// Identifies the target session. /// @@ -17292,54 +20105,24 @@ pub struct SessionPlanReadSqlTodosWithDependenciesResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionWorkspacesGetWorkspaceParams { +pub struct SessionTasksWaitForPendingParams { /// Target session identifier pub session_id: SessionId, } +/// Wait until all in-flight background tasks (agents + shells) and any follow-up turns scheduled by their completions have settled. Returns when the runtime is fully drained or after an internal timeout (default 10 minutes; configurable via COPILOT_TASK_WAIT_TIMEOUT_SECONDS). +/// +///
+/// +/// **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 SessionWorkspacesGetWorkspaceResultWorkspace { - #[serde(skip_serializing_if = "Option::is_none")] - pub branch: Option, - #[serde( - rename = "chronicle_sync_dismissed", - skip_serializing_if = "Option::is_none" - )] - pub chronicle_sync_dismissed: Option, - #[serde(rename = "client_name", skip_serializing_if = "Option::is_none")] - pub client_name: Option, - #[serde(rename = "created_at", skip_serializing_if = "Option::is_none")] - pub created_at: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub cwd: Option, - #[serde(rename = "git_root", skip_serializing_if = "Option::is_none")] - pub git_root: Option, - /// Allowed values for the `WorkspacesWorkspaceDetailsHostType` enumeration. - #[serde(rename = "host_type", skip_serializing_if = "Option::is_none")] - pub host_type: Option, - pub id: String, - #[serde(rename = "mc_last_event_id", skip_serializing_if = "Option::is_none")] - pub mc_last_event_id: Option, - #[serde(rename = "mc_session_id", skip_serializing_if = "Option::is_none")] - pub mc_session_id: Option, - #[serde(rename = "mc_task_id", skip_serializing_if = "Option::is_none")] - pub mc_task_id: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - #[serde(rename = "remote_steerable", skip_serializing_if = "Option::is_none")] - pub remote_steerable: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub repository: Option, - #[serde(rename = "summary_count", skip_serializing_if = "Option::is_none")] - pub summary_count: Option, - #[serde(rename = "updated_at", skip_serializing_if = "Option::is_none")] - pub updated_at: Option, - #[serde(rename = "user_named", skip_serializing_if = "Option::is_none")] - pub user_named: Option, -} +pub struct SessionTasksWaitForPendingResult {} -/// Current workspace metadata for the session, including its absolute filesystem path when available. +/// Progress information for the task, or null when no task with that ID is tracked. /// ///
/// @@ -17349,12 +20132,9 @@ pub struct SessionWorkspacesGetWorkspaceResultWorkspace { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionWorkspacesGetWorkspaceResult { - /// Absolute filesystem path to the workspace directory. Omitted when the session has no workspace (e.g. remote sessions). - #[serde(skip_serializing_if = "Option::is_none")] - pub path: Option, - /// Current workspace metadata, or null if not available - pub workspace: Option, +pub struct SessionTasksGetProgressResult { + /// Progress information for the task, discriminated by type. Returns null when no task with this ID is currently tracked. + pub progress: Option, } /// Identifies the target session. @@ -17367,12 +20147,12 @@ pub struct SessionWorkspacesGetWorkspaceResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionWorkspacesListFilesParams { +pub struct SessionTasksGetCurrentPromotableParams { /// Target session identifier pub session_id: SessionId, } -/// Relative paths of files stored in the session workspace files directory. +/// The first sync-waiting task that can currently be promoted to background mode. /// ///
/// @@ -17382,12 +20162,13 @@ pub struct SessionWorkspacesListFilesParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionWorkspacesListFilesResult { - /// Relative file paths in the workspace files directory - pub files: Vec, +pub struct SessionTasksGetCurrentPromotableResult { + /// The first sync-waiting task (agent first, then shell) that can currently be promoted to background mode. Omitted if no such task exists. The returned task is guaranteed to have executionMode='sync' and canPromoteToBackground=true at the time of the call. + #[serde(skip_serializing_if = "Option::is_none")] + pub task: Option, } -/// Contents of the requested workspace file as a UTF-8 string. +/// Indicates whether the task was successfully promoted to background mode. /// ///
/// @@ -17397,9 +20178,9 @@ pub struct SessionWorkspacesListFilesResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionWorkspacesReadFileResult { - /// File content as a UTF-8 string - pub content: String, +pub struct SessionTasksPromoteToBackgroundResult { + /// Whether the task was successfully promoted to background mode + pub promoted: bool, } /// Identifies the target session. @@ -17412,12 +20193,12 @@ pub struct SessionWorkspacesReadFileResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionWorkspacesListCheckpointsParams { +pub struct SessionTasksPromoteCurrentToBackgroundParams { /// Target session identifier pub session_id: SessionId, } -/// Workspace checkpoints in chronological order; empty when the workspace is not enabled. +/// The promoted task as it now exists in background mode, omitted if no promotable task was waiting. /// ///
/// @@ -17427,12 +20208,13 @@ pub struct SessionWorkspacesListCheckpointsParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionWorkspacesListCheckpointsResult { - /// Workspace checkpoints in chronological order. Empty when workspace is not enabled. - pub checkpoints: Vec, +pub struct SessionTasksPromoteCurrentToBackgroundResult { + /// The promoted task as it now exists in background mode, omitted if no promotable task was waiting. Atomic operation: avoids the race window of getCurrentPromotable + promoteToBackground. + #[serde(skip_serializing_if = "Option::is_none")] + pub task: Option, } -/// Checkpoint content as a UTF-8 string, or null when the checkpoint or workspace is missing. +/// Indicates whether the background task was successfully cancelled. /// ///
/// @@ -17442,23 +20224,12 @@ pub struct SessionWorkspacesListCheckpointsResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionWorkspacesReadCheckpointResult { - /// Checkpoint content as a UTF-8 string, or null when the checkpoint or workspace is missing - pub content: Option, -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionWorkspacesSaveLargePasteResultSaved { - /// Filename within the workspace files directory - pub filename: String, - /// Absolute filesystem path to the saved paste file - pub file_path: String, - /// Size of the saved file in bytes - pub size_bytes: i64, +pub struct SessionTasksCancelResult { + /// Whether the task was successfully cancelled + pub cancelled: bool, } -/// Descriptor for the saved paste file, or null when the workspace is unavailable. +/// Indicates whether the task was removed. False when the task does not exist or is still running/idle. /// ///
/// @@ -17468,12 +20239,12 @@ pub struct SessionWorkspacesSaveLargePasteResultSaved { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionWorkspacesSaveLargePasteResult { - /// Saved-paste descriptor, or null when the workspace is unavailable (e.g. CCA runtime, non-infinite sessions, remote sessions) - pub saved: Option, +pub struct SessionTasksRemoveResult { + /// Whether the task was removed. Returns false if the task does not exist or is still running/idle (cancel it first). + pub removed: bool, } -/// Workspace diff result for the requested mode. +/// Indicates whether the message was delivered, with an error message when delivery failed. /// ///
/// @@ -17483,18 +20254,12 @@ pub struct SessionWorkspacesSaveLargePasteResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionWorkspacesDiffResult { - /// Default branch used for a branch diff, when branch mode was requested. +pub struct SessionTasksSendMessageResult { + /// Error message if delivery failed #[serde(skip_serializing_if = "Option::is_none")] - pub base_branch: Option, - /// Changed files and their unified diffs. - pub changes: Vec, - /// Whether a requested branch diff fell back to unstaged changes because branch diff failed. - pub is_fallback: bool, - /// Effective mode used for the returned changes. - pub mode: WorkspaceDiffMode, - /// Diff mode requested by the client. - pub requested_mode: WorkspaceDiffMode, + pub error: Option, + /// Whether the message was successfully delivered or steered + pub sent: bool, } /// Identifies the target session. @@ -17507,27 +20272,12 @@ pub struct SessionWorkspacesDiffResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionCompletionsGetTriggerCharactersParams { +pub struct SessionSkillsListParams { /// Target session identifier pub session_id: SessionId, } -/// Characters that, when typed in the composer, should trigger a `completions.request`. Empty when the session has no host-driven completions (e.g. local sessions, or a relay host that does not advertise `completionTriggerCharacters`). -/// -///
-/// -/// **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 SessionCompletionsGetTriggerCharactersResult { - /// Trigger characters advertised by the host (e.g. `["@", "#"]`). Empty disables host-driven completions for the session. - pub trigger_characters: Vec, -} - -/// Host-driven completion items for the current composer input. Empty when the host returns no items or does not support completions. +/// Skills available to the session, with their enabled state. /// ///
/// @@ -17537,9 +20287,9 @@ pub struct SessionCompletionsGetTriggerCharactersResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionCompletionsRequestResult { - /// Completion items in host-ranked order. - pub items: Vec, +pub struct SessionSkillsListResult { + /// Available skills + pub skills: Vec, } /// Identifies the target session. @@ -17552,12 +20302,12 @@ pub struct SessionCompletionsRequestResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionInstructionsGetSourcesParams { +pub struct SessionSkillsGetInvokedParams { /// Target session identifier pub session_id: SessionId, } -/// Instruction sources loaded for the session, in merge order. +/// Skills invoked during this session, ordered by invocation time (most recent last). /// ///
/// @@ -17567,12 +20317,12 @@ pub struct SessionInstructionsGetSourcesParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionInstructionsGetSourcesResult { - /// Instruction sources for the session - pub sources: Vec, +pub struct SessionSkillsGetInvokedResult { + /// Skills invoked during this session, ordered by invocation time (most recent last) + pub skills: Vec, } -/// Indicates whether fleet mode was successfully activated. +/// Identifies the target session. /// ///
/// @@ -17582,12 +20332,12 @@ pub struct SessionInstructionsGetSourcesResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionFleetStartResult { - /// Whether fleet mode was successfully activated - pub started: bool, +pub struct SessionSkillsReloadParams { + /// Target session identifier + pub session_id: SessionId, } -/// Identifies the target session. +/// Diagnostics from reloading skill definitions, with warnings and errors as separate lists. /// ///
/// @@ -17597,12 +20347,14 @@ pub struct SessionFleetStartResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionAgentListParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionSkillsReloadResult { + /// Errors emitted while loading skills (e.g. skills that failed to load entirely) + pub errors: Vec, + /// Warnings emitted while loading skills (e.g. skills that loaded but had issues) + pub warnings: Vec, } -/// Custom agents available to the session. +/// Identifies the target session. /// ///
/// @@ -17612,9 +20364,9 @@ pub struct SessionAgentListParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionAgentListResult { - /// Available custom agents - pub agents: Vec, +pub struct SessionSkillsEnsureLoadedParams { + /// Target session identifier + pub session_id: SessionId, } /// Identifies the target session. @@ -17627,12 +20379,12 @@ pub struct SessionAgentListResult { /// #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionAgentGetCurrentParams { +pub struct SessionMcpListParams { /// Target session identifier pub session_id: SessionId, } -/// The currently selected custom agent, or null when using the default agent. +/// MCP servers configured for the session, with their connection status and host-level state. /// ///
/// @@ -17642,12 +20394,15 @@ pub struct SessionAgentGetCurrentParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionAgentGetCurrentResult { - /// Currently selected custom agent, or null if using the default agent - pub agent: AgentInfo, +pub struct SessionMcpListResult { + /// Host-level state, omitted when no MCP host is initialized. + #[serde(skip_serializing_if = "Option::is_none")] + pub host: Option, + /// Configured MCP servers + pub servers: Vec, } -/// The newly selected custom agent. +/// Tools exposed by the connected MCP server. Throws when the server is not connected. /// ///
/// @@ -17657,9 +20412,9 @@ pub struct SessionAgentGetCurrentResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionAgentSelectResult { - /// The newly selected custom agent - pub agent: AgentInfo, +pub struct SessionMcpListToolsResult { + /// Tools exposed by the server. + pub tools: Vec, } /// Identifies the target session. @@ -17672,12 +20427,12 @@ pub struct SessionAgentSelectResult { /// #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionAgentDeselectParams { +pub struct SessionMcpReloadParams { /// Target session identifier pub session_id: SessionId, } -/// Identifies the target session. +/// MCP server startup filtering result. /// ///
/// @@ -17687,12 +20442,15 @@ pub struct SessionAgentDeselectParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionAgentReloadParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionMcpReloadWithConfigResult { + /// Non-default servers allowed by policy + #[serde(skip_serializing_if = "Option::is_none")] + pub allowed_servers: Option>, + /// Servers filtered out before startup + pub filtered_servers: Vec, } -/// Custom agents available to the session after reloading definitions from disk. +/// Outcome of an MCP sampling execution: success result, failure error, or cancellation. /// ///
/// @@ -17702,12 +20460,18 @@ pub struct SessionAgentReloadParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionAgentReloadResult { - /// Reloaded custom agents - pub agents: Vec, +pub struct SessionMcpExecuteSamplingResult { + /// 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. + pub action: McpSamplingExecutionAction, + /// Error description, present when action='failure'. + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, + /// 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. + #[serde(skip_serializing_if = "Option::is_none")] + pub result: Option, } -/// Identifier assigned to the newly started background agent task. +/// Indicates whether an in-flight sampling execution with the given requestId was found and cancelled. /// ///
/// @@ -17717,9 +20481,24 @@ pub struct SessionAgentReloadResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionTasksStartAgentResult { - /// Generated agent ID for the background task - pub agent_id: String, +pub struct SessionMcpCancelSamplingExecutionResult { + /// True if an in-flight execution with the given requestId was found and signalled to cancel. False when no such execution is in flight (already completed, never started, or cancelled by another caller). + pub cancelled: bool, +} + +/// Env-value mode recorded on the session after the update. +/// +///
+/// +/// **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 SessionMcpSetEnvValueModeResult { + /// Mode recorded on the session after the update + pub mode: McpSetEnvValueModeDetails, } /// Identifies the target session. @@ -17732,12 +20511,12 @@ pub struct SessionTasksStartAgentResult { /// #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionTasksListParams { +pub struct SessionMcpRemoveGitHubParams { /// Target session identifier pub session_id: SessionId, } -/// Background tasks currently tracked by the session. +/// Indicates whether the auto-managed `github` MCP server was removed (false when nothing to remove). /// ///
/// @@ -17747,12 +20526,12 @@ pub struct SessionTasksListParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionTasksListResult { - /// Currently tracked tasks - pub tasks: Vec, +pub struct SessionMcpRemoveGitHubResult { + /// True when the auto-managed `github` MCP server was removed; false when no removal happened (e.g. user has explicitly configured a `github` server, or the server was not registered). + pub removed: bool, } -/// Identifies the target session. +/// Result of configuring GitHub MCP. /// ///
/// @@ -17762,12 +20541,12 @@ pub struct SessionTasksListResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionTasksRefreshParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionMcpConfigureGitHubResult { + /// Whether GitHub MCP configuration changed. + pub changed: bool, } -/// Refresh metadata for any detached background shells the runtime knows about. Use after a long pause to pick up exit/output state for shells running outside the agent loop. +/// Whether the named MCP server is running. /// ///
/// @@ -17777,9 +20556,12 @@ pub struct SessionTasksRefreshParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionTasksRefreshResult {} +pub struct SessionMcpIsServerRunningResult { + /// True if the server has an active client and transport. + pub running: bool, +} -/// Identifies the target session. +/// Indicates whether the pending MCP OAuth response was accepted. /// ///
/// @@ -17789,12 +20571,12 @@ pub struct SessionTasksRefreshResult {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionTasksWaitForPendingParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionMcpOauthHandlePendingRequestResult { + /// Whether the response was accepted. False if the request was unknown, timed out, or already resolved. + pub success: bool, } -/// Wait until all in-flight background tasks (agents + shells) and any follow-up turns scheduled by their completions have settled. Returns when the runtime is fully drained or after an internal timeout (default 10 minutes; configurable via COPILOT_TASK_WAIT_TIMEOUT_SECONDS). +/// OAuth authorization URL the caller should open, or empty when cached tokens already authenticated the server. /// ///
/// @@ -17804,9 +20586,13 @@ pub struct SessionTasksWaitForPendingParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionTasksWaitForPendingResult {} +pub struct SessionMcpOauthLoginResult { + /// URL the caller should open in a browser to complete OAuth. Omitted when cached tokens were still valid and no browser interaction was needed — the server is already reconnected in that case. When present, the runtime starts the callback listener before returning and continues the flow in the background; completion is signaled via session.mcp_server_status_changed. + #[serde(skip_serializing_if = "Option::is_none")] + pub authorization_url: Option, +} -/// Progress information for the task, or null when no task with that ID is tracked. +/// Indicates whether the pending MCP OAuth response was accepted. /// ///
/// @@ -17816,12 +20602,12 @@ pub struct SessionTasksWaitForPendingResult {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionTasksGetProgressResult { - /// Progress information for the task, discriminated by type. Returns null when no task with this ID is currently tracked. - pub progress: Option, +pub struct SessionMcpOauthRespondResult { + /// Whether the response was accepted. False if the request was unknown, timed out, or already resolved. + pub success: bool, } -/// Identifies the target session. +/// Indicates whether the pending MCP headers refresh response was accepted. /// ///
/// @@ -17831,12 +20617,12 @@ pub struct SessionTasksGetProgressResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionTasksGetCurrentPromotableParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionMcpHeadersHandlePendingHeadersRefreshRequestResult { + /// Whether the response was accepted. False if the request was unknown, timed out, or already resolved. + pub success: bool, } -/// The first sync-waiting task that can currently be promoted to background mode. +/// Resource contents returned by the MCP server. /// ///
/// @@ -17846,13 +20632,12 @@ pub struct SessionTasksGetCurrentPromotableParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionTasksGetCurrentPromotableResult { - /// The first sync-waiting task (agent first, then shell) that can currently be promoted to background mode. Omitted if no such task exists. The returned task is guaranteed to have executionMode='sync' and canPromoteToBackground=true at the time of the call. - #[serde(skip_serializing_if = "Option::is_none")] - pub task: Option, +pub struct SessionMcpAppsReadResourceResult { + /// Resource contents returned by the server + pub contents: Vec, } -/// Indicates whether the task was successfully promoted to background mode. +/// App-callable tools from the named MCP server. /// ///
/// @@ -17862,9 +20647,9 @@ pub struct SessionTasksGetCurrentPromotableResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionTasksPromoteToBackgroundResult { - /// Whether the task was successfully promoted to background mode - pub promoted: bool, +pub struct SessionMcpAppsListToolsResult { + /// App-callable tools from the server + pub tools: Vec>, } /// Identifies the target session. @@ -17877,12 +20662,12 @@ pub struct SessionTasksPromoteToBackgroundResult { /// #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionTasksPromoteCurrentToBackgroundParams { +pub struct SessionMcpAppsGetHostContextParams { /// Target session identifier pub session_id: SessionId, } -/// The promoted task as it now exists in background mode, omitted if no promotable task was waiting. +/// Current host context advertised to MCP App guests. /// ///
/// @@ -17892,13 +20677,12 @@ pub struct SessionTasksPromoteCurrentToBackgroundParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionTasksPromoteCurrentToBackgroundResult { - /// The promoted task as it now exists in background mode, omitted if no promotable task was waiting. Atomic operation: avoids the race window of getCurrentPromotable + promoteToBackground. - #[serde(skip_serializing_if = "Option::is_none")] - pub task: Option, +pub struct SessionMcpAppsGetHostContextResult { + /// Current host context + pub context: McpAppsHostContextDetails, } -/// Indicates whether the background task was successfully cancelled. +/// Diagnostic snapshot of MCP Apps wiring for the named server. /// ///
/// @@ -17908,12 +20692,14 @@ pub struct SessionTasksPromoteCurrentToBackgroundResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionTasksCancelResult { - /// Whether the task was successfully cancelled - pub cancelled: bool, +pub struct SessionMcpAppsDiagnoseResult { + /// Capability negotiation snapshot + pub capability: McpAppsDiagnoseCapability, + /// What the server returned for this session + pub server: McpAppsDiagnoseServer, } -/// Indicates whether the task was removed. False when the task does not exist or is still running/idle. +/// Resource contents returned by the MCP server. /// ///
/// @@ -17923,12 +20709,12 @@ pub struct SessionTasksCancelResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionTasksRemoveResult { - /// Whether the task was removed. Returns false if the task does not exist or is still running/idle (cancel it first). - pub removed: bool, +pub struct SessionMcpResourcesReadResult { + /// Resource contents returned by the server + pub contents: Vec, } -/// Indicates whether the message was delivered, with an error message when delivery failed. +/// One page of resources advertised by the named MCP server. /// ///
/// @@ -17938,15 +20724,15 @@ pub struct SessionTasksRemoveResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionTasksSendMessageResult { - /// Error message if delivery failed +pub struct SessionMcpResourcesListResult { + /// Opaque cursor for the next page, if the server has more resources #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - /// Whether the message was successfully delivered or steered - pub sent: bool, + pub next_cursor: Option, + /// Resources advertised by the server (proxied MCP `resources/list`) + pub resources: Vec, } -/// Identifies the target session. +/// One page of resource templates advertised by the named MCP server. /// ///
/// @@ -17956,12 +20742,15 @@ pub struct SessionTasksSendMessageResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSkillsListParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionMcpResourcesListTemplatesResult { + /// Opaque cursor for the next page, if the server has more resource templates + #[serde(skip_serializing_if = "Option::is_none")] + pub next_cursor: Option, + /// Resource templates advertised by the server (proxied MCP `resources/templates/list`) + pub resource_templates: Vec, } -/// Skills available to the session, with their enabled state. +/// Identifies the target session. /// ///
/// @@ -17971,12 +20760,12 @@ pub struct SessionSkillsListParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSkillsListResult { - /// Available skills - pub skills: Vec, +pub struct SessionPluginsListParams { + /// Target session identifier + pub session_id: SessionId, } -/// Identifies the target session. +/// Plugins installed for the session, with their enabled state and version metadata. /// ///
/// @@ -17986,12 +20775,12 @@ pub struct SessionSkillsListResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSkillsGetInvokedParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionPluginsListResult { + /// Installed plugins + pub plugins: Vec, } -/// Skills invoked during this session, ordered by invocation time (most recent last). +/// A snapshot of the provider endpoint the session is currently configured to talk to. /// ///
/// @@ -18001,12 +20790,28 @@ pub struct SessionSkillsGetInvokedParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSkillsGetInvokedResult { - /// Skills invoked during this session, ordered by invocation time (most recent last) - pub skills: Vec, +pub struct SessionProviderGetEndpointResult { + /// A credential the caller should use with this endpoint. Omitted only when the endpoint accepts unauthenticated requests. + #[serde(skip_serializing_if = "Option::is_none")] + pub api_key: Option, + /// Base URL to pass to the LLM client library. + pub base_url: String, + /// HTTP headers the caller must include on every outbound request. + pub headers: HashMap, + /// Short-lived, rotating credential the caller must send on every request, in addition to `apiKey` if one is present. Omitted when the endpoint does not require one. + #[serde(skip_serializing_if = "Option::is_none")] + pub session_token: Option, + /// Transport to be used for provider requests. + #[serde(skip_serializing_if = "Option::is_none")] + pub transport: Option, + /// Provider family. Matches the `type` field of a BYOK provider config. + pub r#type: ProviderEndpointType, + /// Wire API to be used, when required for the provider type. + #[serde(skip_serializing_if = "Option::is_none")] + pub wire_api: Option, } -/// Identifies the target session. +/// The selectable model entries synthesized for the models added by this call. /// ///
/// @@ -18016,12 +20821,12 @@ pub struct SessionSkillsGetInvokedResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSkillsReloadParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionProviderAddResult { + /// Synthesized selectable model entries for the newly added BYOK models, each under its provider-qualified selection id (`provider/id`). Empty when only providers were added. + pub models: Vec, } -/// Diagnostics from reloading skill definitions, with warnings and errors as separate lists. +/// Indicates whether the session options patch was applied successfully. /// ///
/// @@ -18031,11 +20836,12 @@ pub struct SessionSkillsReloadParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSkillsReloadResult { - /// Errors emitted while loading skills (e.g. skills that failed to load entirely) - pub errors: Vec, - /// Warnings emitted while loading skills (e.g. skills that loaded but had issues) - pub warnings: Vec, +pub struct SessionOptionsUpdateResult { + /// Number of hooks loaded from installed plugins, returned when installedPlugins is updated + #[serde(skip_serializing_if = "Option::is_none")] + pub plugin_hook_count: Option, + /// Whether the operation succeeded + pub success: bool, } /// Identifies the target session. @@ -18048,12 +20854,12 @@ pub struct SessionSkillsReloadResult { /// #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSkillsEnsureLoadedParams { +pub struct SessionExtensionsListParams { /// Target session identifier pub session_id: SessionId, } -/// Identifies the target session. +/// Extensions discovered for the session, with their current status. /// ///
/// @@ -18063,12 +20869,12 @@ pub struct SessionSkillsEnsureLoadedParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpListParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionExtensionsListResult { + /// Discovered extensions and their current status + pub extensions: Vec, } -/// MCP servers configured for the session, with their connection status and host-level state. +/// Identifies the target session. /// ///
/// @@ -18078,15 +20884,12 @@ pub struct SessionMcpListParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpListResult { - /// Host-level state, omitted when no MCP host is initialized. - #[serde(skip_serializing_if = "Option::is_none")] - pub host: Option, - /// Configured MCP servers - pub servers: Vec, +pub struct SessionExtensionsReloadParams { + /// Target session identifier + pub session_id: SessionId, } -/// Tools exposed by the connected MCP server. Throws when the server is not connected. +/// Indicates whether the external tool call result was handled successfully. /// ///
/// @@ -18096,9 +20899,9 @@ pub struct SessionMcpListResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpListToolsResult { - /// Tools exposed by the server. - pub tools: Vec, +pub struct SessionToolsHandlePendingToolCallResult { + /// Whether the tool call result was handled successfully + pub success: bool, } /// Identifies the target session. @@ -18111,12 +20914,12 @@ pub struct SessionMcpListToolsResult { /// #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpReloadParams { +pub struct SessionToolsInitializeAndValidateParams { /// Target session identifier pub session_id: SessionId, } -/// MCP server startup filtering result. +/// Resolve, build, and validate the runtime tool list for this session. Subagent sessions and consumer flows that need an initialized tool set before `send` invoke this. Default base-class implementation is a no-op for sessions that don't support tool validation. /// ///
/// @@ -18126,15 +20929,9 @@ pub struct SessionMcpReloadParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpReloadWithConfigResult { - /// Non-default servers allowed by policy - #[serde(skip_serializing_if = "Option::is_none")] - pub allowed_servers: Option>, - /// Servers filtered out before startup - pub filtered_servers: Vec, -} +pub struct SessionToolsInitializeAndValidateResult {} -/// Outcome of an MCP sampling execution: success result, failure error, or cancellation. +/// Identifies the target session. /// ///
/// @@ -18144,18 +20941,12 @@ pub struct SessionMcpReloadWithConfigResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpExecuteSamplingResult { - /// 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. - pub action: McpSamplingExecutionAction, - /// Error description, present when action='failure'. - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - /// 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. - #[serde(skip_serializing_if = "Option::is_none")] - pub result: Option, +pub struct SessionToolsGetCurrentMetadataParams { + /// Target session identifier + pub session_id: SessionId, } -/// Indicates whether an in-flight sampling execution with the given requestId was found and cancelled. +/// Current lightweight tool metadata snapshot for the session. /// ///
/// @@ -18165,12 +20956,12 @@ pub struct SessionMcpExecuteSamplingResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpCancelSamplingExecutionResult { - /// True if an in-flight execution with the given requestId was found and signalled to cancel. False when no such execution is in flight (already completed, never started, or cancelled by another caller). - pub cancelled: bool, +pub struct SessionToolsGetCurrentMetadataResult { + /// Current tool metadata, or null when tools have not been initialized yet + pub tools: Option>, } -/// Env-value mode recorded on the session after the update. +/// Empty result after applying subagent settings /// ///
/// @@ -18180,12 +20971,9 @@ pub struct SessionMcpCancelSamplingExecutionResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpSetEnvValueModeResult { - /// Mode recorded on the session after the update - pub mode: McpSetEnvValueModeDetails, -} +pub struct SessionToolsUpdateSubagentSettingsResult {} -/// Identifies the target session. +/// Slash commands available in the session, after applying any include/exclude filters. /// ///
/// @@ -18195,12 +20983,12 @@ pub struct SessionMcpSetEnvValueModeResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpRemoveGitHubParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionCommandsListResult { + /// Commands available in this session + pub commands: Vec, } -/// Indicates whether the auto-managed `github` MCP server was removed (false when nothing to remove). +/// Indicates whether the pending client-handled command was completed successfully. /// ///
/// @@ -18210,12 +20998,12 @@ pub struct SessionMcpRemoveGitHubParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpRemoveGitHubResult { - /// True when the auto-managed `github` MCP server was removed; false when no removal happened (e.g. user has explicitly configured a `github` server, or the server was not registered). - pub removed: bool, +pub struct SessionCommandsHandlePendingCommandResult { + /// Whether the command was handled successfully + pub success: bool, } -/// Result of configuring GitHub MCP. +/// Error message produced while executing the command, if any. /// ///
/// @@ -18225,12 +21013,13 @@ pub struct SessionMcpRemoveGitHubResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpConfigureGitHubResult { - /// Whether GitHub MCP configuration changed. - pub changed: bool, +pub struct SessionCommandsExecuteResult { + /// Error message produced while executing the command, if any. Omitted when the handler succeeded. + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, } -/// Whether the named MCP server is running. +/// Indicates whether the command was accepted into the local execution queue. /// ///
/// @@ -18240,12 +21029,12 @@ pub struct SessionMcpConfigureGitHubResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpIsServerRunningResult { - /// True if the server has an active client and transport. - pub running: bool, +pub struct SessionCommandsEnqueueResult { + /// True when the command was accepted into the local execution queue. False when the call targets a session that does not support local command queueing (e.g. remote sessions). + pub queued: bool, } -/// Indicates whether the pending MCP OAuth response was accepted. +/// Indicates whether the queued-command response was matched to a pending request. /// ///
/// @@ -18255,12 +21044,12 @@ pub struct SessionMcpIsServerRunningResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpOauthHandlePendingRequestResult { - /// Whether the response was accepted. False if the request was unknown, timed out, or already resolved. +pub struct SessionCommandsRespondToQueuedCommandResult { + /// Whether a pending queued command with the given request ID was found and resolved. False when the request was already resolved, cancelled, or unknown. pub success: bool, } -/// OAuth authorization URL the caller should open, or empty when cached tokens already authenticated the server. +/// Identifies the target session. /// ///
/// @@ -18270,13 +21059,12 @@ pub struct SessionMcpOauthHandlePendingRequestResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpOauthLoginResult { - /// URL the caller should open in a browser to complete OAuth. Omitted when cached tokens were still valid and no browser interaction was needed — the server is already reconnected in that case. When present, the runtime starts the callback listener before returning and continues the flow in the background; completion is signaled via session.mcp_server_status_changed. - #[serde(skip_serializing_if = "Option::is_none")] - pub authorization_url: Option, +pub struct SessionTelemetryGetEngagementIdParams { + /// Target session identifier + pub session_id: SessionId, } -/// Indicates whether the pending MCP headers refresh response was accepted. +/// Telemetry engagement ID for the session, when available. /// ///
/// @@ -18286,12 +21074,13 @@ pub struct SessionMcpOauthLoginResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpHeadersHandlePendingHeadersRefreshRequestResult { - /// Whether the response was accepted. False if the request was unknown, timed out, or already resolved. - pub success: bool, +pub struct SessionTelemetryGetEngagementIdResult { + /// Current telemetry engagement ID, when available. + #[serde(skip_serializing_if = "Option::is_none")] + pub engagement_id: Option, } -/// Resource contents returned by the MCP server. +/// Transient answer generated from current conversation context. /// ///
/// @@ -18301,12 +21090,12 @@ pub struct SessionMcpHeadersHandlePendingHeadersRefreshRequestResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpAppsReadResourceResult { - /// Resource contents returned by the server - pub contents: Vec, +pub struct SessionUiEphemeralQueryResult { + /// Full assistant response text. + pub answer: String, } -/// App-callable tools from the named MCP server. +/// The elicitation response (accept with form values, decline, or cancel) /// ///
/// @@ -18316,12 +21105,15 @@ pub struct SessionMcpAppsReadResourceResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpAppsListToolsResult { - /// App-callable tools from the server - pub tools: Vec>, +pub struct SessionUiElicitationResult { + /// The user's response: accept (submitted), decline (rejected), or cancel (dismissed) + pub action: UIElicitationResponseAction, + /// The form values submitted by the user (present when action is 'accept') + #[serde(skip_serializing_if = "Option::is_none")] + pub content: Option>, } -/// Identifies the target session. +/// Indicates whether the elicitation response was accepted; false if it was already resolved by another client. /// ///
/// @@ -18331,12 +21123,12 @@ pub struct SessionMcpAppsListToolsResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpAppsGetHostContextParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionUiHandlePendingElicitationResult { + /// Whether the response was accepted. False if the request was already resolved by another client. + pub success: bool, } -/// Current host context advertised to MCP App guests. +/// Indicates whether the pending UI request was resolved by this call. /// ///
/// @@ -18346,12 +21138,12 @@ pub struct SessionMcpAppsGetHostContextParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpAppsGetHostContextResult { - /// Current host context - pub context: McpAppsHostContextDetails, +pub struct SessionUiHandlePendingUserInputResult { + /// True if the request was still pending and was resolved by this call. False if the request ID was unknown, already resolved by another client (e.g. GitHub), expired, or otherwise no longer pending. + pub success: bool, } -/// Diagnostic snapshot of MCP Apps wiring for the named server. +/// Indicates whether the pending UI request was resolved by this call. /// ///
/// @@ -18361,14 +21153,12 @@ pub struct SessionMcpAppsGetHostContextResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpAppsDiagnoseResult { - /// Capability negotiation snapshot - pub capability: McpAppsDiagnoseCapability, - /// What the server returned for this session - pub server: McpAppsDiagnoseServer, +pub struct SessionUiHandlePendingSamplingResult { + /// True if the request was still pending and was resolved by this call. False if the request ID was unknown, already resolved by another client (e.g. GitHub), expired, or otherwise no longer pending. + pub success: bool, } -/// Resource contents returned by the MCP server. +/// Indicates whether the pending UI request was resolved by this call. /// ///
/// @@ -18378,12 +21168,12 @@ pub struct SessionMcpAppsDiagnoseResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpResourcesReadResult { - /// Resource contents returned by the server - pub contents: Vec, +pub struct SessionUiHandlePendingAutoModeSwitchResult { + /// True if the request was still pending and was resolved by this call. False if the request ID was unknown, already resolved by another client (e.g. GitHub), expired, or otherwise no longer pending. + pub success: bool, } -/// One page of resources advertised by the named MCP server. +/// Indicates whether the pending UI request was resolved by this call. /// ///
/// @@ -18393,15 +21183,12 @@ pub struct SessionMcpResourcesReadResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpResourcesListResult { - /// Opaque cursor for the next page, if the server has more resources - #[serde(skip_serializing_if = "Option::is_none")] - pub next_cursor: Option, - /// Resources advertised by the server (proxied MCP `resources/list`) - pub resources: Vec, +pub struct SessionUiHandlePendingSessionLimitsExhaustedResult { + /// True if the request was still pending and was resolved by this call. False if the request ID was unknown, already resolved by another client (e.g. GitHub), expired, or otherwise no longer pending. + pub success: bool, } -/// One page of resource templates advertised by the named MCP server. +/// Indicates whether the pending UI request was resolved by this call. /// ///
/// @@ -18411,12 +21198,9 @@ pub struct SessionMcpResourcesListResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMcpResourcesListTemplatesResult { - /// Opaque cursor for the next page, if the server has more resource templates - #[serde(skip_serializing_if = "Option::is_none")] - pub next_cursor: Option, - /// Resource templates advertised by the server (proxied MCP `resources/templates/list`) - pub resource_templates: Vec, +pub struct SessionUiHandlePendingExitPlanModeResult { + /// True if the request was still pending and was resolved by this call. False if the request ID was unknown, already resolved by another client (e.g. GitHub), expired, or otherwise no longer pending. + pub success: bool, } /// Identifies the target session. @@ -18429,12 +21213,12 @@ pub struct SessionMcpResourcesListTemplatesResult { /// #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPluginsListParams { +pub struct SessionUiRegisterDirectAutoModeSwitchHandlerParams { /// Target session identifier pub session_id: SessionId, } -/// Plugins installed for the session, with their enabled state and version metadata. +/// Register an in-process handler for `auto_mode_switch.requested` events. The caller still attaches the actual listener via the standard event-subscription mechanism; this registration solely tells the server bridge to skip its own dispatch (so a remote client doesn't race the in-process handler for the same requestId). /// ///
/// @@ -18444,12 +21228,12 @@ pub struct SessionPluginsListParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPluginsListResult { - /// Installed plugins - pub plugins: Vec, +pub struct SessionUiRegisterDirectAutoModeSwitchHandlerResult { + /// Opaque handle representing the registration. Pass this same handle to `unregisterDirectAutoModeSwitchHandler` when the in-process handler is no longer active. Multiple registrations are reference-counted; the server bridge will only dispatch auto-mode-switch requests when no handles are active. + pub handle: String, } -/// A snapshot of the provider endpoint the session is currently configured to talk to. +/// Indicates whether the handle was active and the registration count was decremented. /// ///
/// @@ -18459,28 +21243,12 @@ pub struct SessionPluginsListResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionProviderGetEndpointResult { - /// A credential the caller should use with this endpoint. Omitted only when the endpoint accepts unauthenticated requests. - #[serde(skip_serializing_if = "Option::is_none")] - pub api_key: Option, - /// Base URL to pass to the LLM client library. - pub base_url: String, - /// HTTP headers the caller must include on every outbound request. - pub headers: HashMap, - /// Short-lived, rotating credential the caller must send on every request, in addition to `apiKey` if one is present. Omitted when the endpoint does not require one. - #[serde(skip_serializing_if = "Option::is_none")] - pub session_token: Option, - /// Transport to be used for provider requests. - #[serde(skip_serializing_if = "Option::is_none")] - pub transport: Option, - /// Provider family. Matches the `type` field of a BYOK provider config. - pub r#type: ProviderEndpointType, - /// Wire API to be used, when required for the provider type. - #[serde(skip_serializing_if = "Option::is_none")] - pub wire_api: Option, +pub struct SessionUiUnregisterDirectAutoModeSwitchHandlerResult { + /// True if the handle was active and decremented the counter; false if the handle was unknown. + pub unregistered: bool, } -/// The selectable model entries synthesized for the models added by this call. +/// Indicates whether the operation succeeded. /// ///
/// @@ -18490,12 +21258,12 @@ pub struct SessionProviderGetEndpointResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionProviderAddResult { - /// Synthesized selectable model entries for the newly added BYOK models, each under its provider-qualified selection id (`provider/id`). Empty when only providers were added. - pub models: Vec, +pub struct SessionPermissionsConfigureResult { + /// Whether the operation succeeded + pub success: bool, } -/// Indicates whether the session options patch was applied successfully. +/// Indicates whether the permission decision was applied; false when the request was already resolved. /// ///
/// @@ -18505,15 +21273,12 @@ pub struct SessionProviderAddResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionOptionsUpdateResult { - /// Number of hooks loaded from installed plugins, returned when installedPlugins is updated - #[serde(skip_serializing_if = "Option::is_none")] - pub plugin_hook_count: Option, - /// Whether the operation succeeded +pub struct SessionPermissionsHandlePendingPermissionRequestResult { + /// Whether the permission request was handled successfully pub success: bool, } -/// Identifies the target session. +/// List of pending permission requests reconstructed from event history. /// ///
/// @@ -18523,12 +21288,12 @@ pub struct SessionOptionsUpdateResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionExtensionsListParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionPermissionsPendingRequestsResult { + /// Pending permission prompts reconstructed from the session's event history. Equivalent to the set of `permission.requested` events that have not yet been followed by a matching `permission.completed` event. Used by clients (e.g. the CLI) to hydrate UI for prompts that were emitted before the client attached to the session. + pub items: Vec, } -/// Extensions discovered for the session, with their current status. +/// Indicates whether the operation succeeded. /// ///
/// @@ -18538,12 +21303,12 @@ pub struct SessionExtensionsListParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionExtensionsListResult { - /// Discovered extensions and their current status - pub extensions: Vec, +pub struct SessionPermissionsSetApproveAllResult { + /// Whether the operation succeeded + pub success: bool, } -/// Identifies the target session. +/// Indicates whether the operation succeeded and reports the post-mutation state. /// ///
/// @@ -18553,12 +21318,17 @@ pub struct SessionExtensionsListResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionExtensionsReloadParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionPermissionsSetAllowAllResult { + /// Authoritative full allow-all state after the mutation + pub enabled: bool, + /// Authoritative allow-all mode after the mutation + #[serde(skip_serializing_if = "Option::is_none")] + pub mode: Option, + /// Whether the operation succeeded + pub success: bool, } -/// Indicates whether the external tool call result was handled successfully. +/// Current allow-all permission mode. /// ///
/// @@ -18568,12 +21338,15 @@ pub struct SessionExtensionsReloadParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionToolsHandlePendingToolCallResult { - /// Whether the tool call result was handled successfully - pub success: bool, +pub struct SessionPermissionsGetAllowAllResult { + /// Whether full allow-all permissions are currently active + pub enabled: bool, + /// Current allow-all mode + #[serde(skip_serializing_if = "Option::is_none")] + pub mode: Option, } -/// Identifies the target session. +/// Indicates whether the operation succeeded. /// ///
/// @@ -18583,12 +21356,12 @@ pub struct SessionToolsHandlePendingToolCallResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionToolsInitializeAndValidateParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionPermissionsModifyRulesResult { + /// Whether the operation succeeded + pub success: bool, } -/// Resolve, build, and validate the runtime tool list for this session. Subagent sessions and consumer flows that need an initialized tool set before `send` invoke this. Default base-class implementation is a no-op for sessions that don't support tool validation. +/// Indicates whether the operation succeeded. /// ///
/// @@ -18598,9 +21371,12 @@ pub struct SessionToolsInitializeAndValidateParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionToolsInitializeAndValidateResult {} +pub struct SessionPermissionsSetRequiredResult { + /// Whether the operation succeeded + pub success: bool, +} -/// Identifies the target session. +/// Indicates whether the operation succeeded. /// ///
/// @@ -18610,12 +21386,12 @@ pub struct SessionToolsInitializeAndValidateResult {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionToolsGetCurrentMetadataParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionPermissionsResetSessionApprovalsResult { + /// Whether the operation succeeded + pub success: bool, } -/// Current lightweight tool metadata snapshot for the session. +/// Indicates whether the operation succeeded. /// ///
/// @@ -18625,12 +21401,12 @@ pub struct SessionToolsGetCurrentMetadataParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionToolsGetCurrentMetadataResult { - /// Current tool metadata, or null when tools have not been initialized yet - pub tools: Option>, +pub struct SessionPermissionsNotifyPromptShownResult { + /// Whether the operation succeeded + pub success: bool, } -/// Empty result after applying subagent settings +/// Snapshot of the session's allow-listed directories and primary working directory. /// ///
/// @@ -18640,9 +21416,14 @@ pub struct SessionToolsGetCurrentMetadataResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionToolsUpdateSubagentSettingsResult {} +pub struct SessionPermissionsPathsListResult { + /// All directories currently allowed for tool access on this session. + pub directories: Vec, + /// The primary working directory for this session. + pub primary: String, +} -/// Slash commands available in the session, after applying any include/exclude filters. +/// Indicates whether the operation succeeded. /// ///
/// @@ -18652,12 +21433,12 @@ pub struct SessionToolsUpdateSubagentSettingsResult {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionCommandsListResult { - /// Commands available in this session - pub commands: Vec, +pub struct SessionPermissionsPathsAddResult { + /// Whether the operation succeeded + pub success: bool, } -/// Indicates whether the pending client-handled command was completed successfully. +/// Indicates whether the operation succeeded. /// ///
/// @@ -18667,12 +21448,12 @@ pub struct SessionCommandsListResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionCommandsHandlePendingCommandResult { - /// Whether the command was handled successfully +pub struct SessionPermissionsPathsUpdatePrimaryResult { + /// Whether the operation succeeded pub success: bool, } -/// Error message produced while executing the command, if any. +/// Indicates whether the supplied path is within the session's allowed directories. /// ///
/// @@ -18682,13 +21463,12 @@ pub struct SessionCommandsHandlePendingCommandResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionCommandsExecuteResult { - /// Error message produced while executing the command, if any. Omitted when the handler succeeded. - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, +pub struct SessionPermissionsPathsIsPathWithinAllowedDirectoriesResult { + /// Whether the path is within the session's allowed directories + pub allowed: bool, } -/// Indicates whether the command was accepted into the local execution queue. +/// Indicates whether the supplied path is within the session's workspace directory. /// ///
/// @@ -18698,12 +21478,12 @@ pub struct SessionCommandsExecuteResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionCommandsEnqueueResult { - /// True when the command was accepted into the local execution queue. False when the call targets a session that does not support local command queueing (e.g. remote sessions). - pub queued: bool, +pub struct SessionPermissionsPathsIsPathWithinWorkspaceResult { + /// Whether the path is within the session workspace directory + pub allowed: bool, } -/// Indicates whether the queued-command response was matched to a pending request. +/// Resolved location-permissions key and type. /// ///
/// @@ -18713,12 +21493,14 @@ pub struct SessionCommandsEnqueueResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionCommandsRespondToQueuedCommandResult { - /// Whether a pending queued command with the given request ID was found and resolved. False when the request was already resolved, cancelled, or unknown. - pub success: bool, +pub struct SessionPermissionsLocationsResolveResult { + /// Location key used in the location-permissions store + pub location_key: String, + /// Whether the location is a git repo or directory + pub location_type: PermissionLocationType, } -/// Identifies the target session. +/// Summary of persisted location permissions applied to the session. /// ///
/// @@ -18728,12 +21510,22 @@ pub struct SessionCommandsRespondToQueuedCommandResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionTelemetryGetEngagementIdParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionPermissionsLocationsApplyResult { + /// Number of persisted allowed directories added to the live path manager + pub applied_directory_count: i64, + /// Number of location-scoped rules added to the live permission service + pub applied_rule_count: i64, + /// Location-scoped rules applied to the live permission service + pub applied_rules: Vec, + /// Whether a different location was applied since the previous apply call + pub changed: bool, + /// Location key used in the location-permissions store + pub location_key: String, + /// Whether the location is a git repo or directory + pub location_type: PermissionLocationType, } -/// Telemetry engagement ID for the session, when available. +/// Indicates whether the operation succeeded. /// ///
/// @@ -18743,13 +21535,12 @@ pub struct SessionTelemetryGetEngagementIdParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionTelemetryGetEngagementIdResult { - /// Current telemetry engagement ID, when available. - #[serde(skip_serializing_if = "Option::is_none")] - pub engagement_id: Option, +pub struct SessionPermissionsLocationsAddToolApprovalResult { + /// Whether the operation succeeded + pub success: bool, } -/// Transient answer generated from current conversation context. +/// Folder trust check result. /// ///
/// @@ -18759,12 +21550,12 @@ pub struct SessionTelemetryGetEngagementIdResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionUiEphemeralQueryResult { - /// Full assistant response text. - pub answer: String, +pub struct SessionPermissionsFolderTrustIsTrustedResult { + /// Whether the folder is trusted + pub trusted: bool, } -/// The elicitation response (accept with form values, decline, or cancel) +/// Indicates whether the operation succeeded. /// ///
/// @@ -18774,15 +21565,12 @@ pub struct SessionUiEphemeralQueryResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionUiElicitationResult { - /// The user's response: accept (submitted), decline (rejected), or cancel (dismissed) - pub action: UIElicitationResponseAction, - /// The form values submitted by the user (present when action is 'accept') - #[serde(skip_serializing_if = "Option::is_none")] - pub content: Option>, +pub struct SessionPermissionsFolderTrustAddTrustedResult { + /// Whether the operation succeeded + pub success: bool, } -/// Indicates whether the elicitation response was accepted; false if it was already resolved by another client. +/// Indicates whether the operation succeeded. /// ///
/// @@ -18792,12 +21580,12 @@ pub struct SessionUiElicitationResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionUiHandlePendingElicitationResult { - /// Whether the response was accepted. False if the request was already resolved by another client. +pub struct SessionPermissionsUrlsSetUnrestrictedModeResult { + /// Whether the operation succeeded pub success: bool, } -/// Indicates whether the pending UI request was resolved by this call. +/// Identifier of the session event that was emitted for the log message. /// ///
/// @@ -18807,12 +21595,12 @@ pub struct SessionUiHandlePendingElicitationResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionUiHandlePendingUserInputResult { - /// True if the request was still pending and was resolved by this call. False if the request ID was unknown, already resolved by another client (e.g. GitHub), expired, or otherwise no longer pending. - pub success: bool, +pub struct SessionLogResult { + /// The unique identifier of the emitted session event + pub event_id: String, } -/// Indicates whether the pending UI request was resolved by this call. +/// Identifies the target session. /// ///
/// @@ -18822,12 +21610,47 @@ pub struct SessionUiHandlePendingUserInputResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionUiHandlePendingSamplingResult { - /// True if the request was still pending and was resolved by this call. False if the request ID was unknown, already resolved by another client (e.g. GitHub), expired, or otherwise no longer pending. - pub success: bool, +pub struct SessionMetadataSnapshotParams { + /// Target session identifier + pub session_id: SessionId, } -/// Indicates whether the pending UI request was resolved by this call. +/// Public-facing projection of workspace metadata for SDK / TUI consumers +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionMetadataSnapshotResultWorkspace { + /// Branch checked out at session start, if any + #[serde(skip_serializing_if = "Option::is_none")] + pub branch: Option, + /// ISO 8601 timestamp when the workspace was created + #[serde(rename = "created_at", skip_serializing_if = "Option::is_none")] + pub created_at: Option, + /// Current working directory at session start + #[serde(skip_serializing_if = "Option::is_none")] + pub cwd: Option, + /// Resolved git root for cwd, if any + #[serde(rename = "git_root", skip_serializing_if = "Option::is_none")] + pub git_root: Option, + /// Repository host type, if known + #[serde(rename = "host_type", skip_serializing_if = "Option::is_none")] + pub host_type: Option, + /// Workspace identifier (1:1 with sessionId) + pub id: String, + /// Display name for the session, if set + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option, + /// Repository identifier in 'owner/repo' or 'org/project/repo' format, if any + #[serde(skip_serializing_if = "Option::is_none")] + pub repository: Option, + /// ISO 8601 timestamp when the workspace was last updated + #[serde(rename = "updated_at", skip_serializing_if = "Option::is_none")] + pub updated_at: Option, + /// Whether the display name was explicitly set by the user + #[serde(rename = "user_named", skip_serializing_if = "Option::is_none")] + pub user_named: Option, +} + +/// Point-in-time snapshot of slow-changing session identifier and state fields /// ///
/// @@ -18837,12 +21660,45 @@ pub struct SessionUiHandlePendingSamplingResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionUiHandlePendingAutoModeSwitchResult { - /// True if the request was still pending and was resolved by this call. False if the request ID was unknown, already resolved by another client (e.g. GitHub), expired, or otherwise no longer pending. - pub success: bool, +pub struct SessionMetadataSnapshotResult { + /// True when the session was detected to be in use by another process at construction time. Local consumers may surface a confirmation prompt before fully attaching. Always false for new sessions. + pub already_in_use: bool, + /// Runtime client name associated with the session (telemetry identifier). + #[serde(skip_serializing_if = "Option::is_none")] + pub client_name: Option, + /// The current agent mode for this session (e.g., 'interactive', 'plan', 'autopilot') + pub current_mode: MetadataSnapshotCurrentMode, + /// User-provided name supplied at session construction (via `--name`), if any. Immutable after construction. + #[serde(skip_serializing_if = "Option::is_none")] + pub initial_name: Option, + /// Whether this is a remote session (i.e., one whose runtime executes elsewhere and is steered through this process) + pub is_remote: bool, + /// ISO 8601 timestamp of when the session's persisted state was last modified on disk. For new sessions, equals startTime. For resumed sessions, reflects the previous modification time at construction. + pub modified_time: String, + /// Remote-session-specific metadata. Populated only when `isRemote` is true. Fields are immutable for the lifetime of the session. + #[serde(skip_serializing_if = "Option::is_none")] + pub remote_metadata: Option, + /// Currently selected model identifier, if any + #[serde(skip_serializing_if = "Option::is_none")] + pub selected_model: Option, + /// The unique identifier of the session + pub session_id: SessionId, + /// Current session limits, or null when no limits are active + pub session_limits: Option, + /// ISO 8601 timestamp of when the session started + pub start_time: String, + /// Short human-readable summary of the session, if known. Omitted when no summary has been generated. + #[serde(skip_serializing_if = "Option::is_none")] + pub summary: Option, + /// Absolute path to the session's current working directory + pub working_directory: String, + /// 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). + pub workspace: Option, + /// Absolute path to the session's workspace directory on disk, or null if the session has no associated workspace + pub workspace_path: Option, } -/// Indicates whether the pending UI request was resolved by this call. +/// Identifies the target session. /// ///
/// @@ -18852,12 +21708,12 @@ pub struct SessionUiHandlePendingAutoModeSwitchResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionUiHandlePendingSessionLimitsExhaustedResult { - /// True if the request was still pending and was resolved by this call. False if the request ID was unknown, already resolved by another client (e.g. GitHub), expired, or otherwise no longer pending. - pub success: bool, +pub struct SessionMetadataIsProcessingParams { + /// Target session identifier + pub session_id: SessionId, } -/// Indicates whether the pending UI request was resolved by this call. +/// Indicates whether the local session is currently processing a turn or background continuation. /// ///
/// @@ -18867,9 +21723,9 @@ pub struct SessionUiHandlePendingSessionLimitsExhaustedResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionUiHandlePendingExitPlanModeResult { - /// True if the request was still pending and was resolved by this call. False if the request ID was unknown, already resolved by another client (e.g. GitHub), expired, or otherwise no longer pending. - pub success: bool, +pub struct SessionMetadataIsProcessingResult { + /// Whether the session is currently processing user/agent messages. False for non-local sessions (which don't run a local agentic loop). Reflects an in-flight turn or background continuation. + pub processing: bool, } /// Identifies the target session. @@ -18882,12 +21738,12 @@ pub struct SessionUiHandlePendingExitPlanModeResult { /// #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionUiRegisterDirectAutoModeSwitchHandlerParams { +pub struct SessionMetadataActivityParams { /// Target session identifier pub session_id: SessionId, } -/// Register an in-process handler for `auto_mode_switch.requested` events. The caller still attaches the actual listener via the standard event-subscription mechanism; this registration solely tells the server bridge to skip its own dispatch (so a remote client doesn't race the in-process handler for the same requestId). +/// Current activity flags for the session. /// ///
/// @@ -18897,27 +21753,40 @@ pub struct SessionUiRegisterDirectAutoModeSwitchHandlerParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionUiRegisterDirectAutoModeSwitchHandlerResult { - /// Opaque handle representing the registration. Pass this same handle to `unregisterDirectAutoModeSwitchHandler` when the in-process handler is no longer active. Multiple registrations are reference-counted; the server bridge will only dispatch auto-mode-switch requests when no handles are active. - pub handle: String, +pub struct SessionMetadataActivityResult { + /// Whether an in-flight operation can currently be aborted. + pub abortable: bool, + /// Whether the session currently has active work, including running turns or tasks. + pub has_active_work: bool, } -/// Indicates whether the handle was active and the registration count was decremented. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
+/// Token-usage breakdown for the session's current context window #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionUiUnregisterDirectAutoModeSwitchHandlerResult { - /// True if the handle was active and decremented the counter; false if the handle was unknown. - pub unregistered: bool, +pub struct SessionMetadataContextInfoResultContextInfo { + /// Output reserve plus tokens after the buffer-exhaustion blocking threshold (default 95%) + pub buffer_tokens: i64, + /// Token count at which background compaction starts (configurable percentage of promptTokenLimit) + pub compaction_threshold: i64, + /// Tokens consumed by user/assistant/tool messages + pub conversation_tokens: i64, + /// Prompt token limit plus the model's full output token limit. + pub limit: i64, + /// Tokens consumed by MCP tool definitions (subset of toolDefinitionsTokens, excludes deferred tools) + pub mcp_tools_tokens: i64, + /// The model used for token counting + pub model_name: String, + /// Maximum prompt tokens allowed by the model (or DEFAULT_TOKEN_LIMIT if unspecified) + pub prompt_token_limit: i64, + /// Tokens consumed by the system prompt + pub system_tokens: i64, + /// Tokens consumed by tool definitions sent to the model (excludes deferred tools) + pub tool_definitions_tokens: i64, + /// Sum of system, conversation and tool-definition tokens + pub total_tokens: i64, } -/// Indicates whether the operation succeeded. +/// Token breakdown for the session's current context window, or null if uninitialized. /// ///
/// @@ -18927,12 +21796,12 @@ pub struct SessionUiUnregisterDirectAutoModeSwitchHandlerResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPermissionsConfigureResult { - /// Whether the operation succeeded - pub success: bool, +pub struct SessionMetadataContextInfoResult { + /// Token breakdown for the current context window, or null if the session has not yet been initialized (no system prompt or tool metadata cached). + pub context_info: Option, } -/// Indicates whether the permission decision was applied; false when the request was already resolved. +/// Identifies the target session. /// ///
/// @@ -18942,42 +21811,51 @@ pub struct SessionPermissionsConfigureResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPermissionsHandlePendingPermissionRequestResult { - /// Whether the permission request was handled successfully - pub success: bool, +pub struct SessionMetadataGetContextAttributionParams { + /// Target session identifier + pub session_id: SessionId, } -/// List of pending permission requests reconstructed from event history. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
+/// Successful compaction history for the session. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPermissionsPendingRequestsResult { - /// Pending permission prompts reconstructed from the session's event history. Equivalent to the set of `permission.requested` events that have not yet been followed by a matching `permission.completed` event. Used by clients (e.g. the CLI) to hydrate UI for prompts that were emitted before the client attached to the session. - pub items: Vec, +pub struct SessionMetadataGetContextAttributionResultContextAttributionCompactions { + /// Number of successful compactions in this session. + pub count: i64, } -/// Indicates whether the operation succeeded. -/// -///
-/// -/// **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 SessionPermissionsSetApproveAllResult { - /// Whether the operation succeeded - pub success: bool, +pub struct SessionMetadataGetContextAttributionResultContextAttributionEntriesItem { + /// Supplementary per-entry metadata (e.g. `messageCount`, `role`, `evictable`, `pluginSource`). Values are stringified; parse as needed and ignore unrecognized keys. + #[serde(skip_serializing_if = "Option::is_none")] + pub attributes: Option>, + /// Identifier for this entry, formed by joining its `kind` and source name (e.g. `tool:bash`, `skill:tmux`, `toolDefinition:bash`); unique within the snapshot. Use it to match the same entry across snapshots, to correlate with other APIs (skill/agent/MCP registries), and as the `parentId` target for nesting. Distinct from the human-facing `label`. + pub id: String, + /// Source category for this entry. Not a closed set — tolerate unknown values. Known values today: `skill`, `subagent`, `mcpServer`, `tool`, `system`, `toolDefinition`, `plugin`. + pub kind: String, + /// Human-readable display label, e.g. `bash` or `skill: tmux`. Presentation-only; may be localized/reformatted without notice — do not key off it. + pub label: String, + /// Optional `id` of the parent entry: e.g. a `plugin` entry parenting its `skill`/`mcpServer` entries, or the `system` entry parenting `toolDefinition` entries. Omitted for top-level entries. + #[serde(skip_serializing_if = "Option::is_none")] + pub parent_id: Option, + /// Token count currently in context attributable to this entry. + pub tokens: i64, } -/// Indicates whether the operation succeeded and reports the post-mutation state. +/// Per-source token attribution snapshot for the current context window. The heaviest individual messages are available separately via `metadata.getContextHeaviestMessages`. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionMetadataGetContextAttributionResultContextAttribution { + /// Successful compaction history for the session. + pub compactions: SessionMetadataGetContextAttributionResultContextAttributionCompactions, + /// Flat list of per-source attribution entries. Group by `kind` and render unrecognized kinds generically. Nesting and rollups are expressed via `parentId`. + pub entries: Vec, + /// Total token count of the current context window the entries are measured against (system message + conversation messages + tool definitions — the same total reported by /context). Divide an entry's `tokens` by this to derive its share. + pub total_tokens: i64, +} + +/// Per-source attribution breakdown for the session's current context window, or null if uninitialized. /// ///
/// @@ -18987,17 +21865,12 @@ pub struct SessionPermissionsSetApproveAllResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPermissionsSetAllowAllResult { - /// Authoritative full allow-all state after the mutation - pub enabled: bool, - /// Authoritative allow-all mode after the mutation - #[serde(skip_serializing_if = "Option::is_none")] - pub mode: Option, - /// Whether the operation succeeded - pub success: bool, +pub struct SessionMetadataGetContextAttributionResult { + /// Per-source context-window attribution, or null if the session has not yet been initialized (no system prompt or tool metadata cached). + pub context_attribution: Option, } -/// Current allow-all permission mode. +/// The heaviest individual messages in the session's context window, most-expensive first. /// ///
/// @@ -19007,15 +21880,14 @@ pub struct SessionPermissionsSetAllowAllResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPermissionsGetAllowAllResult { - /// Whether full allow-all permissions are currently active - pub enabled: bool, - /// Current allow-all mode - #[serde(skip_serializing_if = "Option::is_none")] - pub mode: Option, +pub struct SessionMetadataGetContextHeaviestMessagesResult { + /// Heaviest messages, most-expensive first. + pub messages: Vec, + /// Total token count of the current context window, so callers can compute each message's share without a second call. + pub total_tokens: i64, } -/// Indicates whether the operation succeeded. +/// Notify the session that its working directory context has changed. Emits a `session.context_changed` event so consumers (telemetry, OTel tracker, ACP, the timeline UI) can react. Use this when the host has detected a cwd/branch/repo change outside the session's normal lifecycle (e.g., after a shell command in interactive mode). For a local session, a report whose `cwd` diverges from the session's current working directory is ignored (the call still succeeds but records nothing and emits no event); move a local session's working directory via `metadata.setWorkingDirectory` instead. /// ///
/// @@ -19025,12 +21897,9 @@ pub struct SessionPermissionsGetAllowAllResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPermissionsModifyRulesResult { - /// Whether the operation succeeded - pub success: bool, -} +pub struct SessionMetadataRecordContextChangeResult {} -/// Indicates whether the operation succeeded. +/// Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for any related side-effects (file index, etc.); it does NOT change the process working directory (a session's cwd is per-session, not process-global). For local sessions the runtime validates the target first (an absolute path that exists on disk) and re-bases the permission primary directory; a rejected validation fails the call before anything is mutated, persisted, or emitted. Location-scoped permission rules are then re-keyed to the new directory (best-effort). Remote sessions only record the path. /// ///
/// @@ -19040,12 +21909,12 @@ pub struct SessionPermissionsModifyRulesResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPermissionsSetRequiredResult { - /// Whether the operation succeeded - pub success: bool, +pub struct SessionMetadataSetWorkingDirectoryResult { + /// Working directory after the update + pub working_directory: String, } -/// Indicates whether the operation succeeded. +/// Re-tokenize the session's existing messages against `modelId` and return the token totals. Useful for hosts that want an initial estimate of context usage on session resume, before the next agent turn fires `session.context_info_changed` events. Returns zeros for an empty session. /// ///
/// @@ -19055,12 +21924,16 @@ pub struct SessionPermissionsSetRequiredResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPermissionsResetSessionApprovalsResult { - /// Whether the operation succeeded - pub success: bool, +pub struct SessionMetadataRecomputeContextTokensResult { + /// Tokens contributed by user/assistant/tool messages (excludes system/developer prompts). + pub messages_token_count: i64, + /// Tokens contributed by system/developer prompt snapshots. + pub system_token_count: i64, + /// Sum of tokens across chat-context and system-context messages currently held by the session. + pub total_tokens: i64, } -/// Indicates whether the operation succeeded. +/// Identifies the target session. /// ///
/// @@ -19070,12 +21943,12 @@ pub struct SessionPermissionsResetSessionApprovalsResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPermissionsNotifyPromptShownResult { - /// Whether the operation succeeded - pub success: bool, +pub struct SessionSettingsSnapshotParams { + /// Target session identifier + pub session_id: SessionId, } -/// Snapshot of the session's allow-listed directories and primary working directory. +/// Redacted, serializable view of session runtime settings for SDK boundary consumers. Secrets and raw feature flags are intentionally excluded. /// ///
/// @@ -19085,14 +21958,23 @@ pub struct SessionPermissionsNotifyPromptShownResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPermissionsPathsListResult { - /// All directories currently allowed for tool access on this session. - pub directories: Vec, - /// The primary working directory for this session. - pub primary: String, +pub struct SessionSettingsSnapshotResult { + #[serde(skip_serializing_if = "Option::is_none")] + pub client_name: Option, + pub job: SessionSettingsJobSnapshot, + pub model: SessionSettingsModelSnapshot, + pub online_evaluation: SessionSettingsOnlineEvaluationSnapshot, + pub repo: SessionSettingsRepoSnapshot, + #[serde(skip_serializing_if = "Option::is_none")] + pub start_time_ms: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub timeout_ms: Option, + pub validation: SessionSettingsValidationSnapshot, + #[serde(skip_serializing_if = "Option::is_none")] + pub version: Option, } -/// Indicates whether the operation succeeded. +/// Batch content-exclusion result. Callers must fail closed when policy evaluation is unavailable. /// ///
/// @@ -19102,12 +21984,14 @@ pub struct SessionPermissionsPathsListResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPermissionsPathsAddResult { - /// Whether the operation succeeded - pub success: bool, +pub struct SessionContentExclusionCheckPathsResult { + /// Whether the session's policy service was available for the complete batch. When false, checks is empty and callers must treat every requested path as excluded. + pub available: bool, + /// Per-path decisions in request order. Empty when available is false. + pub checks: Vec, } -/// Indicates whether the operation succeeded. +/// Identifier of the spawned process, used to correlate streamed output and exit notifications. /// ///
/// @@ -19117,12 +22001,12 @@ pub struct SessionPermissionsPathsAddResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPermissionsPathsUpdatePrimaryResult { - /// Whether the operation succeeded - pub success: bool, +pub struct SessionShellExecResult { + /// Unique identifier for tracking streamed output + pub process_id: String, } -/// Indicates whether the supplied path is within the session's allowed directories. +/// Indicates whether the signal was delivered; false if the process was unknown or already exited. /// ///
/// @@ -19132,12 +22016,12 @@ pub struct SessionPermissionsPathsUpdatePrimaryResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPermissionsPathsIsPathWithinAllowedDirectoriesResult { - /// Whether the path is within the session's allowed directories - pub allowed: bool, +pub struct SessionShellKillResult { + /// Whether the signal was sent successfully + pub killed: bool, } -/// Indicates whether the supplied path is within the session's workspace directory. +/// Result of a user-requested shell command. /// ///
/// @@ -19147,12 +22031,22 @@ pub struct SessionPermissionsPathsIsPathWithinAllowedDirectoriesResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPermissionsPathsIsPathWithinWorkspaceResult { - /// Whether the path is within the session workspace directory - pub allowed: bool, +pub struct SessionShellExecuteUserRequestedResult { + /// Error output when the execution failed + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, + /// Process exit code, when available + #[serde(skip_serializing_if = "Option::is_none")] + pub exit_code: Option, + /// Captured command output + pub output: String, + /// Whether the command completed successfully + pub success: bool, + /// Tool call id emitted for the shell execution + pub tool_call_id: String, } -/// Resolved location-permissions key and type. +/// Cancellation result for a user-requested shell command. /// ///
/// @@ -19162,14 +22056,12 @@ pub struct SessionPermissionsPathsIsPathWithinWorkspaceResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPermissionsLocationsResolveResult { - /// Location key used in the location-permissions store - pub location_key: String, - /// Whether the location is a git repo or directory - pub location_type: PermissionLocationType, +pub struct SessionShellCancelUserRequestedResult { + /// Whether an in-flight execution was found and signalled to cancel + pub cancelled: bool, } -/// Summary of persisted location permissions applied to the session. +/// Compaction outcome with the number of tokens and messages removed, summary text, and the resulting context window breakdown. /// ///
/// @@ -19179,22 +22071,22 @@ pub struct SessionPermissionsLocationsResolveResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPermissionsLocationsApplyResult { - /// Number of persisted allowed directories added to the live path manager - pub applied_directory_count: i64, - /// Number of location-scoped rules added to the live permission service - pub applied_rule_count: i64, - /// Location-scoped rules applied to the live permission service - pub applied_rules: Vec, - /// Whether a different location was applied since the previous apply call - pub changed: bool, - /// Location key used in the location-permissions store - pub location_key: String, - /// Whether the location is a git repo or directory - pub location_type: PermissionLocationType, +pub struct SessionHistoryCompactResult { + /// Post-compaction context window usage breakdown + #[serde(skip_serializing_if = "Option::is_none")] + pub context_window: Option, + /// Number of messages removed during compaction + pub messages_removed: i64, + /// Whether compaction completed successfully + pub success: bool, + /// Summary text produced by compaction. Omitted when compaction did not produce a summary (e.g. failure path). + #[serde(skip_serializing_if = "Option::is_none")] + pub summary_content: Option, + /// Number of tokens freed by compaction + pub tokens_removed: i64, } -/// Indicates whether the operation succeeded. +/// Number of events that were removed by the truncation. /// ///
/// @@ -19204,12 +22096,18 @@ pub struct SessionPermissionsLocationsApplyResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPermissionsLocationsAddToolApprovalResult { - /// Whether the operation succeeded - pub success: bool, +pub struct SessionHistoryTruncateResult { + /// Failure detail when checkpointCleanupFailed is true. + #[serde(skip_serializing_if = "Option::is_none")] + pub checkpoint_cleanup_error: Option, + /// True when conversation truncation succeeded but post-truncation workspace checkpoint cleanup failed. History is already truncated; callers may still prune snapshots but should report a checkpoint-cleanup rather than a truncation failure. + #[serde(skip_serializing_if = "Option::is_none")] + pub checkpoint_cleanup_failed: Option, + /// Number of events that were removed + pub events_removed: i64, } -/// Folder trust check result. +/// Identifies the target session. /// ///
/// @@ -19219,12 +22117,12 @@ pub struct SessionPermissionsLocationsAddToolApprovalResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPermissionsFolderTrustIsTrustedResult { - /// Whether the folder is trusted - pub trusted: bool, +pub struct SessionHistoryListRewindPointsParams { + /// Target session identifier + pub session_id: SessionId, } -/// Indicates whether the operation succeeded. +/// Rewind points and file-change-tracking availability for the session. /// ///
/// @@ -19234,12 +22132,17 @@ pub struct SessionPermissionsFolderTrustIsTrustedResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPermissionsFolderTrustAddTrustedResult { - /// Whether the operation succeeded - pub success: bool, +pub struct SessionHistoryListRewindPointsResult { + /// Whether this session captured file changes from its first turn. + pub file_change_tracking_enabled: bool, + /// Root user turns in chronological order. Empty when `unavailableReason` is set. + pub points: Vec, + /// Why the listed points could not be produced, when applicable; the points list is empty whenever it is set. `unsupported-remote-session` is permanent for the session and comes with `fileChangeTrackingEnabled: false`. `session-busy` is transient and only ever reported by a session that *is* tracking (`fileChangeTrackingEnabled: true`), because the file-change captures cannot be read while work that may still mutate them is in flight; the same request succeeds once the session settles, so a client that wants points should retry rather than treat it as a failure. It is never `file-change-tracking-disabled`: an untracked local session still lists conversation-only points and reports that through `fileChangeTrackingEnabled: false`. + #[serde(skip_serializing_if = "Option::is_none")] + pub unavailable_reason: Option, } -/// Indicates whether the operation succeeded. +/// Files and aggregate changes for a prospective rewind. /// ///
/// @@ -19249,12 +22152,19 @@ pub struct SessionPermissionsFolderTrustAddTrustedResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionPermissionsUrlsSetUnrestrictedModeResult { - /// Whether the operation succeeded - pub success: bool, +pub struct SessionHistoryPreviewRewindResult { + /// Whether file restore is available for this session. This is authoritative: switch on it and read `reason` only when it is false. + pub available: bool, + /// Number of unique files in the preview. + pub file_count: i64, + /// Files ordered by path. + pub files: Vec, + /// Why file restore is unavailable, when applicable. Populated only when `available` is false and never set when `available` is true. + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, } -/// Identifier of the session event that was emitted for the log message. +/// Structured outcome of a rewind request. /// ///
/// @@ -19264,9 +22174,19 @@ pub struct SessionPermissionsUrlsSetUnrestrictedModeResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionLogResult { - /// The unique identifier of the emitted session event - pub event_id: String, +pub struct SessionHistoryRewindResult { + /// Failure detail. Set only for the failure and partial-failure outcomes (`files-rolled-back`, `rollback-incomplete`, `truncation-failed`, `checkpoint-cleanup-failed`, `snapshot-prune-failed`); omitted for `success` and for the unavailable outcomes (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`). + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, + /// Number of persisted events removed by conversation truncation. Present only when truncation succeeded (outcomes `success`, `checkpoint-cleanup-failed`, and `snapshot-prune-failed`); omitted for every unavailable outcome (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`) and for `truncation-failed`, `files-rolled-back`, and `rollback-incomplete`. + #[serde(skip_serializing_if = "Option::is_none")] + pub events_removed: Option, + /// Overall rewind outcome. This discriminates the result: it governs which of the remaining fields are populated, so consumers must switch on it before reading `eventsRemoved`, `restoredFiles`, `skippedFiles`, or `error`. See each field for the outcomes that populate it. + pub outcome: HistoryRewindOutcome, + /// Absolute paths restored to their captured preimages. Always empty for conversation-only rewinds and for the unavailable outcomes (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`); only conversation-and-files outcomes that reached the file-restore stage populate it. + pub restored_files: Vec, + /// Captured files intentionally left unchanged. Always empty for conversation-only rewinds and for the unavailable outcomes (`session-busy`, `file-change-tracking-disabled`, `unsupported-remote-session`); only conversation-and-files outcomes that reached the file-restore stage populate it. + pub skipped_files: Vec, } /// Identifies the target session. @@ -19279,47 +22199,12 @@ pub struct SessionLogResult { /// #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMetadataSnapshotParams { +pub struct SessionHistoryCancelBackgroundCompactionParams { /// Target session identifier pub session_id: SessionId, } -/// Public-facing projection of workspace metadata for SDK / TUI consumers -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionMetadataSnapshotResultWorkspace { - /// Branch checked out at session start, if any - #[serde(skip_serializing_if = "Option::is_none")] - pub branch: Option, - /// ISO 8601 timestamp when the workspace was created - #[serde(rename = "created_at", skip_serializing_if = "Option::is_none")] - pub created_at: Option, - /// Current working directory at session start - #[serde(skip_serializing_if = "Option::is_none")] - pub cwd: Option, - /// Resolved git root for cwd, if any - #[serde(rename = "git_root", skip_serializing_if = "Option::is_none")] - pub git_root: Option, - /// Repository host type, if known - #[serde(rename = "host_type", skip_serializing_if = "Option::is_none")] - pub host_type: Option, - /// Workspace identifier (1:1 with sessionId) - pub id: String, - /// Display name for the session, if set - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option, - /// Repository identifier in 'owner/repo' or 'org/project/repo' format, if any - #[serde(skip_serializing_if = "Option::is_none")] - pub repository: Option, - /// ISO 8601 timestamp when the workspace was last updated - #[serde(rename = "updated_at", skip_serializing_if = "Option::is_none")] - pub updated_at: Option, - /// Whether the display name was explicitly set by the user - #[serde(rename = "user_named", skip_serializing_if = "Option::is_none")] - pub user_named: Option, -} - -/// Point-in-time snapshot of slow-changing session identifier and state fields +/// Indicates whether an in-progress background compaction was cancelled. /// ///
/// @@ -19329,42 +22214,9 @@ pub struct SessionMetadataSnapshotResultWorkspace { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMetadataSnapshotResult { - /// True when the session was detected to be in use by another process at construction time. Local consumers may surface a confirmation prompt before fully attaching. Always false for new sessions. - pub already_in_use: bool, - /// Runtime client name associated with the session (telemetry identifier). - #[serde(skip_serializing_if = "Option::is_none")] - pub client_name: Option, - /// The current agent mode for this session (e.g., 'interactive', 'plan', 'autopilot') - pub current_mode: MetadataSnapshotCurrentMode, - /// User-provided name supplied at session construction (via `--name`), if any. Immutable after construction. - #[serde(skip_serializing_if = "Option::is_none")] - pub initial_name: Option, - /// Whether this is a remote session (i.e., one whose runtime executes elsewhere and is steered through this process) - pub is_remote: bool, - /// ISO 8601 timestamp of when the session's persisted state was last modified on disk. For new sessions, equals startTime. For resumed sessions, reflects the previous modification time at construction. - pub modified_time: String, - /// Remote-session-specific metadata. Populated only when `isRemote` is true. Fields are immutable for the lifetime of the session. - #[serde(skip_serializing_if = "Option::is_none")] - pub remote_metadata: Option, - /// Currently selected model identifier, if any - #[serde(skip_serializing_if = "Option::is_none")] - pub selected_model: Option, - /// The unique identifier of the session - pub session_id: SessionId, - /// Current session limits, or null when no limits are active - pub session_limits: Option, - /// ISO 8601 timestamp of when the session started - pub start_time: String, - /// Short human-readable summary of the session, if known. Omitted when no summary has been generated. - #[serde(skip_serializing_if = "Option::is_none")] - pub summary: Option, - /// Absolute path to the session's current working directory - pub working_directory: String, - /// 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). - pub workspace: Option, - /// Absolute path to the session's workspace directory on disk, or null if the session has no associated workspace - pub workspace_path: Option, +pub struct SessionHistoryCancelBackgroundCompactionResult { + /// Whether an in-progress background compaction was cancelled. False when no compaction was running, when the session is remote, or when the underlying processor was unavailable. + pub cancelled: bool, } /// Identifies the target session. @@ -19377,12 +22229,12 @@ pub struct SessionMetadataSnapshotResult { /// #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMetadataIsProcessingParams { +pub struct SessionHistoryAbortManualCompactionParams { /// Target session identifier pub session_id: SessionId, } -/// Indicates whether the local session is currently processing a turn or background continuation. +/// Indicates whether an in-progress manual compaction was aborted. /// ///
/// @@ -19392,9 +22244,9 @@ pub struct SessionMetadataIsProcessingParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMetadataIsProcessingResult { - /// Whether the session is currently processing user/agent messages. False for non-local sessions (which don't run a local agentic loop). Reflects an in-flight turn or background continuation. - pub processing: bool, +pub struct SessionHistoryAbortManualCompactionResult { + /// Whether an in-progress manual compaction was aborted. False when no manual compaction was running, when its abort controller was already aborted, or when the session is remote. + pub aborted: bool, } /// Identifies the target session. @@ -19407,12 +22259,12 @@ pub struct SessionMetadataIsProcessingResult { /// #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMetadataActivityParams { +pub struct SessionHistorySummarizeForHandoffParams { /// Target session identifier pub session_id: SessionId, } -/// Current activity flags for the session. +/// Markdown summary of the conversation context (empty when not available). /// ///
/// @@ -19422,40 +22274,27 @@ pub struct SessionMetadataActivityParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMetadataActivityResult { - /// Whether an in-flight operation can currently be aborted. - pub abortable: bool, - /// Whether the session currently has active work, including running turns or tasks. - pub has_active_work: bool, +pub struct SessionHistorySummarizeForHandoffResult { + /// Markdown summary of the conversation context produced by an LLM. Empty string when there are no messages or when the session does not support local summarization. + pub summary: String, } -/// Token-usage breakdown for the session's current context window +/// 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 SessionMetadataContextInfoResultContextInfo { - /// Output reserve plus tokens after the buffer-exhaustion blocking threshold (default 95%) - pub buffer_tokens: i64, - /// Token count at which background compaction starts (configurable percentage of promptTokenLimit) - pub compaction_threshold: i64, - /// Tokens consumed by user/assistant/tool messages - pub conversation_tokens: i64, - /// Prompt token limit plus the model's full output token limit. - pub limit: i64, - /// Tokens consumed by MCP tool definitions (subset of toolDefinitionsTokens, excludes deferred tools) - pub mcp_tools_tokens: i64, - /// The model used for token counting - pub model_name: String, - /// Maximum prompt tokens allowed by the model (or DEFAULT_TOKEN_LIMIT if unspecified) - pub prompt_token_limit: i64, - /// Tokens consumed by the system prompt - pub system_tokens: i64, - /// Tokens consumed by tool definitions sent to the model (excludes deferred tools) - pub tool_definitions_tokens: i64, - /// Sum of system, conversation and tool-definition tokens - pub total_tokens: i64, +pub struct SessionQueuePendingItemsParams { + /// Target session identifier + pub session_id: SessionId, } -/// Token breakdown for the session's current context window, or null if uninitialized. +/// Snapshot of the session's pending queued items and immediate-steering messages. /// ///
/// @@ -19465,9 +22304,11 @@ pub struct SessionMetadataContextInfoResultContextInfo { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMetadataContextInfoResult { - /// Token breakdown for the current context window, or null if the session has not yet been initialized (no system prompt or tool metadata cached). - pub context_info: Option, +pub struct SessionQueuePendingItemsResult { + /// Pending queued items in submission order. Includes user messages, queued slash commands, and queued model changes; omits internal system items. + pub items: Vec, + /// Display text for messages currently in the immediate steering queue (interjections sent during a running turn). + pub steering_messages: Vec, } /// Identifies the target session. @@ -19480,51 +22321,12 @@ pub struct SessionMetadataContextInfoResult { /// #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMetadataGetContextAttributionParams { +pub struct SessionQueueSnapshotParams { /// Target session identifier pub session_id: SessionId, } -/// Successful compaction history for the session. -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionMetadataGetContextAttributionResultContextAttributionCompactions { - /// Number of successful compactions in this session. - pub count: i64, -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionMetadataGetContextAttributionResultContextAttributionEntriesItem { - /// Supplementary per-entry metadata (e.g. `messageCount`, `role`, `evictable`, `pluginSource`). Values are stringified; parse as needed and ignore unrecognized keys. - #[serde(skip_serializing_if = "Option::is_none")] - pub attributes: Option>, - /// Identifier for this entry, formed by joining its `kind` and source name (e.g. `tool:bash`, `skill:tmux`, `toolDefinition:bash`); unique within the snapshot. Use it to match the same entry across snapshots, to correlate with other APIs (skill/agent/MCP registries), and as the `parentId` target for nesting. Distinct from the human-facing `label`. - pub id: String, - /// Source category for this entry. Not a closed set — tolerate unknown values. Known values today: `skill`, `subagent`, `mcpServer`, `tool`, `system`, `toolDefinition`, `plugin`. - pub kind: String, - /// Human-readable display label, e.g. `bash` or `skill: tmux`. Presentation-only; may be localized/reformatted without notice — do not key off it. - pub label: String, - /// Optional `id` of the parent entry: e.g. a `plugin` entry parenting its `skill`/`mcpServer` entries, or the `system` entry parenting `toolDefinition` entries. Omitted for top-level entries. - #[serde(skip_serializing_if = "Option::is_none")] - pub parent_id: Option, - /// Token count currently in context attributable to this entry. - pub tokens: i64, -} - -/// Per-source token attribution snapshot for the current context window. The heaviest individual messages are available separately via `metadata.getContextHeaviestMessages`. -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionMetadataGetContextAttributionResultContextAttribution { - /// Successful compaction history for the session. - pub compactions: SessionMetadataGetContextAttributionResultContextAttributionCompactions, - /// Flat list of per-source attribution entries. Group by `kind` and render unrecognized kinds generically. Nesting and rollups are expressed via `parentId`. - pub entries: Vec, - /// Total token count of the current context window the entries are measured against (system message + conversation messages + tool definitions — the same total reported by /context). Divide an entry's `tokens` by this to derive its share. - pub total_tokens: i64, -} - -/// Per-source attribution breakdown for the session's current context window, or null if uninitialized. +/// Internal snapshot of native queue state for local session orchestration. /// ///
/// @@ -19534,12 +22336,20 @@ pub struct SessionMetadataGetContextAttributionResultContextAttribution { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMetadataGetContextAttributionResult { - /// Per-source context-window attribution, or null if the session has not yet been initialized (no system prompt or tool metadata cached). - pub context_attribution: Option, +pub struct SessionQueueSnapshotResult { + /// Insertion orders for queued items, aligned with `items`. + #[serde(skip_serializing_if = "Option::is_none")] + pub item_orders: Option>, + /// User-facing pending items in FIFO order. + pub items: Vec, + /// Insertion orders for immediate steering messages, aligned with `steeringMessages`. + #[serde(skip_serializing_if = "Option::is_none")] + pub steering_message_orders: Option>, + /// Immediate steering messages waiting for an active turn. + pub steering_messages: Vec, } -/// The heaviest individual messages in the session's context window, most-expensive first. +/// Result of moving a queued item. /// ///
/// @@ -19549,14 +22359,12 @@ pub struct SessionMetadataGetContextAttributionResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMetadataGetContextHeaviestMessagesResult { - /// Heaviest messages, most-expensive first. - pub messages: Vec, - /// Total token count of the current context window, so callers can compute each message's share without a second call. - pub total_tokens: i64, +pub struct SessionQueueMoveItemResult { + /// True when the item changed position; false when it was already at the requested position. + pub changed: bool, } -/// Notify the session that its working directory context has changed. Emits a `session.context_changed` event so consumers (telemetry, OTel tracker, ACP, the timeline UI) can react. Use this when the host has detected a cwd/branch/repo change outside the session's normal lifecycle (e.g., after a shell command in interactive mode). For a local session, a report whose `cwd` diverges from the session's current working directory is ignored (the call still succeeds but records nothing and emits no event); move a local session's working directory via `metadata.setWorkingDirectory` instead. +/// Result of inserting a queued message. /// ///
/// @@ -19566,9 +22374,12 @@ pub struct SessionMetadataGetContextHeaviestMessagesResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMetadataRecordContextChangeResult {} +pub struct SessionQueueInsertAtResult { + /// Fresh stable opaque id assigned to the inserted item. + pub id: String, +} -/// Update the session's working directory. Used by the host when the user explicitly changes cwd (e.g., the `/cd` slash command). The host is responsible for any related side-effects (file index, etc.); it does NOT change the process working directory (a session's cwd is per-session, not process-global). For local sessions the runtime validates the target first (an absolute path that exists on disk) and re-bases the permission primary directory; a rejected validation fails the call before anything is mutated, persisted, or emitted. Location-scoped permission rules are then re-keyed to the new directory (best-effort). Remote sessions only record the path. +/// Result of removing a queued item. /// ///
/// @@ -19578,12 +22389,12 @@ pub struct SessionMetadataRecordContextChangeResult {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMetadataSetWorkingDirectoryResult { - /// Working directory after the update - pub working_directory: String, +pub struct SessionQueueRemoveAtResult { + /// True when the addressed item was removed. + pub removed: bool, } -/// Re-tokenize the session's existing messages against `modelId` and return the token totals. Useful for hosts that want an initial estimate of context usage on session resume, before the next agent turn fires `session.context_info_changed` events. Returns zeros for an empty session. +/// Result of editing a queued message. /// ///
/// @@ -19593,16 +22404,12 @@ pub struct SessionMetadataSetWorkingDirectoryResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionMetadataRecomputeContextTokensResult { - /// Tokens contributed by user/assistant/tool messages (excludes system/developer prompts). - pub messages_token_count: i64, - /// Tokens contributed by system/developer prompt snapshots. - pub system_token_count: i64, - /// Sum of tokens across chat-context and system-context messages currently held by the session. - pub total_tokens: i64, +pub struct SessionQueueUpdateTextResult { + /// True when the stored text changed. + pub updated: bool, } -/// Identifies the target session. +/// Result of duplicating a queued item. /// ///
/// @@ -19612,12 +22419,12 @@ pub struct SessionMetadataRecomputeContextTokensResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSettingsSnapshotParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionQueueDuplicateAtResult { + /// Fresh stable opaque id assigned to the duplicate. + pub id: String, } -/// Redacted, serializable view of session runtime settings for SDK boundary consumers. Secrets and raw feature flags are intentionally excluded. +/// Result of trying to steer a queued message into a live turn. /// ///
/// @@ -19627,23 +22434,12 @@ pub struct SessionSettingsSnapshotParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionSettingsSnapshotResult { - #[serde(skip_serializing_if = "Option::is_none")] - pub client_name: Option, - pub job: SessionSettingsJobSnapshot, - pub model: SessionSettingsModelSnapshot, - pub online_evaluation: SessionSettingsOnlineEvaluationSnapshot, - pub repo: SessionSettingsRepoSnapshot, - #[serde(skip_serializing_if = "Option::is_none")] - pub start_time_ms: Option, - #[serde(skip_serializing_if = "Option::is_none")] - pub timeout_ms: Option, - pub validation: SessionSettingsValidationSnapshot, - #[serde(skip_serializing_if = "Option::is_none")] - pub version: Option, +pub struct SessionQueueSendNowResult { + /// True when the item was accepted into the steering lane; false when no main turn was live. + pub steered: bool, } -/// Identifier of the spawned process, used to correlate streamed output and exit notifications. +/// Identifies the target session. /// ///
/// @@ -19653,12 +22449,12 @@ pub struct SessionSettingsSnapshotResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionShellExecResult { - /// Unique identifier for tracking streamed output - pub process_id: String, +pub struct SessionQueueHasPendingParams { + /// Target session identifier + pub session_id: SessionId, } -/// Indicates whether the signal was delivered; false if the process was unknown or already exited. +/// Whether the native queue has pending work. /// ///
/// @@ -19668,12 +22464,12 @@ pub struct SessionShellExecResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionShellKillResult { - /// Whether the signal was sent successfully - pub killed: bool, +pub struct SessionQueueHasPendingResult { + /// True when queued or immediate native work is pending. + pub has_pending: bool, } -/// Result of a user-requested shell command. +/// Whether a deferred-idle drain should run. /// ///
/// @@ -19683,22 +22479,12 @@ pub struct SessionShellKillResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionShellExecuteUserRequestedResult { - /// Error output when the execution failed - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - /// Process exit code, when available - #[serde(skip_serializing_if = "Option::is_none")] - pub exit_code: Option, - /// Captured command output - pub output: String, - /// Whether the command completed successfully - pub success: bool, - /// Tool call id emitted for the shell execution - pub tool_call_id: String, +pub struct SessionQueueBeginDeferredIdleDrainResult { + /// True when the host should run finishDeferredIdleDrain asynchronously. + pub should_drain: bool, } -/// Cancellation result for a user-requested shell command. +/// Action selected by the native deferred-idle drain. /// ///
/// @@ -19708,12 +22494,14 @@ pub struct SessionShellExecuteUserRequestedResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionShellCancelUserRequestedResult { - /// Whether an in-flight execution was found and signalled to cancel - pub cancelled: bool, +pub struct SessionQueueFinishDeferredIdleDrainResult { + /// Whether the deferred idle was caused by an aborted foreground turn. + pub aborted: bool, + /// One of none, processQueue, or emitSessionIdle. + pub action: String, } -/// Compaction outcome with the number of tokens and messages removed, summary text, and the resulting context window breakdown. +/// Identifies the target session. /// ///
/// @@ -19723,22 +22511,12 @@ pub struct SessionShellCancelUserRequestedResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionHistoryCompactResult { - /// Post-compaction context window usage breakdown - #[serde(skip_serializing_if = "Option::is_none")] - pub context_window: Option, - /// Number of messages removed during compaction - pub messages_removed: i64, - /// Whether compaction completed successfully - pub success: bool, - /// Summary text produced by compaction. Omitted when compaction did not produce a summary (e.g. failure path). - #[serde(skip_serializing_if = "Option::is_none")] - pub summary_content: Option, - /// Number of tokens freed by compaction - pub tokens_removed: i64, +pub struct SessionQueueRemoveMostRecentParams { + /// Target session identifier + pub session_id: SessionId, } -/// Number of events that were removed by the truncation. +/// Indicates whether a user-facing pending item was removed. /// ///
/// @@ -19748,9 +22526,9 @@ pub struct SessionHistoryCompactResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionHistoryTruncateResult { - /// Number of events that were removed - pub events_removed: i64, +pub struct SessionQueueRemoveMostRecentResult { + /// True if a user-facing pending item was removed (LIFO across both queues); false when no removable items remained. + pub removed: bool, } /// Identifies the target session. @@ -19763,12 +22541,12 @@ pub struct SessionHistoryTruncateResult { /// #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionHistoryCancelBackgroundCompactionParams { +pub struct SessionQueueClearParams { /// Target session identifier pub session_id: SessionId, } -/// Indicates whether an in-progress background compaction was cancelled. +/// Indicates whether a user-facing pending item was removed. /// ///
/// @@ -19778,9 +22556,9 @@ pub struct SessionHistoryCancelBackgroundCompactionParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionHistoryCancelBackgroundCompactionResult { - /// Whether an in-progress background compaction was cancelled. False when no compaction was running, when the session is remote, or when the underlying processor was unavailable. - pub cancelled: bool, +pub struct SessionQueueConsumeSystemNotificationsResult { + /// True if a user-facing pending item was removed (LIFO across both queues); false when no removable items remained. + pub removed: bool, } /// Identifies the target session. @@ -19793,12 +22571,12 @@ pub struct SessionHistoryCancelBackgroundCompactionResult { /// #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionHistoryAbortManualCompactionParams { +pub struct SessionQueueEnqueueResumePendingParams { /// Target session identifier pub session_id: SessionId, } -/// Indicates whether an in-progress manual compaction was aborted. +/// Result of enqueueing the resume-pending wake item. /// ///
/// @@ -19808,9 +22586,9 @@ pub struct SessionHistoryAbortManualCompactionParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionHistoryAbortManualCompactionResult { - /// Whether an in-progress manual compaction was aborted. False when no manual compaction was running, when its abort controller was already aborted, or when the session is remote. - pub aborted: bool, +pub struct SessionQueueEnqueueResumePendingResult { + /// True when a wake item was newly queued. + pub queued: bool, } /// Identifies the target session. @@ -19823,12 +22601,12 @@ pub struct SessionHistoryAbortManualCompactionResult { /// #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionHistorySummarizeForHandoffParams { +pub struct SessionQueueProcessParams { /// Target session identifier pub session_id: SessionId, } -/// Markdown summary of the conversation context (empty when not available). +/// Batch of session events returned by a read, with cursor and continuation metadata. /// ///
/// @@ -19838,9 +22616,15 @@ pub struct SessionHistorySummarizeForHandoffParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionHistorySummarizeForHandoffResult { - /// Markdown summary of the conversation context produced by an LLM. Empty string when there are no messages or when the session does not support local summarization. - pub summary: String, +pub struct SessionEventLogReadResult { + /// Opaque cursor for the next read. Pass back unchanged in the next read.cursor to continue from where this read left off. Always present, even when no events were returned. + pub cursor: String, + /// Cursor status: 'ok' means the cursor was applied successfully; 'expired' means the cursor referred to an event that no longer exists in history (e.g. truncated or compacted away) and the read started from the beginning of the remaining history. + pub cursor_status: EventsCursorStatus, + /// Session events for this batch, merged into a single stream in creation order: durable (persisted) events and ephemeral events interleave exactly as they were emitted. Set `includeEphemeral: false` to receive only durable events. Ephemeral events are never replayable once pruned from the in-memory ring, so a consumer that needs them should keep reading with a non-zero `waitMs`. + pub events: Vec, + /// True when the read returned `max` events and more events are available immediately. When false, the next read with a non-zero `waitMs` will block until a new event arrives or the wait expires. + pub has_more: bool, } /// Identifies the target session. @@ -19853,12 +22637,12 @@ pub struct SessionHistorySummarizeForHandoffResult { /// #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionQueuePendingItemsParams { +pub struct SessionEventLogTailParams { /// Target session identifier pub session_id: SessionId, } -/// Snapshot of the session's pending queued items and immediate-steering messages. +/// Snapshot of the current tail cursor without returning any events. Use this when a consumer wants to subscribe to live events going forward without first paginating through the entire persisted history (which would happen if `read` were called without a cursor on a long-lived session). /// ///
/// @@ -19868,14 +22652,12 @@ pub struct SessionQueuePendingItemsParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionQueuePendingItemsResult { - /// Pending queued items in submission order. Includes user messages, queued slash commands, and queued model changes; omits internal system items. - pub items: Vec, - /// Display text for messages currently in the immediate steering queue (interjections sent during a running turn). - pub steering_messages: Vec, +pub struct SessionEventLogTailResult { + /// Opaque cursor pointing at the current tail of the session's persisted-events history. Pass back to `read` to receive only events that arrive AFTER this snapshot. When the session has no events, this returns the same sentinel as an unset cursor (i.e. equivalent to omitting the cursor on a first read). + pub cursor: String, } -/// Identifies the target session. +/// Opaque handle representing an event-type interest registration. /// ///
/// @@ -19885,12 +22667,12 @@ pub struct SessionQueuePendingItemsResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionQueueRemoveMostRecentParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionEventLogRegisterInterestResult { + /// Opaque handle for this registration. Pass to releaseInterest to release. Each call to registerInterest produces a fresh handle, even when the same eventType is registered multiple times. + pub handle: String, } -/// Indicates whether a user-facing pending item was removed. +/// Indicates whether the operation succeeded. /// ///
/// @@ -19900,9 +22682,9 @@ pub struct SessionQueueRemoveMostRecentParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionQueueRemoveMostRecentResult { - /// True if a user-facing pending item was removed (LIFO across both queues); false when no removable items remained. - pub removed: bool, +pub struct SessionEventLogReleaseInterestResult { + /// Whether the operation succeeded + pub success: bool, } /// Identifies the target session. @@ -19915,12 +22697,12 @@ pub struct SessionQueueRemoveMostRecentResult { /// #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionQueueClearParams { +pub struct SessionUsageGetMetricsParams { /// Target session identifier pub session_id: SessionId, } -/// Batch of session events returned by a read, with cursor and continuation metadata. +/// Accumulated session usage metrics, including premium request cost, token counts, model breakdown, and code-change totals. /// ///
/// @@ -19930,15 +22712,50 @@ pub struct SessionQueueClearParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionEventLogReadResult { - /// Opaque cursor for the next read. Pass back unchanged in the next read.cursor to continue from where this read left off. Always present, even when no events were returned. - pub cursor: String, - /// Cursor status: 'ok' means the cursor was applied successfully; 'expired' means the cursor referred to an event that no longer exists in history (e.g. truncated or compacted away) and the read started from the beginning of the remaining history. - pub cursor_status: EventsCursorStatus, - /// Events are delivered in two batches per read: persisted events first (in append order), then ephemeral events (in seq order). When `waitMs > 0` and the catch-up batches were empty, post-wait events follow the same two-batch ordering. Persisted and ephemeral events do not interleave within a single read. - pub events: Vec, - /// True when the read returned `max` events and more events are available immediately. When false, the next read with a non-zero `waitMs` will block until a new event arrives or the wait expires. - pub has_more: bool, +pub struct SessionUsageGetMetricsResult { + /// Aggregated code change metrics + pub code_changes: UsageMetricsCodeChanges, + /// Currently active model identifier + #[serde(skip_serializing_if = "Option::is_none")] + pub current_model: Option, + /// Input tokens from the most recent main-agent API call + pub last_call_input_tokens: i64, + /// Output tokens from the most recent main-agent API call + pub last_call_output_tokens: i64, + /// Per-model token and request metrics, keyed by model identifier + pub model_metrics: HashMap, + /// ISO 8601 timestamp when the session started + pub session_start_time: String, + /// Session-wide per-token-type accumulated token counts + #[serde(skip_serializing_if = "Option::is_none")] + pub token_details: Option>, + /// Total time spent in model API calls (milliseconds) + pub total_api_duration_ms: i64, + /// Session-wide accumulated nano-AI units cost + #[serde(skip_serializing_if = "Option::is_none")] + pub total_nano_aiu: Option, + /// Total user-initiated premium request cost across all models (may be fractional due to multipliers) + pub total_premium_request_cost: f64, + /// Raw count of user-initiated API requests + pub total_user_requests: i64, +} + +/// GitHub URL for the session and a flag indicating whether remote steering is enabled. +/// +///
+/// +/// **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 SessionRemoteEnableResult { + /// Whether remote steering is enabled + pub remote_steerable: bool, + /// GitHub frontend URL for this session + #[serde(skip_serializing_if = "Option::is_none")] + pub url: Option, } /// Identifies the target session. @@ -19951,12 +22768,12 @@ pub struct SessionEventLogReadResult { /// #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionEventLogTailParams { +pub struct SessionRemoteDisableParams { /// Target session identifier pub session_id: SessionId, } -/// Snapshot of the current tail cursor without returning any events. Use this when a consumer wants to subscribe to live events going forward without first paginating through the entire persisted history (which would happen if `read` were called without a cursor on a long-lived session). +/// Persist a steerability change as a `session.remote_steerable_changed` event. Used by the host (CLI / SDK consumer) when it has just finished enabling or disabling steering on a remote exporter that the runtime does not directly own. /// ///
/// @@ -19966,12 +22783,24 @@ pub struct SessionEventLogTailParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionEventLogTailResult { - /// Opaque cursor pointing at the current tail of the session's persisted-events history. Pass back to `read` to receive only events that arrive AFTER this snapshot. When the session has no events, this returns the same sentinel as an unset cursor (i.e. equivalent to omitting the cursor on a first read). - pub cursor: String, +pub struct SessionRemoteNotifySteerableChangedResult {} + +/// 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 SessionVisibilityGetParams { + /// Target session identifier + pub session_id: SessionId, } -/// Opaque handle representing an event-type interest registration. +/// Current sharing status and shareable GitHub URL for a session. /// ///
/// @@ -19981,12 +22810,18 @@ pub struct SessionEventLogTailResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionEventLogRegisterInterestResult { - /// Opaque handle for this registration. Pass to releaseInterest to release. Each call to registerInterest produces a fresh handle, even when the same eventType is registered multiple times. - pub handle: String, +pub struct SessionVisibilityGetResult { + /// Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. + #[serde(skip_serializing_if = "Option::is_none")] + pub share_url: Option, + /// Current sharing status. Absent when the session is not synced or the status could not be retrieved (e.g. the user is not authenticated). + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, + /// Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the session cannot be shared and `status`/`shareUrl` are absent. + pub synced: bool, } -/// Indicates whether the operation succeeded. +/// Effective sharing status and shareable GitHub URL after updating session visibility. /// ///
/// @@ -19996,9 +22831,15 @@ pub struct SessionEventLogRegisterInterestResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionEventLogReleaseInterestResult { - /// Whether the operation succeeded - pub success: bool, +pub struct SessionVisibilitySetResult { + /// Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. + #[serde(skip_serializing_if = "Option::is_none")] + pub share_url: Option, + /// Effective sharing status after the update. May differ from the requested status for task types that are already visible to repository readers by default. Absent when the update could not be applied (e.g. the session is not synced or the user is not authenticated). + #[serde(skip_serializing_if = "Option::is_none")] + pub status: Option, + /// Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the visibility change could not be applied and `status`/`shareUrl` are absent. + pub synced: bool, } /// Identifies the target session. @@ -20011,12 +22852,12 @@ pub struct SessionEventLogReleaseInterestResult { /// #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionUsageGetMetricsParams { +pub struct SessionScheduleListParams { /// Target session identifier pub session_id: SessionId, } -/// Accumulated session usage metrics, including premium request cost, token counts, model breakdown, and code-change totals. +/// Snapshot of the currently active recurring prompts for this session. /// ///
/// @@ -20026,35 +22867,12 @@ pub struct SessionUsageGetMetricsParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionUsageGetMetricsResult { - /// Aggregated code change metrics - pub code_changes: UsageMetricsCodeChanges, - /// Currently active model identifier - #[serde(skip_serializing_if = "Option::is_none")] - pub current_model: Option, - /// Input tokens from the most recent main-agent API call - pub last_call_input_tokens: i64, - /// Output tokens from the most recent main-agent API call - pub last_call_output_tokens: i64, - /// Per-model token and request metrics, keyed by model identifier - pub model_metrics: HashMap, - /// ISO 8601 timestamp when the session started - pub session_start_time: String, - /// Session-wide per-token-type accumulated token counts - #[serde(skip_serializing_if = "Option::is_none")] - pub token_details: Option>, - /// Total time spent in model API calls (milliseconds) - pub total_api_duration_ms: i64, - /// Session-wide accumulated nano-AI units cost - #[serde(skip_serializing_if = "Option::is_none")] - pub total_nano_aiu: Option, - /// Total user-initiated premium request cost across all models (may be fractional due to multipliers) - pub total_premium_request_cost: f64, - /// Raw count of user-initiated API requests - pub total_user_requests: i64, +pub struct SessionScheduleListResult { + /// Active scheduled prompts, ordered by id. + pub entries: Vec, } -/// GitHub URL for the session and a flag indicating whether remote steering is enabled. +/// Identifies the target session. /// ///
/// @@ -20064,12 +22882,9 @@ pub struct SessionUsageGetMetricsResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionRemoteEnableResult { - /// Whether remote steering is enabled - pub remote_steerable: bool, - /// GitHub frontend URL for this session - #[serde(skip_serializing_if = "Option::is_none")] - pub url: Option, +pub struct SessionScheduleHydrateParams { + /// Target session identifier + pub session_id: SessionId, } /// Identifies the target session. @@ -20082,12 +22897,12 @@ pub struct SessionRemoteEnableResult { /// #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionRemoteDisableParams { +pub struct SessionScheduleHasSelfPacedParams { /// Target session identifier pub session_id: SessionId, } -/// Persist a steerability change as a `session.remote_steerable_changed` event. Used by the host (CLI / SDK consumer) when it has just finished enabling or disabling steering on a remote exporter that the runtime does not directly own. +/// Whether the session currently has an active self-paced schedule. /// ///
/// @@ -20097,9 +22912,12 @@ pub struct SessionRemoteDisableParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionRemoteNotifySteerableChangedResult {} +pub struct SessionScheduleHasSelfPacedResult { + /// True when at least one active schedule is self-paced. + pub has_self_paced: bool, +} -/// Identifies the target session. +/// Result of registering or re-arming a scheduled prompt. /// ///
/// @@ -20109,12 +22927,16 @@ pub struct SessionRemoteNotifySteerableChangedResult {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionVisibilityGetParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionScheduleAddResult { + /// The registered or updated schedule entry. + #[serde(skip_serializing_if = "Option::is_none")] + pub entry: Option, + /// User-facing validation error, when registration failed. + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, } -/// Current sharing status and shareable GitHub URL for a session. +/// Result of registering or re-arming a scheduled prompt. /// ///
/// @@ -20124,18 +22946,16 @@ pub struct SessionVisibilityGetParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionVisibilityGetResult { - /// Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. +pub struct SessionScheduleAddCronResult { + /// The registered or updated schedule entry. #[serde(skip_serializing_if = "Option::is_none")] - pub share_url: Option, - /// Current sharing status. Absent when the session is not synced or the status could not be retrieved (e.g. the user is not authenticated). + pub entry: Option, + /// User-facing validation error, when registration failed. #[serde(skip_serializing_if = "Option::is_none")] - pub status: Option, - /// Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the session cannot be shared and `status`/`shareUrl` are absent. - pub synced: bool, + pub error: Option, } -/// Effective sharing status and shareable GitHub URL after updating session visibility. +/// Result of registering or re-arming a scheduled prompt. /// ///
/// @@ -20145,18 +22965,16 @@ pub struct SessionVisibilityGetResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionVisibilitySetResult { - /// Shareable GitHub URL for the session. Present when the session is synced and the URL can be resolved. +pub struct SessionScheduleAddAtResult { + /// The registered or updated schedule entry. #[serde(skip_serializing_if = "Option::is_none")] - pub share_url: Option, - /// Effective sharing status after the update. May differ from the requested status for task types that are already visible to repository readers by default. Absent when the update could not be applied (e.g. the session is not synced or the user is not authenticated). + pub entry: Option, + /// User-facing validation error, when registration failed. #[serde(skip_serializing_if = "Option::is_none")] - pub status: Option, - /// Whether the session has been synced to Mission Control (i.e. has a GitHub task). When false, the visibility change could not be applied and `status`/`shareUrl` are absent. - pub synced: bool, + pub error: Option, } -/// Identifies the target session. +/// Result of registering or re-arming a scheduled prompt. /// ///
/// @@ -20166,12 +22984,16 @@ pub struct SessionVisibilitySetResult { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionScheduleListParams { - /// Target session identifier - pub session_id: SessionId, +pub struct SessionScheduleAddSelfPacedResult { + /// The registered or updated schedule entry. + #[serde(skip_serializing_if = "Option::is_none")] + pub entry: Option, + /// User-facing validation error, when registration failed. + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, } -/// Snapshot of the currently active recurring prompts for this session. +/// Result of registering or re-arming a scheduled prompt. /// ///
/// @@ -20181,9 +23003,13 @@ pub struct SessionScheduleListParams { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct SessionScheduleListResult { - /// Active scheduled prompts, ordered by id. - pub entries: Vec, +pub struct SessionScheduleRearmSelfPacedResult { + /// The registered or updated schedule entry. + #[serde(skip_serializing_if = "Option::is_none")] + pub entry: Option, + /// User-facing validation error, when registration failed. + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, } /// Remove a scheduled prompt by id. The result entry is omitted if the id was unknown. @@ -20306,6 +23132,16 @@ pub type UIElicitationResponseContent = HashMap; /// pub type AccountGetAllUsersResult = Vec; +/// The number of running background agents (task-registry agents) that were cancelled. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+pub type SessionCancelAllBackgroundAgentsResult = i64; + /// Standard MCP CallToolResult /// ///
@@ -21364,6 +24200,86 @@ pub enum ExternalToolTextResultForLlmContentTextType { Text, } +/// Execution-critical factory storage operation. +/// +///
+/// +/// **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, PartialEq, Eq, Serialize, Deserialize)] +pub enum FactoryDurableOperation { + /// Creating the durable run and declared phases. + #[serde(rename = "createRun")] + CreateRun, + /// Persisting the transition to running. + #[serde(rename = "markRunStarted")] + MarkRunStarted, + /// Persisting the terminal run envelope. + #[serde(rename = "finishRun")] + FinishRun, + /// Persisting subagent admission accounting. + #[serde(rename = "reserveAgent")] + ReserveAgent, + /// Rolling back an uncommitted subagent admission. + #[serde(rename = "releaseAgent")] + ReleaseAgent, + /// Persisting an idempotent model-usage charge. + #[serde(rename = "chargeCredit")] + ChargeCredit, + /// Persisting active execution time. + #[serde(rename = "addElapsed")] + AddElapsed, + /// Reading the authoritative AI-credit total. + #[serde(rename = "reconcileCreditTotal")] + ReconcileCreditTotal, + /// Reading a journal entry without treating storage failure as a cache miss. + #[serde(rename = "journalGet")] + JournalGet, + /// Persisting a journal entry before reporting success. + #[serde(rename = "journalPut")] + JournalPut, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// Current or terminal state of a factory run. +/// +///
+/// +/// **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, PartialEq, Eq, Serialize, Deserialize)] +pub enum FactoryRunStatus { + /// The run was minted and is awaiting approval. + #[serde(rename = "pending")] + Pending, + /// The run is executing. + #[serde(rename = "running")] + Running, + /// The run completed successfully. + #[serde(rename = "completed")] + Completed, + /// The run was interrupted while resource budget remained. + #[serde(rename = "halted")] + Halted, + /// The run was cancelled before completion. + #[serde(rename = "cancelled")] + Cancelled, + /// The factory body failed or reached a cumulative resource ceiling. + #[serde(rename = "error")] + Error, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + /// Kind of factory progress line. /// ///
@@ -21386,6 +24302,34 @@ pub enum FactoryLogLineKind { Unknown, } +/// Derived lifecycle state of a factory phase. +/// +///
+/// +/// **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, PartialEq, Eq, Serialize, Deserialize)] +pub enum FactoryPhaseStatus { + /// The phase has not been entered yet. + #[serde(rename = "pending")] + Pending, + /// The phase is currently entered and accumulating active time. + #[serde(rename = "active")] + Active, + /// The phase was entered and has since been closed. + #[serde(rename = "completed")] + Completed, + /// The phase was never entered because a later phase was entered or the run reached a terminal state. + #[serde(rename = "skipped")] + Skipped, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + /// Cumulative resource ceiling that stopped a factory run. /// ///
@@ -21399,16 +24343,136 @@ pub enum FactoryRunFailureKind { /// The run admitted the approved maximum total number of subagents. #[serde(rename = "maxTotalSubagents")] MaxTotalSubagents, - /// The run reached the approved timeout deadline. - #[serde(rename = "timeout")] - Timeout, + /// The run reached the approved accumulated active-execution time in seconds. + #[serde(rename = "timeoutSeconds")] + TimeoutSeconds, + /// The run's settled subagent model usage exceeded the approved AI-credit ceiling, or no headroom remained for another subagent. + #[serde(rename = "maxAiCredits")] + MaxAiCredits, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// Authentication via the `gh` CLI's saved credentials. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum GhCliAuthInfoType { + #[serde(rename = "gh-cli")] + #[default] + GhCli, +} + +/// What initiated this compaction request, recorded as the `trigger` on the persisted `session.compaction_start` / `session.compaction_complete` events. When absent, the compaction is persisted without trigger attribution (initiator unknown). +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum HistoryCompactRequestTrigger { + /// User-requested compaction, e.g. the /compact command or a direct history.compact call. + #[serde(rename = "manual")] + Manual, + /// Compaction requested while switching to a model with a smaller context window. + #[serde(rename = "model_switch")] + ModelSwitch, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// Reason a captured file was not restored. +/// +///
+/// +/// **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, PartialEq, Eq, Serialize, Deserialize)] +pub enum HistoryFileRestoreSkipReason { + /// The file changed after Copilot's last captured write. + #[serde(rename = "user-modified")] + UserModified, + /// A faithful preimage was not captured. + #[serde(rename = "skipped-capture")] + SkippedCapture, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// Reason a rewind read (rewind points, file-restore preview, or session diff) could not be answered from the session's file-change captures. +/// +///
+/// +/// **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, PartialEq, Eq, Serialize, Deserialize)] +pub enum HistoryRewindUnavailableReason { + /// The session did not opt into file-change tracking before its first turn. + #[serde(rename = "file-change-tracking-disabled")] + FileChangeTrackingDisabled, + /// The session still has work that may mutate files or history. Transient: the same request succeeds once the session settles, so callers should retry rather than treat it as a failure. + #[serde(rename = "session-busy")] + SessionBusy, + /// Remote-backed rewind routing is not supported. + #[serde(rename = "unsupported-remote-session")] + UnsupportedRemoteSession, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// Aggregate file change represented by a rewind preview. +/// +///
+/// +/// **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, PartialEq, Eq, Serialize, Deserialize)] +pub enum HistoryRewindChangeType { + /// The discarded turns created the file. + #[serde(rename = "created")] + Created, + /// The discarded turns deleted the file. + #[serde(rename = "deleted")] + Deleted, + /// The discarded turns modified the file. + #[serde(rename = "modified")] + Modified, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// Scope of a rewind operation. +/// +///
+/// +/// **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, PartialEq, Eq, Serialize, Deserialize)] +pub enum HistoryRewindMode { + /// Discard conversation events while leaving files unchanged. + #[serde(rename = "conversation")] + Conversation, + /// Discard conversation events and restore captured files changed by those turns. + #[serde(rename = "conversation-and-files")] + ConversationAndFiles, /// Unknown variant for forward compatibility. #[default] #[serde(other)] Unknown, } -/// Current or terminal state of a factory run. +/// Outcome of a rewind request. /// ///
/// @@ -21417,39 +24481,40 @@ pub enum FactoryRunFailureKind { /// ///
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum FactoryRunStatus { - /// The run was minted and is awaiting approval. - #[serde(rename = "pending")] - Pending, - /// The run is executing. - #[serde(rename = "running")] - Running, - /// The run completed successfully. - #[serde(rename = "completed")] - Completed, - /// The run was interrupted while resource budget remained. - #[serde(rename = "halted")] - Halted, - /// The run was cancelled before completion. - #[serde(rename = "cancelled")] - Cancelled, - /// The factory body failed or reached a cumulative resource ceiling. - #[serde(rename = "error")] - Error, +pub enum HistoryRewindOutcome { + /// The requested rewind completed; reachable in either mode. + #[serde(rename = "success")] + Success, + /// The session still has work that may mutate files or history; reachable in either mode. + #[serde(rename = "session-busy")] + SessionBusy, + /// A conversation-and-files rewind was requested for a session that did not enable capture; conversation-only rewinds never produce this. + #[serde(rename = "file-change-tracking-disabled")] + FileChangeTrackingDisabled, + /// Remote-backed rewind routing is not supported; reachable in either mode. + #[serde(rename = "unsupported-remote-session")] + UnsupportedRemoteSession, + /// File restore failed and all applied file changes were rolled back; only conversation-and-files rewinds produce this. + #[serde(rename = "files-rolled-back")] + FilesRolledBack, + /// File restore failed and its rollback could not fully restore the pre-rewind state; only conversation-and-files rewinds produce this. + #[serde(rename = "rollback-incomplete")] + RollbackIncomplete, + /// Conversation truncation failed. In conversation-and-files mode any files that were restored are left in place because conversation history cannot be un-truncated; in conversation-only mode no files are restored. Consult restoredFiles for what, if anything, was applied. + #[serde(rename = "truncation-failed")] + TruncationFailed, + /// The conversation was rewound (and, in conversation-and-files mode, captured files were restored), but persisted checkpoints could not be cleaned up; reachable in either mode. + #[serde(rename = "checkpoint-cleanup-failed")] + CheckpointCleanupFailed, + /// Files and conversation were rewound, but obsolete file snapshots could not be removed; only conversation-and-files rewinds produce this. + #[serde(rename = "snapshot-prune-failed")] + SnapshotPruneFailed, /// Unknown variant for forward compatibility. #[default] #[serde(other)] Unknown, } -/// Authentication via the `gh` CLI's saved credentials. -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum GhCliAuthInfoType { - #[serde(rename = "gh-cli")] - #[default] - GhCli, -} - /// Authentication host. HMAC auth always targets the public GitHub host. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum HMACAuthInfoHost { @@ -23219,6 +26284,56 @@ pub enum PushAttachmentSelectionType { Selection, } +/// The UI mode the agent was in when this message was sent. Defaults to the session's current mode. +/// +///
+/// +/// **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, PartialEq, Eq, Serialize, Deserialize)] +pub enum SendAgentMode { + /// The agent is responding interactively to the user. + #[serde(rename = "interactive")] + Interactive, + /// The agent is preparing a plan before making changes. + #[serde(rename = "plan")] + Plan, + /// The agent is working autonomously toward task completion. + #[serde(rename = "autopilot")] + Autopilot, + /// The agent is in shell-focused UI mode. + #[serde(rename = "shell")] + Shell, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// How to deliver the message. `enqueue` (default) appends to the message queue. `immediate` interjects during an in-progress turn. +/// +///
+/// +/// **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, PartialEq, Eq, Serialize, Deserialize)] +pub enum SendMode { + /// Append the message to the normal session queue. + #[serde(rename = "enqueue")] + Enqueue, + /// Interject the message during the in-progress turn. + #[serde(rename = "immediate")] + Immediate, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + /// Whether this item is a queued user message or a queued slash command / model change /// ///
@@ -23320,56 +26435,6 @@ pub enum RemoteSessionMetadataTaskType { Unknown, } -/// The UI mode the agent was in when this message was sent. Defaults to the session's current mode. -/// -///
-/// -/// **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, PartialEq, Eq, Serialize, Deserialize)] -pub enum SendAgentMode { - /// The agent is responding interactively to the user. - #[serde(rename = "interactive")] - Interactive, - /// The agent is preparing a plan before making changes. - #[serde(rename = "plan")] - Plan, - /// The agent is working autonomously toward task completion. - #[serde(rename = "autopilot")] - Autopilot, - /// The agent is in shell-focused UI mode. - #[serde(rename = "shell")] - Shell, - /// Unknown variant for forward compatibility. - #[default] - #[serde(other)] - Unknown, -} - -/// How to deliver the message. `enqueue` (default) appends to the message queue. `immediate` interjects during an in-progress turn. -/// -///
-/// -/// **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, PartialEq, Eq, Serialize, Deserialize)] -pub enum SendMode { - /// Append the message to the normal session queue. - #[serde(rename = "enqueue")] - Enqueue, - /// Interject the message during the in-progress turn. - #[serde(rename = "immediate")] - Immediate, - /// Unknown variant for forward compatibility. - #[default] - #[serde(other)] - Unknown, -} - /// Session capability enabled for this session /// ///
@@ -23508,6 +26573,31 @@ pub enum SessionFsSqliteQueryType { Unknown, } +/// SQLite transaction failure classification. +/// +///
+/// +/// **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, PartialEq, Eq, Serialize, Deserialize)] +pub enum SessionFsSqliteTransactionErrorClass { + /// SQLite reported BUSY or LOCKED before commit; the transaction was rolled back and may be retried. + #[serde(rename = "busyOrLocked")] + BusyOrLocked, + /// The statement, database, or provider failed definitively and must not be retried automatically. + #[serde(rename = "fatal")] + Fatal, + /// The transport failed after the provider may have committed; retrying could duplicate effects. + #[serde(rename = "postCommitAmbiguous")] + PostCommitAmbiguous, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + /// Constant value. Always "github". #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum SessionInstalledPluginSourceGitHubSource { @@ -23532,6 +26622,132 @@ pub enum SessionInstalledPluginSourceUrlSource { Url, } +/// Client population used for the prediction baseline. +/// +///
+/// +/// **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, PartialEq, Eq, Serialize, Deserialize)] +pub enum SessionLimitPredictionClientType { + /// Interactive CLI sessions where a user can accept, edit, or top up the limit. + #[serde(rename = "cli-interactive")] + CliInteractive, + /// Prompt/non-interactive CLI sessions where the initial limit must cover more of the run. + #[serde(rename = "cli-prompt")] + CliPrompt, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// Semantic usage tier used for a recommended cap or additional headroom. +/// +///
+/// +/// **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, PartialEq, Eq, Serialize, Deserialize)] +pub enum SessionLimitPredictionTier { + /// Recommended starting tier. + #[serde(rename = "recommended")] + Recommended, + /// Additional headroom for longer-running sessions. + #[serde(rename = "additional_headroom")] + AdditionalHeadroom, + /// Generous headroom for unusually high usage. + #[serde(rename = "generous_headroom")] + GenerousHeadroom, + /// Maximum available headroom tier. + #[serde(rename = "maximum_headroom")] + MaximumHeadroom, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// Baseline fallback level used to create the prediction. +/// +///
+/// +/// **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, PartialEq, Eq, Serialize, Deserialize)] +pub enum SessionLimitPredictionSource { + /// The prediction used the exact resolved model's baseline cell. + #[serde(rename = "model")] + Model, + /// The exact model was unavailable, so the prediction used the model family's baseline cell. + #[serde(rename = "family")] + Family, + /// No model or family cell was available, so the prediction used the global client-type baseline cell. + #[serde(rename = "global")] + Global, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum SessionLimitPredictionResultAvailableKind { + #[serde(rename = "available")] + #[default] + Available, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum SessionLimitPredictionResultUnavailableKind { + #[serde(rename = "unavailable")] + #[default] + Unavailable, +} + +/// Reason a prediction could not be computed. +/// +///
+/// +/// **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, PartialEq, Eq, Serialize, Deserialize)] +pub enum SessionLimitPredictionUnavailableReason { + /// The current model is auto and has not resolved to a concrete model yet. + #[serde(rename = "auto_unresolved")] + AutoUnresolved, + /// No model was provided and the session does not currently have a selected model. + #[serde(rename = "no_model")] + NoModel, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// Prediction result. Available results include prediction details; unavailable results include an explicit reason. +/// +///
+/// +/// **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, Serialize, Deserialize)] +#[serde(untagged)] +pub enum SessionLimitPredictionResult { + Available(SessionLimitPredictionResultAvailable), + Unavailable(SessionLimitPredictionResultUnavailable), +} + /// Repository host type, if known /// ///
@@ -23623,6 +26839,50 @@ pub enum SessionOpenOptionsReasoningSummary { Unknown, } +/// Controls automatic non-interactive profile loading where supported. Explicit initScripts are unaffected. +/// +///
+/// +/// **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, PartialEq, Eq, Serialize, Deserialize)] +pub enum ShellInitProfile { + /// Disable automatic non-interactive profile loading. Explicit initScripts still run. + #[serde(rename = "none")] + None, + /// Allow automatic non-interactive profile loading when supported. Explicit initScripts still run. + #[serde(rename = "non-interactive")] + NonInteractive, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// Supported built-in shells for initialization scripts. +/// +///
+/// +/// **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, PartialEq, Eq, Serialize, Deserialize)] +pub enum ShellInitScriptShell { + /// Source the script in the built-in Bash shell on macOS and Linux. + #[serde(rename = "bash")] + Bash, + /// Source the script in the built-in PowerShell shell on Windows. + #[serde(rename = "powershell")] + Powershell, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + /// Create a new local session. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum SessionsOpenCreateKind { diff --git a/rust/src/generated/rpc.rs b/rust/src/generated/rpc.rs index 431ffa3aed..e9bbef1d1a 100644 --- a/rust/src/generated/rpc.rs +++ b/rust/src/generated/rpc.rs @@ -942,6 +942,30 @@ impl<'a> ClientRpcModels<'a> { .await?; Ok(serde_json::from_value(_value)?) } + + /// Returns the running runtime's complete catalog of well-known built-in model IDs without authentication or network access. + /// + /// Wire method: `models.getBuiltInCatalog`. + /// + /// # Returns + /// + /// The running runtime's complete catalog of well-known built-in model IDs, including supported models and additional IDs with built-in metadata. + /// + ///
+ /// + /// **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 get_built_in_catalog(&self) -> Result { + let wire_params = serde_json::json!({}); + let _value = self + .client + .call(rpc_methods::MODELS_GETBUILTINCATALOG, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } } /// `plugins.*` RPCs. @@ -1569,6 +1593,71 @@ impl<'a> ClientRpcSessions<'a> { Ok(serde_json::from_value(_value)?) } + /// Reads lightweight persisted metadata for one local session without opening it. + /// + /// Wire method: `sessions.getMetadata`. + /// + /// # Parameters + /// + /// * `params` - Session ID whose persisted metadata should be read. + /// + /// # Returns + /// + /// Persisted local session metadata when the session exists. + /// + ///
+ /// + /// **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(crate) async fn get_metadata( + &self, + params: SessionsGetMetadataRequest, + ) -> Result { + let wire_params = serde_json::to_value(params)?; + let _value = self + .client + .call(rpc_methods::SESSIONS_GETMETADATA, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Lists recent local session IDs that contain user-visible history, omitting housekeeping-only sessions. + /// + /// Wire method: `sessions.listNonEmptySessionIds`. + /// + /// # Parameters + /// + /// * `params` - Limit for non-empty local session IDs. + /// + /// # Returns + /// + /// Recent local session IDs that contain user-visible history. + /// + ///
+ /// + /// **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(crate) async fn list_non_empty_session_ids( + &self, + params: SessionsListNonEmptySessionIdsRequest, + ) -> Result { + let wire_params = serde_json::to_value(params)?; + let _value = self + .client + .call( + rpc_methods::SESSIONS_LISTNONEMPTYSESSIONIDS, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + /// Finds the local session bound to a GitHub task ID, if any. /// /// Wire method: `sessions.findByTaskId`. @@ -1841,6 +1930,30 @@ impl<'a> ClientRpcSessions<'a> { Ok(serde_json::from_value(_value)?) } + /// Deletes one local session from disk after running the same lifecycle hooks as the session manager. + /// + /// Wire method: `sessions.delete`. + /// + /// # Parameters + /// + /// * `params` - Session ID to delete from disk. + /// + ///
+ /// + /// **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(crate) async fn delete(&self, params: SessionsDeleteRequest) -> Result<(), Error> { + let wire_params = serde_json::to_value(params)?; + let _value = self + .client + .call(rpc_methods::SESSIONS_DELETE, Some(wire_params)) + .await?; + Ok(()) + } + /// Deletes sessions older than the given threshold, with optional dry-run and exclusion list. /// /// Wire method: `sessions.pruneOld`. @@ -2619,6 +2732,13 @@ impl<'a> SessionRpc<'a> { } } + /// `session.contentExclusion.*` sub-namespace. + pub fn content_exclusion(&self) -> SessionRpcContentExclusion<'a> { + SessionRpcContentExclusion { + session: self.session, + } + } + /// `session.debug.*` sub-namespace. pub fn debug(&self) -> SessionRpcDebug<'a> { SessionRpcDebug { @@ -2675,6 +2795,13 @@ impl<'a> SessionRpc<'a> { } } + /// `session.limitPrediction.*` sub-namespace. + pub fn limit_prediction(&self) -> SessionRpcLimitPrediction<'a> { + SessionRpcLimitPrediction { + session: self.session, + } + } + /// `session.lsp.*` sub-namespace. pub fn lsp(&self) -> SessionRpcLsp<'a> { SessionRpcLsp { @@ -2927,6 +3054,38 @@ impl<'a> SessionRpc<'a> { Ok(serde_json::from_value(_value)?) } + /// Queues or sends an internal system notification to the session according to its passive policy. + /// + /// Wire method: `session.sendSystemNotification`. + /// + /// # Parameters + /// + /// * `params` - Internal request for sending a system notification. + /// + ///
+ /// + /// **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(crate) async fn send_system_notification( + &self, + params: SendSystemNotificationRequest, + ) -> Result<(), Error> { + 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_SENDSYSTEMNOTIFICATION, + Some(wire_params), + ) + .await?; + Ok(()) + } + /// Aborts the current agent turn. /// /// Wire method: `session.abort`. @@ -2957,6 +3116,69 @@ impl<'a> SessionRpc<'a> { Ok(serde_json::from_value(_value)?) } + /// Interrupts the current main agent turn while leaving running background work (subagents, sidekicks, and promoted attached shells) alive. No-op when the main loop is not processing. + /// + /// Wire method: `session.interruptMainTurn`. + /// + /// # Parameters + /// + /// * `params` - Parameters for interrupting the main agent turn. + /// + /// # Returns + /// + /// Result of interrupting the main agent turn. + /// + ///
+ /// + /// **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 interrupt_main_turn( + &self, + params: InterruptMainTurnRequest, + ) -> 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_INTERRUPTMAINTURN, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Cancels every running background agent (task-registry subagents plus sidekick agents) without interrupting the main agent loop. Promoted attached shells are left running. + /// + /// Wire method: `session.cancelAllBackgroundAgents`. + /// + /// # Returns + /// + /// The number of running background agents (task-registry agents) that were cancelled. + /// + ///
+ /// + /// **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 cancel_all_background_agents( + &self, + ) -> Result { + let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + let _value = self + .session + .client() + .call( + rpc_methods::SESSION_CANCELALLBACKGROUNDAGENTS, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + /// Shuts down the session and persists its final state. Awaits any deferred sessionEnd hooks before resolving so user-supplied hook scripts complete before the runtime tears down. /// /// Wire method: `session.shutdown`. @@ -3021,13 +3243,13 @@ pub struct SessionRpcAgent<'a> { } impl<'a> SessionRpcAgent<'a> { - /// Lists custom agents available to the session. + /// Lists agents available to the session. Defaults to custom agents only; pass includeBuiltInAgents to include the effective built-in agents. /// /// Wire method: `session.agent.list`. /// /// # Returns /// - /// Custom agents available to the session. + /// Agents available to the session. /// ///
/// @@ -3046,6 +3268,36 @@ impl<'a> SessionRpcAgent<'a> { Ok(serde_json::from_value(_value)?) } + /// Lists agents available to the session. Defaults to custom agents only; pass includeBuiltInAgents to include the effective built-in agents. + /// + /// Wire method: `session.agent.list`. + /// + /// # Parameters + /// + /// * `params` - Controls whether built-in agents and authored prompt text are included. + /// + /// # Returns + /// + /// Agents available to the session. + /// + ///
+ /// + /// **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 list_with_params(&self, params: AgentListRequest) -> 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_AGENT_LIST, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + /// Gets the currently selected custom agent for the session. /// /// Wire method: `session.agent.getCurrent`. @@ -3618,6 +3870,50 @@ impl<'a> SessionRpcCompletions<'a> { } } +/// `session.contentExclusion.*` RPCs. +#[derive(Clone, Copy)] +pub struct SessionRpcContentExclusion<'a> { + pub(crate) session: &'a Session, +} + +impl<'a> SessionRpcContentExclusion<'a> { + /// Checks local file system absolute paths within the session working directory against its content-exclusion policy. Results preserve input order. Unsupported paths/filesystems and unavailable policy evaluation return available false, and callers must treat every requested path as excluded. + /// + /// Wire method: `session.contentExclusion.checkPaths`. + /// + /// # Parameters + /// + /// * `params` - Local file system absolute paths within the session working directory to check against its content-exclusion policy. + /// + /// # Returns + /// + /// Batch content-exclusion result. Callers must fail closed when policy evaluation is unavailable. + /// + ///
+ /// + /// **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 check_paths( + &self, + params: ContentExclusionCheckPathsRequest, + ) -> 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_CONTENTEXCLUSION_CHECKPATHS, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } +} + /// `session.debug.*` RPCs. #[derive(Clone, Copy)] pub struct SessionRpcDebug<'a> { @@ -3976,17 +4272,17 @@ impl<'a> SessionRpcFactory<'a> { Ok(serde_json::from_value(_value)?) } - /// Gets the current or settled envelope for a factory run. + /// Resumes a factory run using its persisted name, arguments, journal, and accounting. /// - /// Wire method: `session.factory.getRun`. + /// Wire method: `session.factory.resume`. /// /// # Parameters /// - /// * `params` - Parameters for retrieving a factory run. + /// * `params` - Parameters for resuming a factory run from its persisted identity. /// /// # Returns /// - /// Complete current or terminal factory run envelope. + /// Resolved persisted factory identity and resumed run envelope. /// ///
/// @@ -3995,24 +4291,24 @@ impl<'a> SessionRpcFactory<'a> { /// SDK and CLI versions if your code depends on it. /// ///
- pub async fn get_run(&self, params: FactoryGetRunRequest) -> Result { + pub async fn resume(&self, params: FactoryResumeRequest) -> 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_FACTORY_GETRUN, Some(wire_params)) + .call(rpc_methods::SESSION_FACTORY_RESUME, Some(wire_params)) .await?; Ok(serde_json::from_value(_value)?) } - /// Requests cancellation of a factory run and returns its run envelope. + /// Gets the current or settled envelope for a factory run. /// - /// Wire method: `session.factory.cancel`. + /// Wire method: `session.factory.getRun`. /// /// # Parameters /// - /// * `params` - Parameters for cancelling a factory run. + /// * `params` - Parameters for retrieving a factory run. /// /// # Returns /// @@ -4025,28 +4321,24 @@ impl<'a> SessionRpcFactory<'a> { /// SDK and CLI versions if your code depends on it. /// ///
- pub async fn cancel(&self, params: FactoryCancelRequest) -> Result { + pub async fn get_run(&self, params: FactoryGetRunRequest) -> 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_FACTORY_CANCEL, Some(wire_params)) + .call(rpc_methods::SESSION_FACTORY_GETRUN, Some(wire_params)) .await?; Ok(serde_json::from_value(_value)?) } - /// Records a batch of ordered factory progress lines. - /// - /// Wire method: `session.factory.log`. + /// Lists durable factory runs for this session in creation order. /// - /// # Parameters - /// - /// * `params` - Parameters for recording factory progress. + /// Wire method: `session.factory.listRuns`. /// /// # Returns /// - /// Acknowledgement that a factory request was accepted. + /// Factory runs in durable creation order. /// ///
/// @@ -4055,9 +4347,137 @@ impl<'a> SessionRpcFactory<'a> { /// SDK and CLI versions if your code depends on it. /// ///
- pub async fn log(&self, params: FactoryLogRequest) -> Result { - let mut wire_params = serde_json::to_value(params)?; - wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); + pub async fn list_runs(&self) -> Result { + let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + let _value = self + .session + .client() + .call(rpc_methods::SESSION_FACTORY_LISTRUNS, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Gets durable and live observability detail for one factory run. + /// + /// Wire method: `session.factory.getRunDetail`. + /// + /// # Parameters + /// + /// * `params` - Parameters for retrieving a factory run. + /// + /// # Returns + /// + /// Full factory run observability detail. + /// + ///
+ /// + /// **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 get_run_detail( + &self, + params: FactoryGetRunRequest, + ) -> 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_FACTORY_GETRUNDETAIL, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Pages durable progress for one factory run. + /// + /// Wire method: `session.factory.getRunProgress`. + /// + /// # Parameters + /// + /// * `params` - Parameters for paging factory progress. + /// + /// # Returns + /// + /// A bidirectional page of factory progress. + /// + ///
+ /// + /// **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 get_run_progress( + &self, + params: FactoryGetRunProgressRequest, + ) -> 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_FACTORY_GETRUNPROGRESS, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Requests cancellation of a factory run and returns its run envelope. + /// + /// Wire method: `session.factory.cancel`. + /// + /// # Parameters + /// + /// * `params` - Parameters for cancelling a factory run. + /// + /// # Returns + /// + /// Complete current or terminal factory run envelope. + /// + ///
+ /// + /// **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 cancel(&self, params: FactoryCancelRequest) -> 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_FACTORY_CANCEL, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Records a batch of ordered factory progress lines. + /// + /// Wire method: `session.factory.log`. + /// + /// # Parameters + /// + /// * `params` - Parameters for recording factory progress. + /// + /// # Returns + /// + /// Acknowledgement that a factory request was accepted. + /// + ///
+ /// + /// **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 log(&self, params: FactoryLogRequest) -> 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() @@ -4373,6 +4793,100 @@ impl<'a> SessionRpcHistory<'a> { Ok(serde_json::from_value(_value)?) } + /// Lists the user turns that the session can rewind to. Never rejects for a busy session: rewind reads need the session's file-change captures to be settled, so a session that still holds active work answers with `unavailableReason: "session-busy"` and no points, which the caller can retry. + /// + /// Wire method: `session.history.listRewindPoints`. + /// + /// # Returns + /// + /// Rewind points and file-change-tracking availability for the session. + /// + ///
+ /// + /// **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 list_rewind_points(&self) -> Result { + let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + let _value = self + .session + .client() + .call( + rpc_methods::SESSION_HISTORY_LISTREWINDPOINTS, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Previews the files that a conversation-and-files rewind would restore. + /// + /// Wire method: `session.history.previewRewind`. + /// + /// # Parameters + /// + /// * `params` - Event boundary to preview for conversation-and-files rewind. + /// + /// # Returns + /// + /// Files and aggregate changes for a prospective rewind. + /// + ///
+ /// + /// **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 preview_rewind( + &self, + params: HistoryPreviewRewindRequest, + ) -> 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_PREVIEWREWIND, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Rewinds the session conversation, optionally restoring files changed by the discarded turns. Not crash-atomic: file restore and conversation truncation are separate stores, applied in that order, so a process crash between them can leave the workspace rewound while the conversation still contains the discarded turns. There is no recovery journal; re-running the same rewind is the recovery path for a crash before truncation lands, since file restore is idempotent (already-restored files are reported as skipped) and truncation is re-derived from the still-retained boundary event. After truncation lands that boundary no longer exists, so the same request is rejected; the only stage that can still be outstanding is snapshot pruning, whose failure leaves orphan snapshots the capture store tolerates. The reverse inconsistency cannot occur, because truncation is never applied before file restore succeeds. + /// + /// Wire method: `session.history.rewind`. + /// + /// # Parameters + /// + /// * `params` - Boundary and mode for rewinding session history. + /// + /// # Returns + /// + /// Structured outcome of a rewind request. + /// + ///
+ /// + /// **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 rewind(&self, params: HistoryRewindRequest) -> 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_REWIND, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + /// Cancels any in-progress background compaction on a local session. /// /// Wire method: `session.history.cancelBackgroundCompaction`. @@ -4498,6 +5012,78 @@ impl<'a> SessionRpcInstructions<'a> { } } +/// `session.limitPrediction.*` RPCs. +#[derive(Clone, Copy)] +pub struct SessionRpcLimitPrediction<'a> { + pub(crate) session: &'a Session, +} + +impl<'a> SessionRpcLimitPrediction<'a> { + /// Predicts an AI-credit session limit for the session's resolved model. Returns an unavailable result instead of falling back when the current model is unresolved auto. + /// + /// Wire method: `session.limitPrediction.predict`. + /// + /// # Returns + /// + /// Prediction result. Available results include prediction details; unavailable results include an explicit reason. + /// + ///
+ /// + /// **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 predict(&self) -> Result { + let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + let _value = self + .session + .client() + .call( + rpc_methods::SESSION_LIMITPREDICTION_PREDICT, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Predicts an AI-credit session limit for the session's resolved model. Returns an unavailable result instead of falling back when the current model is unresolved auto. + /// + /// Wire method: `session.limitPrediction.predict`. + /// + /// # Parameters + /// + /// * `params` - Parameters for predicting an AI-credit session limit. Omitting `modelId` uses the session's currently selected model. + /// + /// # Returns + /// + /// Prediction result. Available results include prediction details; unavailable results include an explicit reason. + /// + ///
+ /// + /// **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 predict_with_params( + &self, + params: SessionLimitPredictionRequest, + ) -> 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_LIMITPREDICTION_PREDICT, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } +} + /// `session.lsp.*` RPCs. #[derive(Clone, Copy)] pub struct SessionRpcLsp<'a> { @@ -4891,13 +5477,13 @@ impl<'a> SessionRpcMcp<'a> { Ok(serde_json::from_value(_value)?) } - /// Starts an individual MCP server on the live session from a caller-supplied config. Session-scoped and ephemeral: the server is added to this session's running set only and is reaped when the session ends. Does NOT modify persistent user configuration (`mcp.config.*`), so it does not affect future sessions. The server surfaces through `session.mcp.list` and the `session.mcp_servers_loaded` / `session.mcp_server_status_changed` events like any other server. + /// Starts an individual MCP server on the live session. Omit `config` for a config-free start-by-name of an already-configured server (reuses the server's already-registered configuration); supply `config` to start from a caller-supplied configuration. Session-scoped and ephemeral: the server is added to this session's running set only and is reaped when the session ends. Does NOT modify persistent user configuration (`mcp.config.*`), so it does not affect future sessions. The server surfaces through `session.mcp.list` and the `session.mcp_servers_loaded` / `session.mcp_server_status_changed` events like any other server. /// /// Wire method: `session.mcp.startServer`. /// /// # Parameters /// - /// * `params` - Server name and configuration for an individual MCP server start. + /// * `params` - Server name and optional configuration for an individual MCP server start. Omit `config` for a config-free start-by-name of an already-configured server. /// ///
/// @@ -5386,26 +5972,59 @@ impl<'a> SessionRpcMcpOauth<'a> { .await?; Ok(serde_json::from_value(_value)?) } -} - -/// `session.mcp.resources.*` RPCs. -#[derive(Clone, Copy)] -pub struct SessionRpcMcpResources<'a> { - pub(crate) session: &'a Session, -} -impl<'a> SessionRpcMcpResources<'a> { - /// Fetch an MCP resource from a connected server by URI (proxies MCP `resources/read`). + /// Responds to a pending MCP OAuth authorization request by its request id. /// - /// Wire method: `session.mcp.resources.read`. + /// Wire method: `session.mcp.oauth.respond`. /// /// # Parameters /// - /// * `params` - MCP server and resource URI to fetch. + /// * `params` - Pending MCP OAuth request id to respond to. /// /// # Returns /// - /// Resource contents returned by the MCP server. + /// Indicates whether the pending MCP OAuth response was accepted. + /// + ///
+ /// + /// **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 respond( + &self, + params: McpOauthRespondRequest, + ) -> 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_MCP_OAUTH_RESPOND, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } +} + +/// `session.mcp.resources.*` RPCs. +#[derive(Clone, Copy)] +pub struct SessionRpcMcpResources<'a> { + pub(crate) session: &'a Session, +} + +impl<'a> SessionRpcMcpResources<'a> { + /// Fetch an MCP resource from a connected server by URI (proxies MCP `resources/read`). + /// + /// Wire method: `session.mcp.resources.read`. + /// + /// # Parameters + /// + /// * `params` - MCP server and resource URI to fetch. + /// + /// # Returns + /// + /// Resource contents returned by the MCP server. /// ///
/// @@ -6449,6 +7068,10 @@ impl<'a> SessionRpcPermissions<'a> { /// /// Wire method: `session.permissions.resetSessionApprovals`. /// + /// # Parameters + /// + /// * `params` - Clears session-scoped tool permission approvals, and optionally the location-scoped ones. + /// /// # Returns /// /// Indicates whether the operation succeeded. @@ -6462,8 +7085,10 @@ impl<'a> SessionRpcPermissions<'a> { ///
pub async fn reset_session_approvals( &self, + params: PermissionsResetSessionApprovalsRequest, ) -> Result { - let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + 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() @@ -7275,13 +7900,13 @@ impl<'a> SessionRpcQueue<'a> { Ok(serde_json::from_value(_value)?) } - /// Removes the most recently queued user-facing item (LIFO). + /// Returns the internal native queue snapshot for in-process session orchestration. /// - /// Wire method: `session.queue.removeMostRecent`. + /// Wire method: `session.queue.snapshot`. /// /// # Returns /// - /// Indicates whether a user-facing pending item was removed. + /// Internal snapshot of native queue state for local session orchestration. /// ///
/// @@ -7290,22 +7915,27 @@ impl<'a> SessionRpcQueue<'a> { /// SDK and CLI versions if your code depends on it. /// ///
- pub async fn remove_most_recent(&self) -> Result { + pub(crate) async fn snapshot(&self) -> Result { let wire_params = serde_json::json!({ "sessionId": self.session.id() }); let _value = self .session .client() - .call( - rpc_methods::SESSION_QUEUE_REMOVEMOSTRECENT, - Some(wire_params), - ) + .call(rpc_methods::SESSION_QUEUE_SNAPSHOT, Some(wire_params)) .await?; Ok(serde_json::from_value(_value)?) } - /// Clears all pending queued items on the local session. + /// Moves an addressable queued item to a public visible position. /// - /// Wire method: `session.queue.clear`. + /// Wire method: `session.queue.moveItem`. + /// + /// # Parameters + /// + /// * `params` - Parameters for moving a queued item by stable id. + /// + /// # Returns + /// + /// Result of moving a queued item. /// ///
/// @@ -7314,35 +7944,244 @@ impl<'a> SessionRpcQueue<'a> { /// SDK and CLI versions if your code depends on it. /// ///
- pub async fn clear(&self) -> Result<(), Error> { - let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + pub async fn move_item( + &self, + params: QueueMoveItemRequest, + ) -> 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_QUEUE_CLEAR, Some(wire_params)) + .call(rpc_methods::SESSION_QUEUE_MOVEITEM, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Inserts a new queued message at a public visible position. + /// + /// Wire method: `session.queue.insertAt`. + /// + /// # Parameters + /// + /// * `params` - Parameters for inserting a queued message at a public visible position. + /// + /// # Returns + /// + /// Result of inserting a queued message. + /// + ///
+ /// + /// **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 insert_at( + &self, + params: QueueInsertAtRequest, + ) -> 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_QUEUE_INSERTAT, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Removes an addressable queued item by its stable id. + /// + /// Wire method: `session.queue.removeAt`. + /// + /// # Parameters + /// + /// * `params` - Parameters for removing a queued item by stable id. + /// + /// # Returns + /// + /// Result of removing a queued item. + /// + ///
+ /// + /// **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 remove_at( + &self, + params: QueueRemoveAtRequest, + ) -> 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_QUEUE_REMOVEAT, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Updates the text of an addressable single-message queue item. + /// + /// Wire method: `session.queue.updateText`. + /// + /// # Parameters + /// + /// * `params` - Parameters for editing a single queued message. + /// + /// # Returns + /// + /// Result of editing a queued message. + /// + ///
+ /// + /// **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_text( + &self, + params: QueueUpdateTextRequest, + ) -> 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_QUEUE_UPDATETEXT, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Duplicates an addressable queued item immediately after its source. + /// + /// Wire method: `session.queue.duplicateAt`. + /// + /// # Parameters + /// + /// * `params` - Parameters for duplicating a queued item. + /// + /// # Returns + /// + /// Result of duplicating a queued item. + /// + ///
+ /// + /// **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 duplicate_at( + &self, + params: QueueDuplicateAtRequest, + ) -> 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_QUEUE_DUPLICATEAT, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Acquires or releases the queued-lane drain pause. + /// + /// Wire method: `session.queue.setDrainPaused`. + /// + /// # Parameters + /// + /// * `params` - Parameters for acquiring or releasing the queued-lane drain pause. Acquisition is exclusive and non-idempotent: `paused: true` against an already-paused session fails with `queue_already_paused`. The pause is never released automatically — it is not tied to the caller's lifetime, so a client that exits without sending `paused: false` leaves the lane frozen. Release is unowned: `paused: false` clears the pause for any caller, including one that never acquired it. + /// + ///
+ /// + /// **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 set_drain_paused(&self, params: QueueSetDrainPausedRequest) -> Result<(), Error> { + 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_QUEUE_SETDRAINPAUSED, Some(wire_params)) .await?; Ok(()) } -} -/// `session.remote.*` RPCs. -#[derive(Clone, Copy)] -pub struct SessionRpcRemote<'a> { - pub(crate) session: &'a Session, -} + /// Moves an addressable queued message into the live turn's steering lane. + /// + /// Wire method: `session.queue.sendNow`. + /// + /// # Parameters + /// + /// * `params` - Parameters for steering a queued message into a live turn. + /// + /// # Returns + /// + /// Result of trying to steer a queued message into a live turn. + /// + ///
+ /// + /// **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 send_now(&self, params: QueueSendNowRequest) -> 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_QUEUE_SENDNOW, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } -impl<'a> SessionRpcRemote<'a> { - /// Enables remote session export or steering. + /// Reports whether the local session has native queued work pending. /// - /// Wire method: `session.remote.enable`. + /// Wire method: `session.queue.hasPending`. + /// + /// # Returns + /// + /// Whether the native queue has pending work. + /// + ///
+ /// + /// **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(crate) async fn has_pending(&self) -> Result { + let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + let _value = self + .session + .client() + .call(rpc_methods::SESSION_QUEUE_HASPENDING, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Begins a native deferred-idle drain when background work has quiesced. + /// + /// Wire method: `session.queue.beginDeferredIdleDrain`. /// /// # Parameters /// - /// * `params` - Optional remote session mode ("off", "export", or "on"); defaults to enabling both export and remote steering. + /// * `params` - Inputs for starting a deferred-idle drain. /// /// # Returns /// - /// GitHub URL for the session and a flag indicating whether remote steering is enabled. + /// Whether a deferred-idle drain should run. /// ///
/// @@ -7351,20 +8190,478 @@ impl<'a> SessionRpcRemote<'a> { /// SDK and CLI versions if your code depends on it. /// ///
- pub async fn enable(&self, params: RemoteEnableRequest) -> Result { + pub(crate) async fn begin_deferred_idle_drain( + &self, + params: QueueBeginDeferredIdleDrainRequest, + ) -> 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_REMOTE_ENABLE, Some(wire_params)) + .call( + rpc_methods::SESSION_QUEUE_BEGINDEFERREDIDLEDRAIN, + Some(wire_params), + ) .await?; Ok(serde_json::from_value(_value)?) } - /// Disables remote session export and steering. + /// Finishes a native deferred-idle drain and reports whether to drain queue work or emit idle. + /// + /// Wire method: `session.queue.finishDeferredIdleDrain`. + /// + /// # Parameters + /// + /// * `params` - Inputs for completing a deferred-idle drain. + /// + /// # Returns + /// + /// Action selected by the native deferred-idle drain. + /// + ///
+ /// + /// **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(crate) async fn finish_deferred_idle_drain( + &self, + params: QueueFinishDeferredIdleDrainRequest, + ) -> 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_QUEUE_FINISHDEFERREDIDLEDRAIN, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Marks session.idle as deferred by native background work state. + /// + /// Wire method: `session.queue.deferSessionIdle`. + /// + /// # Parameters + /// + /// * `params` - Inputs for marking session.idle deferred in native state. + /// + ///
+ /// + /// **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(crate) async fn defer_session_idle( + &self, + params: QueueDeferSessionIdleRequest, + ) -> Result<(), Error> { + 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_QUEUE_DEFERSESSIONIDLE, + Some(wire_params), + ) + .await?; + Ok(()) + } + + /// Removes the most recently queued user-facing item (LIFO). + /// + /// Wire method: `session.queue.removeMostRecent`. + /// + /// # Returns + /// + /// Indicates whether a user-facing pending item was removed. + /// + ///
+ /// + /// **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 remove_most_recent(&self) -> Result { + let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + let _value = self + .session + .client() + .call( + rpc_methods::SESSION_QUEUE_REMOVEMOSTRECENT, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Clears all pending queued items on the local session. + /// + /// Wire method: `session.queue.clear`. + /// + ///
+ /// + /// **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 clear(&self) -> Result<(), Error> { + let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + let _value = self + .session + .client() + .call(rpc_methods::SESSION_QUEUE_CLEAR, Some(wire_params)) + .await?; + Ok(()) + } + + /// Consumes queued native system notifications matching an internal filter. + /// + /// Wire method: `session.queue.consumeSystemNotifications`. + /// + /// # Parameters + /// + /// * `params` - Internal filter for consuming queued system notifications. + /// + /// # Returns + /// + /// Indicates whether a user-facing pending item was removed. + /// + ///
+ /// + /// **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(crate) async fn consume_system_notifications( + &self, + params: QueueConsumeSystemNotificationsRequest, + ) -> 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_QUEUE_CONSUMESYSTEMNOTIFICATIONS, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Enqueues the internal resume-pending wake item when orphan handling needs a follow-up turn. + /// + /// Wire method: `session.queue.enqueueResumePending`. + /// + /// # Returns + /// + /// Result of enqueueing the resume-pending wake item. + /// + ///
+ /// + /// **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(crate) async fn enqueue_resume_pending( + &self, + ) -> Result { + let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + let _value = self + .session + .client() + .call( + rpc_methods::SESSION_QUEUE_ENQUEUERESUMEPENDING, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Drains the native local-session work queue for in-process session orchestration. + /// + /// Wire method: `session.queue.process`. + /// + ///
+ /// + /// **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(crate) async fn process(&self) -> Result<(), Error> { + let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + let _value = self + .session + .client() + .call(rpc_methods::SESSION_QUEUE_PROCESS, Some(wire_params)) + .await?; + Ok(()) + } +} + +/// `session.remote.*` RPCs. +#[derive(Clone, Copy)] +pub struct SessionRpcRemote<'a> { + pub(crate) session: &'a Session, +} + +impl<'a> SessionRpcRemote<'a> { + /// Enables remote session export or steering. + /// + /// Wire method: `session.remote.enable`. + /// + /// # Parameters + /// + /// * `params` - Optional remote session mode ("off", "export", or "on"); defaults to enabling both export and remote steering. + /// + /// # Returns + /// + /// GitHub URL for the session and a flag indicating whether remote steering is enabled. + /// + ///
+ /// + /// **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 enable(&self, params: RemoteEnableRequest) -> 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_REMOTE_ENABLE, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Disables remote session export and steering. + /// + /// Wire method: `session.remote.disable`. + /// + ///
+ /// + /// **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 disable(&self) -> Result<(), Error> { + let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + let _value = self + .session + .client() + .call(rpc_methods::SESSION_REMOTE_DISABLE, Some(wire_params)) + .await?; + Ok(()) + } + + /// Persists a remote-steerability change emitted by the host as a session event. + /// + /// Wire method: `session.remote.notifySteerableChanged`. + /// + /// # Parameters + /// + /// * `params` - New remote-steerability state to persist as a `session.remote_steerable_changed` event. + /// + /// # Returns + /// + /// Persist a steerability change as a `session.remote_steerable_changed` event. Used by the host (CLI / SDK consumer) when it has just finished enabling or disabling steering on a remote exporter that the runtime does not directly own. + /// + ///
+ /// + /// **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 notify_steerable_changed( + &self, + params: RemoteNotifySteerableChangedRequest, + ) -> 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_REMOTE_NOTIFYSTEERABLECHANGED, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } +} + +/// `session.schedule.*` RPCs. +#[derive(Clone, Copy)] +pub struct SessionRpcSchedule<'a> { + pub(crate) session: &'a Session, +} + +impl<'a> SessionRpcSchedule<'a> { + /// Lists the session's currently active scheduled prompts. + /// + /// Wire method: `session.schedule.list`. + /// + /// # Returns + /// + /// Snapshot of the currently active recurring prompts for this session. + /// + ///
+ /// + /// **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 list(&self) -> Result { + let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + let _value = self + .session + .client() + .call(rpc_methods::SESSION_SCHEDULE_LIST, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Hydrates the native schedule registry from persisted session events. + /// + /// Wire method: `session.schedule.hydrate`. + /// + ///
+ /// + /// **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(crate) async fn hydrate(&self) -> Result<(), Error> { + let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + let _value = self + .session + .client() + .call(rpc_methods::SESSION_SCHEDULE_HYDRATE, Some(wire_params)) + .await?; + Ok(()) + } + + /// Reports whether the session has an active self-paced scheduled prompt. + /// + /// Wire method: `session.schedule.hasSelfPaced`. + /// + /// # Returns + /// + /// Whether the session currently has an active self-paced schedule. + /// + ///
+ /// + /// **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(crate) async fn has_self_paced(&self) -> Result { + let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + let _value = self + .session + .client() + .call( + rpc_methods::SESSION_SCHEDULE_HASSELFPACED, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Registers a relative-interval scheduled prompt. + /// + /// Wire method: `session.schedule.add`. + /// + /// # Parameters + /// + /// * `params` - Register a relative-interval scheduled prompt. + /// + /// # Returns + /// + /// Result of registering or re-arming a scheduled prompt. + /// + ///
+ /// + /// **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(crate) async fn add(&self, params: ScheduleAddRequest) -> 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_SCHEDULE_ADD, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Registers a recurring cron scheduled prompt. + /// + /// Wire method: `session.schedule.addCron`. + /// + /// # Parameters + /// + /// * `params` - Register a cron scheduled prompt. + /// + /// # Returns + /// + /// Result of registering or re-arming a scheduled prompt. + /// + ///
+ /// + /// **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(crate) async fn add_cron( + &self, + params: ScheduleAddCronRequest, + ) -> 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_SCHEDULE_ADDCRON, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Registers an absolute-time scheduled prompt. + /// + /// Wire method: `session.schedule.addAt`. + /// + /// # Parameters /// - /// Wire method: `session.remote.disable`. + /// * `params` - Register an absolute-time scheduled prompt. + /// + /// # Returns + /// + /// Result of registering or re-arming a scheduled prompt. /// ///
/// @@ -7373,27 +8670,31 @@ impl<'a> SessionRpcRemote<'a> { /// SDK and CLI versions if your code depends on it. /// ///
- pub async fn disable(&self) -> Result<(), Error> { - let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + pub(crate) async fn add_at( + &self, + params: ScheduleAddAtRequest, + ) -> 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_REMOTE_DISABLE, Some(wire_params)) + .call(rpc_methods::SESSION_SCHEDULE_ADDAT, Some(wire_params)) .await?; - Ok(()) + Ok(serde_json::from_value(_value)?) } - /// Persists a remote-steerability change emitted by the host as a session event. + /// Registers a self-paced scheduled prompt. /// - /// Wire method: `session.remote.notifySteerableChanged`. + /// Wire method: `session.schedule.addSelfPaced`. /// /// # Parameters /// - /// * `params` - New remote-steerability state to persist as a `session.remote_steerable_changed` event. + /// * `params` - Register a self-paced scheduled prompt. /// /// # Returns /// - /// Persist a steerability change as a `session.remote_steerable_changed` event. Used by the host (CLI / SDK consumer) when it has just finished enabling or disabling steering on a remote exporter that the runtime does not directly own. + /// Result of registering or re-arming a scheduled prompt. /// ///
/// @@ -7402,38 +8703,34 @@ impl<'a> SessionRpcRemote<'a> { /// SDK and CLI versions if your code depends on it. /// ///
- pub async fn notify_steerable_changed( + pub(crate) async fn add_self_paced( &self, - params: RemoteNotifySteerableChangedRequest, - ) -> Result { + params: ScheduleAddSelfPacedRequest, + ) -> 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_REMOTE_NOTIFYSTEERABLECHANGED, + rpc_methods::SESSION_SCHEDULE_ADDSELFPACED, Some(wire_params), ) .await?; Ok(serde_json::from_value(_value)?) } -} - -/// `session.schedule.*` RPCs. -#[derive(Clone, Copy)] -pub struct SessionRpcSchedule<'a> { - pub(crate) session: &'a Session, -} -impl<'a> SessionRpcSchedule<'a> { - /// Lists the session's currently active scheduled prompts. + /// Re-arms an active self-paced scheduled prompt. /// - /// Wire method: `session.schedule.list`. + /// Wire method: `session.schedule.rearmSelfPaced`. + /// + /// # Parameters + /// + /// * `params` - Re-arm a self-paced scheduled prompt. /// /// # Returns /// - /// Snapshot of the currently active recurring prompts for this session. + /// Result of registering or re-arming a scheduled prompt. /// ///
/// @@ -7442,12 +8739,19 @@ impl<'a> SessionRpcSchedule<'a> { /// SDK and CLI versions if your code depends on it. /// ///
- pub async fn list(&self) -> Result { - let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + pub(crate) async fn rearm_self_paced( + &self, + params: ScheduleRearmSelfPacedRequest, + ) -> 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_SCHEDULE_LIST, Some(wire_params)) + .call( + rpc_methods::SESSION_SCHEDULE_REARMSELFPACED, + Some(wire_params), + ) .await?; Ok(serde_json::from_value(_value)?) } @@ -7559,7 +8863,7 @@ pub struct SessionRpcShell<'a> { } impl<'a> SessionRpcShell<'a> { - /// Starts a shell command and streams output through session notifications. + /// Starts a shell command and streams output through session notifications. The command runs as the leader of its own process group (POSIX) or in a dedicated job object (Windows), so a forced termination — via "shell.kill", the request timeout, or session disposal — signals that whole group/job rather than only the direct child. Two gaps are worth planning for: a command that exits on its own does not trigger that teardown, and on POSIX a descendant that moves itself into a new session or process group (for example via "setsid") leaves the signalled group, so either can leave a background process running. /// /// Wire method: `session.shell.exec`. /// @@ -7589,7 +8893,7 @@ impl<'a> SessionRpcShell<'a> { Ok(serde_json::from_value(_value)?) } - /// Sends a signal to a shell process previously started via "shell.exec". + /// Sends a signal to a shell process previously started via "shell.exec". The signal targets the command's whole process group (POSIX) or job object (Windows), so descendants still in that group are signalled too, not just the direct child. On POSIX a descendant that moved itself into a new session or process group (for example via "setsid") is no longer in the signalled group and survives. /// /// Wire method: `session.shell.kill`. /// @@ -8875,6 +10179,75 @@ impl<'a> SessionRpcWorkspaces<'a> { Ok(serde_json::from_value(_value)?) } + /// Updates workspace metadata for a local session and returns the refreshed workspace. + /// + /// Wire method: `session.workspaces.updateMetadata`. + /// + /// # Parameters + /// + /// * `params` - Workspace metadata fields to update. + /// + /// # Returns + /// + /// Current workspace metadata for the session, including its absolute filesystem path when available. + /// + ///
+ /// + /// **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_metadata( + &self, + params: WorkspacesUpdateMetadataRequest, + ) -> 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_WORKSPACES_UPDATEMETADATA, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Ensures a local session workspace exists and returns it. + /// + /// Wire method: `session.workspaces.ensure`. + /// + /// # Parameters + /// + /// * `params` - Optional session context used when creating a local workspace. + /// + /// # Returns + /// + /// Current workspace metadata for the session, including its absolute filesystem path when available. + /// + ///
+ /// + /// **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 ensure( + &self, + params: WorkspacesEnsureRequest, + ) -> 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_WORKSPACES_ENSURE, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + /// Lists files stored in the session workspace files directory. /// /// Wire method: `session.workspaces.listFiles`. @@ -9026,6 +10399,204 @@ impl<'a> SessionRpcWorkspaces<'a> { Ok(serde_json::from_value(_value)?) } + /// Adds a compaction summary checkpoint to the local session workspace. + /// + /// Wire method: `session.workspaces.addSummary`. + /// + /// # Parameters + /// + /// * `params` - Compaction summary checkpoint to persist. + /// + /// # Returns + /// + /// Persisted summary metadata and refreshed workspace metadata. + /// + ///
+ /// + /// **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_summary( + &self, + params: WorkspacesAddSummaryRequest, + ) -> 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_WORKSPACES_ADDSUMMARY, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Truncates local workspace compaction summaries after a rollback. + /// + /// Wire method: `session.workspaces.truncateSummaries`. + /// + /// # Parameters + /// + /// * `params` - Rollback point for local workspace summaries. + /// + /// # Returns + /// + /// Current workspace metadata for the session, including its absolute filesystem path when available. + /// + ///
+ /// + /// **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 truncate_summaries( + &self, + params: WorkspacesTruncateSummariesRequest, + ) -> 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_WORKSPACES_TRUNCATESUMMARIES, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Reads the autopilot objective state file from the local session workspace. + /// + /// Wire method: `session.workspaces.readAutopilotObjective`. + /// + /// # Returns + /// + /// Autopilot objective file content, or null when missing. + /// + ///
+ /// + /// **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 read_autopilot_objective( + &self, + ) -> Result { + let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + let _value = self + .session + .client() + .call( + rpc_methods::SESSION_WORKSPACES_READAUTOPILOTOBJECTIVE, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Writes the autopilot objective state file in the local session workspace. + /// + /// Wire method: `session.workspaces.writeAutopilotObjective`. + /// + /// # Parameters + /// + /// * `params` - Autopilot objective file content to persist. + /// + /// # Returns + /// + /// Result of writing the autopilot objective file. + /// + ///
+ /// + /// **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 write_autopilot_objective( + &self, + params: WorkspacesWriteAutopilotObjectiveRequest, + ) -> 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_WORKSPACES_WRITEAUTOPILOTOBJECTIVE, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Deletes the autopilot objective state file from the local session workspace. + /// + /// Wire method: `session.workspaces.deleteAutopilotObjective`. + /// + /// # Returns + /// + /// Result of deleting the autopilot objective file. + /// + ///
+ /// + /// **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 delete_autopilot_objective( + &self, + ) -> Result { + let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + let _value = self + .session + .client() + .call( + rpc_methods::SESSION_WORKSPACES_DELETEAUTOPILOTOBJECTIVE, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Checks whether the local session workspace has an autopilot objective state file. + /// + /// Wire method: `session.workspaces.autopilotObjectiveExists`. + /// + /// # Returns + /// + /// Whether the autopilot objective file exists. + /// + ///
+ /// + /// **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 autopilot_objective_exists( + &self, + ) -> Result { + let wire_params = serde_json::json!({ "sessionId": self.session.id() }); + let _value = self + .session + .client() + .call( + rpc_methods::SESSION_WORKSPACES_AUTOPILOTOBJECTIVEEXISTS, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + /// Saves pasted content as a UTF-8 file in the session workspace. /// /// Wire method: `session.workspaces.saveLargePaste`. @@ -9062,7 +10633,7 @@ impl<'a> SessionRpcWorkspaces<'a> { Ok(serde_json::from_value(_value)?) } - /// Computes a diff for the session workspace. + /// Computes a diff for the session workspace. Never rejects for a busy session: a `session`-mode diff that cannot read the session's file-change captures falls back to an unstaged git diff with `isFallback: true` and reports why in `unavailableReason`. /// /// Wire method: `session.workspaces.diff`. /// diff --git a/rust/src/generated/session_events.rs b/rust/src/generated/session_events.rs index abc7dca626..cb3a45b21a 100644 --- a/rust/src/generated/session_events.rs +++ b/rust/src/generated/session_events.rs @@ -233,6 +233,15 @@ pub enum SessionEventType { SessionToolsUpdated, #[serde(rename = "session.background_tasks_changed")] SessionBackgroundTasksChanged, + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(rename = "factory.run_updated")] + FactoryRunUpdated, #[serde(rename = "session.skills_loaded")] SessionSkillsLoaded, #[serde(rename = "session.custom_agents_updated")] @@ -534,6 +543,15 @@ pub enum SessionEventData { SessionToolsUpdated(SessionToolsUpdatedData), #[serde(rename = "session.background_tasks_changed")] SessionBackgroundTasksChanged(SessionBackgroundTasksChangedData), + /// + ///
+ /// + /// **Experimental.** This type is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. + /// + ///
+ #[serde(rename = "factory.run_updated")] + FactoryRunUpdated(FactoryRunUpdatedData), #[serde(rename = "session.skills_loaded")] SessionSkillsLoaded(SessionSkillsLoadedData), #[serde(rename = "session.custom_agents_updated")] @@ -658,6 +676,9 @@ pub struct WorkingDirectoryContext { /// Hosting platform type of the repository (github or ado) #[serde(skip_serializing_if = "Option::is_none")] pub host_type: Option, + /// Set on the immediate preliminary event of a working-directory change, before the git context is resolved. A settled follow-up event (enriched with git context, or cwd-only for a non-repository) is always emitted afterward, so observers may defer to it. Absent on standalone/final events (e.g. relay context changes). + #[serde(skip_serializing_if = "Option::is_none")] + pub pending_git_context: Option, /// Repository identifier derived from the git remote URL ("owner/name" for GitHub, "org/project/repo" for Azure DevOps) #[serde(skip_serializing_if = "Option::is_none")] pub repository: Option, @@ -734,7 +755,7 @@ pub struct SessionResumeData { /// Context tier currently selected at resume time; null when no tier is active #[serde(skip_serializing_if = "Option::is_none")] pub context_tier: Option, - /// When true, tool calls and permission requests left in flight by the previous session lifetime remain pending after resume and the agentic loop awaits their results. User sends are queued behind the pending work until all such requests reach a terminal state. When false (the default), any such tool calls and permission requests are immediately marked as interrupted on resume. + /// When true, tool calls and permission requests left in flight by the previous session lifetime remain pending after resume and the agentic loop awaits their results. User sends are queued behind the pending work until all such requests reach a terminal state. When false or omitted, pending work is normally marked as interrupted unless the resume passively joined live work owned by another client; sessionWasActive distinguishes that case. #[serde(skip_serializing_if = "Option::is_none")] pub continue_pending_work: Option, /// Total number of persisted events in the session at the time of resume @@ -759,7 +780,7 @@ pub struct SessionResumeData { /// Session limits currently configured at resume time; null when no limits are active #[serde(skip_serializing_if = "Option::is_none")] pub session_limits: Option, - /// True when this resume attached to a session that the runtime already had running in-memory (for example, an extension joining a session another client was actively driving). False (or omitted) for cold resumes — the runtime had to reconstitute the session from its persisted event log. + /// True when this resume passively joined a session that already had live work running in the runtime - an agent turn, a native queue run, a queued resume continuation, or an in-flight send (for example, an extension joining a session another client was actively driving). False (or omitted) when the session had no live work or when the resume explicitly abandoned pending work, including cold resumes and suspended sessions that remain resident in memory. #[serde(skip_serializing_if = "Option::is_none")] pub session_was_active: Option, /// Output verbosity level used for model calls, if applicable (e.g. "low", "medium", "high") @@ -841,6 +862,9 @@ pub struct SessionScheduleCreatedData { /// Interval between ticks in milliseconds (relative-interval schedules) #[serde(skip_serializing_if = "Option::is_none")] pub interval_ms: Option, + /// Who created the schedule (`user` or `model`). Persisted so a resumed session keeps gating non-user schedules from firing skills that opted out of model invocation. Absent on entries created before this field existed; a missing origin fails closed (treated the same as a non-user origin), so such a schedule may not resolve a `disable-model-invocation` skill. + #[serde(skip_serializing_if = "Option::is_none")] + pub origin: Option, /// Prompt text that gets enqueued on every tick pub prompt: String, /// Whether the schedule re-arms after each tick (`/every`) or fires once (`/after`) @@ -1289,6 +1313,9 @@ pub struct SessionContextChangedData { /// Hosting platform type of the repository (github or ado) #[serde(skip_serializing_if = "Option::is_none")] pub host_type: Option, + /// Set on the immediate preliminary event of a working-directory change, before the git context is resolved. A settled follow-up event (enriched with git context, or cwd-only for a non-repository) is always emitted afterward, so observers may defer to it. Absent on standalone/final events (e.g. relay context changes). + #[serde(skip_serializing_if = "Option::is_none")] + pub pending_git_context: Option, /// Repository identifier derived from the git remote URL ("owner/name" for GitHub, "org/project/repo" for Azure DevOps) #[serde(skip_serializing_if = "Option::is_none")] pub repository: Option, @@ -1328,15 +1355,24 @@ pub struct SessionCompactionStartData { /// Token count from non-system messages (user, assistant, tool) at compaction start #[serde(skip_serializing_if = "Option::is_none")] pub conversation_tokens: Option, + /// Total context tokens (system + conversation + tool definitions) at compaction start, when known + #[serde(skip_serializing_if = "Option::is_none")] + pub current_tokens: Option, /// Model identifier used for compaction, when known #[serde(skip_serializing_if = "Option::is_none")] pub model: Option, /// Token count from system message(s) at compaction start #[serde(skip_serializing_if = "Option::is_none")] pub system_tokens: Option, + /// Model context window token limit the compaction is targeting, when known + #[serde(skip_serializing_if = "Option::is_none")] + pub token_limit: Option, /// Token count from tool definitions at compaction start #[serde(skip_serializing_if = "Option::is_none")] pub tool_definitions_tokens: Option, + /// What initiated this compaction, when known + #[serde(skip_serializing_if = "Option::is_none")] + pub trigger: Option, } /// Token usage detail for a single billing category @@ -1445,19 +1481,34 @@ pub struct SessionCompactionCompleteData { /// Token count from system message(s) after compaction #[serde(skip_serializing_if = "Option::is_none")] pub system_tokens: Option, + /// Model context window token limit the compaction was targeting, when known + #[serde(skip_serializing_if = "Option::is_none")] + pub token_limit: Option, /// Number of tokens removed during compaction #[serde(skip_serializing_if = "Option::is_none")] pub tokens_removed: Option, /// Token count from tool definitions after compaction #[serde(skip_serializing_if = "Option::is_none")] pub tool_definitions_tokens: Option, + /// What initiated this compaction, when known + #[serde(skip_serializing_if = "Option::is_none")] + pub trigger: Option, } /// Session event "session.task_complete". Task completion notification with summary from the agent #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SessionTaskCompleteData { - /// Whether the tool call succeeded. False when validation failed (e.g., invalid arguments) + /// Active autopilot objective ID evaluated by the completion reviewer + #[serde(skip_serializing_if = "Option::is_none")] + pub objective_id: Option, + /// Semantic completion decision. Absent on legacy events and invalid tool calls + #[serde(skip_serializing_if = "Option::is_none")] + pub outcome: Option, + /// Label-safe runtime rationale for the completion decision (e.g. a cancellation or pause/resume downgrade), when one applies. Reviewer-authored rationale is intentionally omitted here because this event has no IFC label channel; the reviewer's findings remain available through its own labeled sub-agent events + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, + /// Whether the task was accepted as complete. False when validation failed or completion was rejected or blocked by the reviewer #[serde(skip_serializing_if = "Option::is_none")] pub success: Option, /// Summary of the completed task, provided by the agent @@ -1492,7 +1543,7 @@ pub struct UserMessageData { /// Parent agent task ID for background telemetry correlated to this user turn #[serde(skip_serializing_if = "Option::is_none")] pub parent_agent_task_id: Option, - /// Origin of this message, used for timeline filtering (e.g., "skill-pdf" for skill-injected messages that should be hidden from the user) + /// Origin of this message, used for timeline filtering and attribution (e.g., `skill-pdf` for hidden skill injection or `agent-` for an inter-agent prompt) #[serde(skip_serializing_if = "Option::is_none")] pub source: Option, /// Normalized document MIME types that were sent natively instead of through tagged_files XML @@ -1564,6 +1615,8 @@ pub struct AssistantReasoningData { pub content: String, /// Unique identifier for this reasoning block pub reasoning_id: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub rte: Option, } /// Session event "assistant.reasoning_delta". Streaming reasoning delta for incremental extended thinking updates @@ -1792,6 +1845,8 @@ pub struct AssistantMessageData { /// GitHub request tracing ID (x-github-request-id header) for correlating with server-side logs #[serde(skip_serializing_if = "Option::is_none")] pub request_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub rte: Option, /// Neutral provider-tagged server-side tool-use payload (tool search, advisor) for verbatim round-tripping #[serde(skip_serializing_if = "Option::is_none")] pub server_tools: Option, @@ -1968,6 +2023,9 @@ pub struct AssistantUsageData { /// Number of input tokens consumed #[serde(skip_serializing_if = "Option::is_none")] pub input_tokens: Option, + /// Coarse classification of the interaction that produced this call, mirroring the session's per-request agent context (e.g. `conversation-agent`, `conversation-subagent`, `conversation-sampling`, `conversation-background`, `conversation-compaction`, `conversation-user`). Non-billing; lets consumers attribute a model call to a call class (e.g. sub-agent/sidekick) independently of the billing initiator. Absent when the runtime did not classify the request. + #[serde(skip_serializing_if = "Option::is_none")] + pub interaction_type: Option, /// Average inter-token latency in milliseconds. Only available for streaming requests #[serde(skip_serializing_if = "Option::is_none")] pub inter_token_latency_ms: Option, @@ -1994,6 +2052,8 @@ pub struct AssistantUsageData { /// Number of output tokens used for reasoning (e.g., chain-of-thought) #[serde(skip_serializing_if = "Option::is_none")] pub reasoning_tokens: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub rte: Option, /// Copilot service request ID (x-copilot-service-request-id header) for CAPI log correlation #[serde(skip_serializing_if = "Option::is_none")] pub service_request_id: Option, @@ -2082,6 +2142,8 @@ pub struct ModelCallFailureData { /// Content-free structural summary of the failing request. Contains only counts and shape flags (no prompt content), so it is safe for unrestricted telemetry. Populated only for client-error (4xx) failures. #[serde(skip_serializing_if = "Option::is_none")] pub request_fingerprint: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub rte: Option, /// Copilot service request ID (x-copilot-service-request-id header) for CAPI log correlation #[serde(skip_serializing_if = "Option::is_none")] pub service_request_id: Option, @@ -2102,6 +2164,10 @@ pub struct ModelCallStartData { /// Model identifier used for this API call, when known #[serde(skip_serializing_if = "Option::is_none")] pub model: Option, + /// Previous response or interaction identifier included in the model request, when present + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) previous_response_id: Option, /// Identifier of the assistant turn that initiated the model call pub turn_id: String, } @@ -2196,6 +2262,8 @@ pub struct ToolExecutionStartData { #[deprecated] #[serde(skip_serializing_if = "Option::is_none")] pub parent_tool_call_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub rte: Option, /// Shell-tool path hints derived from the command at start time for shell tools (bash/powershell/local_shell). Produced by the same shell-aware extractor as PermissionRequestShell.possiblePaths, so it is present even when the command is auto-approved and no permission request fires. Absent for non-shell tools. #[serde(skip_serializing_if = "Option::is_none")] pub shell_tool_info: Option, @@ -2636,6 +2704,8 @@ pub struct ToolExecutionCompleteData { /// Tool execution result on success #[serde(skip_serializing_if = "Option::is_none")] pub result: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub rte: Option, /// Whether this tool execution ran inside a sandbox container #[serde(skip_serializing_if = "Option::is_none")] pub sandboxed: Option, @@ -2877,6 +2947,9 @@ pub struct SystemMessageMetadata { pub struct SystemMessageData { /// The system or developer prompt text sent as model input pub content: String, + /// Logical interaction identifier for the model run receiving this prompt + #[serde(skip_serializing_if = "Option::is_none")] + pub interaction_id: Option, /// Metadata about the prompt template and its construction #[serde(skip_serializing_if = "Option::is_none")] pub metadata: Option, @@ -2907,6 +2980,16 @@ pub struct PermissionRequestShellCommand { pub read_only: bool, } +/// A parsed shell command segment used for argument-aware managed policy matching. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PermissionRequestShellCommandSegment { + /// Full text of this command segment, including arguments + pub full_command_text: String, + /// Command identifier (e.g., executable name) + pub identifier: String, +} + /// A URL that may be accessed by a command in a shell permission request. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -2923,6 +3006,9 @@ pub struct PermissionRequestShell { pub can_offer_session_approval: bool, /// Parsed command identifiers found in the command text pub commands: Vec, + /// Parsed command segments, including arguments, used for managed policy matching + #[serde(skip_serializing_if = "Option::is_none")] + pub command_segments: Option>, /// The complete shell command text to be executed pub full_command_text: String, /// Whether the command includes a file write redirection (e.g., > or >>) @@ -2931,6 +3017,9 @@ pub struct PermissionRequestShell { pub intention: String, /// Permission kind discriminator pub kind: PermissionRequestShellKind, + /// Whether managed policy requires a human response and forbids host auto-approval + #[serde(skip_serializing_if = "Option::is_none")] + pub managed_approval_required: Option, /// File paths that may be read or written by the command pub possible_paths: Vec, /// URLs that may be accessed by the command @@ -2963,6 +3052,9 @@ pub struct PermissionRequestWrite { pub intention: String, /// Permission kind discriminator pub kind: PermissionRequestWriteKind, + /// Whether managed policy requires a human response and forbids host auto-approval + #[serde(skip_serializing_if = "Option::is_none")] + pub managed_approval_required: Option, /// Complete new file contents for newly created files #[serde(skip_serializing_if = "Option::is_none")] pub new_file_contents: Option, @@ -2985,6 +3077,9 @@ pub struct PermissionRequestRead { pub intention: String, /// Permission kind discriminator pub kind: PermissionRequestReadKind, + /// Whether managed policy requires a human response and forbids host auto-approval + #[serde(skip_serializing_if = "Option::is_none")] + pub managed_approval_required: Option, /// Path of the file or directory being read pub path: String, /// True when the model has requested to run this search outside the sandbox (it set requestSandboxBypass: true and the host opted in via sandbox.allowBypass). This is a request, not a grant: the search runs unsandboxed only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. @@ -3028,6 +3123,12 @@ pub struct PermissionRequestUrl { pub intention: String, /// Permission kind discriminator pub kind: PermissionRequestUrlKind, + /// Whether managed policy requires a human response and forbids host auto-approval + #[serde(skip_serializing_if = "Option::is_none")] + pub managed_approval_required: Option, + /// Immediately preceding URL when this request is for a redirect target + #[serde(skip_serializing_if = "Option::is_none")] + pub redirected_from: Option, /// True when this URL fetch is requesting to bypass the sandbox network policy: either the model set requestSandboxBypass: true, or the tool re-issued the request as an interactive bypass after the network policy denied the approved URL (host opted in via sandbox.allowBypass). This is a request, not a grant: the fetch runs only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. #[serde(skip_serializing_if = "Option::is_none")] pub request_sandbox_bypass: Option, @@ -3148,6 +3249,12 @@ pub struct PermissionRequestExtensionPermissionAccess { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PermissionAutoApproval { + /// Classified cause of an `error` recommendation. Absent for every other recommendation. + #[serde(skip_serializing_if = "Option::is_none")] + pub failure_reason: Option, + /// Model id that produced the recommendation, when the judge was consulted and reported one. Absent for `excluded` (the judge was not consulted) and for failures that occurred before a model was selected. + #[serde(skip_serializing_if = "Option::is_none")] + pub model: Option, /// Human-readable reason for the judge's recommendation, when available. #[serde(skip_serializing_if = "Option::is_none")] pub reason: Option, @@ -3179,6 +3286,9 @@ pub struct PermissionPromptRequestCommands { pub intention: String, /// Prompt kind discriminator pub kind: PermissionPromptRequestCommandsKind, + /// Whether managed policy requires a human response and forbids host auto-approval + #[serde(skip_serializing_if = "Option::is_none")] + pub managed_approval_required: Option, /// Tool call ID that triggered this permission request #[serde(skip_serializing_if = "Option::is_none")] pub tool_call_id: Option, @@ -3211,6 +3321,9 @@ pub struct PermissionPromptRequestWrite { pub intention: String, /// Prompt kind discriminator pub kind: PermissionPromptRequestWriteKind, + /// Whether managed policy requires a human response and forbids host auto-approval + #[serde(skip_serializing_if = "Option::is_none")] + pub managed_approval_required: Option, /// Complete new file contents for newly created files #[serde(skip_serializing_if = "Option::is_none")] pub new_file_contents: Option, @@ -3237,6 +3350,9 @@ pub struct PermissionPromptRequestRead { pub intention: String, /// Prompt kind discriminator pub kind: PermissionPromptRequestReadKind, + /// Whether managed policy requires a human response and forbids host auto-approval + #[serde(skip_serializing_if = "Option::is_none")] + pub managed_approval_required: Option, /// Path of the file or directory being read pub path: String, /// Tool call ID that triggered this permission request @@ -3292,6 +3408,12 @@ pub struct PermissionPromptRequestUrl { pub intention: String, /// Prompt kind discriminator pub kind: PermissionPromptRequestUrlKind, + /// Whether managed policy requires a human response and forbids host auto-approval + #[serde(skip_serializing_if = "Option::is_none")] + pub managed_approval_required: Option, + /// Immediately preceding URL when this prompt is for a redirect target + #[serde(skip_serializing_if = "Option::is_none")] + pub redirected_from: Option, /// True when this URL fetch is requesting to bypass the sandbox network policy: either the model set requestSandboxBypass: true, or the tool re-issued the request as an interactive bypass after the network policy denied the approved URL (host opted in via sandbox.allowBypass). This is a request, not a grant: the fetch runs only if the user approves this permission request. Hosts should highlight the elevated risk in the approval UI. #[serde(skip_serializing_if = "Option::is_none")] pub request_sandbox_bypass: Option, @@ -3490,6 +3612,9 @@ pub struct PermissionRequestedData { /// When true, this permission was already resolved by a permissionRequest hook and requires no client action #[serde(skip_serializing_if = "Option::is_none")] pub resolved_by_hook: Option, + /// Neutral risk metadata supplied by the tool host. Consumers may display this value but must not use it to bypass the permission decision. + #[serde(skip_serializing_if = "Option::is_none")] + pub risk_assessment: Option, } /// Permission response variant indicating the request was approved without persisting an approval rule. @@ -4066,6 +4191,9 @@ pub struct SessionLimitsExhaustedCompletedData { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SessionAutoModeResolvedData { + /// Models offered to the router for this resolution + #[serde(skip_serializing_if = "Option::is_none")] + pub available_models: Option>, /// Ordered candidate model list the router returned, when not a fallback #[serde(skip_serializing_if = "Option::is_none")] pub candidate_models: Option>, @@ -4074,15 +4202,39 @@ pub struct SessionAutoModeResolvedData { pub category_scores: Option>, /// The concrete model the session will use after any intent refinement pub chosen_model: String, + /// The chosen model's score shortfall relative to the top candidate + #[serde(skip_serializing_if = "Option::is_none")] + pub chosen_shortfall: Option, /// Classifier confidence for the predicted label, when available #[serde(skip_serializing_if = "Option::is_none")] pub confidence: Option, + /// End-to-end client wait time for the router request in milliseconds + #[serde(skip_serializing_if = "Option::is_none")] + pub end_to_end_latency_ms: Option, + /// Whether the router fell back to the standard Auto selection + #[serde(skip_serializing_if = "Option::is_none")] + pub fallback: Option, + /// Server-provided reason for falling back, when available + #[serde(skip_serializing_if = "Option::is_none")] + pub fallback_reason: Option, + /// Whether the routed prompt contained an image + #[serde(skip_serializing_if = "Option::is_none")] + pub has_image: Option, /// The predicted classifier label (e.g. `needs_reasoning`), when available #[serde(skip_serializing_if = "Option::is_none")] pub predicted_label: Option, /// Coarse request-difficulty bucket, for explaining why a model was chosen ("picked X because this looks like high-reasoning work") #[serde(skip_serializing_if = "Option::is_none")] pub reasoning_bucket: Option, + /// Server-reported router processing time in milliseconds + #[serde(skip_serializing_if = "Option::is_none")] + pub router_latency_ms: Option, + /// The routing method the server applied, when Auto Intent ran + #[serde(skip_serializing_if = "Option::is_none")] + pub routing_method: Option, + /// Whether a sticky model choice overrode the router result + #[serde(skip_serializing_if = "Option::is_none")] + pub sticky_override: Option, } /// Session event "session.managed_settings_resolved". Enterprise managed-settings resolution: the effective managed settings the session applied and where they came from, so SDK clients can show users what is enterprise-managed and by which authority. Fires whenever managed policy is (re)applied — at session start, on resume, and on account switch. This is an ephemeral live snapshot (delivered to subscribers but not persisted to the session event log), because at session start it resolves before `session.start` is emitted; for a session-independent pull, use the SDK `getManagedSettings()` API, which returns the identical payload. Managed settings have a single authoritative source, so the highest-authority present layer (server > device) wins wholesale; `bypassPermissionsDisabled` is deny-wins across layers. Marked experimental while the managed-settings surface stabilizes. @@ -4104,6 +4256,9 @@ pub struct SessionManagedSettingsResolvedData { pub fail_closed: bool, /// The setting keys under enterprise management in the effective managed settings (e.g. `model`, `enabledPlugins`, `permissions`). Empty when no managed settings are in force. pub managed_keys: Vec, + /// Whether server and device each supplied a permission allowlist, so enforcement intersects them and the flattened settings payload omits `permissions.allow`. + #[serde(skip_serializing_if = "Option::is_none")] + pub permissions_allow_intersected: Option, /// Whether the server (account/org) managed-settings layer was present pub server_managed: bool, /// The effective (resolved) managed settings values, so clients can render exactly what is enforced. Absent when no managed policy is in force. @@ -4229,6 +4384,22 @@ pub struct SessionToolsUpdatedData { #[serde(rename_all = "camelCase")] pub struct SessionBackgroundTasksChangedData {} +/// Session event "factory.run_updated". Ephemeral invalidation signal for a changed factory run. +/// +///
+/// +/// **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 FactoryRunUpdatedData { + /// Monotonic revision now available for the run. + pub revision: i64, + pub run_id: String, +} + /// A single resolved skill in `session.skills_loaded`, including source, invocability, enabled state, path, and argument hint. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -4703,6 +4874,21 @@ pub enum Verbosity { Unknown, } +/// Who created the schedule: `user` (an explicit user action such as `/every` or `/after`) or `model` (the agent via the `manage_schedule` tool). Gates whether a scheduled skill that opted out of model invocation may fire: only user-created schedules may. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum ScheduleOrigin { + /// The schedule was created by an explicit user action, such as `/every` or `/after`. + #[serde(rename = "user")] + User, + /// The schedule was created by the agent via the `manage_schedule` tool. + #[serde(rename = "model")] + Model, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + /// The type of operation performed on the autopilot objective state file #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum AutopilotObjectiveChangedOperation { @@ -4848,6 +5034,48 @@ pub enum ShutdownType { Unknown, } +/// What initiated a conversation compaction +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum CompactionTrigger { + /// Background compaction started automatically because context utilization crossed the background threshold. + #[serde(rename = "threshold")] + Threshold, + /// Compaction forced by a context-limit model response (e.g. HTTP 413) before retrying the request. + #[serde(rename = "context_limit_retry")] + ContextLimitRetry, + /// User-requested compaction, e.g. the /compact command or the history.compact API. + #[serde(rename = "manual")] + Manual, + /// Emergency compaction triggered by high process memory usage. + #[serde(rename = "memory_pressure")] + MemoryPressure, + /// Compaction requested while switching to a model with a smaller context window. + #[serde(rename = "model_switch")] + ModelSwitch, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// Semantic result of evaluating a task completion request +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum TaskCompletionOutcome { + /// The completion request was accepted and the objective is complete. + #[serde(rename = "completed")] + Completed, + /// The completion request was rejected because more work or validation remains. + #[serde(rename = "continue")] + Continue, + /// Completion cannot proceed without intervention; the active objective is paused when one is identified. + #[serde(rename = "blocked")] + Blocked, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + /// The agent mode that was active when this message was sent #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum UserMessageAgentMode { @@ -5325,6 +5553,37 @@ pub enum PermissionRequest { ExtensionPermissionAccess(PermissionRequestExtensionPermissionAccess), } +/// Why the auto-approval judge produced no usable recommendation. Present only alongside an `error` recommendation, where the human-readable reason is a fixed string and therefore cannot distinguish these cases. Intended to make a judge failure reportable by a consumer that has no access to the host's logs. +/// +///
+/// +/// **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, PartialEq, Eq, Serialize, Deserialize)] +pub enum AutoApprovalJudgeFailureReason { + /// The judge model call exceeded its deadline. + #[serde(rename = "timeout")] + Timeout, + /// The judge model call was cancelled before it returned. + #[serde(rename = "abort")] + Abort, + /// The judge model call completed but returned no content. + #[serde(rename = "empty_response")] + EmptyResponse, + /// The judge model call failed (for example a transport, authentication, or rate-limit error). + #[serde(rename = "model_error")] + ModelError, + /// The judge model replied, but the reply carried no ALLOW/DENY verdict. + #[serde(rename = "parse_error")] + ParseError, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + /// Outcome of the auto-approval safety judge for a permission request. Present only when auto mode is enabled; its absence means the judge did not evaluate the request (auto mode was off). /// ///
diff --git a/test/harness/package-lock.json b/test/harness/package-lock.json index ca426f38a6..1b414dcad2 100644 --- a/test/harness/package-lock.json +++ b/test/harness/package-lock.json @@ -9,7 +9,7 @@ "version": "1.0.0", "license": "ISC", "devDependencies": { - "@github/copilot": "^1.0.73", + "@github/copilot": "^1.0.76-5", "@modelcontextprotocol/sdk": "^1.26.0", "@types/node": "^25.3.3", "@types/node-forge": "^1.3.14", @@ -501,9 +501,9 @@ } }, "node_modules/@github/copilot": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot/-/copilot-1.0.73.tgz", - "integrity": "sha512-8I2Ejg2CX/PQA3c2H8W1zuqhniCeR1q1/bD8CrV53/ZLw8GF7DAV0xQpwa8ELYvFgjXb6AADojafCKwdbVef+A==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot/-/copilot-1.0.76-5.tgz", + "integrity": "sha512-hbE+dgYeR59lEGTNFgBi7G2xbMNetzq2G9FFrLVD1k0Z1ZavSeZAfrfAuBbVCXvYjr2cfKE6oSeMYUB0fArFjw==", "dev": true, "license": "SEE LICENSE IN LICENSE.md", "dependencies": { @@ -513,20 +513,20 @@ "copilot": "npm-loader.js" }, "optionalDependencies": { - "@github/copilot-darwin-arm64": "1.0.73", - "@github/copilot-darwin-x64": "1.0.73", - "@github/copilot-linux-arm64": "1.0.73", - "@github/copilot-linux-x64": "1.0.73", - "@github/copilot-linuxmusl-arm64": "1.0.73", - "@github/copilot-linuxmusl-x64": "1.0.73", - "@github/copilot-win32-arm64": "1.0.73", - "@github/copilot-win32-x64": "1.0.73" + "@github/copilot-darwin-arm64": "1.0.76-5", + "@github/copilot-darwin-x64": "1.0.76-5", + "@github/copilot-linux-arm64": "1.0.76-5", + "@github/copilot-linux-x64": "1.0.76-5", + "@github/copilot-linuxmusl-arm64": "1.0.76-5", + "@github/copilot-linuxmusl-x64": "1.0.76-5", + "@github/copilot-win32-arm64": "1.0.76-5", + "@github/copilot-win32-x64": "1.0.76-5" } }, "node_modules/@github/copilot-darwin-arm64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-darwin-arm64/-/copilot-darwin-arm64-1.0.73.tgz", - "integrity": "sha512-5jv7t2sw35/zI0cPze38hG6239NT5/q/Emjx6gLibYkolDqMDJjpm17Ps7tc8oafUEOiMQMb+ar7+qi6rSiGJA==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-darwin-arm64/-/copilot-darwin-arm64-1.0.76-5.tgz", + "integrity": "sha512-kHg7wUP1RJoNHAd520I1g+nE0kHl4bxQtufg7CE18Xa0aNgC10PcSe9BwqcFEe8RiGdMCUMtohGMKJIqKdyv8Q==", "cpu": [ "arm64" ], @@ -541,9 +541,9 @@ } }, "node_modules/@github/copilot-darwin-x64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-darwin-x64/-/copilot-darwin-x64-1.0.73.tgz", - "integrity": "sha512-l794k6Ahb11AG2FQT/P4TEWxWblzM1h8aQQCzG8jBWp8dfwjhyYjJ+d+0CWQzM3Fc1ddNUZRjKXCUsfvFjiZhQ==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-darwin-x64/-/copilot-darwin-x64-1.0.76-5.tgz", + "integrity": "sha512-B01l/9qLn+BI3yjsTn7tPHJaCA+2hM6KrqSF7NR5HgQ+AtwRriC+ufwlbWPUatrwtXneQZIRgaSKCNUwLsBrBw==", "cpu": [ "x64" ], @@ -558,9 +558,9 @@ } }, "node_modules/@github/copilot-linux-arm64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-linux-arm64/-/copilot-linux-arm64-1.0.73.tgz", - "integrity": "sha512-Zu0W5nupJjNeem0brqU/pG+VY0IWr6EWr/FsC90g5SEDiaM4VhVNVWcz8t0E3DQCSYetV6IBaNMtjs/3uIIiDQ==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-linux-arm64/-/copilot-linux-arm64-1.0.76-5.tgz", + "integrity": "sha512-QvZSCcIA5cxOhWtviLAMHHn8em7PNSTM9DMujfgAAGKl9w1AFhbN+hsTOtvOojdZYXVMZuiQlYmtZ8EemyiZOg==", "cpu": [ "arm64" ], @@ -575,9 +575,9 @@ } }, "node_modules/@github/copilot-linux-x64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-linux-x64/-/copilot-linux-x64-1.0.73.tgz", - "integrity": "sha512-k33XIr6/PVp+K+5F/zv3No4PPaNImvHz73mcbIw63oxh5iiacXjgr0WqbBIS5s/rkhOWjNPIkbof/TTPZ7mQjA==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-linux-x64/-/copilot-linux-x64-1.0.76-5.tgz", + "integrity": "sha512-61wmKXleon7KGv7e2WtbUC6oYH/QkpjowTI3YvgriNaey8/SaZo4ODt59D/L47s8PqqpvPCbe/f6zmjGLNNWEw==", "cpu": [ "x64" ], @@ -592,9 +592,9 @@ } }, "node_modules/@github/copilot-linuxmusl-arm64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-arm64/-/copilot-linuxmusl-arm64-1.0.73.tgz", - "integrity": "sha512-HJWzhfD3oaiIgfRAHkNWzp17fELtshqM9HVN5n+lFEmSO2EETCEh0P1lhJc4m+FYfXSJnL0raAqVuyaNMuPoPw==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-arm64/-/copilot-linuxmusl-arm64-1.0.76-5.tgz", + "integrity": "sha512-WUD8c5YFEL3LecdocT+VIj83EqnNKrb3YL7Wqk+FtFzzjNmF3UGrVo1CbMerTuQzWU65QhgIt1mEBKN1bMSJqQ==", "cpu": [ "arm64" ], @@ -609,9 +609,9 @@ } }, "node_modules/@github/copilot-linuxmusl-x64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-x64/-/copilot-linuxmusl-x64-1.0.73.tgz", - "integrity": "sha512-/BpOXSb16wHEu8I1SaKiLszQ4Kvu4+Z4uCn7W0bv4xI4fPZwTEG0u3zgaI2W9Ao3+aBl0XRpPmpWzE9ziYEq+w==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-linuxmusl-x64/-/copilot-linuxmusl-x64-1.0.76-5.tgz", + "integrity": "sha512-HM44XEx1TcZfpLDcFPf0ya0Bi/0wxJzrrR7FRhRG6C2VYBr/mfUsXBUF9V7vZZMv7yKDPro27PLjpsuMDJyYsQ==", "cpu": [ "x64" ], @@ -626,9 +626,9 @@ } }, "node_modules/@github/copilot-win32-arm64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-win32-arm64/-/copilot-win32-arm64-1.0.73.tgz", - "integrity": "sha512-DbPeXiYzQjpOy9oboaBvuCzjRwfcL987c3bG09cK1crdCDrKfkTJ7NXpcp1KWRPIRFO1FQm1qToNE89J+L3uvg==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-win32-arm64/-/copilot-win32-arm64-1.0.76-5.tgz", + "integrity": "sha512-cbrnDRo7cYAbJuCt4f+1Cw8SiFfNOkCBg3RR/jAcV7Y5ED3QEEoad3WN8avFaiAOGHyTJYqBRTQJNBkyRTmrEw==", "cpu": [ "arm64" ], @@ -643,9 +643,9 @@ } }, "node_modules/@github/copilot-win32-x64": { - "version": "1.0.73", - "resolved": "https://registry.npmjs.org/@github/copilot-win32-x64/-/copilot-win32-x64-1.0.73.tgz", - "integrity": "sha512-8D3E1l5i+N5Eq8HIOQpx+Zbcb3MXdFxszksM2gqq175Z1S7Zna67oY4GoR3psxlbIpSyHKiLEBWYiaps6ayHWw==", + "version": "1.0.76-5", + "resolved": "https://registry.npmjs.org/@github/copilot-win32-x64/-/copilot-win32-x64-1.0.76-5.tgz", + "integrity": "sha512-ShgpTm07YqQQuRLgJ5BqVzKfSlZ4YMmlz7rl/Br5Ifkz57+/HUF2EJBX2LDt05ha1isOaN1ekZQmWvdzWrVCoQ==", "cpu": [ "x64" ], diff --git a/test/harness/package.json b/test/harness/package.json index c77a25f541..bd49e5bddf 100644 --- a/test/harness/package.json +++ b/test/harness/package.json @@ -14,7 +14,7 @@ "node": "^20.19.0 || >=22.12.0" }, "devDependencies": { - "@github/copilot": "^1.0.73", + "@github/copilot": "^1.0.76-5", "@modelcontextprotocol/sdk": "^1.26.0", "@types/node": "^25.3.3", "@types/node-forge": "^1.3.14", From eb8e07df553ed7124546a6095913119d3a6effbd Mon Sep 17 00:00:00 2001 From: Mackinnon Buck Date: Wed, 29 Jul 2026 16:10:17 -0700 Subject: [PATCH 2/6] Fix SDK compatibility with Copilot 1.0.76-5 Update protocol generators and handwritten adapters for the latest RPC schema, including session filesystem SQLite transactions and newly required request fields. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 7b5e2763-c535-4d58-bd7d-409c5d27c448 --- dotnet/src/Generated/Rpc.cs | 64 +------ dotnet/src/Session.cs | 3 +- dotnet/src/SessionFsProvider.cs | 116 +++++++++++++ dotnet/test/E2E/CommandsE2ETests.cs | 8 +- .../E2E/InMemorySessionFsSqliteHandler.cs | 58 ++++++- dotnet/test/E2E/SessionFsE2ETests.cs | 3 + .../e2e/commands_and_elicitation_e2e_test.go | 8 +- go/internal/e2e/rpc_session_state_e2e_test.go | 2 +- go/internal/e2e/session_fs_sqlite_e2e_test.go | 53 ++++-- go/session_fs_provider.go | 74 +++++++++ java/scripts/codegen/java.ts | 90 +++++++--- .../generated/rpc/AccountGetQuotaParams.java | 30 ++++ .../generated/rpc/MemoryConfiguration.java | 27 +++ .../generated/rpc/ModelsListParams.java | 30 ++++ .../rpc/PluginsMarketplacesRefreshParams.java | 30 ++++ .../generated/rpc/ServerAccountApi.java | 15 +- .../generated/rpc/ServerModelsApi.java | 15 +- .../rpc/ServerPluginsMarketplacesApi.java | 15 +- .../generated/rpc/ServerSessionsApi.java | 45 ++++- .../generated/rpc/SessionAgentApi.java | 20 ++- .../generated/rpc/SessionAgentListParams.java | 34 ++++ .../generated/rpc/SessionCommandsApi.java | 20 ++- .../rpc/SessionCommandsListParams.java | 36 ++++ .../generated/rpc/SessionHistoryApi.java | 20 ++- .../rpc/SessionHistoryCompactParams.java | 56 +++++++ .../rpc/SessionLimitPredictionApi.java | 22 ++- .../SessionLimitPredictionPredictParams.java | 34 ++++ .../generated/rpc/SessionListFilter.java | 33 ++++ .../generated/rpc/SessionModelApi.java | 20 ++- .../generated/rpc/SessionModelListParams.java | 32 ++++ .../generated/rpc/SessionOpenOptions.java | 157 ++++++++++++++++++ ...tionsAdditionalContentExclusionPolicy.java | 30 ++++ ...sAdditionalContentExclusionPolicyRule.java | 31 ++++ ...ionalContentExclusionPolicyRuleSource.java | 27 +++ ...AdditionalContentExclusionPolicyScope.java | 35 ++++ .../rpc/SessionOpenOptionsEnvValueMode.java | 35 ++++ .../SessionOpenOptionsReasoningSummary.java | 37 +++++ .../generated/rpc/SessionPluginsApi.java | 22 ++- .../rpc/SessionPluginsReloadParams.java | 40 +++++ .../generated/rpc/SessionProviderApi.java | 20 ++- .../rpc/SessionProviderGetEndpointParams.java | 32 ++++ .../copilot/generated/rpc/SessionSource.java | 37 +++++ .../generated/rpc/SessionsListParams.java | 38 +++++ .../generated/rpc/SessionsOpenParams.java | 34 ++++ .../rpc/SessionsStopRemoteControlParams.java | 32 ++++ .../com/github/copilot/CopilotClient.java | 2 + .../com/github/copilot/CopilotSession.java | 5 +- .../copilot/RpcSessionStateExtrasE2ETest.java | 2 +- .../com/github/copilot/RpcWrappersTest.java | 2 +- .../SessionEventDeserializationTest.java | 3 +- .../copilot/SessionEventHandlingTest.java | 2 +- .../rpc/GeneratedRpcRecordsCoverageTest.java | 29 ++-- nodejs/src/index.ts | 3 + nodejs/src/sessionFsProvider.ts | 80 ++++++++- nodejs/src/types.ts | 3 + nodejs/test/e2e/session_fs.e2e.test.ts | 24 +++ nodejs/test/e2e/session_fs_sqlite.e2e.test.ts | 106 ++++++++---- nodejs/test/session_fs_adapter.test.ts | 23 +++ python/copilot/__init__.py | 2 + python/copilot/session_fs_provider.py | 78 +++++++++ python/e2e/test_rpc_commands_e2e.py | 4 +- python/e2e/test_rpc_session_state_e2e.py | 5 +- python/e2e/test_session_fs_e2e.py | 19 +++ python/e2e/test_session_fs_sqlite_e2e.py | 46 ++++- rust/examples/manual_tool_resume.rs | 1 + rust/src/session.rs | 1 + rust/src/session_fs.rs | 59 ++++++- rust/src/session_fs_dispatch.rs | 69 +++++++- rust/src/types.rs | 3 +- rust/tests/e2e/rpc_additional_edge_cases.rs | 7 +- rust/tests/e2e/rpc_event_log.rs | 3 + rust/tests/e2e/rpc_session_state.rs | 6 +- rust/tests/e2e/rpc_session_state_extras.rs | 1 + rust/tests/e2e/rpc_tasks_and_handlers.rs | 2 + rust/tests/e2e/session_fs_sqlite.rs | 106 ++++++++---- rust/tests/session_test.rs | 27 ++- scripts/codegen/csharp.ts | 15 +- 77 files changed, 2128 insertions(+), 230 deletions(-) create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/AccountGetQuotaParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/MemoryConfiguration.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/ModelsListParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/PluginsMarketplacesRefreshParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionAgentListParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionCommandsListParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryCompactParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionPredictParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionListFilter.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionModelListParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptions.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsAdditionalContentExclusionPolicy.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsAdditionalContentExclusionPolicyRule.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsAdditionalContentExclusionPolicyScope.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsEnvValueMode.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsReasoningSummary.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionPluginsReloadParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionProviderGetEndpointParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionSource.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionsListParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenParams.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionsStopRemoteControlParams.java diff --git a/dotnet/src/Generated/Rpc.cs b/dotnet/src/Generated/Rpc.cs index 427cc0d77c..a10efe5577 100644 --- a/dotnet/src/Generated/Rpc.cs +++ b/dotnet/src/Generated/Rpc.cs @@ -12671,7 +12671,7 @@ internal sealed class SessionHistoryCompactRequestWithSession /// What initiated this compaction request, recorded as the `trigger` on the persisted `session.compaction_start` / `session.compaction_complete` events. When absent, the compaction is persisted without trigger attribution (initiator unknown). [JsonPropertyName("trigger")] - public SessionHistoryCompactRequestWithSessionTrigger? Trigger { get; set; } + public SessionHistoryCompactRequestTrigger? Trigger { get; set; } } /// Number of events that were removed by the truncation. @@ -21441,68 +21441,6 @@ public override void Write(Utf8JsonWriter writer, SessionHistoryCompactRequestTr } -/// What initiated this compaction request, recorded as the `trigger` on the persisted `session.compaction_start` / `session.compaction_complete` events. When absent, the compaction is persisted without trigger attribution (initiator unknown). -[JsonConverter(typeof(Converter))] -[DebuggerDisplay("{Value,nq}")] -public readonly struct SessionHistoryCompactRequestWithSessionTrigger : IEquatable -{ - private readonly string? _value; - - /// Initializes a new instance of the struct. - /// The value to associate with this . - [JsonConstructor] - public SessionHistoryCompactRequestWithSessionTrigger(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - _value = value; - } - - /// Gets the value associated with this . - public string Value => _value ?? string.Empty; - - /// User-requested compaction, e.g. the /compact command or a direct history.compact call. - public static SessionHistoryCompactRequestWithSessionTrigger Manual { get; } = new("manual"); - - /// Compaction requested while switching to a model with a smaller context window. - public static SessionHistoryCompactRequestWithSessionTrigger ModelSwitch { get; } = new("model_switch"); - - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(SessionHistoryCompactRequestWithSessionTrigger left, SessionHistoryCompactRequestWithSessionTrigger right) => left.Equals(right); - - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(SessionHistoryCompactRequestWithSessionTrigger left, SessionHistoryCompactRequestWithSessionTrigger right) => !(left == right); - - /// - public override bool Equals(object? obj) => obj is SessionHistoryCompactRequestWithSessionTrigger other && Equals(other); - - /// - public bool Equals(SessionHistoryCompactRequestWithSessionTrigger other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); - - /// - public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); - - /// - public override string ToString() => Value; - - /// Provides a for serializing instances. - [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter - { - /// - public override SessionHistoryCompactRequestWithSessionTrigger Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); - } - - /// - public override void Write(Utf8JsonWriter writer, SessionHistoryCompactRequestWithSessionTrigger value, JsonSerializerOptions options) - { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SessionHistoryCompactRequestWithSessionTrigger)); - } - } -} - - /// Aggregate file change represented by a rewind preview. [Experimental(Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] diff --git a/dotnet/src/Session.cs b/dotnet/src/Session.cs index de25b78256..6db0744b48 100644 --- a/dotnet/src/Session.cs +++ b/dotnet/src/Session.cs @@ -1145,7 +1145,7 @@ internal void SetCanvasHandler(ICanvasHandler? handler) ClientSessionApis.Canvas = handler is null ? null : new CanvasHandlerAdapter(handler); } - private static readonly JsonElement NullJsonElement = JsonDocument.Parse("null").RootElement.Clone(); + private static readonly JsonElement NullJsonElement = JsonElement.Parse("null"); private static JsonElement SerializeActionResult(object? value) { @@ -1823,6 +1823,7 @@ await Rpc.Model.SwitchToAsync( null, options.ModelCapabilities, options.ContextTier, + null, cancellationToken); } diff --git a/dotnet/src/SessionFsProvider.cs b/dotnet/src/SessionFsProvider.cs index fbb8df507d..d4e99567ca 100644 --- a/dotnet/src/SessionFsProvider.cs +++ b/dotnet/src/SessionFsProvider.cs @@ -3,6 +3,7 @@ *--------------------------------------------------------------------------------------------*/ using GitHub.Copilot.Rpc; +using System.Diagnostics.CodeAnalysis; using System.Text.Json; namespace GitHub.Copilot; @@ -27,6 +28,23 @@ public sealed class SessionFsSqliteResult public long? LastInsertRowid { get; set; } } +/// +/// One statement in an atomic SQLite transaction passed to +/// . +/// +[Experimental(Diagnostics.Experimental)] +public sealed class SessionFsSqliteStatement +{ + /// How to execute: "exec", "query", or "run". + public SessionFsSqliteQueryType QueryType { get; set; } + + /// SQL statement to execute. + public string Query { get; set; } = string.Empty; + + /// Optional named bind parameters. + public IDictionary? Params { get; set; } +} + /// /// Optional interface for subclasses that support /// per-session SQLite databases. Implement this interface on your provider to enable @@ -48,6 +66,20 @@ public interface ISessionFsSqliteProvider IDictionary? bindParams, CancellationToken cancellationToken); + /// + /// Executes atomically against the per-session database. + /// + /// Statements to execute in order, inside a single transaction. + /// Cancellation token. + /// One result per statement, in the same order as . + /// + /// Thrown to tell the runtime how the failure should be classified. Any other exception + /// is reported as . + /// + Task> TransactionAsync( + IList statements, + CancellationToken cancellationToken); + /// /// Checks whether the per-session SQLite database already exists, without creating it. /// @@ -55,6 +87,32 @@ public interface ISessionFsSqliteProvider Task ExistsAsync(CancellationToken cancellationToken); } +/// +/// Thrown by an to classify a failed SQLite transaction. +/// guarantees the transaction +/// rolled back and is safe to retry; +/// must never be retried. +/// +[Experimental(Diagnostics.Experimental)] +public sealed class SessionFsSqliteTransactionException : Exception +{ + /// Initializes a new instance of the class. + /// Human-readable failure description. + /// How the runtime should classify the failure. + /// Optional underlying exception. + public SessionFsSqliteTransactionException( + string message, + SessionFsSqliteTransactionErrorClass errorClass, + Exception? innerException = null) + : base(message, innerException) + { + ErrorClass = errorClass; + } + + /// Gets the failure classification reported to the runtime. + public SessionFsSqliteTransactionErrorClass ErrorClass { get; } +} + /// /// Base class for session filesystem providers. Subclasses override the /// virtual methods and use normal C# patterns (return values, throw exceptions). @@ -309,6 +367,64 @@ async Task ISessionFsHandler.SqliteQueryAsync(Sessio } } + async Task ISessionFsHandler.SqliteTransactionAsync(SessionFsSqliteTransactionRequest request, CancellationToken cancellationToken) + { + if (this is not ISessionFsSqliteProvider sqliteProvider) + { + return new SessionFsSqliteTransactionResult + { + Error = new SessionFsSqliteTransactionError + { + ErrorClass = SessionFsSqliteTransactionErrorClass.Fatal, + Message = "SQLite is not supported by this provider.", + }, + }; + } + + IList results; + try + { + var statements = request.Statements.Select(statement => new SessionFsSqliteStatement + { + QueryType = statement.QueryType, + Query = statement.Query, + Params = statement.Params?.ToDictionary(kvp => kvp.Key, kvp => JsonElementToValue(kvp.Value)), + }).ToList(); + results = await sqliteProvider.TransactionAsync(statements, cancellationToken).ConfigureAwait(false); + } + catch (SessionFsSqliteTransactionException ex) + { + return new SessionFsSqliteTransactionResult + { + Error = new SessionFsSqliteTransactionError { ErrorClass = ex.ErrorClass, Message = ex.Message }, + }; + } + catch (Exception ex) + { + return new SessionFsSqliteTransactionResult + { + Error = new SessionFsSqliteTransactionError + { + ErrorClass = SessionFsSqliteTransactionErrorClass.Fatal, + Message = ex.Message, + }, + }; + } + + return new SessionFsSqliteTransactionResult + { + Results = results.Select(result => new SessionFsSqliteQueryResult + { + Rows = result.Rows?.Select(row => (IDictionary)row.ToDictionary( + kvp => kvp.Key, + kvp => CopilotClient.ToJsonElementForWire(kvp.Value)!.Value)).ToList() ?? [], + Columns = result.Columns ?? [], + RowsAffected = result.RowsAffected, + LastInsertRowid = result.LastInsertRowid, + }).ToList(), + }; + } + async Task ISessionFsHandler.SqliteExistsAsync(SessionFsSqliteExistsRequest request, CancellationToken cancellationToken) { if (this is not ISessionFsSqliteProvider sqliteProvider) diff --git a/dotnet/test/E2E/CommandsE2ETests.cs b/dotnet/test/E2E/CommandsE2ETests.cs index 20db2d7cb4..9d7c1bb52c 100644 --- a/dotnet/test/E2E/CommandsE2ETests.cs +++ b/dotnet/test/E2E/CommandsE2ETests.cs @@ -30,7 +30,7 @@ public async Task Session_Commands_List_Returns_Builtins_And_Respects_Client_Com await TestHelper.WaitForConditionAsync( async () => { - clientCommands = await session.Rpc.Commands.ListAsync(new CommandsListRequest + clientCommands = await session.Rpc.Commands.ListAsync(new SessionCommandsListRequest { IncludeBuiltins = false, IncludeClientCommands = true, @@ -45,7 +45,7 @@ await TestHelper.WaitForConditionAsync( Assert.Contains(clientCommands.Commands, c => IsCommand(c, "rollback", SlashCommandKind.Client)); Assert.DoesNotContain(clientCommands.Commands, c => c.Kind == SlashCommandKind.Builtin); - var builtinCommands = await session.Rpc.Commands.ListAsync(new CommandsListRequest + var builtinCommands = await session.Rpc.Commands.ListAsync(new SessionCommandsListRequest { IncludeBuiltins = true, IncludeClientCommands = false, @@ -64,7 +64,7 @@ public async Task Session_Commands_Invoke_Known_Builtin_Returns_Expected_Result( { var session = await CreateSessionAsync(); - var builtinCommands = await session.Rpc.Commands.ListAsync(new CommandsListRequest + var builtinCommands = await session.Rpc.Commands.ListAsync(new SessionCommandsListRequest { IncludeBuiltins = true, IncludeClientCommands = false, @@ -128,7 +128,7 @@ public async Task Session_Commands_Execute_Runs_Registered_Command_Handler() await TestHelper.WaitForConditionAsync( async () => { - var commands = await session.Rpc.Commands.ListAsync(new CommandsListRequest + var commands = await session.Rpc.Commands.ListAsync(new SessionCommandsListRequest { IncludeBuiltins = false, IncludeClientCommands = true, diff --git a/dotnet/test/E2E/InMemorySessionFsSqliteHandler.cs b/dotnet/test/E2E/InMemorySessionFsSqliteHandler.cs index 4e573ff5ca..8a6e81cd60 100644 --- a/dotnet/test/E2E/InMemorySessionFsSqliteHandler.cs +++ b/dotnet/test/E2E/InMemorySessionFsSqliteHandler.cs @@ -45,28 +45,68 @@ private SqliteConnection GetOrCreateDb() string query, IDictionary? bindParams, CancellationToken cancellationToken) + { + return Task.FromResult(RunStatement(GetOrCreateDb(), null, queryType, query, bindParams)); + } + + public Task> TransactionAsync( + IList statements, + CancellationToken cancellationToken) + { + var db = GetOrCreateDb(); + using var transaction = db.BeginTransaction(); + try + { + IList results = statements + .Select(statement => RunStatement(db, transaction, statement.QueryType, statement.Query, statement.Params) + ?? new SessionFsSqliteResult()) + .ToList(); + transaction.Commit(); + return Task.FromResult(results); + } + catch (SqliteException ex) + { + transaction.Rollback(); + var errorClass = ex.SqliteErrorCode is 5 or 6 + ? SessionFsSqliteTransactionErrorClass.BusyOrLocked + : SessionFsSqliteTransactionErrorClass.Fatal; + throw new SessionFsSqliteTransactionException(ex.Message, errorClass, ex); + } + catch (Exception ex) + { + transaction.Rollback(); + throw new SessionFsSqliteTransactionException(ex.Message, SessionFsSqliteTransactionErrorClass.Fatal, ex); + } + } + + private SessionFsSqliteResult? RunStatement( + SqliteConnection db, + SqliteTransaction? transaction, + SessionFsSqliteQueryType queryType, + string query, + IDictionary? bindParams) { sqliteCalls.Add(new SqliteCall(sessionId, queryType.Value, query)); var trimmed = query.Trim(); if (trimmed.Length == 0) { - return Task.FromResult(null); + return null; } - var db = GetOrCreateDb(); - if (queryType == SessionFsSqliteQueryType.Exec) { using var cmd = db.CreateCommand(); + cmd.Transaction = transaction; cmd.CommandText = trimmed; cmd.ExecuteNonQuery(); - return Task.FromResult(null); + return null; } if (queryType == SessionFsSqliteQueryType.Query) { using var cmd = db.CreateCommand(); + cmd.Transaction = transaction; cmd.CommandText = trimmed; AddParams(cmd, bindParams); @@ -88,33 +128,35 @@ private SqliteConnection GetOrCreateDb() rows.Add(row); } - return Task.FromResult(new SessionFsSqliteResult + return new SessionFsSqliteResult { Columns = columns, Rows = rows, RowsAffected = 0, - }); + }; } if (queryType == SessionFsSqliteQueryType.Run) { using var cmd = db.CreateCommand(); + cmd.Transaction = transaction; cmd.CommandText = trimmed; AddParams(cmd, bindParams); var rowsAffected = cmd.ExecuteNonQuery(); using var rowidCmd = db.CreateCommand(); + rowidCmd.Transaction = transaction; rowidCmd.CommandText = "SELECT last_insert_rowid()"; var lastRowid = rowidCmd.ExecuteScalar(); - return Task.FromResult(new SessionFsSqliteResult + return new SessionFsSqliteResult { Columns = [], Rows = [], RowsAffected = rowsAffected, LastInsertRowid = lastRowid is long l ? l : null, - }); + }; } throw new ArgumentException($"Unknown queryType: {queryType}"); diff --git a/dotnet/test/E2E/SessionFsE2ETests.cs b/dotnet/test/E2E/SessionFsE2ETests.cs index cf91e3ddc8..b2f93addda 100644 --- a/dotnet/test/E2E/SessionFsE2ETests.cs +++ b/dotnet/test/E2E/SessionFsE2ETests.cs @@ -616,6 +616,9 @@ protected override Task RenameAsync(string src, string dest, CancellationToken c Task ISessionFsSqliteProvider.QueryAsync(SessionFsSqliteQueryType queryType, string query, IDictionary? bindParams, CancellationToken cancellationToken) => Task.FromException(exception); + Task> ISessionFsSqliteProvider.TransactionAsync(IList statements, CancellationToken cancellationToken) => + Task.FromException>(exception); + Task ISessionFsSqliteProvider.ExistsAsync(CancellationToken cancellationToken) => Task.FromException(exception); } diff --git a/go/internal/e2e/commands_and_elicitation_e2e_test.go b/go/internal/e2e/commands_and_elicitation_e2e_test.go index 8d2d40f2f0..af7520a4cc 100644 --- a/go/internal/e2e/commands_and_elicitation_e2e_test.go +++ b/go/internal/e2e/commands_and_elicitation_e2e_test.go @@ -53,7 +53,7 @@ func TestCommandsE2E(t *testing.T) { var clientCommands *rpc.CommandList waitForRPCCondition(t, 30*time.Second, "client commands to be listed", func() (bool, error) { var err error - clientCommands, err = session.RPC.Commands.List(t.Context(), &rpc.CommandsListRequest{ + clientCommands, err = session.RPC.Commands.List(t.Context(), &rpc.SessionCommandsListRequest{ IncludeBuiltins: rpcPtr(false), IncludeClientCommands: rpcPtr(true), IncludeSkills: rpcPtr(false), @@ -68,7 +68,7 @@ func TestCommandsE2E(t *testing.T) { t.Fatalf("Expected client-command-only list to exclude builtins, got %+v", clientCommands.Commands) } - builtinCommands, err := session.RPC.Commands.List(t.Context(), &rpc.CommandsListRequest{ + builtinCommands, err := session.RPC.Commands.List(t.Context(), &rpc.SessionCommandsListRequest{ IncludeBuiltins: rpcPtr(true), IncludeClientCommands: rpcPtr(false), IncludeSkills: rpcPtr(false), @@ -93,7 +93,7 @@ func TestCommandsE2E(t *testing.T) { } defer session.Disconnect() - builtinCommands, err := session.RPC.Commands.List(t.Context(), &rpc.CommandsListRequest{ + builtinCommands, err := session.RPC.Commands.List(t.Context(), &rpc.SessionCommandsListRequest{ IncludeBuiltins: rpcPtr(true), IncludeClientCommands: rpcPtr(false), IncludeSkills: rpcPtr(false), @@ -152,7 +152,7 @@ func TestCommandsE2E(t *testing.T) { defer session.Disconnect() waitForRPCCondition(t, 30*time.Second, "registered deploy command", func() (bool, error) { - commands, err := session.RPC.Commands.List(t.Context(), &rpc.CommandsListRequest{ + commands, err := session.RPC.Commands.List(t.Context(), &rpc.SessionCommandsListRequest{ IncludeBuiltins: rpcPtr(false), IncludeClientCommands: rpcPtr(true), IncludeSkills: rpcPtr(false), diff --git a/go/internal/e2e/rpc_session_state_e2e_test.go b/go/internal/e2e/rpc_session_state_e2e_test.go index 00c2e9ef63..4046ab97fe 100644 --- a/go/internal/e2e/rpc_session_state_e2e_test.go +++ b/go/internal/e2e/rpc_session_state_e2e_test.go @@ -1083,7 +1083,7 @@ func TestRPCSessionStateE2E(t *testing.T) { t.Errorf("Expected SetApproveAll(true) to succeed, got %+v", approve) } - reset, err := session.RPC.Permissions.ResetSessionApprovals(t.Context()) + reset, err := session.RPC.Permissions.ResetSessionApprovals(t.Context(), &rpc.PermissionsResetSessionApprovalsRequest{}) if err != nil { t.Fatalf("Failed to call ResetSessionApprovals: %v", err) } diff --git a/go/internal/e2e/session_fs_sqlite_e2e_test.go b/go/internal/e2e/session_fs_sqlite_e2e_test.go index fa3b49e488..20cd777834 100644 --- a/go/internal/e2e/session_fs_sqlite_e2e_test.go +++ b/go/internal/e2e/session_fs_sqlite_e2e_test.go @@ -198,6 +198,26 @@ func (p *inMemorySqliteProvider) Rename(src string, dest string) error { func (p *inMemorySqliteProvider) SqliteQuery(queryType rpc.SessionFSSqliteQueryType, query string, params map[string]any) (*copilot.SessionFSSqliteQueryResult, error) { p.mu.Lock() defer p.mu.Unlock() + return p.runQueryLocked(queryType, query), nil +} + +func (p *inMemorySqliteProvider) SqliteTransaction(statements []rpc.SessionFSSqliteTransactionStatement) ([]copilot.SessionFSSqliteQueryResult, error) { + p.mu.Lock() + defer p.mu.Unlock() + results := make([]copilot.SessionFSSqliteQueryResult, 0, len(statements)) + for _, statement := range statements { + results = append(results, *p.runQueryLocked(statement.QueryType, statement.Query)) + } + return results, nil +} + +// runQueryLocked returns canned results based on query type. The agent doesn't +// know or care whether a real SQLite database is behind this — it just receives +// SQL tool results. These stubs return plausible responses so the agent can +// proceed normally without pulling in a real SQLite dependency. +// +// Callers must hold p.mu. +func (p *inMemorySqliteProvider) runQueryLocked(queryType rpc.SessionFSSqliteQueryType, query string) *copilot.SessionFSSqliteQueryResult { p.hadQuery = true *p.sqliteCalls = append(*p.sqliteCalls, sqliteCall{ SessionID: p.sessionID, @@ -205,14 +225,10 @@ func (p *inMemorySqliteProvider) SqliteQuery(queryType rpc.SessionFSSqliteQueryT Query: query, }) - // Return canned results based on query type. The agent doesn't know or care - // whether a real SQLite database is behind this — it just receives SQL tool - // results. These stubs return plausible responses so the agent can proceed - // normally without pulling in a real SQLite dependency. upper := strings.ToUpper(strings.TrimSpace(query)) switch queryType { case rpc.SessionFSSqliteQueryTypeExec: - return &copilot.SessionFSSqliteQueryResult{Columns: []string{}, Rows: []map[string]any{}}, nil + return &copilot.SessionFSSqliteQueryResult{Columns: []string{}, Rows: []map[string]any{}} case rpc.SessionFSSqliteQueryTypeRun: lastID := int64(1) return &copilot.SessionFSSqliteQueryResult{ @@ -220,17 +236,34 @@ func (p *inMemorySqliteProvider) SqliteQuery(queryType rpc.SessionFSSqliteQueryT Rows: []map[string]any{}, RowsAffected: 1, LastInsertRowid: &lastID, - }, nil + } case rpc.SessionFSSqliteQueryTypeQuery: - if strings.Contains(upper, "SELECT") { + // Only the "items" table the test asks the agent to create is modelled + // here. The runtime also reads its own bookkeeping tables (for example + // inbox_entries) through this provider and deserializes those rows into + // typed structs, so returning the canned item row for every SELECT would + // make the runtime reject rows it cannot parse. + if strings.Contains(upper, "SELECT") && readsTable(upper, "ITEMS") { return &copilot.SessionFSSqliteQueryResult{ Columns: []string{"id", "name"}, Rows: []map[string]any{{"id": "a1", "name": "Widget"}}, - }, nil + } + } + return &copilot.SessionFSSqliteQueryResult{Columns: []string{}, Rows: []map[string]any{}} + } + return &copilot.SessionFSSqliteQueryResult{Columns: []string{}, Rows: []map[string]any{}} +} + +// readsTable reports whether an upper-cased SQL statement selects from the given +// table, tolerating the quoting styles the agent may emit. +func readsTable(upperQuery string, table string) bool { + names := []string{table, `"` + table + `"`, "`" + table + "`", "[" + table + "]", "MAIN." + table} + for _, name := range names { + if strings.Contains(upperQuery, "FROM "+name) { + return true } - return &copilot.SessionFSSqliteQueryResult{Columns: []string{}, Rows: []map[string]any{}}, nil } - return &copilot.SessionFSSqliteQueryResult{Columns: []string{}, Rows: []map[string]any{}}, nil + return false } func (p *inMemorySqliteProvider) SqliteExists() (bool, error) { diff --git a/go/session_fs_provider.go b/go/session_fs_provider.go index d2227d629e..45061ff8a0 100644 --- a/go/session_fs_provider.go +++ b/go/session_fs_provider.go @@ -58,10 +58,35 @@ type SessionFSProvider interface { type SessionFSSqliteProvider interface { // SqliteQuery executes a SQLite query against the provider's per-session database. SqliteQuery(queryType rpc.SessionFSSqliteQueryType, query string, params map[string]any) (*SessionFSSqliteQueryResult, error) + // SqliteTransaction executes statements atomically against the provider's + // per-session database, applying busy handling to every statement and rolling + // the whole batch back if any statement fails. It returns one result per + // statement, in the same order. + // + // Return a [*SessionFSSqliteTransactionFailure] to classify the failure for + // the runtime; any other error is reported as + // [rpc.SessionFSSqliteTransactionErrorClassFatal]. + SqliteTransaction(statements []rpc.SessionFSSqliteTransactionStatement) ([]SessionFSSqliteQueryResult, error) // SqliteExists checks whether the provider has a SQLite database for the session. SqliteExists() (bool, error) } +// SessionFSSqliteTransactionFailure classifies a SQLite transaction failure for +// the runtime. Return it from [SessionFSSqliteProvider.SqliteTransaction] with +// [rpc.SessionFSSqliteTransactionErrorClassBusyOrLocked] when SQLite reported +// BUSY or LOCKED before commit and the transaction was rolled back, so the +// runtime knows the call is safe to retry. +type SessionFSSqliteTransactionFailure struct { + // Class is the failure classification reported to the runtime. + Class rpc.SessionFSSqliteTransactionErrorClass + // Message describes the failure. + Message string +} + +func (e *SessionFSSqliteTransactionFailure) Error() string { + return e.Message +} + // SessionFSSqliteQueryResult holds the result of a SQLite query execution. // Same shape as the generated RPC type but without the Error field, // since providers signal errors by returning a Go error. @@ -230,6 +255,41 @@ func (a *sessionFSAdapter) SqliteQuery(request *rpc.SessionFSSqliteQueryRequest) }, nil } +func (a *sessionFSAdapter) SqliteTransaction(request *rpc.SessionFSSqliteTransactionRequest) (*rpc.SessionFSSqliteTransactionResult, error) { + sp, ok := a.provider.(SessionFSSqliteProvider) + if !ok { + return &rpc.SessionFSSqliteTransactionResult{ + Results: []rpc.SessionFSSqliteQueryResult{}, + Error: &rpc.SessionFSSqliteTransactionError{ + ErrorClass: rpc.SessionFSSqliteTransactionErrorClassFatal, + Message: "SQLite is not supported by this session filesystem provider", + }, + }, nil + } + results, err := sp.SqliteTransaction(request.Statements) + if err != nil { + return &rpc.SessionFSSqliteTransactionResult{ + Results: []rpc.SessionFSSqliteQueryResult{}, + Error: toSessionFSSqliteTransactionError(err), + }, nil + } + wireResults := make([]rpc.SessionFSSqliteQueryResult, 0, len(results)) + for _, result := range results { + var wireRowid *int64 + if result.LastInsertRowid != nil { + rowid := *result.LastInsertRowid + wireRowid = &rowid + } + wireResults = append(wireResults, rpc.SessionFSSqliteQueryResult{ + Columns: result.Columns, + Rows: result.Rows, + RowsAffected: result.RowsAffected, + LastInsertRowid: wireRowid, + }) + } + return &rpc.SessionFSSqliteTransactionResult{Results: wireResults}, nil +} + func (a *sessionFSAdapter) SqliteExists(request *rpc.SessionFSSqliteExistsRequest) (*rpc.SessionFSSqliteExistsResult, error) { sp, ok := a.provider.(SessionFSSqliteProvider) if !ok { @@ -250,3 +310,17 @@ func toSessionFSError(err error) *rpc.SessionFSError { msg := err.Error() return &rpc.SessionFSError{Code: code, Message: &msg} } + +func toSessionFSSqliteTransactionError(err error) *rpc.SessionFSSqliteTransactionError { + var failure *SessionFSSqliteTransactionFailure + if errors.As(err, &failure) { + return &rpc.SessionFSSqliteTransactionError{ + ErrorClass: failure.Class, + Message: failure.Message, + } + } + return &rpc.SessionFSSqliteTransactionError{ + ErrorClass: rpc.SessionFSSqliteTransactionErrorClassFatal, + Message: err.Error(), + } +} diff --git a/java/scripts/codegen/java.ts b/java/scripts/codegen/java.ts index f0c083c6b9..cb70ecb032 100644 --- a/java/scripts/codegen/java.ts +++ b/java/scripts/codegen/java.ts @@ -256,6 +256,21 @@ function resolveRef(schema: JSONSchema7 | undefined): JSONSchema7 | undefined { return schema; } +/** + * Resolve a method's params schema to the object schema that carries its properties. + * + * Methods whose params object is entirely optional are published as + * `anyOf: [{ not: {} }, { ...object }]`, so the properties live on a variant + * rather than on the schema itself. + */ +function resolveMethodParamsSchema(method: RpcMethodNode): JSONSchema7 | undefined { + const params = resolveRef(method.params ?? undefined); + if (!params || typeof params !== "object") return undefined; + if (params.properties) return params; + if (!Array.isArray(params.anyOf)) return undefined; + return resolveAnyOfVariants(params.anyOf as JSONSchema7[]).find((variant) => !!variant.properties); +} + /** Extract the definition name from a $ref string (e.g., "#/definitions/Foo" → "Foo") */ function extractRefName(schema: JSONSchema7 | null | undefined): string | null { if (!schema?.$ref) return null; @@ -1379,6 +1394,9 @@ async function generateRpcTypes(schemaPath: string): Promise { } else if (paramsSchema?.$ref) { paramsSchema = resolveRef(paramsSchema) as JSONSchema7; } + if (paramsSchema && !paramsSchema.properties) { + paramsSchema = resolveMethodParamsSchema(method) ?? paramsSchema; + } if (paramsSchema && typeof paramsSchema === "object" && paramsSchema.properties) { const paramsClassName = `${className}Params`; if (!generatedClasses.has(paramsClassName)) { @@ -1669,9 +1687,8 @@ function addWrapperResultImports(resultType: string, allImports: Set, pa * callers supply it explicitly. */ function wrapperParamsClassName(method: RpcMethodNode, isSession: boolean): string | null { - let params = method.params; - if (params?.$ref) params = resolveRef(params) as JSONSchema7; - if (!params || typeof params !== "object") return null; + const params = resolveMethodParamsSchema(method); + if (!params) return null; const props = params.properties ?? {}; const userProps = Object.keys(props).filter((k) => !isSession || k !== "sessionId"); if (userProps.length === 0) return null; @@ -1680,11 +1697,16 @@ function wrapperParamsClassName(method: RpcMethodNode, isSession: boolean): stri /** True if the method's params schema contains a "sessionId" property */ function methodHasSessionId(method: RpcMethodNode): boolean { - let params = method.params; - if (params?.$ref) params = resolveRef(params) as JSONSchema7; + const params = resolveMethodParamsSchema(method); return !!params?.properties && "sessionId" in params.properties; } +/** True if the method's params object may be omitted entirely */ +function methodParamsAreOptional(method: RpcMethodNode): boolean { + const params = resolveRef(method.params ?? undefined); + return !!params && typeof params === "object" && !params.properties && Array.isArray(params.anyOf); +} + /** * Generate the Java source for a single method in a wrapper API class. * Returns the Java source lines and whether an ObjectMapper is required. @@ -1699,6 +1721,7 @@ function generateApiMethod( const paramsClass = wrapperParamsClassName(method, isSession); const hasSessionId = methodHasSessionId(method); const hasExtraParams = paramsClass !== null; + const paramsOptional = hasExtraParams && methodParamsAreOptional(method); let needsMapper = false; const lines: string[] = []; @@ -1707,26 +1730,39 @@ function generateApiMethod( const description = (method.params as JSONSchema7 | null)?.description ?? (method.result as JSONSchema7 | null)?.description ?? `Invokes {@code ${method.rpcMethod}}.`; - lines.push(` /**`); - lines.push(` * ${description}`); - if (isSession && hasExtraParams && hasSessionId) { - lines.push(` *

`); - lines.push(` * Note: the {@code sessionId} field in the params record is overridden`); - lines.push(` * by the session-scoped wrapper; any value provided is ignored.`); - } - if (method.stability === "experimental") { - lines.push(` *`); - lines.push(` * @apiNote This method is experimental and may change in a future version.`); - } - lines.push(` * @since 1.0.0`); - lines.push(` */`); - if (method.deprecated) { - lines.push(` @Deprecated`); - } - if (method.stability === "experimental") { - lines.push(` @CopilotExperimental`); + const pushJavadoc = (extraLines: string[] = [], includeSessionIdNote = true): void => { + lines.push(` /**`); + lines.push(` * ${description}`); + if (includeSessionIdNote && isSession && hasExtraParams && hasSessionId) { + lines.push(` *

`); + lines.push(` * Note: the {@code sessionId} field in the params record is overridden`); + lines.push(` * by the session-scoped wrapper; any value provided is ignored.`); + } + lines.push(...extraLines); + if (method.stability === "experimental") { + lines.push(` *`); + lines.push(` * @apiNote This method is experimental and may change in a future version.`); + } + lines.push(` * @since 1.0.0`); + lines.push(` */`); + if (method.deprecated) { + lines.push(` @Deprecated`); + } + if (method.stability === "experimental") { + lines.push(` @CopilotExperimental`); + } + }; + + if (paramsOptional) { + pushJavadoc([` *

`, ` * Invokes the method with no params, applying the runtime defaults.`], false); + lines.push(` public CompletableFuture<${resultClass}> ${key}() {`); + lines.push(` return ${key}(null);`); + lines.push(` }`); + lines.push(``); } + pushJavadoc(); + // Signature if (hasExtraParams) { lines.push(` public CompletableFuture<${resultClass}> ${key}(${paramsClass} params) {`); @@ -1739,7 +1775,10 @@ function generateApiMethod( if (hasExtraParams) { // Merge sessionId into the params using Jackson ObjectNode needsMapper = true; - lines.push(` com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params);`); + const paramsNode = paramsOptional + ? `params == null ? MAPPER.createObjectNode() : MAPPER.valueToTree(params)` + : `MAPPER.valueToTree(params)`; + lines.push(` com.fasterxml.jackson.databind.node.ObjectNode _p = ${paramsNode};`); lines.push(` _p.put("sessionId", ${sessionIdExpr});`); lines.push(` return caller.invoke("${method.rpcMethod}", _p, ${wrapperResultTypeExpression(resultClass)});`); } else if (hasSessionId) { @@ -1750,7 +1789,8 @@ function generateApiMethod( } else { // Server-side: pass params directly (or empty map if no params) if (hasExtraParams) { - lines.push(` return caller.invoke("${method.rpcMethod}", params, ${wrapperResultTypeExpression(resultClass)});`); + const paramsArg = paramsOptional ? `params == null ? java.util.Map.of() : params` : `params`; + lines.push(` return caller.invoke("${method.rpcMethod}", ${paramsArg}, ${wrapperResultTypeExpression(resultClass)});`); } else { lines.push(` return caller.invoke("${method.rpcMethod}", java.util.Map.of(), ${wrapperResultTypeExpression(resultClass)});`); } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/AccountGetQuotaParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/AccountGetQuotaParams.java new file mode 100644 index 0000000000..cea523551f --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/AccountGetQuotaParams.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Request parameters for the {@code account.getQuota} RPC method. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record AccountGetQuotaParams( + /** GitHub token for per-user quota lookup. When provided, resolves this token to determine the user's quota instead of using the global auth. */ + @JsonProperty("gitHubToken") String gitHubToken +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/MemoryConfiguration.java b/java/src/generated/java/com/github/copilot/generated/rpc/MemoryConfiguration.java new file mode 100644 index 0000000000..63d327a415 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/MemoryConfiguration.java @@ -0,0 +1,27 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Memory configuration for this session. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record MemoryConfiguration( + /** Whether memory is enabled for the session. */ + @JsonProperty("enabled") Boolean enabled +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ModelsListParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/ModelsListParams.java new file mode 100644 index 0000000000..3366ff61c4 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ModelsListParams.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Request parameters for the {@code models.list} RPC method. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record ModelsListParams( + /** GitHub token for per-user model listing. When provided, resolves this token to determine the user's Copilot plan and available models instead of using the global auth. */ + @JsonProperty("gitHubToken") String gitHubToken +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/PluginsMarketplacesRefreshParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/PluginsMarketplacesRefreshParams.java new file mode 100644 index 0000000000..a390962b50 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/PluginsMarketplacesRefreshParams.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Request parameters for the {@code plugins.marketplaces.refresh} RPC method. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record PluginsMarketplacesRefreshParams( + /** Marketplace name to refresh. When omitted, every registered marketplace is refreshed. */ + @JsonProperty("name") String name +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerAccountApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerAccountApi.java index 4b7cf718ee..a6ecb05547 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ServerAccountApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerAccountApi.java @@ -29,13 +29,26 @@ public final class ServerAccountApi { /** * Optional GitHub token used to look up quota for a specific user instead of the global auth context. + *

+ * Invokes the method with no params, applying the runtime defaults. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ @CopilotExperimental public CompletableFuture getQuota() { - return caller.invoke("account.getQuota", java.util.Map.of(), AccountGetQuotaResult.class); + return getQuota(null); + } + + /** + * Optional GitHub token used to look up quota for a specific user instead of the global auth context. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture getQuota(AccountGetQuotaParams params) { + return caller.invoke("account.getQuota", params == null ? java.util.Map.of() : params, AccountGetQuotaResult.class); } /** diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerModelsApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerModelsApi.java index ad3d04ce9f..0b14979707 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ServerModelsApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerModelsApi.java @@ -28,13 +28,26 @@ public final class ServerModelsApi { /** * Optional GitHub token used to list models for a specific user instead of the global auth context. + *

+ * Invokes the method with no params, applying the runtime defaults. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ @CopilotExperimental public CompletableFuture list() { - return caller.invoke("models.list", java.util.Map.of(), ModelsListResult.class); + return list(null); + } + + /** + * Optional GitHub token used to list models for a specific user instead of the global auth context. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture list(ModelsListParams params) { + return caller.invoke("models.list", params == null ? java.util.Map.of() : params, ModelsListResult.class); } /** diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerPluginsMarketplacesApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerPluginsMarketplacesApi.java index 47b239a0c0..e01bbeeec7 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ServerPluginsMarketplacesApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerPluginsMarketplacesApi.java @@ -72,13 +72,26 @@ public CompletableFuture browse(PluginsMarketpl /** * Optional marketplace name; omit to refresh all. + *

+ * Invokes the method with no params, applying the runtime defaults. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ @CopilotExperimental public CompletableFuture refresh() { - return caller.invoke("plugins.marketplaces.refresh", java.util.Map.of(), PluginsMarketplacesRefreshResult.class); + return refresh(null); + } + + /** + * Optional marketplace name; omit to refresh all. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture refresh(PluginsMarketplacesRefreshParams params) { + return caller.invoke("plugins.marketplaces.refresh", params == null ? java.util.Map.of() : params, PluginsMarketplacesRefreshResult.class); } } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerSessionsApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerSessionsApi.java index 1288cfb94e..d64dbaa9eb 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ServerSessionsApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerSessionsApi.java @@ -28,13 +28,26 @@ public final class ServerSessionsApi { /** * Open a session by creating, resuming, attaching, connecting to a remote, or handing off. + *

+ * Invokes the method with no params, applying the runtime defaults. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ @CopilotExperimental public CompletableFuture open() { - return caller.invoke("sessions.open", java.util.Map.of(), SessionsOpenResult.class); + return open(null); + } + + /** + * Open a session by creating, resuming, attaching, connecting to a remote, or handing off. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture open(SessionsOpenParams params) { + return caller.invoke("sessions.open", params == null ? java.util.Map.of() : params, SessionsOpenResult.class); } /** @@ -61,13 +74,26 @@ public CompletableFuture connect(SessionsConnectParams pa /** * Optional source filter, metadata-load limit, and context filter applied to the returned sessions. + *

+ * Invokes the method with no params, applying the runtime defaults. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ @CopilotExperimental public CompletableFuture list() { - return caller.invoke("sessions.list", java.util.Map.of(), SessionsListResult.class); + return list(null); + } + + /** + * Optional source filter, metadata-load limit, and context filter applied to the returned sessions. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture list(SessionsListParams params) { + return caller.invoke("sessions.list", params == null ? java.util.Map.of() : params, SessionsListResult.class); } /** @@ -325,13 +351,26 @@ public CompletableFuture setRemoteContro /** * Parameters for stopping the remote-control singleton. + *

+ * Invokes the method with no params, applying the runtime defaults. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ @CopilotExperimental public CompletableFuture stopRemoteControl() { - return caller.invoke("sessions.stopRemoteControl", java.util.Map.of(), SessionsStopRemoteControlResult.class); + return stopRemoteControl(null); + } + + /** + * Parameters for stopping the remote-control singleton. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture stopRemoteControl(SessionsStopRemoteControlParams params) { + return caller.invoke("sessions.stopRemoteControl", params == null ? java.util.Map.of() : params, SessionsStopRemoteControlResult.class); } /** diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionAgentApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionAgentApi.java index 69ce7cf43a..3a17960749 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionAgentApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionAgentApi.java @@ -32,13 +32,31 @@ public final class SessionAgentApi { /** * Controls whether built-in agents and authored prompt text are included. + *

+ * Invokes the method with no params, applying the runtime defaults. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ @CopilotExperimental public CompletableFuture list() { - return caller.invoke("session.agent.list", java.util.Map.of(), SessionAgentListResult.class); + return list(null); + } + + /** + * Controls whether built-in agents and authored prompt text are included. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture list(SessionAgentListParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = params == null ? MAPPER.createObjectNode() : MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.agent.list", _p, SessionAgentListResult.class); } /** diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionAgentListParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionAgentListParams.java new file mode 100644 index 0000000000..00743cff66 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionAgentListParams.java @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Request parameters for the {@code session.agent.list} RPC method. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionAgentListParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** When true, request the session's configured built-in agents alongside custom agents. Listing applies feature, context, inclusion, exclusion, and user-disabled-agent policy, but does not evaluate transient invocation requirements such as model availability. Built-in metadata may be omitted when the session cannot project it, such as a relay session. */ + @JsonProperty("includeBuiltInAgents") Boolean includeBuiltInAgents, + /** When true, request authored base prompt text on each AgentInfo. Prompt text may be omitted when unavailable, such as for agents projected through a relay session. */ + @JsonProperty("includePrompt") Boolean includePrompt +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionCommandsApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionCommandsApi.java index e2e770ed72..facb3fcfc5 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionCommandsApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionCommandsApi.java @@ -32,13 +32,31 @@ public final class SessionCommandsApi { /** * Optional filters controlling which command sources to include in the listing. + *

+ * Invokes the method with no params, applying the runtime defaults. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ @CopilotExperimental public CompletableFuture list() { - return caller.invoke("session.commands.list", java.util.Map.of(), SessionCommandsListResult.class); + return list(null); + } + + /** + * Optional filters controlling which command sources to include in the listing. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture list(SessionCommandsListParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = params == null ? MAPPER.createObjectNode() : MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.commands.list", _p, SessionCommandsListResult.class); } /** diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionCommandsListParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionCommandsListParams.java new file mode 100644 index 0000000000..0e2dd73aa4 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionCommandsListParams.java @@ -0,0 +1,36 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Request parameters for the {@code session.commands.list} RPC method. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionCommandsListParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Include runtime built-in commands */ + @JsonProperty("includeBuiltins") Boolean includeBuiltins, + /** Include enabled user-invocable skills and commands */ + @JsonProperty("includeSkills") Boolean includeSkills, + /** Include commands registered by protocol clients, including SDK clients and extensions */ + @JsonProperty("includeClientCommands") Boolean includeClientCommands +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryApi.java index ef9464ae4f..0d4367f36c 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryApi.java @@ -32,13 +32,31 @@ public final class SessionHistoryApi { /** * Optional compaction parameters. + *

+ * Invokes the method with no params, applying the runtime defaults. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ @CopilotExperimental public CompletableFuture compact() { - return caller.invoke("session.history.compact", java.util.Map.of(), SessionHistoryCompactResult.class); + return compact(null); + } + + /** + * Optional compaction parameters. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture compact(SessionHistoryCompactParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = params == null ? MAPPER.createObjectNode() : MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.history.compact", _p, SessionHistoryCompactResult.class); } /** diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryCompactParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryCompactParams.java new file mode 100644 index 0000000000..d25c80b55a --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionHistoryCompactParams.java @@ -0,0 +1,56 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Request parameters for the {@code session.history.compact} RPC method. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionHistoryCompactParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Optional user-provided instructions to focus the compaction summary */ + @JsonProperty("customInstructions") String customInstructions, + /** What initiated this compaction request, recorded as the `trigger` on the persisted `session.compaction_start` / `session.compaction_complete` events. When absent, the compaction is persisted without trigger attribution (initiator unknown). */ + @JsonProperty("trigger") SessionHistoryCompactParamsTrigger trigger, + /** Context window token limit this compaction is targeting, recorded as the `tokenLimit` on the persisted `session.compaction_start` / `session.compaction_complete` events. Set it when the compaction targets a window other than the compacting model's own, e.g. switching to a model with a smaller context window: the compaction still runs on the current model, so the limit that motivated it would otherwise be lost. When absent, the events record the compacting model's own resolved limit. Attribution metadata only - it does not change how much the compaction removes. */ + @JsonProperty("tokenLimit") Long tokenLimit +) { + + /** What initiated this compaction request, recorded as the `trigger` on the persisted `session.compaction_start` / `session.compaction_complete` events. When absent, the compaction is persisted without trigger attribution (initiator unknown). */ + public enum SessionHistoryCompactParamsTrigger { + /** The {@code manual} variant. */ + MANUAL("manual"), + /** The {@code model_switch} variant. */ + MODEL_SWITCH("model_switch"); + + private final String value; + SessionHistoryCompactParamsTrigger(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static SessionHistoryCompactParamsTrigger fromValue(String value) { + for (SessionHistoryCompactParamsTrigger v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown SessionHistoryCompactParamsTrigger value: " + value); + } + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionApi.java index 830132938a..a64f82afae 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionApi.java @@ -19,6 +19,8 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") public final class SessionLimitPredictionApi { + private static final com.fasterxml.jackson.databind.ObjectMapper MAPPER = RpcMapper.INSTANCE; + private final RpcCaller caller; private final String sessionId; @@ -30,13 +32,31 @@ public final class SessionLimitPredictionApi { /** * Parameters for predicting an AI-credit session limit. Omitting `modelId` uses the session's currently selected model. + *

+ * Invokes the method with no params, applying the runtime defaults. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ @CopilotExperimental public CompletableFuture predict() { - return caller.invoke("session.limitPrediction.predict", java.util.Map.of(), SessionLimitPredictionResult.class); + return predict(null); + } + + /** + * Parameters for predicting an AI-credit session limit. Omitting `modelId` uses the session's currently selected model. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture predict(SessionLimitPredictionPredictParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = params == null ? MAPPER.createObjectNode() : MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.limitPrediction.predict", _p, SessionLimitPredictionResult.class); } } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionPredictParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionPredictParams.java new file mode 100644 index 0000000000..b02e82ca84 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionLimitPredictionPredictParams.java @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Request parameters for the {@code session.limitPrediction.predict} RPC method. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionLimitPredictionPredictParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Optional model identifier override. If omitted, the session's current model is used. */ + @JsonProperty("modelId") String modelId, + /** Client type to size for. Defaults to `cli-interactive`. */ + @JsonProperty("clientType") SessionLimitPredictionClientType clientType +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionListFilter.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionListFilter.java new file mode 100644 index 0000000000..c5b92cb042 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionListFilter.java @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Optional filter applied to the returned sessions + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionListFilter( + /** Match sessions whose context.cwd equals this value */ + @JsonProperty("cwd") String cwd, + /** Match sessions whose context.gitRoot equals this value */ + @JsonProperty("gitRoot") String gitRoot, + /** Match sessions whose context.repository equals this value */ + @JsonProperty("repository") String repository, + /** Match sessions whose context.branch equals this value */ + @JsonProperty("branch") String branch +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelApi.java index 4e6ce5dbc5..9d20e86272 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelApi.java @@ -75,13 +75,31 @@ public CompletableFuture setReasoningEffor /** * Optional listing options. + *

+ * Invokes the method with no params, applying the runtime defaults. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ @CopilotExperimental public CompletableFuture list() { - return caller.invoke("session.model.list", java.util.Map.of(), SessionModelListResult.class); + return list(null); + } + + /** + * Optional listing options. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture list(SessionModelListParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = params == null ? MAPPER.createObjectNode() : MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.model.list", _p, SessionModelListResult.class); } } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelListParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelListParams.java new file mode 100644 index 0000000000..dc521fe2e6 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionModelListParams.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Request parameters for the {@code session.model.list} RPC method. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionModelListParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** If true, bypasses the per-session model list cache and re-fetches from CAPI. */ + @JsonProperty("skipCache") Boolean skipCache +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptions.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptions.java new file mode 100644 index 0000000000..10fa26ff37 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptions.java @@ -0,0 +1,157 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import java.util.Map; +import javax.annotation.processing.Generated; + +/** + * Session construction options. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionOpenOptions( + /** Optional stable session identifier to use for a new session. */ + @JsonProperty("sessionId") String sessionId, + /** Optional human-friendly session name. */ + @JsonProperty("name") String name, + /** Initial model identifier. */ + @JsonProperty("model") String model, + /** Initial reasoning effort level. */ + @JsonProperty("reasoningEffort") String reasoningEffort, + /** Initial reasoning summary mode for supported model clients. */ + @JsonProperty("reasoningSummary") SessionOpenOptionsReasoningSummary reasoningSummary, + /** Initial output verbosity level for supported models. */ + @JsonProperty("verbosity") Verbosity verbosity, + /** Identifier of the client driving the session. */ + @JsonProperty("clientName") String clientName, + /** Structured client kind used for runtime behavior gates. */ + @JsonProperty("clientKind") String clientKind, + /** Identifier sent to LSP-style integrations. */ + @JsonProperty("lspClientName") String lspClientName, + /** Stable integration identifier for analytics. */ + @JsonProperty("integrationId") String integrationId, + /** ExP assignment ('flight') data injected by an SDK integrator, in the same JSON shape the Copilot CLI fetches from the experimentation service (CopilotExpAssignmentResponse). When supplied this is fed into the FeatureFlagService exactly like CLI-fetched assignments and ExP-backed flags wait for it. When absent the session does not block on ExP. */ + @JsonProperty("expAssignments") Object expAssignments, + /** Opt-in: self-fetch and enforce enterprise managed settings at session bootstrap. */ + @JsonProperty("enableManagedSettings") Boolean enableManagedSettings, + /** Opt in to capturing file changes for session rewind and session diff. Capture cannot reconstruct changes made before it was enabled. On create it starts capture from the first turn. It is also honored on resume: for a session that already has tracked prior turns, tracking continues automatically even if this is omitted; passing it on resume additionally enables tracking for an eligible session that has no prior root turn yet. Resuming a session whose prior root turns were never tracked has no restorable baseline, so tracking stays disabled for it and rewind reports file change tracking as unavailable; the resume itself still succeeds, so sessions that predate tracking remain loadable. The opt-in is only rejected when the session can never track (a subagent session, or one without local session storage). It is intentionally absent from the mutable options update because enabling it after edits have occurred would create an incomplete, misleading baseline. Subagents share the parent session's capture store and are not tracked as separate rewind points: a file a subagent writes is attributed to whichever root user turn was open when the capture was staged, just before the tool body ran. A turn cannot open while a staged capture is still in flight, so a subagent tool that staged under the spawning turn stays attributed to it however late the write lands, while a capture it stages after the user's next message belongs to that later turn. Attribution decides which turn's rewind point counts and file preview include that write; it does not narrow which rewinds revert it, because a rewind restores every capture from the selected turn onward, so the earlier spawning turn reverts it as well. */ + @JsonProperty("enableFileChangeTracking") Boolean enableFileChangeTracking, + /** Feature-flag values resolved by the host. */ + @JsonProperty("featureFlags") Map featureFlags, + /** Whether experimental behavior is enabled. */ + @JsonProperty("isExperimentalMode") Boolean isExperimentalMode, + /** Initial authentication info for the session. */ + @JsonProperty("authInfo") Object authInfo, + /** Custom model-provider configuration (BYOK). */ + @JsonProperty("provider") ProviderConfig provider, + /** Options scoped to the built-in CAPI (Copilot API) provider. */ + @JsonProperty("capi") CapiSessionOptions capi, + /** Named BYOK provider connections, additive to CAPI auth. Combining with `provider` is rejected. */ + @JsonProperty("providers") List providers, + /** BYOK model definitions added to the selectable model list, each referencing a provider name. */ + @JsonProperty("models") List models, + /** Working directory to anchor the session. */ + @JsonProperty("workingDirectory") String workingDirectory, + /** Additional directories the agent may access beyond the working directory. Each entry is granted to the session's file-access allow-list and surfaced to the model (system prompt context and `@`-mention completion). Absolute paths are recommended; a relative path is resolved against the session's working directory. Nonexistent or unresolvable entries are skipped with a warning. This is applied on both session creation and resume, and is not persisted: a resumed session that omits this option does not retain previously supplied directories (re-supply them, exactly as the CLI re-passes `--add-dir`). */ + @JsonProperty("additionalDirectories") List additionalDirectories, + /** Pre-resolved working-directory context for session startup. */ + @JsonProperty("workingDirectoryContext") SessionContext workingDirectoryContext, + /** Whether this session supports remote steering. */ + @JsonProperty("remoteSteerable") Boolean remoteSteerable, + /** Telemetry-only remote exporting flag. */ + @JsonProperty("remoteExporting") Boolean remoteExporting, + /** Telemetry-only remote-defaulted flag. */ + @JsonProperty("remoteDefaultedOn") Boolean remoteDefaultedOn, + /** Parent session ID for detached child telemetry rollup. */ + @JsonProperty("detachedFromSpawningParentSessionId") String detachedFromSpawningParentSessionId, + /** Parent engagement ID for detached child telemetry rollup. */ + @JsonProperty("detachedFromSpawningParentEngagementId") String detachedFromSpawningParentEngagementId, + /** Allowlist of available tool names. */ + @JsonProperty("availableTools") List availableTools, + /** Denylist of tool names. */ + @JsonProperty("excludedTools") List excludedTools, + /** Built-in subagent names to include in this session. When specified, only these built-ins are available, subject to runtime availability and exclusions. Custom agents with the same name remain available. */ + @JsonProperty("includedBuiltinAgents") List includedBuiltinAgents, + /** Built-in subagent names to exclude from this session. Excluded built-ins are hidden from agent discovery and cannot be dispatched unless a custom agent with the same name is available. */ + @JsonProperty("excludedBuiltinAgents") List excludedBuiltinAgents, + /** Whether shell-script safety heuristics are enabled. */ + @JsonProperty("enableScriptSafety") Boolean enableScriptSafety, + /** Per-session settings for built-in shell tools. */ + @JsonProperty("shell") ShellOptions shell, + /** Use shell.initProfile instead. Shell init profile. */ + @JsonProperty("shellInitProfile") String shellInitProfile, + /** PowerShell process flags applied to built-in and user-requested shell commands. */ + @JsonProperty("shellProcessFlags") List shellProcessFlags, + /** Resolved sandbox configuration. */ + @JsonProperty("sandboxConfig") SandboxConfig sandboxConfig, + /** Whether interactive shell sessions are logged. */ + @JsonProperty("logInteractiveShells") Boolean logInteractiveShells, + /** How MCP server environment values are interpreted. */ + @JsonProperty("envValueMode") SessionOpenOptionsEnvValueMode envValueMode, + /** Whether to include instructions from every MCP server in the system prompt instead of only allowlisted servers. */ + @JsonProperty("allowAllMcpServerInstructions") Boolean allowAllMcpServerInstructions, + /** Additional directories to search for skills. */ + @JsonProperty("skillDirectories") List skillDirectories, + /** Skill IDs disabled for this session. */ + @JsonProperty("disabledSkills") List disabledSkills, + /** Installed plugins visible to the session. */ + @JsonProperty("installedPlugins") List installedPlugins, + /** Whether custom agents default to local-only execution. */ + @JsonProperty("customAgentsLocalOnly") Boolean customAgentsLocalOnly, + /** Whether to skip custom instruction sources. */ + @JsonProperty("skipCustomInstructions") Boolean skipCustomInstructions, + /** Instruction source IDs disabled for this session. */ + @JsonProperty("disabledInstructionSources") List disabledInstructionSources, + /** Whether commit-message coauthor trailers are enabled. */ + @JsonProperty("coauthorEnabled") Boolean coauthorEnabled, + /** Optional trajectory output file path. */ + @JsonProperty("trajectoryFile") String trajectoryFile, + /** Whether model responses stream as delta events. */ + @JsonProperty("enableStreaming") Boolean enableStreaming, + /** Experimental: enable native model citations (Anthropic models today), normalized onto the `assistant.message` event. Off by default; may change or be removed while the citations surface is experimental. */ + @JsonProperty("enableCitations") Boolean enableCitations, + /** Override URL for the Copilot API endpoint. */ + @JsonProperty("copilotUrl") String copilotUrl, + /** Whether ask_user is explicitly disabled. */ + @JsonProperty("askUserDisabled") Boolean askUserDisabled, + /** Whether auto-mode continuation is enabled. */ + @JsonProperty("continueOnAutoMode") Boolean continueOnAutoMode, + /** Whether the host is an interactive UI. */ + @JsonProperty("runningInInteractiveMode") Boolean runningInInteractiveMode, + /** Whether on-demand custom instruction discovery is enabled. */ + @JsonProperty("enableOnDemandInstructionDiscovery") Boolean enableOnDemandInstructionDiscovery, + /** Maximum decoded byte size of a single inline model-facing binary tool result persisted in session events (default 10 MB). */ + @JsonProperty("maxInlineBinaryBytes") Long maxInlineBinaryBytes, + /** Initial model capability overrides. */ + @JsonProperty("modelCapabilitiesOverrides") ModelCapabilitiesOverride modelCapabilitiesOverrides, + /** Initial session limits. */ + @JsonProperty("sessionLimits") SessionLimitsConfig sessionLimits, + /** Runtime context discriminator for agent filtering. */ + @JsonProperty("agentContext") String agentContext, + /** Override directory for session event logs. */ + @JsonProperty("eventsLogDirectory") String eventsLogDirectory, + /** Whether subagent callback events should be forwarded into the session event log sink. */ + @JsonProperty("eventsLogIncludesSubagents") Boolean eventsLogIncludesSubagents, + /** Override Copilot configuration directory. */ + @JsonProperty("configDir") String configDir, + /** Additional content-exclusion policies to merge into the session policy set. */ + @JsonProperty("additionalContentExclusionPolicies") List additionalContentExclusionPolicies, + /** Memory configuration for this session. */ + @JsonProperty("memory") MemoryConfiguration memory, + /** Capabilities enabled for this session. */ + @JsonProperty("sessionCapabilities") List sessionCapabilities +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsAdditionalContentExclusionPolicy.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsAdditionalContentExclusionPolicy.java new file mode 100644 index 0000000000..bbc53711a4 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsAdditionalContentExclusionPolicy.java @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Content-exclusion policy supplied to `sessions.open` options, with rules, last-updated data, and scope. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionOpenOptionsAdditionalContentExclusionPolicy( + @JsonProperty("rules") List rules, + @JsonProperty("last_updated_at") Object lastUpdatedAt, + /** Allowed values for the `SessionOpenOptionsAdditionalContentExclusionPolicyScope` enumeration. */ + @JsonProperty("scope") SessionOpenOptionsAdditionalContentExclusionPolicyScope scope +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsAdditionalContentExclusionPolicyRule.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsAdditionalContentExclusionPolicyRule.java new file mode 100644 index 0000000000..403550ae24 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsAdditionalContentExclusionPolicyRule.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; +import javax.annotation.processing.Generated; + +/** + * Single content-exclusion rule supplied to `sessions.open` options, with paths, match conditions, and source. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionOpenOptionsAdditionalContentExclusionPolicyRule( + @JsonProperty("paths") List paths, + @JsonProperty("ifAnyMatch") List ifAnyMatch, + @JsonProperty("ifNoneMatch") List ifNoneMatch, + /** Source descriptor for a `sessions.open` content-exclusion rule, with source name and type. */ + @JsonProperty("source") SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource source +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource.java new file mode 100644 index 0000000000..9cfa5894cf --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource.java @@ -0,0 +1,27 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Source descriptor for a `sessions.open` content-exclusion rule, with source name and type. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionOpenOptionsAdditionalContentExclusionPolicyRuleSource( + @JsonProperty("name") String name, + @JsonProperty("type") String type +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsAdditionalContentExclusionPolicyScope.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsAdditionalContentExclusionPolicyScope.java new file mode 100644 index 0000000000..66296cd190 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsAdditionalContentExclusionPolicyScope.java @@ -0,0 +1,35 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Allowed values for the `SessionOpenOptionsAdditionalContentExclusionPolicyScope` enumeration. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum SessionOpenOptionsAdditionalContentExclusionPolicyScope { + /** The {@code repo} variant. */ + REPO("repo"), + /** The {@code all} variant. */ + ALL("all"); + + private final String value; + SessionOpenOptionsAdditionalContentExclusionPolicyScope(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static SessionOpenOptionsAdditionalContentExclusionPolicyScope fromValue(String value) { + for (SessionOpenOptionsAdditionalContentExclusionPolicyScope v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown SessionOpenOptionsAdditionalContentExclusionPolicyScope value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsEnvValueMode.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsEnvValueMode.java new file mode 100644 index 0000000000..cfbfeaa742 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsEnvValueMode.java @@ -0,0 +1,35 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * How MCP server environment values are interpreted. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum SessionOpenOptionsEnvValueMode { + /** The {@code direct} variant. */ + DIRECT("direct"), + /** The {@code indirect} variant. */ + INDIRECT("indirect"); + + private final String value; + SessionOpenOptionsEnvValueMode(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static SessionOpenOptionsEnvValueMode fromValue(String value) { + for (SessionOpenOptionsEnvValueMode v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown SessionOpenOptionsEnvValueMode value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsReasoningSummary.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsReasoningSummary.java new file mode 100644 index 0000000000..391e45a290 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionOpenOptionsReasoningSummary.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Initial reasoning summary mode for supported model clients. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum SessionOpenOptionsReasoningSummary { + /** The {@code none} variant. */ + NONE("none"), + /** The {@code concise} variant. */ + CONCISE("concise"), + /** The {@code detailed} variant. */ + DETAILED("detailed"); + + private final String value; + SessionOpenOptionsReasoningSummary(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static SessionOpenOptionsReasoningSummary fromValue(String value) { + for (SessionOpenOptionsReasoningSummary v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown SessionOpenOptionsReasoningSummary value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionPluginsApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionPluginsApi.java index 1d3e5dea9d..fa4da43dc3 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionPluginsApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionPluginsApi.java @@ -19,6 +19,8 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") public final class SessionPluginsApi { + private static final com.fasterxml.jackson.databind.ObjectMapper MAPPER = RpcMapper.INSTANCE; + private final RpcCaller caller; private final String sessionId; @@ -41,13 +43,31 @@ public CompletableFuture list() { /** * Optional flags controlling which side effects the reload performs. + *

+ * Invokes the method with no params, applying the runtime defaults. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ @CopilotExperimental public CompletableFuture reload() { - return caller.invoke("session.plugins.reload", java.util.Map.of(), Void.class); + return reload(null); + } + + /** + * Optional flags controlling which side effects the reload performs. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture reload(SessionPluginsReloadParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = params == null ? MAPPER.createObjectNode() : MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.plugins.reload", _p, Void.class); } } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionPluginsReloadParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionPluginsReloadParams.java new file mode 100644 index 0000000000..b844a21c8b --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionPluginsReloadParams.java @@ -0,0 +1,40 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Request parameters for the {@code session.plugins.reload} RPC method. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionPluginsReloadParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Reload MCP server connections after refreshing plugins. Defaults to true. */ + @JsonProperty("reloadMcp") Boolean reloadMcp, + /** Re-run custom-agent discovery after refreshing plugins. Defaults to true. */ + @JsonProperty("reloadCustomAgents") Boolean reloadCustomAgents, + /** Re-load user, plugin, and (subject to `deferRepoHooks`) repo hooks. Defaults to true. Has no effect when the host has not registered a hook reloader (e.g. remote sessions). */ + @JsonProperty("reloadHooks") Boolean reloadHooks, + /** Re-discover and relaunch subprocess extensions (including plugin-shipped extensions) after refreshing plugins. Defaults to true. Has no effect when the session has no active extension controller (e.g. extensions were not requested for the session). */ + @JsonProperty("reloadExtensions") Boolean reloadExtensions, + /** When true, skip repo-level hooks during the hook reload. Use before folder trust is confirmed; load them post-trust via `sessions.loadDeferredRepoHooks`. */ + @JsonProperty("deferRepoHooks") Boolean deferRepoHooks +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionProviderApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionProviderApi.java index 5abded471b..b4c6b8ccdc 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionProviderApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionProviderApi.java @@ -32,13 +32,31 @@ public final class SessionProviderApi { /** * Optional model identifier to scope the endpoint snapshot to. + *

+ * Invokes the method with no params, applying the runtime defaults. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ @CopilotExperimental public CompletableFuture getEndpoint() { - return caller.invoke("session.provider.getEndpoint", java.util.Map.of(), SessionProviderGetEndpointResult.class); + return getEndpoint(null); + } + + /** + * Optional model identifier to scope the endpoint snapshot to. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture getEndpoint(SessionProviderGetEndpointParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = params == null ? MAPPER.createObjectNode() : MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.provider.getEndpoint", _p, SessionProviderGetEndpointResult.class); } /** diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionProviderGetEndpointParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionProviderGetEndpointParams.java new file mode 100644 index 0000000000..c885b47cd1 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionProviderGetEndpointParams.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Request parameters for the {@code session.provider.getEndpoint} RPC method. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionProviderGetEndpointParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** Model identifier the caller intends to use against the returned endpoint. Used to pick the correct wire shape. Omit to use whichever model the session is currently using. */ + @JsonProperty("modelId") String modelId +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionSource.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSource.java new file mode 100644 index 0000000000..2914e3c30c --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionSource.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Which session sources to include. Defaults to `local` for backward compatibility. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum SessionSource { + /** The {@code local} variant. */ + LOCAL("local"), + /** The {@code remote} variant. */ + REMOTE("remote"), + /** The {@code all} variant. */ + ALL("all"); + + private final String value; + SessionSource(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static SessionSource fromValue(String value) { + for (SessionSource v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown SessionSource value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsListParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsListParams.java new file mode 100644 index 0000000000..61e01b1c7a --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsListParams.java @@ -0,0 +1,38 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Optional source filter, metadata-load limit, and context filter applied to the returned sessions. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionsListParams( + /** Which session sources to include. Defaults to `local` for backward compatibility. */ + @JsonProperty("source") SessionSource source, + /** When provided, only the first N local sessions (sorted by modification time, newest first) load full metadata; remaining sessions return basic info only. Use 0 to return only basic info for every local session. Has no effect on remote entries (which always carry their full shape). */ + @JsonProperty("metadataLimit") Long metadataLimit, + /** Optional filter applied to the returned sessions */ + @JsonProperty("filter") SessionListFilter filter, + /** When true, include detached maintenance sessions. Defaults to false for user-facing session lists. */ + @JsonProperty("includeDetached") Boolean includeDetached, + /** Only meaningful when `source` includes remote. When true, propagates errors from the remote service instead of silently returning an empty remote list. Defaults to false. */ + @JsonProperty("throwOnError") Boolean throwOnError +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenParams.java new file mode 100644 index 0000000000..9931a240b6 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenParams.java @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Parameters for creating a new local session. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionsOpenParams( + /** Create a new local session. */ + @JsonProperty("kind") String kind, + /** Session construction options. */ + @JsonProperty("options") SessionOpenOptions options, + /** Whether to emit session.start during creation. Defaults to true. */ + @JsonProperty("emitStart") Boolean emitStart +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsStopRemoteControlParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsStopRemoteControlParams.java new file mode 100644 index 0000000000..3cd2065d6e --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsStopRemoteControlParams.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Request parameters for the {@code sessions.stopRemoteControl} RPC method. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionsStopRemoteControlParams( + /** When provided, the stop is rejected unless the singleton currently points at this session id (compare-and-swap semantics). */ + @JsonProperty("expectedSessionId") String expectedSessionId, + /** When true, the singleton is unconditionally torn down regardless of `expectedSessionId`. Use during shutdown or explicit `/remote off`. */ + @JsonProperty("force") Boolean force +) { +} diff --git a/java/src/main/java/com/github/copilot/CopilotClient.java b/java/src/main/java/com/github/copilot/CopilotClient.java index 7244c8c0a5..7112a3d339 100644 --- a/java/src/main/java/com/github/copilot/CopilotClient.java +++ b/java/src/main/java/com/github/copilot/CopilotClient.java @@ -941,6 +941,7 @@ CompletableFuture updateSessionOptionsForMode(CopilotSession session, Bool null, // excludedBuiltinAgents null, // toolFilterPrecedence null, // enableScriptSafety + null, // shell null, // shellInitProfile null, // shellProcessFlags null, // sandboxConfig @@ -966,6 +967,7 @@ CompletableFuture updateSessionOptionsForMode(CopilotSession session, Bool null, // enableReasoningSummaries null, // agentContext null, // eventsLogDirectory + null, // eventsLogIncludesSubagents null, // additionalContentExclusionPolicies patchSchedule, // manageScheduleEnabled null, // sessionCapabilities diff --git a/java/src/main/java/com/github/copilot/CopilotSession.java b/java/src/main/java/com/github/copilot/CopilotSession.java index b8b253de2e..c484fb1b16 100644 --- a/java/src/main/java/com/github/copilot/CopilotSession.java +++ b/java/src/main/java/com/github/copilot/CopilotSession.java @@ -1973,7 +1973,8 @@ public CompletableFuture abort() { public CompletableFuture setModel(String model, String reasoningEffort) { ensureNotTerminated(); return getRpc().model - .switchTo(new SessionModelSwitchToParams(sessionId, model, reasoningEffort, null, null, null, null)) + .switchTo( + new SessionModelSwitchToParams(sessionId, model, reasoningEffort, null, null, null, null, null)) .thenApply(r -> null); } @@ -2054,7 +2055,7 @@ public CompletableFuture setModel(String model, String reasoningEffort, St ? null : com.github.copilot.generated.rpc.ReasoningSummary.fromValue(reasoningSummary); return getRpc().model.switchTo(new SessionModelSwitchToParams(sessionId, model, reasoningEffort, - generatedReasoningSummary, null, generatedCapabilities, null)).thenApply(r -> null); + generatedReasoningSummary, null, generatedCapabilities, null, null)).thenApply(r -> null); } /** diff --git a/java/src/test/java/com/github/copilot/RpcSessionStateExtrasE2ETest.java b/java/src/test/java/com/github/copilot/RpcSessionStateExtrasE2ETest.java index 83365455e7..5022d2a563 100644 --- a/java/src/test/java/com/github/copilot/RpcSessionStateExtrasE2ETest.java +++ b/java/src/test/java/com/github/copilot/RpcSessionStateExtrasE2ETest.java @@ -65,7 +65,7 @@ void testShouldAddByokProviderAndModelAtRuntime() throws Exception { var selectionId = "java-e2e-provider/small"; session.getRpc().model - .switchTo(new SessionModelSwitchToParams(null, selectionId, null, null, null, null, null)) + .switchTo(new SessionModelSwitchToParams(null, selectionId, null, null, null, null, null, null)) .get(30, TimeUnit.SECONDS); var current = session.getRpc().model.getCurrent().get(30, TimeUnit.SECONDS); assertEquals(selectionId, current.modelId()); diff --git a/java/src/test/java/com/github/copilot/RpcWrappersTest.java b/java/src/test/java/com/github/copilot/RpcWrappersTest.java index 7493c6e470..689aeb8cc1 100644 --- a/java/src/test/java/com/github/copilot/RpcWrappersTest.java +++ b/java/src/test/java/com/github/copilot/RpcWrappersTest.java @@ -205,7 +205,7 @@ void sessionRpc_model_switchTo_merges_sessionId_with_extra_params() { var session = new SessionRpc(stub, "sess-xyz"); // switchTo takes extra params beyond sessionId - var switchParams = new SessionModelSwitchToParams(null, "gpt-5", null, null, null, null, null); + var switchParams = new SessionModelSwitchToParams(null, "gpt-5", null, null, null, null, null, null); session.model.switchTo(switchParams); assertEquals(1, stub.calls.size()); diff --git a/java/src/test/java/com/github/copilot/SessionEventDeserializationTest.java b/java/src/test/java/com/github/copilot/SessionEventDeserializationTest.java index 516d1ecf4a..fc978ed65b 100644 --- a/java/src/test/java/com/github/copilot/SessionEventDeserializationTest.java +++ b/java/src/test/java/com/github/copilot/SessionEventDeserializationTest.java @@ -2553,7 +2553,8 @@ void testParseSessionTaskCompleteEvent() throws Exception { assertEquals("Task completed successfully", castedEvent.getData().summary()); // Verify setData round-trip - castedEvent.setData(new SessionTaskCompleteEvent.SessionTaskCompleteEventData("New summary", null)); + castedEvent.setData( + new SessionTaskCompleteEvent.SessionTaskCompleteEventData("New summary", null, null, null, null)); assertEquals("New summary", castedEvent.getData().summary()); } diff --git a/java/src/test/java/com/github/copilot/SessionEventHandlingTest.java b/java/src/test/java/com/github/copilot/SessionEventHandlingTest.java index 1cf3ceff1f..6363e90caf 100644 --- a/java/src/test/java/com/github/copilot/SessionEventHandlingTest.java +++ b/java/src/test/java/com/github/copilot/SessionEventHandlingTest.java @@ -865,7 +865,7 @@ private SessionStartEvent createSessionStartEvent(String sessionId) { private AssistantMessageEvent createAssistantMessageEvent(String content) { var event = new AssistantMessageEvent(); var data = new AssistantMessageEvent.AssistantMessageEventData(null, null, content, null, null, null, null, - null, null, null, null, null, null, null, null, null, null, null, null); + null, null, null, null, null, null, null, null, null, null, null, null, null); event.setData(data); return event; } diff --git a/java/src/test/java/com/github/copilot/generated/rpc/GeneratedRpcRecordsCoverageTest.java b/java/src/test/java/com/github/copilot/generated/rpc/GeneratedRpcRecordsCoverageTest.java index 2b6b0164d5..1b1cccabac 100644 --- a/java/src/test/java/com/github/copilot/generated/rpc/GeneratedRpcRecordsCoverageTest.java +++ b/java/src/test/java/com/github/copilot/generated/rpc/GeneratedRpcRecordsCoverageTest.java @@ -87,7 +87,7 @@ void sessionAgentGetCurrentParams_record() { @Test void sessionAgentListParams_record() { - var params = new SessionAgentListParams("sess-3"); + var params = new SessionAgentListParams("sess-3", null, null); assertEquals("sess-3", params.sessionId()); } @@ -234,8 +234,12 @@ void sessionFsWriteFileParams_record() { @Test void sessionHistoryCompactParams_record() { - var params = new SessionHistoryCompactParams("sess-22"); + var params = new SessionHistoryCompactParams("sess-22", "focus on the API surface", + SessionHistoryCompactParams.SessionHistoryCompactParamsTrigger.MANUAL, 4096L); assertEquals("sess-22", params.sessionId()); + assertEquals("focus on the API surface", params.customInstructions()); + assertEquals(SessionHistoryCompactParams.SessionHistoryCompactParamsTrigger.MANUAL, params.trigger()); + assertEquals(4096L, params.tokenLimit()); } @Test @@ -321,13 +325,15 @@ void sessionModelGetCurrentParams_record() { @Test void sessionModelSwitchToParams_record() { - var params = new SessionModelSwitchToParams("sess-32", "claude-sonnet-4.5", "high", null, null, null, null); + var params = new SessionModelSwitchToParams("sess-32", "claude-sonnet-4.5", "high", null, null, null, null, + null); assertEquals("sess-32", params.sessionId()); assertEquals("claude-sonnet-4.5", params.modelId()); assertEquals("high", params.reasoningEffort()); assertNull(params.reasoningSummary()); assertNull(params.verbosity()); assertNull(params.modelCapabilities()); + assertNull(params.deferIfModelChangeQueued()); } @Test @@ -462,7 +468,7 @@ void pingResult_fields() { @Test void sessionAgentListResult_with_items() { var item = new AgentInfo("name1", "Name One", "Desc 1", "/path/to/agent1", null, null, null, null, null, null, - null); + null, null); var result = new SessionAgentListResult(List.of(item)); assertEquals(1, result.agents().size()); assertEquals("name1", result.agents().get(0).name()); @@ -473,7 +479,7 @@ void sessionAgentListResult_with_items() { @Test void sessionAgentGetCurrentResult_nested() { - var agent = new AgentInfo("agent-1", "Agent One", "Does things", null, null, null, null, null, null, null, + var agent = new AgentInfo("agent-1", "Agent One", "Does things", null, null, null, null, null, null, null, null, null); var result = new SessionAgentGetCurrentResult(agent); assertEquals("agent-1", result.agent().name()); @@ -490,7 +496,7 @@ void sessionAgentGetCurrentResult_null_agent() { @Test void sessionAgentReloadResult_with_items() { - var item = new AgentInfo("a", "A", "Desc", "/path/to/a", null, null, null, null, null, null, null); + var item = new AgentInfo("a", "A", "Desc", "/path/to/a", null, null, null, null, null, null, null, null); var result = new SessionAgentReloadResult(List.of(item)); assertEquals(1, result.agents().size()); assertEquals("a", result.agents().get(0).name()); @@ -499,7 +505,7 @@ void sessionAgentReloadResult_with_items() { @Test void sessionAgentSelectResult_nested() { var agent = new AgentInfo("selected", "Selected", "The selected agent", "/path/to/selected", null, null, null, - null, null, null, null); + null, null, null, null, null); var result = new SessionAgentSelectResult(agent); assertEquals("selected", result.agent().name()); } @@ -614,8 +620,10 @@ void sessionHistoryCompactResult_nested() { @Test void sessionHistoryTruncateResult_record() { - var result = new SessionHistoryTruncateResult(3L); + var result = new SessionHistoryTruncateResult(3L, false, null); assertEquals(3L, result.eventsRemoved()); + assertEquals(false, result.checkpointCleanupFailed()); + assertNull(result.checkpointCleanupError()); } @Test @@ -652,8 +660,9 @@ void sessionModelGetCurrentResult_record() { @Test void sessionModelSwitchToResult_record() { - var result = new SessionModelSwitchToResult("gpt-5"); + var result = new SessionModelSwitchToResult("gpt-5", true); assertEquals("gpt-5", result.modelId()); + assertEquals(true, result.deferred()); } @Test @@ -842,7 +851,7 @@ void sessionModelSwitchToParams_nested_records() { var limits = new ModelCapabilitiesOverrideLimits(100000L, 8192L, 128000L, limitsVision); var supports = new ModelCapabilitiesOverrideSupports(true, true, null); var capabilities = new ModelCapabilitiesOverride(supports, limits); - var params = new SessionModelSwitchToParams("sess-m", "gpt-5", null, null, null, capabilities, null); + var params = new SessionModelSwitchToParams("sess-m", "gpt-5", null, null, null, capabilities, null, null); assertEquals("gpt-5", params.modelId()); assertNotNull(params.modelCapabilities()); diff --git a/nodejs/src/index.ts b/nodejs/src/index.ts index 352afc6a94..683adb4d5b 100644 --- a/nodejs/src/index.ts +++ b/nodejs/src/index.ts @@ -32,6 +32,7 @@ export { CopilotWebSocketHandler, CopilotWebSocketCloseStatus, CopilotWebSocketForwarder, + SessionFsSqliteTransactionFailure, SYSTEM_MESSAGE_SECTIONS, } from "./types.js"; // Re-export the generated session-event types (every *Event interface and @@ -145,6 +146,8 @@ export type { SessionFsSqliteQueryResult, SessionFsSqliteQueryType, SessionFsSqliteProvider, + SessionFsSqliteStatement, + SessionFsSqliteTransactionErrorClass, CopilotRequestContext, SystemMessageAppendConfig, SystemMessageConfig, diff --git a/nodejs/src/sessionFsProvider.ts b/nodejs/src/sessionFsProvider.ts index 0bc1987503..8280e701d8 100644 --- a/nodejs/src/sessionFsProvider.ts +++ b/nodejs/src/sessionFsProvider.ts @@ -8,10 +8,12 @@ import type { SessionFsStatResult, SessionFsReaddirWithTypesEntry, SessionFsSqliteQueryResult as GeneratedSqliteQueryResult, + SessionFsSqliteTransactionError as GeneratedSqliteTransactionError, + SessionFsSqliteTransactionErrorClass, SessionFsSqliteQueryType, } from "./generated/rpc.js"; -export type { SessionFsSqliteQueryType }; +export type { SessionFsSqliteQueryType, SessionFsSqliteTransactionErrorClass }; /** * File metadata returned by {@link SessionFsProvider.stat}. @@ -27,6 +29,40 @@ export type SessionFsFileInfo = Omit; */ export type SessionFsSqliteQueryResult = Omit; +/** + * One statement in an atomic SQLite transaction passed to + * {@link SessionFsSqliteProvider.transaction}. + */ +export interface SessionFsSqliteStatement { + /** How to execute: `"exec"` for DDL/multi-statement, `"query"` for SELECT, `"run"` for INSERT/UPDATE/DELETE. */ + queryType: SessionFsSqliteQueryType; + + /** SQL statement to execute. */ + query: string; + + /** Optional named bind parameters. */ + params?: Record; +} + +/** + * Error thrown by {@link SessionFsSqliteProvider.transaction} to classify a + * transaction failure for the runtime. + * + * Any other thrown value is reported as `"fatal"`. Throw this with + * `"busyOrLocked"` when SQLite reported BUSY/LOCKED before commit and the + * transaction was rolled back, so the runtime knows the call is safe to retry. + */ +export class SessionFsSqliteTransactionFailure extends Error { + /** Failure classification reported to the runtime. */ + readonly errorClass: SessionFsSqliteTransactionErrorClass; + + constructor(message: string, errorClass: SessionFsSqliteTransactionErrorClass = "fatal") { + super(message); + this.name = "SessionFsSqliteTransactionFailure"; + this.errorClass = errorClass; + } +} + /** * SQLite operations for the per-session database. * Implementers provide query execution and existence checking. @@ -45,6 +81,18 @@ export interface SessionFsSqliteProvider { params?: Record ): Promise; + /** + * Execute `statements` atomically against the per-session database. + * + * Apply busy handling to every statement and roll back the whole batch if + * any statement fails. Throw {@link SessionFsSqliteTransactionFailure} to + * classify the failure; any other thrown value is reported as `"fatal"`. + * + * @param statements - Statements to execute in order inside a single transaction. + * @returns One result per statement, in the same order. + */ + transaction(statements: SessionFsSqliteStatement[]): Promise; + /** * Check whether the per-session database already exists, without creating it. */ @@ -219,6 +267,26 @@ export function createSessionFsAdapter(provider: SessionFsProvider): SessionFsHa ); return result ?? { rows: [], columns: [], rowsAffected: 0 }; }, + sqliteTransaction: async ({ statements }) => { + if (!provider.sqlite) { + throw new Error("SQLite is not supported by this provider"); + } + try { + const results = await provider.sqlite.transaction( + statements.map((statement) => ({ + queryType: statement.queryType, + query: statement.query, + params: normalizeSqliteParams(statement.params), + })) + ); + return { results: results.map((result) => ({ ...result })) }; + } catch (err) { + // Unlike sqliteQuery, transaction failures carry a classification the + // runtime uses to decide whether a retry is safe, so they are reported + // as a result-level error instead of a JSON-RPC error. + return { results: [], error: toSqliteTransactionError(err) }; + } + }, sqliteExists: async () => { if (!provider.sqlite) { throw new Error("SQLite is not supported by this provider"); @@ -233,3 +301,13 @@ function toSessionFsError(err: unknown): SessionFsError { const code = e.code === "ENOENT" ? "ENOENT" : "UNKNOWN"; return { code, message: e.message ?? String(err) }; } + +function toSqliteTransactionError(err: unknown): GeneratedSqliteTransactionError { + if (err instanceof SessionFsSqliteTransactionFailure) { + return { errorClass: err.errorClass, message: err.message }; + } + return { + errorClass: "fatal", + message: err instanceof Error ? err.message : String(err), + }; +} diff --git a/nodejs/src/types.ts b/nodejs/src/types.ts index 5f89ca3bed..9084e7db1c 100644 --- a/nodejs/src/types.ts +++ b/nodejs/src/types.ts @@ -43,6 +43,9 @@ export type { SessionFsFileInfo } from "./sessionFsProvider.js"; export type { SessionFsSqliteQueryResult } from "./sessionFsProvider.js"; export type { SessionFsSqliteQueryType } from "./sessionFsProvider.js"; export type { SessionFsSqliteProvider } from "./sessionFsProvider.js"; +export type { SessionFsSqliteStatement } from "./sessionFsProvider.js"; +export type { SessionFsSqliteTransactionErrorClass } from "./sessionFsProvider.js"; +export { SessionFsSqliteTransactionFailure } from "./sessionFsProvider.js"; export type { LlmInferenceHeaders } from "./generated/rpc.js"; export type { CopilotRequestContext } from "./copilotRequestHandler.js"; export { diff --git a/nodejs/test/e2e/session_fs.e2e.test.ts b/nodejs/test/e2e/session_fs.e2e.test.ts index 11de9582e1..5726d39b5f 100644 --- a/nodejs/test/e2e/session_fs.e2e.test.ts +++ b/nodejs/test/e2e/session_fs.e2e.test.ts @@ -299,6 +299,20 @@ describe("Session Fs Adapter", () => { rowsAffected: 0, }; }, + async transaction(statements) { + return statements.map((statement) => ({ + columns: ["sessionId", "query", "queryType", "answer"], + rows: [ + { + sessionId: "handler-session", + query: statement.query, + queryType: statement.queryType, + answer: statement.params?.answer, + }, + ], + rowsAffected: 0, + })); + }, async exists() { return true; }, @@ -433,6 +447,9 @@ describe("Session Fs Adapter", () => { query: async () => { throw enoent; }, + transaction: async () => { + throw enoent; + }, exists: async () => { throw enoent; }, @@ -589,6 +606,13 @@ function createTestSessionFsHandler( rowsAffected: 0, }; }, + async transaction(statements) { + return statements.map(() => ({ + columns: [], + rows: [], + rowsAffected: 0, + })); + }, async exists() { return true; }, diff --git a/nodejs/test/e2e/session_fs_sqlite.e2e.test.ts b/nodejs/test/e2e/session_fs_sqlite.e2e.test.ts index cea67c1453..4383f561f0 100644 --- a/nodejs/test/e2e/session_fs_sqlite.e2e.test.ts +++ b/nodejs/test/e2e/session_fs_sqlite.e2e.test.ts @@ -18,6 +18,8 @@ import { type SessionFsFileInfo, type SessionFsSqliteQueryResult, type SessionFsSqliteQueryType, + type SessionFsSqliteStatement, + SessionFsSqliteTransactionFailure, } from "../../src/index.js"; import { createSdkTestContext } from "./harness/sdkTestContext.js"; @@ -207,41 +209,38 @@ function createTestSessionFsHandlerWithSqlite( params?: Record ): Promise { sqliteCalls.push({ sessionId: session.sessionId, queryType, query }); - + return runStatement(getOrCreateDb(), queryType, query, params); + }, + async transaction( + statements: SessionFsSqliteStatement[] + ): Promise { const database = getOrCreateDb(); - const trimmed = query.trim(); - if (trimmed.length === 0) { - return undefined; - } - - switch (queryType) { - case "exec": - database.exec(trimmed); - return undefined; - - case "query": { - const stmt = database.prepare(trimmed); - const rows = (params ? stmt.all(params) : stmt.all()) as Record< - string, - unknown - >[]; - const columns = rows.length > 0 ? Object.keys(rows[0]) : []; - return { rows, columns, rowsAffected: 0 }; - } - - case "run": { - const stmt = database.prepare(trimmed); - const result = params ? stmt.run(params) : stmt.run(); - return { - rows: [], - columns: [], - rowsAffected: Number(result.changes), - lastInsertRowid: - result.lastInsertRowid !== undefined - ? Number(result.lastInsertRowid) - : undefined, - }; - } + database.exec("BEGIN IMMEDIATE"); + try { + const results = statements.map((statement) => { + sqliteCalls.push({ + sessionId: session.sessionId, + queryType: statement.queryType, + query: statement.query, + }); + return ( + runStatement( + database, + statement.queryType, + statement.query, + statement.params + ) ?? { rows: [], columns: [], rowsAffected: 0 } + ); + }); + database.exec("COMMIT"); + return results; + } catch (err) { + database.exec("ROLLBACK"); + const message = err instanceof Error ? err.message : String(err); + throw new SessionFsSqliteTransactionFailure( + message, + /busy|locked/i.test(message) ? "busyOrLocked" : "fatal" + ); } }, async exists(): Promise { @@ -250,3 +249,42 @@ function createTestSessionFsHandlerWithSqlite( }, }; } + +function runStatement( + database: DatabaseSync, + queryType: SessionFsSqliteQueryType, + query: string, + params?: Record +): SessionFsSqliteQueryResult | undefined { + const trimmed = query.trim(); + if (trimmed.length === 0) { + return undefined; + } + + switch (queryType) { + case "exec": + database.exec(trimmed); + return undefined; + + case "query": { + const stmt = database.prepare(trimmed); + const rows = (params ? stmt.all(params) : stmt.all()) as Record[]; + const columns = rows.length > 0 ? Object.keys(rows[0]) : []; + return { rows, columns, rowsAffected: 0 }; + } + + case "run": { + const stmt = database.prepare(trimmed); + const result = params ? stmt.run(params) : stmt.run(); + return { + rows: [], + columns: [], + rowsAffected: Number(result.changes), + lastInsertRowid: + result.lastInsertRowid !== undefined + ? Number(result.lastInsertRowid) + : undefined, + }; + } + } +} diff --git a/nodejs/test/session_fs_adapter.test.ts b/nodejs/test/session_fs_adapter.test.ts index fb62d99045..98749dffba 100644 --- a/nodejs/test/session_fs_adapter.test.ts +++ b/nodejs/test/session_fs_adapter.test.ts @@ -67,6 +67,20 @@ describe("SessionFsAdapter", () => { rowsAffected: 0, }; }, + async transaction(statements) { + return statements.map((statement) => ({ + columns: ["sessionId", "query", "queryType", "answer"], + rows: [ + { + sessionId, + query: statement.query, + queryType: statement.queryType, + answer: statement.params?.answer, + }, + ], + rowsAffected: 0, + })); + }, async exists() { return true; }, @@ -205,6 +219,7 @@ describe("SessionFsAdapter", () => { rename: () => Promise.reject(error), sqlite: { query: () => Promise.reject(error), + transaction: () => Promise.reject(error), exists: () => Promise.reject(error), }, }; @@ -244,6 +259,14 @@ describe("SessionFsAdapter", () => { ).rejects.toThrow("missing file"); await expect(handler.sqliteExists({ sessionId })).rejects.toThrow("missing file"); + // sqliteTransaction reports a classified result-level error instead + const transaction = await handler.sqliteTransaction({ + sessionId, + statements: [{ query: "select 1", queryType: "query" }], + }); + expect(transaction.results).toEqual([]); + expect(transaction.error).toEqual({ errorClass: "fatal", message: "missing file" }); + const unknownProvider = createSessionFsAdapter(makeThrowingProvider(makeError("bad path"))); const unknownError = await unknownProvider.writeFile({ sessionId, diff --git a/python/copilot/__init__.py b/python/copilot/__init__.py index 27c220ecf2..8b62c3c25e 100644 --- a/python/copilot/__init__.py +++ b/python/copilot/__init__.py @@ -178,6 +178,7 @@ SessionFsProvider, SessionFsSqliteProvider, SessionFsSqliteQueryResult, + SessionFsSqliteTransactionFailure, create_session_fs_adapter, ) from .tools import ( @@ -324,6 +325,7 @@ "SessionFsProvider", "SessionFsSqliteProvider", "SessionFsSqliteQueryResult", + "SessionFsSqliteTransactionFailure", "SessionHooks", "SessionLimitsConfig", "SessionLifecycleEvent", diff --git a/python/copilot/session_fs_provider.py b/python/copilot/session_fs_provider.py index 355724da48..c07aae6d42 100644 --- a/python/copilot/session_fs_provider.py +++ b/python/copilot/session_fs_provider.py @@ -34,11 +34,19 @@ SessionFSReadFileResult, SessionFSSqliteExistsResult, SessionFSSqliteQueryType, + SessionFSSqliteTransactionErrorClass, + SessionFSSqliteTransactionStatement, SessionFSStatResult, ) from .generated.rpc import ( SessionFSSqliteQueryResult as _GeneratedSqliteQueryResult, ) +from .generated.rpc import ( + SessionFSSqliteTransactionError as _GeneratedSqliteTransactionError, +) +from .generated.rpc import ( + SessionFSSqliteTransactionResult as _GeneratedSqliteTransactionResult, +) @dataclass @@ -130,11 +138,42 @@ async def sqlite_query( no result set is produced; the adapter will substitute an empty result. """ + @abc.abstractmethod + async def sqlite_transaction( + self, + statements: list[SessionFSSqliteTransactionStatement], + ) -> list[SessionFsSqliteQueryResult]: + """Execute ``statements`` atomically against the per-session database. + + Return one result per statement, in order. Raise + :class:`SessionFsSqliteTransactionFailure` to tell the runtime how the + failure should be classified; any other exception is reported as + ``fatal``. + """ + @abc.abstractmethod async def sqlite_exists(self) -> bool: """Return whether the provider has a SQLite database for this session.""" +class SessionFsSqliteTransactionFailure(Exception): + """Raised by a provider to classify a failed SQLite transaction. + + ``busy_or_locked`` guarantees the transaction rolled back and is safe to + retry; ``post_commit_ambiguous`` must never be retried. + """ + + def __init__( + self, + message: str, + error_class: SessionFSSqliteTransactionErrorClass = ( + SessionFSSqliteTransactionErrorClass.FATAL + ), + ) -> None: + super().__init__(message) + self.error_class = error_class + + @dataclass class SessionFsSqliteQueryResult: """Result of a SQLite query execution. @@ -294,6 +333,45 @@ async def sqlite_query(self, params: Any) -> _GeneratedSqliteQueryResult: last_insert_rowid=result.last_insert_rowid, ) + async def sqlite_transaction(self, params: Any) -> _GeneratedSqliteTransactionResult: + if not isinstance(self._p, SessionFsSqliteProvider): + return _GeneratedSqliteTransactionResult( + results=[], + error=_GeneratedSqliteTransactionError( + error_class=SessionFSSqliteTransactionErrorClass.FATAL, + message="SQLite is not supported by this SessionFs provider", + ), + ) + try: + results = await self._p.sqlite_transaction(list(params.statements)) + except SessionFsSqliteTransactionFailure as exc: + return _GeneratedSqliteTransactionResult( + results=[], + error=_GeneratedSqliteTransactionError( + error_class=exc.error_class, + message=str(exc), + ), + ) + except Exception as exc: + return _GeneratedSqliteTransactionResult( + results=[], + error=_GeneratedSqliteTransactionError( + error_class=SessionFSSqliteTransactionErrorClass.FATAL, + message=str(exc), + ), + ) + return _GeneratedSqliteTransactionResult( + results=[ + _GeneratedSqliteQueryResult( + columns=result.columns, + rows=result.rows, + rows_affected=result.rows_affected, + last_insert_rowid=result.last_insert_rowid, + ) + for result in results + ], + ) + async def sqlite_exists(self, params: Any) -> SessionFSSqliteExistsResult: if not isinstance(self._p, SessionFsSqliteProvider): return SessionFSSqliteExistsResult.from_dict({"exists": False}) diff --git a/python/e2e/test_rpc_commands_e2e.py b/python/e2e/test_rpc_commands_e2e.py index 747eb4d1ef..32fbc5b184 100644 --- a/python/e2e/test_rpc_commands_e2e.py +++ b/python/e2e/test_rpc_commands_e2e.py @@ -6,10 +6,10 @@ from copilot.rpc import ( CommandsInvokeRequest, - CommandsListRequest, CommandsRespondToQueuedCommandRequest, ExecuteCommandParams, QueuedCommandHandled, + SessionCommandsListRequest, SlashCommandKind, SlashCommandTextResult, ) @@ -33,7 +33,7 @@ async def test_should_list_builtin_and_client_commands(self, ctx: E2ETestContext ], ) try: - commands = await session.rpc.commands.list(CommandsListRequest()) + commands = await session.rpc.commands.list(SessionCommandsListRequest()) by_name = {command.name: command for command in commands.commands} builtins = [ diff --git a/python/e2e/test_rpc_session_state_e2e.py b/python/e2e/test_rpc_session_state_e2e.py index 51c1059bb7..f4b03d2e65 100644 --- a/python/e2e/test_rpc_session_state_e2e.py +++ b/python/e2e/test_rpc_session_state_e2e.py @@ -33,6 +33,7 @@ ModeSetRequest, NameSetAutoRequest, NameSetRequest, + PermissionsResetSessionApprovalsRequest, PermissionsSetApproveAllRequest, PlanUpdateRequest, SessionSetCredentialsParams, @@ -594,7 +595,9 @@ async def test_should_call_session_usage_and_permission_rpcs(self, ctx: E2ETestC ) assert approve_all.success - reset = await session.rpc.permissions.reset_session_approvals() + reset = await session.rpc.permissions.reset_session_approvals( + PermissionsResetSessionApprovalsRequest() + ) assert reset.success finally: await session.rpc.permissions.set_approve_all( diff --git a/python/e2e/test_session_fs_e2e.py b/python/e2e/test_session_fs_e2e.py index fbfde6ee78..0d86303264 100644 --- a/python/e2e/test_session_fs_e2e.py +++ b/python/e2e/test_session_fs_e2e.py @@ -280,6 +280,8 @@ async def test_should_map_all_sessionfs_handler_operations(self, ctx: E2ETestCon SessionFSSqliteExistsRequest, SessionFSSqliteQueryRequest, SessionFSSqliteQueryType, + SessionFSSqliteTransactionErrorClass, + SessionFSSqliteTransactionRequest, SessionFSStatRequest, SessionFSWriteFileRequest, ) @@ -403,6 +405,15 @@ async def test_should_map_all_sessionfs_handler_operations(self, ctx: E2ETestCon assert sqlite_query.error is not None assert sqlite_query.error.code == SessionFSErrorCode.UNKNOWN + sqlite_transaction = await handler.sqlite_transaction( + SessionFSSqliteTransactionRequest(session_id=session_id, statements=[]) + ) + assert sqlite_transaction.results == [] + assert sqlite_transaction.error is not None + assert ( + sqlite_transaction.error.error_class == SessionFSSqliteTransactionErrorClass.FATAL + ) + sqlite_exists = await handler.sqlite_exists( SessionFSSqliteExistsRequest(session_id=session_id) ) @@ -429,6 +440,8 @@ async def test_sessionfsprovider_converts_exceptions_to_rpc_errors(self): SessionFSSqliteExistsRequest, SessionFSSqliteQueryRequest, SessionFSSqliteQueryType, + SessionFSSqliteTransactionErrorClass, + SessionFSSqliteTransactionRequest, SessionFSStatRequest, SessionFSWriteFileRequest, ) @@ -536,6 +549,12 @@ def assert_fs_error(error) -> None: assert sqlite_query.columns == [] assert sqlite_query.rows == [] assert sqlite_query.rows_affected == 0 + sqlite_transaction = await handler.sqlite_transaction( + SessionFSSqliteTransactionRequest(session_id=sid, statements=[]) + ) + assert sqlite_transaction.results == [] + assert sqlite_transaction.error is not None + assert sqlite_transaction.error.error_class == SessionFSSqliteTransactionErrorClass.FATAL sqlite_exists = await handler.sqlite_exists(SessionFSSqliteExistsRequest(session_id=sid)) assert sqlite_exists.exists is False diff --git a/python/e2e/test_session_fs_sqlite_e2e.py b/python/e2e/test_session_fs_sqlite_e2e.py index c82cc793f1..d5d79edd47 100644 --- a/python/e2e/test_session_fs_sqlite_e2e.py +++ b/python/e2e/test_session_fs_sqlite_e2e.py @@ -8,6 +8,7 @@ import sqlite3 import tempfile from pathlib import Path +from typing import Any import pytest import pytest_asyncio @@ -17,6 +18,8 @@ SessionFSReaddirWithTypesEntry, SessionFSReaddirWithTypesEntryType, SessionFSSqliteQueryType, + SessionFSSqliteTransactionErrorClass, + SessionFSSqliteTransactionStatement, ) from copilot.session import PermissionHandler from copilot.session_fs_provider import ( @@ -24,6 +27,7 @@ SessionFsProvider, SessionFsSqliteProvider, SessionFsSqliteQueryResult, + SessionFsSqliteTransactionFailure, ) from .testharness import DEFAULT_GITHUB_TOKEN, E2ETestContext @@ -151,6 +155,41 @@ async def sqlite_query( query: str, params: dict[str, float | str | None] | None = None, ) -> SessionFsSqliteQueryResult | None: + return self._run_statement(self._get_or_create_db(), query_type, query, params) + + async def sqlite_transaction( + self, + statements: list[SessionFSSqliteTransactionStatement], + ) -> list[SessionFsSqliteQueryResult]: + db = self._get_or_create_db() + db.execute("BEGIN IMMEDIATE") + try: + results = [ + self._run_statement( + db, statement.query_type, statement.query, statement.params, commit=False + ) + for statement in statements + ] + db.commit() + except Exception as exc: + db.rollback() + message = str(exc) + error_class = ( + SessionFSSqliteTransactionErrorClass.BUSY_OR_LOCKED + if "locked" in message or "busy" in message + else SessionFSSqliteTransactionErrorClass.FATAL + ) + raise SessionFsSqliteTransactionFailure(message, error_class) from exc + return results + + def _run_statement( + self, + db: sqlite3.Connection, + query_type: SessionFSSqliteQueryType, + query: str, + params: dict[str, Any] | None = None, + commit: bool = True, + ) -> SessionFsSqliteQueryResult: self._sqlite_calls.append( { "sessionId": self._session_id, @@ -159,14 +198,14 @@ async def sqlite_query( } ) - db = self._get_or_create_db() trimmed = query.strip() if not trimmed: return SessionFsSqliteQueryResult(columns=[], rows=[], rows_affected=0) if query_type == SessionFSSqliteQueryType.EXEC: db.executescript(trimmed) - db.commit() + if commit: + db.commit() return SessionFsSqliteQueryResult(columns=[], rows=[], rows_affected=0) if query_type == SessionFSSqliteQueryType.QUERY: @@ -177,7 +216,8 @@ async def sqlite_query( # run (INSERT/UPDATE/DELETE) cursor = db.execute(trimmed, params or {}) - db.commit() + if commit: + db.commit() return SessionFsSqliteQueryResult( columns=[], rows=[], diff --git a/rust/examples/manual_tool_resume.rs b/rust/examples/manual_tool_resume.rs index e513cf921c..85add798a1 100644 --- a/rust/examples/manual_tool_resume.rs +++ b/rust/examples/manual_tool_resume.rs @@ -115,6 +115,7 @@ async fn main() -> Result<(), Box> { .handle_pending_permission_request(PermissionDecisionRequest { request_id: permission.request_id, result: PermissionDecision::ApproveOnce(PermissionDecisionApproveOnce { + approved_interactively: None, kind: PermissionDecisionApproveOnceKind::ApproveOnce, }), }) diff --git a/rust/src/session.rs b/rust/src/session.rs index 89162346e4..165dc2e17f 100644 --- a/rust/src/session.rs +++ b/rust/src/session.rs @@ -538,6 +538,7 @@ impl Session { verbosity: None, context_tier: opts.context_tier, model_capabilities: opts.model_capabilities, + defer_if_model_change_queued: None, }; self.rpc().model().switch_to(request).await?; Ok(()) diff --git a/rust/src/session_fs.rs b/rust/src/session_fs.rs index da4d3e3c96..68babd0c30 100644 --- a/rust/src/session_fs.rs +++ b/rust/src/session_fs.rs @@ -47,11 +47,14 @@ use std::fmt; use async_trait::async_trait; -pub use crate::generated::api_types::SessionFsSqliteQueryType; use crate::generated::api_types::{ SessionFsError, SessionFsErrorCode, SessionFsReaddirWithTypesEntry, SessionFsReaddirWithTypesEntryType, SessionFsSetProviderConventions, SessionFsStatResult, }; +pub use crate::generated::api_types::{ + SessionFsSqliteQueryType, SessionFsSqliteTransactionErrorClass, + SessionFsSqliteTransactionStatement, +}; use crate::{Custom, Repr}; /// Optional capabilities declared by a session filesystem provider. @@ -528,10 +531,64 @@ pub trait SessionFsSqliteProvider: Send + Sync { params: Option<&HashMap>, ) -> Result, FsError>; + /// Execute `statements` atomically against the provider's per-session + /// database, returning one result per statement, in order. + /// + /// Return `Err` with a [`SessionFsSqliteTransactionError`] describing how + /// the failure should be classified. `BusyOrLocked` guarantees the + /// transaction rolled back and is safe to retry; `PostCommitAmbiguous` + /// must never be retried. + async fn sqlite_transaction( + &self, + statements: &[SessionFsSqliteTransactionStatement], + ) -> Result, SessionFsSqliteTransactionError>; + /// Check whether the provider has a SQLite database for this session. async fn sqlite_exists(&self) -> Result; } +/// Classified SQLite transaction failure returned by +/// [`SessionFsSqliteProvider::sqlite_transaction`]. +#[derive(Debug, Clone)] +pub struct SessionFsSqliteTransactionError { + /// How the runtime should classify the failure. + pub error_class: SessionFsSqliteTransactionErrorClass, + /// Human-readable failure description. + pub message: String, +} + +impl SessionFsSqliteTransactionError { + /// Create a `Fatal` transaction error with the given message. + pub fn fatal(message: impl Into) -> Self { + Self { + error_class: SessionFsSqliteTransactionErrorClass::Fatal, + message: message.into(), + } + } + + /// Create a `BusyOrLocked` transaction error with the given message. + pub fn busy_or_locked(message: impl Into) -> Self { + Self { + error_class: SessionFsSqliteTransactionErrorClass::BusyOrLocked, + message: message.into(), + } + } +} + +impl std::fmt::Display for SessionFsSqliteTransactionError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.message) + } +} + +impl std::error::Error for SessionFsSqliteTransactionError {} + +impl From for SessionFsSqliteTransactionError { + fn from(error: FsError) -> Self { + Self::fatal(error.to_string()) + } +} + /// Result of a SQLite query execution via [`SessionFsSqliteProvider::sqlite_query`]. /// /// Same shape as the generated RPC type but without the `error` field, diff --git a/rust/src/session_fs_dispatch.rs b/rust/src/session_fs_dispatch.rs index 9c5780d37f..c84981ac0c 100644 --- a/rust/src/session_fs_dispatch.rs +++ b/rust/src/session_fs_dispatch.rs @@ -18,7 +18,10 @@ use crate::generated::api_types::{ SessionFsReaddirWithTypesRequest, SessionFsReaddirWithTypesResult, SessionFsRenameRequest, SessionFsRmRequest, SessionFsSqliteExistsParams, SessionFsSqliteExistsResult, SessionFsSqliteQueryRequest, SessionFsSqliteQueryResult as GeneratedSqliteQueryResult, - SessionFsStatRequest, SessionFsStatResult, SessionFsWriteFileRequest, + SessionFsSqliteTransactionError as GeneratedSqliteTransactionError, + SessionFsSqliteTransactionErrorClass, SessionFsSqliteTransactionRequest, + SessionFsSqliteTransactionResult as GeneratedSqliteTransactionResult, SessionFsStatRequest, + SessionFsStatResult, SessionFsWriteFileRequest, }; use crate::session_fs::SessionFsProvider; use crate::{Client, JsonRpcRequest, JsonRpcResponse, error_codes}; @@ -371,6 +374,69 @@ pub(crate) async fn sqlite_query( respond(client, id, result).await; } +pub(crate) async fn sqlite_transaction( + client: &Client, + provider: &Arc, + request: JsonRpcRequest, +) { + let params: SessionFsSqliteTransactionRequest = match parse_params(&request) { + Some(p) => p, + None => { + send_error( + client, + request.id, + "invalid sessionFs.sqliteTransaction params", + ) + .await; + return; + } + }; + let id = request.id; + let sqlite = match provider.sqlite() { + Some(s) => s, + None => { + // SQLite not supported — return a result-level error, not a + // transport error, so the CLI can surface it gracefully. + respond( + client, + id, + GeneratedSqliteTransactionResult { + results: Vec::new(), + error: Some(GeneratedSqliteTransactionError { + error_class: SessionFsSqliteTransactionErrorClass::Fatal, + message: "SQLite is not supported by this SessionFs provider".to_string(), + }), + }, + ) + .await; + return; + } + }; + let result = match sqlite.sqlite_transaction(¶ms.statements).await { + Ok(results) => GeneratedSqliteTransactionResult { + results: results + .into_iter() + .map(|result| GeneratedSqliteQueryResult { + columns: result.columns, + rows: result.rows, + rows_affected: result.rows_affected, + last_insert_rowid: result.last_insert_rowid, + error: None, + }) + .collect(), + error: None, + }, + Err(e) => GeneratedSqliteTransactionResult { + results: Vec::new(), + error: Some(GeneratedSqliteTransactionError { + error_class: e.error_class, + message: e.message, + }), + }, + }; + respond(client, id, result).await; +} + pub(crate) async fn sqlite_exists( client: &Client, provider: &Arc, @@ -431,6 +497,7 @@ pub(crate) async fn dispatch( "sessionFs.rm" => rm(client, &provider, request).await, "sessionFs.rename" => rename(client, &provider, request).await, "sessionFs.sqliteQuery" => sqlite_query(client, &provider, request).await, + "sessionFs.sqliteTransaction" => sqlite_transaction(client, &provider, request).await, "sessionFs.sqliteExists" => sqlite_exists(client, &provider, request).await, _ => { warn!(method = %method, "unknown sessionFs.* method"); diff --git a/rust/src/types.rs b/rust/src/types.rs index 163e1d29c0..b93c8fad91 100644 --- a/rust/src/types.rs +++ b/rust/src/types.rs @@ -33,7 +33,8 @@ use crate::provider_token::BearerTokenProvider; pub use crate::session_fs::{ DirEntry, DirEntryKind, FileInfo, FsError, SessionFsCapabilities, SessionFsConfig, SessionFsConventions, SessionFsProvider, SessionFsSqliteProvider, SessionFsSqliteQueryResult, - SessionFsSqliteQueryType, + SessionFsSqliteQueryType, SessionFsSqliteTransactionError, + SessionFsSqliteTransactionErrorClass, SessionFsSqliteTransactionStatement, }; pub use crate::trace_context::{TraceContext, TraceContextProvider}; use crate::transforms::SystemMessageTransform; diff --git a/rust/tests/e2e/rpc_additional_edge_cases.rs b/rust/tests/e2e/rpc_additional_edge_cases.rs index cce35a9856..59891e94a7 100644 --- a/rust/tests/e2e/rpc_additional_edge_cases.rs +++ b/rust/tests/e2e/rpc_additional_edge_cases.rs @@ -1,6 +1,7 @@ use github_copilot_sdk::rpc::{ - ModeSetRequest, NameSetRequest, PermissionsSetApproveAllRequest, PlanUpdateRequest, - ShellExecRequest, WorkspacesCreateFileRequest, WorkspacesReadFileRequest, + ModeSetRequest, NameSetRequest, PermissionsResetSessionApprovalsRequest, + PermissionsSetApproveAllRequest, PlanUpdateRequest, ShellExecRequest, + WorkspacesCreateFileRequest, WorkspacesReadFileRequest, }; use github_copilot_sdk::session_events::SessionMode; @@ -365,7 +366,7 @@ async fn permissions_reset_session_approvals_on_fresh_session_is_noop() { let result = session .rpc() .permissions() - .reset_session_approvals() + .reset_session_approvals(PermissionsResetSessionApprovalsRequest::default()) .await .expect("reset approvals"); assert!(result.success); diff --git a/rust/tests/e2e/rpc_event_log.rs b/rust/tests/e2e/rpc_event_log.rs index 96eccced90..18122337ab 100644 --- a/rust/tests/e2e/rpc_event_log.rs +++ b/rust/tests/e2e/rpc_event_log.rs @@ -45,6 +45,7 @@ async fn should_read_persisted_events_from_beginning() { .read(EventLogReadRequest { agent_scope: None, cursor: None, + include_ephemeral: None, max: Some(100), types: Some(json!("*")), wait_ms: Some(0), @@ -90,6 +91,7 @@ async fn should_return_tail_cursor_and_read_empty_when_no_new_events() { .read(EventLogReadRequest { agent_scope: None, cursor: Some(tail.cursor), + include_ephemeral: None, max: Some(10), types: Some(json!("*")), wait_ms: Some(0), @@ -172,6 +174,7 @@ async fn should_longpoll_with_types_filter_for_titlechanged_event() { let read_future = event_log.read(EventLogReadRequest { agent_scope: None, cursor: Some(tail.cursor), + include_ephemeral: None, max: Some(10), types: Some(json!(["session.title_changed"])), wait_ms: Some(5_000), diff --git a/rust/tests/e2e/rpc_session_state.rs b/rust/tests/e2e/rpc_session_state.rs index 199ff2a2b5..6292521903 100644 --- a/rust/tests/e2e/rpc_session_state.rs +++ b/rust/tests/e2e/rpc_session_state.rs @@ -5,8 +5,8 @@ use github_copilot_sdk::rpc::{ MetadataRecomputeContextTokensRequest, MetadataRecordContextChangeRequest, MetadataSetWorkingDirectoryRequest, MetadataSnapshotCurrentMode, ModeSetRequest, ModelSetReasoningEffortRequest, ModelSwitchToRequest, NameSetAutoRequest, NameSetRequest, - PermissionsSetApproveAllRequest, PlanUpdateRequest, SessionSetCredentialsParams, - SessionUpdateOptionsParams, SessionWorkingDirectoryContext, + PermissionsResetSessionApprovalsRequest, PermissionsSetApproveAllRequest, PlanUpdateRequest, + SessionSetCredentialsParams, SessionUpdateOptionsParams, SessionWorkingDirectoryContext, SessionWorkingDirectoryContextHostType, SessionsForkRequest, ShutdownRequest, TelemetrySetFeatureOverridesRequest, WorkspacesCreateFileRequest, WorkspacesReadFileRequest, }; @@ -1023,7 +1023,7 @@ async fn should_call_session_usage_and_permission_rpcs() { session .rpc() .permissions() - .reset_session_approvals() + .reset_session_approvals(PermissionsResetSessionApprovalsRequest::default()) .await .expect("reset approvals") .success diff --git a/rust/tests/e2e/rpc_session_state_extras.rs b/rust/tests/e2e/rpc_session_state_extras.rs index 3bd6c99bee..749e9706d3 100644 --- a/rust/tests/e2e/rpc_session_state_extras.rs +++ b/rust/tests/e2e/rpc_session_state_extras.rs @@ -315,6 +315,7 @@ async fn should_add_byok_provider_and_model_at_runtime() { .model() .switch_to(ModelSwitchToRequest { context_tier: None, + defer_if_model_change_queued: None, model_capabilities: None, model_id: selection_id.to_string(), reasoning_effort: None, diff --git a/rust/tests/e2e/rpc_tasks_and_handlers.rs b/rust/tests/e2e/rpc_tasks_and_handlers.rs index 601cc70bf2..6d15d75b4b 100644 --- a/rust/tests/e2e/rpc_tasks_and_handlers.rs +++ b/rust/tests/e2e/rpc_tasks_and_handlers.rs @@ -322,6 +322,7 @@ async fn should_return_expected_results_for_missing_pending_handler_requestids() response: UIExitPlanModeResponse { approved: false, auto_approve_edits: None, + defer_implementation: None, feedback: Some("not now".to_string()), selected_action: None, }, @@ -358,6 +359,7 @@ async fn should_return_expected_results_for_missing_pending_handler_requestids() ( "missing-approve-once-request", PermissionDecision::ApproveOnce(PermissionDecisionApproveOnce { + approved_interactively: None, kind: PermissionDecisionApproveOnceKind::ApproveOnce, }), ), diff --git a/rust/tests/e2e/session_fs_sqlite.rs b/rust/tests/e2e/session_fs_sqlite.rs index 0b99d951b0..ed7f8a1a72 100644 --- a/rust/tests/e2e/session_fs_sqlite.rs +++ b/rust/tests/e2e/session_fs_sqlite.rs @@ -6,7 +6,8 @@ use github_copilot_sdk::session_fs::{FsError, FsErrorKind}; use github_copilot_sdk::{ Client, DirEntry, DirEntryKind, FileInfo, SessionConfig, SessionFsCapabilities, SessionFsConfig, SessionFsConventions, SessionFsProvider, SessionFsSqliteProvider, - SessionFsSqliteQueryResult, SessionFsSqliteQueryType, + SessionFsSqliteQueryResult, SessionFsSqliteQueryType, SessionFsSqliteTransactionError, + SessionFsSqliteTransactionStatement, }; use rusqlite::Connection; @@ -219,40 +220,92 @@ impl SessionFsSqliteProvider for InMemorySqliteProvider { query: &str, _params: Option<&HashMap>, ) -> Result, FsError> { + let mut db_guard = self.db.lock().unwrap(); + let db = Self::get_or_create_db(&mut db_guard)?; + Ok(Some(Self::run_statement( + db, + query_type, + query, + &self.session_id, + &self.sqlite_calls, + )?)) + } + + async fn sqlite_transaction( + &self, + statements: &[SessionFsSqliteTransactionStatement], + ) -> Result, SessionFsSqliteTransactionError> { + let mut db_guard = self.db.lock().unwrap(); + let db = Self::get_or_create_db(&mut db_guard)?; + db.execute_batch("BEGIN IMMEDIATE") + .map_err(|e| Self::classify_sqlite_error(&e))?; + let mut results = Vec::with_capacity(statements.len()); + for statement in statements { + match Self::run_statement( + db, + statement.query_type.clone(), + &statement.query, + &self.session_id, + &self.sqlite_calls, + ) { + Ok(result) => results.push(result), + Err(e) => { + let _ = db.execute_batch("ROLLBACK"); + return Err(SessionFsSqliteTransactionError::fatal(e.to_string())); + } + } + } + db.execute_batch("COMMIT").map_err(|e| { + let _ = db.execute_batch("ROLLBACK"); + Self::classify_sqlite_error(&e) + })?; + Ok(results) + } + + async fn sqlite_exists(&self) -> Result { + Ok(self.db.lock().unwrap().is_some()) + } +} + +impl InMemorySqliteProvider { + fn classify_sqlite_error(error: &rusqlite::Error) -> SessionFsSqliteTransactionError { + let message = error.to_string(); + if message.contains("locked") || message.contains("busy") { + SessionFsSqliteTransactionError::busy_or_locked(message) + } else { + SessionFsSqliteTransactionError::fatal(message) + } + } + + fn run_statement( + db: &Connection, + query_type: SessionFsSqliteQueryType, + query: &str, + session_id: &str, + sqlite_calls: &Arc>>, + ) -> Result { let qt_str = match query_type { SessionFsSqliteQueryType::Exec => "exec", SessionFsSqliteQueryType::Query => "query", SessionFsSqliteQueryType::Run => "run", SessionFsSqliteQueryType::Unknown => "unknown", }; - self.sqlite_calls.lock().unwrap().push(SqliteCall { - session_id: self.session_id.clone(), + sqlite_calls.lock().unwrap().push(SqliteCall { + session_id: session_id.to_string(), query_type: qt_str.to_string(), query: query.to_string(), }); - let mut db_guard = self.db.lock().unwrap(); - let db = Self::get_or_create_db(&mut db_guard)?; let trimmed = query.trim(); if trimmed.is_empty() { - return Ok(Some(SessionFsSqliteQueryResult { - columns: vec![], - rows: vec![], - rows_affected: 0, - last_insert_rowid: None, - })); + return Ok(SessionFsSqliteQueryResult::default()); } match query_type { SessionFsSqliteQueryType::Exec => { db.execute_batch(trimmed) .map_err(|e| FsError::new(FsErrorKind::Other, e))?; - Ok(Some(SessionFsSqliteQueryResult { - columns: vec![], - rows: vec![], - rows_affected: 0, - last_insert_rowid: None, - })) + Ok(SessionFsSqliteQueryResult::default()) } SessionFsSqliteQueryType::Query => { let mut stmt = db @@ -292,37 +345,28 @@ impl SessionFsSqliteProvider for InMemorySqliteProvider { } rows.push(map); } - Ok(Some(SessionFsSqliteQueryResult { + Ok(SessionFsSqliteQueryResult { columns, rows, rows_affected: 0, last_insert_rowid: None, - })) + }) } SessionFsSqliteQueryType::Run => { let affected = db .execute(trimmed, []) .map_err(|e| FsError::new(FsErrorKind::Other, e))?; let last_id = db.last_insert_rowid(); - Ok(Some(SessionFsSqliteQueryResult { + Ok(SessionFsSqliteQueryResult { columns: vec![], rows: vec![], rows_affected: affected as i64, last_insert_rowid: Some(last_id), - })) + }) } - _ => Ok(Some(SessionFsSqliteQueryResult { - columns: vec![], - rows: vec![], - rows_affected: 0, - last_insert_rowid: None, - })), + _ => Ok(SessionFsSqliteQueryResult::default()), } } - - async fn sqlite_exists(&self) -> Result { - Ok(self.db.lock().unwrap().is_some()) - } } fn session_state_path_sqlite() -> String { diff --git a/rust/tests/session_test.rs b/rust/tests/session_test.rs index 122ec475df..41cae3e950 100644 --- a/rust/tests/session_test.rs +++ b/rust/tests/session_test.rs @@ -4309,7 +4309,7 @@ async fn command_execute_handler_error_propagates_to_ack() { use github_copilot_sdk::session_fs::{ DirEntry, DirEntryKind, FileInfo, FsError, FsErrorKind, SessionFsConventions, SessionFsProvider, SessionFsSqliteProvider, SessionFsSqliteQueryResult, - SessionFsSqliteQueryType, + SessionFsSqliteQueryType, SessionFsSqliteTransactionError, SessionFsSqliteTransactionStatement, }; struct RecordingFsProvider { @@ -4431,6 +4431,24 @@ impl SessionFsSqliteProvider for RecordingFsProvider { })) } + async fn sqlite_transaction( + &self, + statements: &[SessionFsSqliteTransactionStatement], + ) -> Result, SessionFsSqliteTransactionError> { + let mut results = Vec::with_capacity(statements.len()); + for statement in statements { + let result = self + .sqlite_query( + statement.query_type.clone(), + &statement.query, + statement.params.as_ref(), + ) + .await?; + results.push(result.unwrap_or_default()); + } + Ok(results) + } + async fn sqlite_exists(&self) -> Result { Ok(true) } @@ -4619,6 +4637,13 @@ async fn session_fs_maps_sqlite_errors_to_results() { )) } + async fn sqlite_transaction( + &self, + _statements: &[SessionFsSqliteTransactionStatement], + ) -> Result, SessionFsSqliteTransactionError> { + Err(SessionFsSqliteTransactionError::fatal("sqlite unavailable")) + } + async fn sqlite_exists(&self) -> Result { Err(FsError::with_message( FsErrorKind::Other, diff --git a/scripts/codegen/csharp.ts b/scripts/codegen/csharp.ts index 24ec217f5b..808562630f 100644 --- a/scripts/codegen/csharp.ts +++ b/scripts/codegen/csharp.ts @@ -1624,7 +1624,8 @@ function emitRpcClass( className: string, schema: JSONSchema7, visibility: "public" | "internal", - extraClasses: string[] + extraClasses: string[], + inlineTypeParentName: string = className ): string { const effectiveSchema = resolveObjectSchema(schema, rpcDefinitions) ?? @@ -1671,7 +1672,7 @@ function emitRpcClass( const prop = propSchema as JSONSchema7; const isReq = requiredSet.has(propName); const csharpName = toCSharpPropertyName(propName, prop); - const csharpType = resolveRpcType(prop, isReq, className, csharpName, extraClasses); + const csharpType = resolveRpcType(prop, isReq, inlineTypeParentName, csharpName, extraClasses); lines.push(...xmlDocPropertyComment(prop.description, propName, " ")); lines.push(...emitDataAnnotations(prop, " ", csharpType)); @@ -2037,7 +2038,15 @@ function emitSessionMethod(key: string, method: RpcMethod, lines: string[], clas }; const publicReqClass = emitRpcClass(requestClassName, publicParams, methodVisibility, classes); if (publicReqClass) classes.push(publicReqClass); - const wireReqClass = emitRpcClass(wireRequestClassName, effectiveParams, "internal", classes); + // The wire wrapper carries the same properties as the public request + // type plus `sessionId`, so both must reuse the same inline types. + const wireReqClass = emitRpcClass( + wireRequestClassName, + effectiveParams, + "internal", + classes, + requestClassName + ); if (wireReqClass) classes.push(wireReqClass); } else { const reqClass = emitRpcClass(requestClassName, effectiveParams, "internal", classes); From 5e0520b904a7b9b223cea5d7e72e103020f679ea Mon Sep 17 00:00:00 2001 From: Mackinnon Buck Date: Wed, 29 Jul 2026 18:03:57 -0700 Subject: [PATCH 3/6] Preserve SDK compatibility in Copilot update Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 7b5e2763-c535-4d58-bd7d-409c5d27c448 --- .gitattributes | 3 + dotnet/src/SessionFsProvider.cs | 65 +++++++++++++------ .../E2E/InMemorySessionFsSqliteHandler.cs | 18 ++++- dotnet/test/E2E/SessionFsE2ETests.cs | 5 +- go/session_fs_provider.go | 55 ++++++++-------- java/scripts/codegen/java.ts | 36 +++++++++- .../rpc/RemoteSessionRepository.java | 31 +++++++++ .../generated/rpc/ServerSessionsApi.java | 15 +---- .../generated/rpc/SessionsOpenAttach.java | 37 +++++++++++ .../generated/rpc/SessionsOpenCloud.java | 58 +++++++++++++++++ .../generated/rpc/SessionsOpenCreate.java | 44 +++++++++++++ .../generated/rpc/SessionsOpenHandoff.java | 65 +++++++++++++++++++ .../rpc/SessionsOpenHandoffTaskType.java | 35 ++++++++++ .../generated/rpc/SessionsOpenParams.java | 38 ++++++----- .../generated/rpc/SessionsOpenRemote.java | 51 +++++++++++++++ .../generated/rpc/SessionsOpenResume.java | 58 +++++++++++++++++ .../generated/rpc/SessionsOpenResumeLast.java | 51 +++++++++++++++ .../com/github/copilot/RpcWrappersTest.java | 4 +- .../rpc/GeneratedRpcApiCoverageTest.java | 4 +- nodejs/src/sessionFsProvider.ts | 12 +++- nodejs/test/e2e/session_fs_sqlite.e2e.test.ts | 25 ++++++- python/copilot/session_fs_provider.py | 5 +- python/e2e/test_session_fs_e2e.py | 3 +- python/e2e/test_session_fs_sqlite_e2e.py | 11 +++- rust/src/session_fs.rs | 16 ++++- rust/tests/e2e/rpc_shell_edge_cases.rs | 12 +++- rust/tests/e2e/session_fs_sqlite.rs | 13 ++-- 27 files changed, 665 insertions(+), 105 deletions(-) create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/RemoteSessionRepository.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenAttach.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenCloud.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenCreate.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenHandoff.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenHandoffTaskType.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenRemote.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenResume.java create mode 100644 java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenResumeLast.java diff --git a/.gitattributes b/.gitattributes index 379a6bbdb4..2a92ef0172 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,5 +1,8 @@ .github/workflows/*.lock.yml linguist-generated=true merge=ours +# Cross-platform tools rewrite these files, so keep their output deterministic. +java/**/*.java text eol=lf + # Generated files — keep LF line endings so codegen output is deterministic across platforms. nodejs/src/generated/* eol=lf linguist-generated=true dotnet/src/Generated/* eol=lf linguist-generated=true diff --git a/dotnet/src/SessionFsProvider.cs b/dotnet/src/SessionFsProvider.cs index d4e99567ca..a353c93ad0 100644 --- a/dotnet/src/SessionFsProvider.cs +++ b/dotnet/src/SessionFsProvider.cs @@ -30,7 +30,7 @@ public sealed class SessionFsSqliteResult ///

/// One statement in an atomic SQLite transaction passed to -/// . +/// . /// [Experimental(Diagnostics.Experimental)] public sealed class SessionFsSqliteStatement @@ -66,6 +66,18 @@ public interface ISessionFsSqliteProvider IDictionary? bindParams, CancellationToken cancellationToken); + /// + /// Checks whether the per-session SQLite database already exists, without creating it. + /// + /// Cancellation token. + Task ExistsAsync(CancellationToken cancellationToken); +} + +/// +/// Optional capability for session filesystem providers that support atomic SQLite transactions. +/// +public interface ISessionFsSqliteTransactionProvider +{ /// /// Executes atomically against the per-session database. /// @@ -79,16 +91,10 @@ public interface ISessionFsSqliteProvider Task> TransactionAsync( IList statements, CancellationToken cancellationToken); - - /// - /// Checks whether the per-session SQLite database already exists, without creating it. - /// - /// Cancellation token. - Task ExistsAsync(CancellationToken cancellationToken); } /// -/// Thrown by an to classify a failed SQLite transaction. +/// Thrown by an to classify a failed SQLite transaction. /// guarantees the transaction /// rolled back and is safe to retry; /// must never be retried. @@ -355,7 +361,7 @@ async Task ISessionFsHandler.SqliteQueryAsync(Sessio { Rows = result?.Rows?.Select(row => (IDictionary)row.ToDictionary( kvp => kvp.Key, - kvp => CopilotClient.ToJsonElementForWire(kvp.Value)!.Value)).ToList() ?? [], + kvp => ToJsonElement(kvp.Value))).ToList() ?? [], Columns = result?.Columns ?? [], RowsAffected = result?.RowsAffected ?? 0, LastInsertRowid = result?.LastInsertRowid, @@ -369,7 +375,7 @@ async Task ISessionFsHandler.SqliteQueryAsync(Sessio async Task ISessionFsHandler.SqliteTransactionAsync(SessionFsSqliteTransactionRequest request, CancellationToken cancellationToken) { - if (this is not ISessionFsSqliteProvider sqliteProvider) + if (this is not ISessionFsSqliteTransactionProvider transactionProvider) { return new SessionFsSqliteTransactionResult { @@ -390,7 +396,7 @@ async Task ISessionFsHandler.SqliteTransaction Query = statement.Query, Params = statement.Params?.ToDictionary(kvp => kvp.Key, kvp => JsonElementToValue(kvp.Value)), }).ToList(); - results = await sqliteProvider.TransactionAsync(statements, cancellationToken).ConfigureAwait(false); + results = await transactionProvider.TransactionAsync(statements, cancellationToken).ConfigureAwait(false); } catch (SessionFsSqliteTransactionException ex) { @@ -411,18 +417,32 @@ async Task ISessionFsHandler.SqliteTransaction }; } - return new SessionFsSqliteTransactionResult + try { - Results = results.Select(result => new SessionFsSqliteQueryResult + return new SessionFsSqliteTransactionResult { - Rows = result.Rows?.Select(row => (IDictionary)row.ToDictionary( - kvp => kvp.Key, - kvp => CopilotClient.ToJsonElementForWire(kvp.Value)!.Value)).ToList() ?? [], - Columns = result.Columns ?? [], - RowsAffected = result.RowsAffected, - LastInsertRowid = result.LastInsertRowid, - }).ToList(), - }; + Results = results.Select(result => new SessionFsSqliteQueryResult + { + Rows = result.Rows?.Select(row => (IDictionary)row.ToDictionary( + kvp => kvp.Key, + kvp => ToJsonElement(kvp.Value))).ToList() ?? [], + Columns = result.Columns ?? [], + RowsAffected = result.RowsAffected, + LastInsertRowid = result.LastInsertRowid, + }).ToList(), + }; + } + catch (Exception ex) + { + return new SessionFsSqliteTransactionResult + { + Error = new SessionFsSqliteTransactionError + { + ErrorClass = SessionFsSqliteTransactionErrorClass.PostCommitAmbiguous, + Message = ex.Message, + }, + }; + } } async Task ISessionFsHandler.SqliteExistsAsync(SessionFsSqliteExistsRequest request, CancellationToken cancellationToken) @@ -452,6 +472,9 @@ private static SessionFsError ToSessionFsError(Exception ex) return new SessionFsError { Code = code, Message = ex.Message }; } + private static JsonElement ToJsonElement(object? value) => + CopilotClient.ToJsonElementForWire(value) ?? JsonElement.Parse("null"); + private static object? JsonElementToValue(JsonElement element) => element.ValueKind switch { JsonValueKind.Null => null, diff --git a/dotnet/test/E2E/InMemorySessionFsSqliteHandler.cs b/dotnet/test/E2E/InMemorySessionFsSqliteHandler.cs index 8a6e81cd60..caf49fa6d9 100644 --- a/dotnet/test/E2E/InMemorySessionFsSqliteHandler.cs +++ b/dotnet/test/E2E/InMemorySessionFsSqliteHandler.cs @@ -17,7 +17,7 @@ internal record SqliteCall(string SessionId, string QueryType, string Query); /// for file operations instead of touching disk. /// internal sealed class InMemorySessionFsSqliteHandler(string sessionId, List sqliteCalls) - : SessionFsProvider, ISessionFsSqliteProvider + : SessionFsProvider, ISessionFsSqliteProvider, ISessionFsSqliteTransactionProvider { internal ConcurrentDictionary Files { get; } = new(); private readonly ConcurrentDictionary _directories = new(); @@ -61,9 +61,23 @@ public Task> TransactionAsync( .Select(statement => RunStatement(db, transaction, statement.QueryType, statement.Query, statement.Params) ?? new SessionFsSqliteResult()) .ToList(); - transaction.Commit(); + try + { + transaction.Commit(); + } + catch (Exception ex) + { + throw new SessionFsSqliteTransactionException( + ex.Message, + SessionFsSqliteTransactionErrorClass.PostCommitAmbiguous, + ex); + } return Task.FromResult(results); } + catch (SessionFsSqliteTransactionException) + { + throw; + } catch (SqliteException ex) { transaction.Rollback(); diff --git a/dotnet/test/E2E/SessionFsE2ETests.cs b/dotnet/test/E2E/SessionFsE2ETests.cs index b2f93addda..cc02b5abfa 100644 --- a/dotnet/test/E2E/SessionFsE2ETests.cs +++ b/dotnet/test/E2E/SessionFsE2ETests.cs @@ -581,7 +581,8 @@ private static string NormalizeRelativePathSegment(string segment, string paramN return normalized; } - private sealed class ThrowingSessionFsProvider(Exception exception) : SessionFsProvider, ISessionFsSqliteProvider + private sealed class ThrowingSessionFsProvider(Exception exception) + : SessionFsProvider, ISessionFsSqliteProvider, ISessionFsSqliteTransactionProvider { protected override Task ReadFileAsync(string path, CancellationToken cancellationToken) => Task.FromException(exception); @@ -616,7 +617,7 @@ protected override Task RenameAsync(string src, string dest, CancellationToken c Task ISessionFsSqliteProvider.QueryAsync(SessionFsSqliteQueryType queryType, string query, IDictionary? bindParams, CancellationToken cancellationToken) => Task.FromException(exception); - Task> ISessionFsSqliteProvider.TransactionAsync(IList statements, CancellationToken cancellationToken) => + Task> ISessionFsSqliteTransactionProvider.TransactionAsync(IList statements, CancellationToken cancellationToken) => Task.FromException>(exception); Task ISessionFsSqliteProvider.ExistsAsync(CancellationToken cancellationToken) => diff --git a/go/session_fs_provider.go b/go/session_fs_provider.go index 45061ff8a0..86aa63f7be 100644 --- a/go/session_fs_provider.go +++ b/go/session_fs_provider.go @@ -58,6 +58,13 @@ type SessionFSProvider interface { type SessionFSSqliteProvider interface { // SqliteQuery executes a SQLite query against the provider's per-session database. SqliteQuery(queryType rpc.SessionFSSqliteQueryType, query string, params map[string]any) (*SessionFSSqliteQueryResult, error) + // SqliteExists checks whether the provider has a SQLite database for the session. + SqliteExists() (bool, error) +} + +// SessionFSSqliteTransactionProvider is an optional interface that a +// [SessionFSSqliteProvider] may also implement to support atomic transactions. +type SessionFSSqliteTransactionProvider interface { // SqliteTransaction executes statements atomically against the provider's // per-session database, applying busy handling to every statement and rolling // the whole batch back if any statement fails. It returns one result per @@ -67,12 +74,10 @@ type SessionFSSqliteProvider interface { // the runtime; any other error is reported as // [rpc.SessionFSSqliteTransactionErrorClassFatal]. SqliteTransaction(statements []rpc.SessionFSSqliteTransactionStatement) ([]SessionFSSqliteQueryResult, error) - // SqliteExists checks whether the provider has a SQLite database for the session. - SqliteExists() (bool, error) } // SessionFSSqliteTransactionFailure classifies a SQLite transaction failure for -// the runtime. Return it from [SessionFSSqliteProvider.SqliteTransaction] with +// the runtime. Return it from [SessionFSSqliteTransactionProvider.SqliteTransaction] with // [rpc.SessionFSSqliteTransactionErrorClassBusyOrLocked] when SQLite reported // BUSY or LOCKED before commit and the transaction was rolled back, so the // runtime knows the call is safe to retry. @@ -242,21 +247,12 @@ func (a *sessionFSAdapter) SqliteQuery(request *rpc.SessionFSSqliteQueryRequest) RowsAffected: 0, }, nil } - var wireRowid *int64 - if result.LastInsertRowid != nil { - rowid := *result.LastInsertRowid - wireRowid = &rowid - } - return &rpc.SessionFSSqliteQueryResult{ - Columns: result.Columns, - Rows: result.Rows, - RowsAffected: result.RowsAffected, - LastInsertRowid: wireRowid, - }, nil + wireResult := toWireSqliteQueryResult(*result) + return &wireResult, nil } func (a *sessionFSAdapter) SqliteTransaction(request *rpc.SessionFSSqliteTransactionRequest) (*rpc.SessionFSSqliteTransactionResult, error) { - sp, ok := a.provider.(SessionFSSqliteProvider) + sp, ok := a.provider.(SessionFSSqliteTransactionProvider) if !ok { return &rpc.SessionFSSqliteTransactionResult{ Results: []rpc.SessionFSSqliteQueryResult{}, @@ -275,21 +271,28 @@ func (a *sessionFSAdapter) SqliteTransaction(request *rpc.SessionFSSqliteTransac } wireResults := make([]rpc.SessionFSSqliteQueryResult, 0, len(results)) for _, result := range results { - var wireRowid *int64 - if result.LastInsertRowid != nil { - rowid := *result.LastInsertRowid - wireRowid = &rowid - } - wireResults = append(wireResults, rpc.SessionFSSqliteQueryResult{ - Columns: result.Columns, - Rows: result.Rows, - RowsAffected: result.RowsAffected, - LastInsertRowid: wireRowid, - }) + wireResults = append(wireResults, toWireSqliteQueryResult(result)) } return &rpc.SessionFSSqliteTransactionResult{Results: wireResults}, nil } +func toWireSqliteQueryResult(result SessionFSSqliteQueryResult) rpc.SessionFSSqliteQueryResult { + columns := result.Columns + if columns == nil { + columns = []string{} + } + rows := result.Rows + if rows == nil { + rows = []map[string]any{} + } + return rpc.SessionFSSqliteQueryResult{ + Columns: columns, + Rows: rows, + RowsAffected: result.RowsAffected, + LastInsertRowid: result.LastInsertRowid, + } +} + func (a *sessionFSAdapter) SqliteExists(request *rpc.SessionFSSqliteExistsRequest) (*rpc.SessionFSSqliteExistsResult, error) { sp, ok := a.provider.(SessionFSSqliteProvider) if !ok { diff --git a/java/scripts/codegen/java.ts b/java/scripts/codegen/java.ts index cb70ecb032..9f7eb40039 100644 --- a/java/scripts/codegen/java.ts +++ b/java/scripts/codegen/java.ts @@ -256,6 +256,17 @@ function resolveRef(schema: JSONSchema7 | undefined): JSONSchema7 | undefined { return schema; } +function hasOmissionSentinel(schema: JSONSchema7): boolean { + return (schema.anyOf ?? []).some( + (variant) => + typeof variant === "object" + && variant !== null + && typeof (variant as JSONSchema7).not === "object" + && (variant as JSONSchema7).not !== null + && Object.keys((variant as JSONSchema7).not as object).length === 0 + ); +} + /** * Resolve a method's params schema to the object schema that carries its properties. * @@ -268,7 +279,15 @@ function resolveMethodParamsSchema(method: RpcMethodNode): JSONSchema7 | undefin if (!params || typeof params !== "object") return undefined; if (params.properties) return params; if (!Array.isArray(params.anyOf)) return undefined; - return resolveAnyOfVariants(params.anyOf as JSONSchema7[]).find((variant) => !!variant.properties); + const objectVariants = resolveAnyOfVariants(params.anyOf as JSONSchema7[]).filter((variant) => !!variant.properties); + return hasOmissionSentinel(params) && objectVariants.length === 1 ? objectVariants[0] : undefined; +} + +function resolveMethodParamsUnionSchema(method: RpcMethodNode): JSONSchema7 | undefined { + const params = resolveRef(method.params ?? undefined); + if (!params || typeof params !== "object" || !Array.isArray(params.anyOf)) return undefined; + const variants = resolveAnyOfVariants(params.anyOf as JSONSchema7[]); + return variants.length > 1 && findDiscriminator(variants) ? params : undefined; } /** Extract the definition name from a $ref string (e.g., "#/definitions/Foo" → "Foo") */ @@ -1394,6 +1413,16 @@ async function generateRpcTypes(schemaPath: string): Promise { } else if (paramsSchema?.$ref) { paramsSchema = resolveRef(paramsSchema) as JSONSchema7; } + const paramsUnionSchema = resolveMethodParamsUnionSchema(method); + if (paramsUnionSchema) { + const paramsClassName = `${className}Params`; + if (!generatedClasses.has(paramsClassName)) { + generatedClasses.set(paramsClassName, true); + await generatePolymorphicResultClass(paramsClassName, paramsUnionSchema, packageName, packageDir); + allFiles.push(`${paramsClassName}.java`); + } + paramsSchema = null; + } if (paramsSchema && !paramsSchema.properties) { paramsSchema = resolveMethodParamsSchema(method) ?? paramsSchema; } @@ -1687,6 +1716,9 @@ function addWrapperResultImports(resultType: string, allImports: Set, pa * callers supply it explicitly. */ function wrapperParamsClassName(method: RpcMethodNode, isSession: boolean): string | null { + if (resolveMethodParamsUnionSchema(method)) { + return rpcMethodToClassName(method.rpcMethod) + "Params"; + } const params = resolveMethodParamsSchema(method); if (!params) return null; const props = params.properties ?? {}; @@ -1704,7 +1736,7 @@ function methodHasSessionId(method: RpcMethodNode): boolean { /** True if the method's params object may be omitted entirely */ function methodParamsAreOptional(method: RpcMethodNode): boolean { const params = resolveRef(method.params ?? undefined); - return !!params && typeof params === "object" && !params.properties && Array.isArray(params.anyOf); + return !!params && typeof params === "object" && hasOmissionSentinel(params); } /** diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/RemoteSessionRepository.java b/java/src/generated/java/com/github/copilot/generated/rpc/RemoteSessionRepository.java new file mode 100644 index 0000000000..1ab906bb10 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/RemoteSessionRepository.java @@ -0,0 +1,31 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Repository context for the remote session. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record RemoteSessionRepository( + /** Repository owner or organization login. */ + @JsonProperty("owner") String owner, + /** Repository name. */ + @JsonProperty("name") String name, + /** Optional branch associated with the remote session. */ + @JsonProperty("branch") String branch +) { +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/ServerSessionsApi.java b/java/src/generated/java/com/github/copilot/generated/rpc/ServerSessionsApi.java index d64dbaa9eb..52481a7d73 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/ServerSessionsApi.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/ServerSessionsApi.java @@ -26,19 +26,6 @@ public final class ServerSessionsApi { this.caller = caller; } - /** - * Open a session by creating, resuming, attaching, connecting to a remote, or handing off. - *

- * Invokes the method with no params, applying the runtime defaults. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ - @CopilotExperimental - public CompletableFuture open() { - return open(null); - } - /** * Open a session by creating, resuming, attaching, connecting to a remote, or handing off. * @@ -47,7 +34,7 @@ public CompletableFuture open() { */ @CopilotExperimental public CompletableFuture open(SessionsOpenParams params) { - return caller.invoke("sessions.open", params == null ? java.util.Map.of() : params, SessionsOpenResult.class); + return caller.invoke("sessions.open", params, SessionsOpenResult.class); } /** diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenAttach.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenAttach.java new file mode 100644 index 0000000000..1554425a77 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenAttach.java @@ -0,0 +1,37 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Parameters for attaching to an already-active session by ID. + * + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionsOpenAttach extends SessionsOpenParams { + + @JsonProperty("kind") + private final String kind = "attach"; + + @Override + public String getKind() { return kind; } + + /** Session ID to attach to. */ + @JsonProperty("sessionId") + private String sessionId; + + public String getSessionId() { return sessionId; } + public void setSessionId(String sessionId) { this.sessionId = sessionId; } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenCloud.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenCloud.java new file mode 100644 index 0000000000..8e4a74bd88 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenCloud.java @@ -0,0 +1,58 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Parameters for creating a new cloud session. + * + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionsOpenCloud extends SessionsOpenParams { + + @JsonProperty("kind") + private final String kind = "cloud"; + + @Override + public String getKind() { return kind; } + + /** Repository for the cloud session. */ + @JsonProperty("repository") + private RemoteSessionRepository repository; + + /** Optional owner (user or organization login) to associate with the cloud session when no repository is provided. Ignored when `repository` is set (the repo's owner takes precedence). */ + @JsonProperty("owner") + private String owner; + + /** Session options for cloud session creation. */ + @JsonProperty("options") + private SessionOpenOptions options; + + /** In-process callback invoked when the cloud task is created (before connection). Marked internal because a function reference cannot cross the JSON-RPC boundary. Disappears in the SDK migration: the field is purely cosmetic (it flips a single CLI phase label from 'creating' to 'connecting') and the wire-clean version just drops the intermediate phase. */ + @JsonProperty("onTaskCreated") + private Object onTaskCreated; + + public RemoteSessionRepository getRepository() { return repository; } + public void setRepository(RemoteSessionRepository repository) { this.repository = repository; } + + public String getOwner() { return owner; } + public void setOwner(String owner) { this.owner = owner; } + + public SessionOpenOptions getOptions() { return options; } + public void setOptions(SessionOpenOptions options) { this.options = options; } + + public Object getOnTaskCreated() { return onTaskCreated; } + public void setOnTaskCreated(Object onTaskCreated) { this.onTaskCreated = onTaskCreated; } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenCreate.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenCreate.java new file mode 100644 index 0000000000..0394cffa6e --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenCreate.java @@ -0,0 +1,44 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Parameters for creating a new local session. + * + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionsOpenCreate extends SessionsOpenParams { + + @JsonProperty("kind") + private final String kind = "create"; + + @Override + public String getKind() { return kind; } + + /** Session construction options. */ + @JsonProperty("options") + private SessionOpenOptions options; + + /** Whether to emit session.start during creation. Defaults to true. */ + @JsonProperty("emitStart") + private Boolean emitStart; + + public SessionOpenOptions getOptions() { return options; } + public void setOptions(SessionOpenOptions options) { this.options = options; } + + public Boolean getEmitStart() { return emitStart; } + public void setEmitStart(Boolean emitStart) { this.emitStart = emitStart; } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenHandoff.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenHandoff.java new file mode 100644 index 0000000000..bb67c43387 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenHandoff.java @@ -0,0 +1,65 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Parameters for fetching a remote session and handing it off to a new local session. + * + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionsOpenHandoff extends SessionsOpenParams { + + @JsonProperty("kind") + private final String kind = "handoff"; + + @Override + public String getKind() { return kind; } + + /** Remote session metadata for the session to hand off (typically obtained from `sessions.list` with `source: "remote"`). */ + @JsonProperty("metadata") + private RemoteSessionMetadataValue metadata; + + /** Session construction options for the new local session. */ + @JsonProperty("options") + private SessionOpenOptions options; + + /** Task type determines the handoff strategy (CCA fetches events; CLI prepares a transient session). */ + @JsonProperty("taskType") + private SessionsOpenHandoffTaskType taskType; + + /** In-process progress callback `(update) => void` invoked for each handoff step. Marked internal because a function reference cannot cross the JSON-RPC boundary. The host-side `handoffSession` is already declared as `AsyncGenerator`; the schema layer flattens it because it does not yet support streaming methods. The wire-clean replacement is to expose the AsyncGenerator directly (or use vscode-jsonrpc `$/progress` notifications) once the schema/transport layer supports it. */ + @JsonProperty("onProgress") + private Object onProgress; + + /** In-process confirmation callback `(request) => boolean | Promise` invoked when the handoff needs the caller to confirm a non-fatal blocker (e.g. a repository mismatch between the current working directory and the remote session). Returning `true` proceeds with the handoff; returning `false` (or omitting the callback) aborts it. Marked internal because a function reference cannot cross the JSON-RPC boundary, for the same reasons as `onProgress`. */ + @JsonProperty("onConfirm") + private Object onConfirm; + + public RemoteSessionMetadataValue getMetadata() { return metadata; } + public void setMetadata(RemoteSessionMetadataValue metadata) { this.metadata = metadata; } + + public SessionOpenOptions getOptions() { return options; } + public void setOptions(SessionOpenOptions options) { this.options = options; } + + public SessionsOpenHandoffTaskType getTaskType() { return taskType; } + public void setTaskType(SessionsOpenHandoffTaskType taskType) { this.taskType = taskType; } + + public Object getOnProgress() { return onProgress; } + public void setOnProgress(Object onProgress) { this.onProgress = onProgress; } + + public Object getOnConfirm() { return onConfirm; } + public void setOnConfirm(Object onConfirm) { this.onConfirm = onConfirm; } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenHandoffTaskType.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenHandoffTaskType.java new file mode 100644 index 0000000000..39d7eff421 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenHandoffTaskType.java @@ -0,0 +1,35 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import javax.annotation.processing.Generated; + +/** + * Task type determines the handoff strategy (CCA fetches events; CLI prepares a transient session). + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum SessionsOpenHandoffTaskType { + /** The {@code cca} variant. */ + CCA("cca"), + /** The {@code cli} variant. */ + CLI("cli"); + + private final String value; + SessionsOpenHandoffTaskType(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static SessionsOpenHandoffTaskType fromValue(String value) { + for (SessionsOpenHandoffTaskType v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown SessionsOpenHandoffTaskType value: " + value); + } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenParams.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenParams.java index 9931a240b6..dd97950248 100644 --- a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenParams.java +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenParams.java @@ -8,27 +8,33 @@ package com.github.copilot.generated.rpc; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; import javax.annotation.processing.Generated; /** - * Parameters for creating a new local session. + * Open a session by creating, resuming, attaching, connecting to a remote, or handing off. * - * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "kind", visible = true) +@JsonSubTypes({ + @JsonSubTypes.Type(value = SessionsOpenCreate.class, name = "create"), + @JsonSubTypes.Type(value = SessionsOpenResume.class, name = "resume"), + @JsonSubTypes.Type(value = SessionsOpenResumeLast.class, name = "resumeLast"), + @JsonSubTypes.Type(value = SessionsOpenAttach.class, name = "attach"), + @JsonSubTypes.Type(value = SessionsOpenRemote.class, name = "remote"), + @JsonSubTypes.Type(value = SessionsOpenCloud.class, name = "cloud"), + @JsonSubTypes.Type(value = SessionsOpenHandoff.class, name = "handoff") +}) @JsonIgnoreProperties(ignoreUnknown = true) -public record SessionsOpenParams( - /** Create a new local session. */ - @JsonProperty("kind") String kind, - /** Session construction options. */ - @JsonProperty("options") SessionOpenOptions options, - /** Whether to emit session.start during creation. Defaults to true. */ - @JsonProperty("emitStart") Boolean emitStart -) { +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public abstract class SessionsOpenParams { + + /** + * Returns the discriminator value for this variant. + * + * @return the kind discriminator + */ + public abstract String getKind(); } diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenRemote.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenRemote.java new file mode 100644 index 0000000000..a51660d809 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenRemote.java @@ -0,0 +1,51 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Parameters for connecting to a live remote session. + * + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionsOpenRemote extends SessionsOpenParams { + + @JsonProperty("kind") + private final String kind = "remote"; + + @Override + public String getKind() { return kind; } + + /** Remote session identifier to connect to. */ + @JsonProperty("remoteSessionId") + private String remoteSessionId; + + /** Repository context for the remote session. */ + @JsonProperty("repository") + private RemoteSessionRepository repository; + + /** Session options for the connection. */ + @JsonProperty("options") + private SessionOpenOptions options; + + public String getRemoteSessionId() { return remoteSessionId; } + public void setRemoteSessionId(String remoteSessionId) { this.remoteSessionId = remoteSessionId; } + + public RemoteSessionRepository getRepository() { return repository; } + public void setRepository(RemoteSessionRepository repository) { this.repository = repository; } + + public SessionOpenOptions getOptions() { return options; } + public void setOptions(SessionOpenOptions options) { this.options = options; } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenResume.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenResume.java new file mode 100644 index 0000000000..664e5a0052 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenResume.java @@ -0,0 +1,58 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Parameters for resuming a specific local session. + * + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionsOpenResume extends SessionsOpenParams { + + @JsonProperty("kind") + private final String kind = "resume"; + + @Override + public String getKind() { return kind; } + + /** Session ID or unique prefix to resume. */ + @JsonProperty("sessionId") + private String sessionId; + + /** Session resume options. */ + @JsonProperty("options") + private SessionOpenOptions options; + + /** Whether to emit session.resume after loading. Defaults to true. */ + @JsonProperty("resume") + private Boolean resume; + + /** Suppress workspace.yaml metadata writeback when resuming from an incidental cwd. */ + @JsonProperty("suppressResumeWorkspaceMetadataWriteback") + private Boolean suppressResumeWorkspaceMetadataWriteback; + + public String getSessionId() { return sessionId; } + public void setSessionId(String sessionId) { this.sessionId = sessionId; } + + public SessionOpenOptions getOptions() { return options; } + public void setOptions(SessionOpenOptions options) { this.options = options; } + + public Boolean getResume() { return resume; } + public void setResume(Boolean resume) { this.resume = resume; } + + public Boolean getSuppressResumeWorkspaceMetadataWriteback() { return suppressResumeWorkspaceMetadataWriteback; } + public void setSuppressResumeWorkspaceMetadataWriteback(Boolean suppressResumeWorkspaceMetadataWriteback) { this.suppressResumeWorkspaceMetadataWriteback = suppressResumeWorkspaceMetadataWriteback; } +} diff --git a/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenResumeLast.java b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenResumeLast.java new file mode 100644 index 0000000000..a93afe7741 --- /dev/null +++ b/java/src/generated/java/com/github/copilot/generated/rpc/SessionsOpenResumeLast.java @@ -0,0 +1,51 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import javax.annotation.processing.Generated; + +/** + * Parameters for resuming the most relevant local session. + * + * @since 1.0.0 + */ +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionsOpenResumeLast extends SessionsOpenParams { + + @JsonProperty("kind") + private final String kind = "resumeLast"; + + @Override + public String getKind() { return kind; } + + /** Working-directory context used to choose the most relevant session. */ + @JsonProperty("context") + private SessionContext context; + + /** Session resume options. */ + @JsonProperty("options") + private SessionOpenOptions options; + + /** Suppress workspace.yaml metadata writeback when resuming from an incidental cwd. */ + @JsonProperty("suppressResumeWorkspaceMetadataWriteback") + private Boolean suppressResumeWorkspaceMetadataWriteback; + + public SessionContext getContext() { return context; } + public void setContext(SessionContext context) { this.context = context; } + + public SessionOpenOptions getOptions() { return options; } + public void setOptions(SessionOpenOptions options) { this.options = options; } + + public Boolean getSuppressResumeWorkspaceMetadataWriteback() { return suppressResumeWorkspaceMetadataWriteback; } + public void setSuppressResumeWorkspaceMetadataWriteback(Boolean suppressResumeWorkspaceMetadataWriteback) { this.suppressResumeWorkspaceMetadataWriteback = suppressResumeWorkspaceMetadataWriteback; } +} diff --git a/java/src/test/java/com/github/copilot/RpcWrappersTest.java b/java/src/test/java/com/github/copilot/RpcWrappersTest.java index 689aeb8cc1..1f1785cba7 100644 --- a/java/src/test/java/com/github/copilot/RpcWrappersTest.java +++ b/java/src/test/java/com/github/copilot/RpcWrappersTest.java @@ -230,8 +230,8 @@ void sessionRpc_agent_list_injects_sessionId() { assertEquals("session.agent.list", stub.calls.get(0).method()); var params = stub.calls.get(0).params(); - assertInstanceOf(Map.class, params); - assertEquals("sess-999", ((Map) params).get("sessionId")); + assertInstanceOf(com.fasterxml.jackson.databind.node.ObjectNode.class, params); + assertEquals("sess-999", ((com.fasterxml.jackson.databind.node.ObjectNode) params).get("sessionId").asText()); } @Test diff --git a/java/src/test/java/com/github/copilot/generated/rpc/GeneratedRpcApiCoverageTest.java b/java/src/test/java/com/github/copilot/generated/rpc/GeneratedRpcApiCoverageTest.java index a4c9344631..f3b3f98083 100644 --- a/java/src/test/java/com/github/copilot/generated/rpc/GeneratedRpcApiCoverageTest.java +++ b/java/src/test/java/com/github/copilot/generated/rpc/GeneratedRpcApiCoverageTest.java @@ -551,8 +551,8 @@ void sessionRpc_history_compact_injects_sessionId() { assertEquals(1, stub.calls.size()); assertEquals("session.history.compact", stub.calls.get(0).method()); - var params = (Map) stub.calls.get(0).params(); - assertEquals("sess-hist", params.get("sessionId")); + var params = (com.fasterxml.jackson.databind.node.ObjectNode) stub.calls.get(0).params(); + assertEquals("sess-hist", params.get("sessionId").asText()); } @Test diff --git a/nodejs/src/sessionFsProvider.ts b/nodejs/src/sessionFsProvider.ts index 8280e701d8..ecb18a5702 100644 --- a/nodejs/src/sessionFsProvider.ts +++ b/nodejs/src/sessionFsProvider.ts @@ -91,7 +91,7 @@ export interface SessionFsSqliteProvider { * @param statements - Statements to execute in order inside a single transaction. * @returns One result per statement, in the same order. */ - transaction(statements: SessionFsSqliteStatement[]): Promise; + transaction?(statements: SessionFsSqliteStatement[]): Promise; /** * Check whether the per-session database already exists, without creating it. @@ -268,8 +268,14 @@ export function createSessionFsAdapter(provider: SessionFsProvider): SessionFsHa return result ?? { rows: [], columns: [], rowsAffected: 0 }; }, sqliteTransaction: async ({ statements }) => { - if (!provider.sqlite) { - throw new Error("SQLite is not supported by this provider"); + if (!provider.sqlite?.transaction) { + return { + results: [], + error: { + errorClass: "fatal", + message: "SQLite transactions are not supported by this provider", + }, + }; } try { const results = await provider.sqlite.transaction( diff --git a/nodejs/test/e2e/session_fs_sqlite.e2e.test.ts b/nodejs/test/e2e/session_fs_sqlite.e2e.test.ts index 4383f561f0..8b58416928 100644 --- a/nodejs/test/e2e/session_fs_sqlite.e2e.test.ts +++ b/nodejs/test/e2e/session_fs_sqlite.e2e.test.ts @@ -215,8 +215,9 @@ function createTestSessionFsHandlerWithSqlite( statements: SessionFsSqliteStatement[] ): Promise { const database = getOrCreateDb(); - database.exec("BEGIN IMMEDIATE"); + let commitStarted = false; try { + database.exec("BEGIN IMMEDIATE"); const results = statements.map((statement) => { sqliteCalls.push({ sessionId: session.sessionId, @@ -232,11 +233,31 @@ function createTestSessionFsHandlerWithSqlite( ) ?? { rows: [], columns: [], rowsAffected: 0 } ); }); + commitStarted = true; database.exec("COMMIT"); return results; } catch (err) { - database.exec("ROLLBACK"); const message = err instanceof Error ? err.message : String(err); + if (commitStarted) { + throw new SessionFsSqliteTransactionFailure( + message, + "postCommitAmbiguous" + ); + } + if (database.inTransaction) { + try { + database.exec("ROLLBACK"); + } catch (rollbackError) { + const rollbackMessage = + rollbackError instanceof Error + ? rollbackError.message + : String(rollbackError); + throw new SessionFsSqliteTransactionFailure( + `${message}; rollback failed: ${rollbackMessage}`, + "fatal" + ); + } + } throw new SessionFsSqliteTransactionFailure( message, /busy|locked/i.test(message) ? "busyOrLocked" : "fatal" diff --git a/python/copilot/session_fs_provider.py b/python/copilot/session_fs_provider.py index c07aae6d42..c9e90a6442 100644 --- a/python/copilot/session_fs_provider.py +++ b/python/copilot/session_fs_provider.py @@ -138,7 +138,6 @@ async def sqlite_query( no result set is produced; the adapter will substitute an empty result. """ - @abc.abstractmethod async def sqlite_transaction( self, statements: list[SessionFSSqliteTransactionStatement], @@ -150,6 +149,10 @@ async def sqlite_transaction( failure should be classified; any other exception is reported as ``fatal``. """ + raise SessionFsSqliteTransactionFailure( + "SQLite transactions are not supported by this SessionFs provider", + SessionFSSqliteTransactionErrorClass.FATAL, + ) @abc.abstractmethod async def sqlite_exists(self) -> bool: diff --git a/python/e2e/test_session_fs_e2e.py b/python/e2e/test_session_fs_e2e.py index 0d86303264..bb6e47af7b 100644 --- a/python/e2e/test_session_fs_e2e.py +++ b/python/e2e/test_session_fs_e2e.py @@ -643,7 +643,8 @@ def create_handler(session): def provider_path(provider_root: Path, session_id: str, path: str) -> Path: - return provider_root / session_id / path.lstrip("/") + relative_path = path.replace("\\", "/").lstrip("/") + return provider_root / session_id / relative_path def find_tool_call_result(messages: list[SessionEvent], tool_name: str) -> str | None: diff --git a/python/e2e/test_session_fs_sqlite_e2e.py b/python/e2e/test_session_fs_sqlite_e2e.py index d5d79edd47..f48bcd2cdc 100644 --- a/python/e2e/test_session_fs_sqlite_e2e.py +++ b/python/e2e/test_session_fs_sqlite_e2e.py @@ -170,7 +170,6 @@ async def sqlite_transaction( ) for statement in statements ] - db.commit() except Exception as exc: db.rollback() message = str(exc) @@ -180,6 +179,12 @@ async def sqlite_transaction( else SessionFSSqliteTransactionErrorClass.FATAL ) raise SessionFsSqliteTransactionFailure(message, error_class) from exc + try: + db.commit() + except Exception as exc: + raise SessionFsSqliteTransactionFailure( + str(exc), SessionFSSqliteTransactionErrorClass.POST_COMMIT_AMBIGUOUS + ) from exc return results def _run_statement( @@ -203,9 +208,11 @@ def _run_statement( return SessionFsSqliteQueryResult(columns=[], rows=[], rows_affected=0) if query_type == SessionFSSqliteQueryType.EXEC: - db.executescript(trimmed) if commit: + db.executescript(trimmed) db.commit() + else: + db.execute(trimmed) return SessionFsSqliteQueryResult(columns=[], rows=[], rows_affected=0) if query_type == SessionFSSqliteQueryType.QUERY: diff --git a/rust/src/session_fs.rs b/rust/src/session_fs.rs index 68babd0c30..87868101f5 100644 --- a/rust/src/session_fs.rs +++ b/rust/src/session_fs.rs @@ -540,8 +540,12 @@ pub trait SessionFsSqliteProvider: Send + Sync { /// must never be retried. async fn sqlite_transaction( &self, - statements: &[SessionFsSqliteTransactionStatement], - ) -> Result, SessionFsSqliteTransactionError>; + _statements: &[SessionFsSqliteTransactionStatement], + ) -> Result, SessionFsSqliteTransactionError> { + Err(SessionFsSqliteTransactionError::fatal( + "SQLite transactions are not supported by this SessionFs provider", + )) + } /// Check whether the provider has a SQLite database for this session. async fn sqlite_exists(&self) -> Result; @@ -573,6 +577,14 @@ impl SessionFsSqliteTransactionError { message: message.into(), } } + + /// Create a `PostCommitAmbiguous` transaction error with the given message. + pub fn post_commit_ambiguous(message: impl Into) -> Self { + Self { + error_class: SessionFsSqliteTransactionErrorClass::PostCommitAmbiguous, + message: message.into(), + } + } } impl std::fmt::Display for SessionFsSqliteTransactionError { diff --git a/rust/tests/e2e/rpc_shell_edge_cases.rs b/rust/tests/e2e/rpc_shell_edge_cases.rs index 74ae897369..112b23d411 100644 --- a/rust/tests/e2e/rpc_shell_edge_cases.rs +++ b/rust/tests/e2e/rpc_shell_edge_cases.rs @@ -26,7 +26,7 @@ async fn shell_exec_with_timeout_kills_long_running_command() { .exec(ShellExecRequest { command: delayed_write_command(&started_path, &marker_path), cwd: Some(ctx.work_dir().display().to_string()), - timeout: Some(200), + timeout: Some(shell_timeout_ms()), }) .await .expect("execute timed command"); @@ -316,6 +316,11 @@ fn delayed_write_command(started_path: &Path, marker_path: &Path) -> String { ) } +#[cfg(windows)] +fn shell_timeout_ms() -> i64 { + 2_000 +} + #[cfg(not(windows))] fn delayed_write_command(started_path: &Path, marker_path: &Path) -> String { format!( @@ -325,6 +330,11 @@ fn delayed_write_command(started_path: &Path, marker_path: &Path) -> String { ) } +#[cfg(not(windows))] +fn shell_timeout_ms() -> i64 { + 200 +} + #[cfg(windows)] fn write_relative_marker_command(marker: &str) -> String { format!( diff --git a/rust/tests/e2e/session_fs_sqlite.rs b/rust/tests/e2e/session_fs_sqlite.rs index ed7f8a1a72..595a2c6b07 100644 --- a/rust/tests/e2e/session_fs_sqlite.rs +++ b/rust/tests/e2e/session_fs_sqlite.rs @@ -251,14 +251,12 @@ impl SessionFsSqliteProvider for InMemorySqliteProvider { Ok(result) => results.push(result), Err(e) => { let _ = db.execute_batch("ROLLBACK"); - return Err(SessionFsSqliteTransactionError::fatal(e.to_string())); + return Err(Self::classify_error_message(e.to_string())); } } } - db.execute_batch("COMMIT").map_err(|e| { - let _ = db.execute_batch("ROLLBACK"); - Self::classify_sqlite_error(&e) - })?; + db.execute_batch("COMMIT") + .map_err(|e| SessionFsSqliteTransactionError::post_commit_ambiguous(e.to_string()))?; Ok(results) } @@ -269,7 +267,10 @@ impl SessionFsSqliteProvider for InMemorySqliteProvider { impl InMemorySqliteProvider { fn classify_sqlite_error(error: &rusqlite::Error) -> SessionFsSqliteTransactionError { - let message = error.to_string(); + Self::classify_error_message(error.to_string()) + } + + fn classify_error_message(message: String) -> SessionFsSqliteTransactionError { if message.contains("locked") || message.contains("busy") { SessionFsSqliteTransactionError::busy_or_locked(message) } else { From ebbd55af0565358d7d3a6cd5ae956a2e704963ce Mon Sep 17 00:00:00 2001 From: Mackinnon Buck Date: Wed, 29 Jul 2026 18:12:51 -0700 Subject: [PATCH 4/6] Format SessionFs transaction changes Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 7b5e2763-c535-4d58-bd7d-409c5d27c448 --- go/session_fs_provider.go | 12 ++++++------ nodejs/test/e2e/session_fs_sqlite.e2e.test.ts | 5 +---- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/go/session_fs_provider.go b/go/session_fs_provider.go index 86aa63f7be..0f653f1a0f 100644 --- a/go/session_fs_provider.go +++ b/go/session_fs_provider.go @@ -279,17 +279,17 @@ func (a *sessionFSAdapter) SqliteTransaction(request *rpc.SessionFSSqliteTransac func toWireSqliteQueryResult(result SessionFSSqliteQueryResult) rpc.SessionFSSqliteQueryResult { columns := result.Columns if columns == nil { - columns = []string{} + columns = []string{} } rows := result.Rows if rows == nil { - rows = []map[string]any{} + rows = []map[string]any{} } return rpc.SessionFSSqliteQueryResult{ - Columns: columns, - Rows: rows, - RowsAffected: result.RowsAffected, - LastInsertRowid: result.LastInsertRowid, + Columns: columns, + Rows: rows, + RowsAffected: result.RowsAffected, + LastInsertRowid: result.LastInsertRowid, } } diff --git a/nodejs/test/e2e/session_fs_sqlite.e2e.test.ts b/nodejs/test/e2e/session_fs_sqlite.e2e.test.ts index 8b58416928..5bc944240d 100644 --- a/nodejs/test/e2e/session_fs_sqlite.e2e.test.ts +++ b/nodejs/test/e2e/session_fs_sqlite.e2e.test.ts @@ -239,10 +239,7 @@ function createTestSessionFsHandlerWithSqlite( } catch (err) { const message = err instanceof Error ? err.message : String(err); if (commitStarted) { - throw new SessionFsSqliteTransactionFailure( - message, - "postCommitAmbiguous" - ); + throw new SessionFsSqliteTransactionFailure(message, "postCommitAmbiguous"); } if (database.inTransaction) { try { From df983ddec5f5d96e650dc5cbce64ddbfec57c39d Mon Sep 17 00:00:00 2001 From: Mackinnon Buck Date: Wed, 29 Jul 2026 18:54:58 -0700 Subject: [PATCH 5/6] Fix Windows shell timeout test timing Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 7b5e2763-c535-4d58-bd7d-409c5d27c448 --- rust/tests/e2e/rpc_shell_edge_cases.rs | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/rust/tests/e2e/rpc_shell_edge_cases.rs b/rust/tests/e2e/rpc_shell_edge_cases.rs index 112b23d411..b5476e5b32 100644 --- a/rust/tests/e2e/rpc_shell_edge_cases.rs +++ b/rust/tests/e2e/rpc_shell_edge_cases.rs @@ -1,4 +1,4 @@ -use std::path::Path; +use std::{path::Path, time::Duration}; use github_copilot_sdk::rpc::{ShellExecRequest, ShellKillRequest, ShellKillSignal}; @@ -12,6 +12,7 @@ async fn shell_exec_with_timeout_kills_long_running_command() { |ctx| { Box::pin(async move { ctx.set_default_copilot_user(); + let timeout = shell_timeout(); let started_path = ctx.work_dir().join("shell-timeout-started.txt"); let marker_path = ctx.work_dir().join("shell-timeout-marker.txt"); let client = ctx.start_client().await; @@ -26,13 +27,20 @@ async fn shell_exec_with_timeout_kills_long_running_command() { .exec(ShellExecRequest { command: delayed_write_command(&started_path, &marker_path), cwd: Some(ctx.work_dir().display().to_string()), - timeout: Some(shell_timeout_ms()), + timeout: Some( + timeout + .as_millis() + .try_into() + .expect("shell timeout fits in i64"), + ), }) .await .expect("execute timed command"); assert!(!result.process_id.trim().is_empty()); wait_for_exists(&started_path).await; + // The cleanup probe should not terminate a process before its timeout expires. + tokio::time::sleep(timeout).await; wait_for_process_cleanup(&session, result.process_id, "timed-out command").await; assert!( !marker_path.exists(), @@ -317,8 +325,8 @@ fn delayed_write_command(started_path: &Path, marker_path: &Path) -> String { } #[cfg(windows)] -fn shell_timeout_ms() -> i64 { - 2_000 +fn shell_timeout() -> Duration { + Duration::from_secs(2) } #[cfg(not(windows))] @@ -331,8 +339,8 @@ fn delayed_write_command(started_path: &Path, marker_path: &Path) -> String { } #[cfg(not(windows))] -fn shell_timeout_ms() -> i64 { - 200 +fn shell_timeout() -> Duration { + Duration::from_millis(200) } #[cfg(windows)] From a6319b999db2113a929aa1ab09baaccde21a77b7 Mon Sep 17 00:00:00 2001 From: Mackinnon Buck Date: Wed, 29 Jul 2026 19:00:41 -0700 Subject: [PATCH 6/6] Apply nightly Rust formatting Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 7b5e2763-c535-4d58-bd7d-409c5d27c448 --- rust/tests/e2e/rpc_shell_edge_cases.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/rust/tests/e2e/rpc_shell_edge_cases.rs b/rust/tests/e2e/rpc_shell_edge_cases.rs index b5476e5b32..318a7e5005 100644 --- a/rust/tests/e2e/rpc_shell_edge_cases.rs +++ b/rust/tests/e2e/rpc_shell_edge_cases.rs @@ -1,4 +1,5 @@ -use std::{path::Path, time::Duration}; +use std::path::Path; +use std::time::Duration; use github_copilot_sdk::rpc::{ShellExecRequest, ShellKillRequest, ShellKillSignal};