This package is not in the latest version of its module.
Package copilot provides a Go SDK for interacting with the GitHub Copilot CLI.
The copilot package enables Go applications to communicate with the Copilot CLI server, create and manage conversation sessions, and integrate custom tools.
Basic usage:
client := copilot.NewClient(nil)
if err := client.Start(); err != nil {
log.Fatal(err)
}
defer client.Stop()
session, err := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-4",
})
if err != nil {
log.Fatal(err)
}
session.On(func(event copilot.SessionEvent) {
if d, ok := event.Data.(*copilot.AssistantMessageData); ok {
fmt.Println(d.Content)
}
})
session.Send(copilot.MessageOptions{Prompt: "Hello!"})
Package copilot provides a Go SDK for interacting with the GitHub Copilot CLI.
const ( // GitHubTokenRequestReasonInitial indicates the session needs its initial token. GitHubTokenRequestReasonInitial = rpc.GitHubTokenAcquireReasonInitial // GitHubTokenRequestReasonRefresh indicates the session needs a refreshed token. GitHubTokenRequestReasonRefresh = rpc.GitHubTokenAcquireReasonRefresh )
const ( AhpHostAuthenticationModeGitHub = rpc.HostAuthenticationModeGitHub AhpHostAuthenticationModeCustom = rpc.HostAuthenticationModeCustom AhpHostAuthenticationModeNone = rpc.HostAuthenticationModeNone )
const ( // InstallationConfirmationDecisionCancel cancels the pending decision without granting consent. InstallationConfirmationDecisionCancel = rpc.InstallationDecisionCancel // InstallationConfirmationDecisionConfirm explicitly approves the exact review. InstallationConfirmationDecisionConfirm = rpc.InstallationDecisionConfirm // InstallationConfirmationDecisionDecline declines the reviewed operation. InstallationConfirmationDecisionDecline = rpc.InstallationDecisionDecline )
const ( // SectionPreamble is the agent identity preamble and mode statement. SectionPreamble = "preamble" // SectionIdentity is the section group covering the identity preamble and its // sibling sub-sections (tone, tool efficiency, etc.). SectionIdentity = "identity" // SectionTone covers response style, conciseness rules, and output formatting preferences. SectionTone = "tone" // SectionToolEfficiency covers tool usage patterns, parallel calling, and batching guidelines. SectionToolEfficiency = "tool_efficiency" // SectionEnvironmentContext covers CWD, OS, git root, directory listing, and available tools. SectionEnvironmentContext = "environment_context" // SectionCodeChangeRules covers coding rules, linting/testing, ecosystem tools, and style. SectionCodeChangeRules = "code_change_rules" // SectionGuidelines covers tips, behavioral best practices, and behavioral guidelines. SectionGuidelines = "guidelines" // SectionSafety covers environment limitations, prohibited actions, and security policies. SectionSafety = "safety" // SectionToolInstructions covers per-tool usage instructions. SectionToolInstructions = "tool_instructions" // SectionCustomInstructions covers repository and organization custom instructions. SectionCustomInstructions = "custom_instructions" // SectionRuntimeInstructions targets runtime-provided system-prompt context and // instructions, such as system notifications, memories, workspace context, and // content-exclusion policy. Mode-specific instructions can travel in transition // messages instead. SectionRuntimeInstructions = "runtime_instructions" // SectionLastInstructions covers end-of-prompt instructions: parallel tool calling, // persistence, task completion, and configured subagent-model guidance when the // task tool is available. SectionLastInstructions = "last_instructions" )
Known system message section identifiers for the "customize" mode.
const ( PermissionResponseCapabilityHeadless = rpc.PermissionResponseCapabilityHeadless PermissionResponseCapabilityInteractive = rpc.PermissionResponseCapabilityInteractive PermissionResponseCapabilityNone = rpc.PermissionResponseCapabilityNone )
const ( PermissionDecisionOutcomeAutoApproved = rpc.PermissionDecisionOutcomeAutoApproved PermissionDecisionOutcomeAutopilotDenied = rpc.PermissionDecisionOutcomeAutopilotDenied PermissionDecisionOutcomePromptedUser = rpc.PermissionDecisionOutcomePromptedUser )
const ( PermissionDecisionSourceAssistedApproval = rpc.PermissionDecisionSourceAssistedApproval PermissionDecisionSourceHostPolicy = rpc.PermissionDecisionSourceHostPolicy PermissionDecisionSourceHumanResponse = rpc.PermissionDecisionSourceHumanResponse PermissionDecisionSourceUnattendedFallback = rpc.PermissionDecisionSourceUnattendedFallback )
const ( PermissionDecisionSurfaceAcp = rpc.PermissionDecisionSurfaceAcp PermissionDecisionSurfaceCopilotApp = rpc.PermissionDecisionSurfaceCopilotApp PermissionDecisionSurfacePromptMode = rpc.PermissionDecisionSurfacePromptMode PermissionDecisionSurfaceSDK = rpc.PermissionDecisionSurfaceSDK PermissionDecisionSurfaceTui = rpc.PermissionDecisionSurfaceTui )
const ( // MCPAuthResultKindToken indicates that the host provided token data. MCPAuthResultKindToken = "token" // MCPAuthResultKindCancelled indicates that the host declined the request. MCPAuthResultKindCancelled = "cancelled" // MCPAuthResultKindRuntimeRefresh hands an advertised Refresh back to its original runtime operation. MCPAuthResultKindRuntimeRefresh = "runtimeRefresh" )
const ( // MemoryModeSystemPrompt includes memories in the system prompt (the default). MemoryModeSystemPrompt = rpc.MemoryModeSystemPrompt // MemoryModeUserPrompt includes memories in user messages. MemoryModeUserPrompt = rpc.MemoryModeUserPrompt )
const ( // AutoTierEfficiency selects the efficiency routing tier. AutoTierEfficiency = rpc.AutoTierEfficiency // AutoTierBalance selects the balance routing tier. AutoTierBalance = rpc.AutoTierBalance // AutoTierIntelligence selects the intelligence routing tier. AutoTierIntelligence = rpc.AutoTierIntelligence // AutoTierFast selects the integrator-only latency preset. AutoTierFast = rpc.AutoTierFast )
const ( AgentModeInteractive = rpc.SendAgentModeInteractive AgentModePlan = rpc.SendAgentModePlan AgentModeAutopilot = rpc.SendAgentModeAutopilot AgentModeShell = rpc.SendAgentModeShell )
AgentMode values supported by the runtime.
const ( AbortReasonAutopilotCreditLimit = rpc.AbortReasonAutopilotCreditLimit AbortReasonRemoteCommand = rpc.AbortReasonRemoteCommand AbortReasonUserAbort = rpc.AbortReasonUserAbort AbortReasonUserInitiated = rpc.AbortReasonUserInitiated AgentInterruptedActivityBackgroundAgent = rpc.AgentInterruptedActivityBackgroundAgent AgentInterruptedActivityModelCall = rpc.AgentInterruptedActivityModelCall AgentInterruptedActivityRetryBackoff = rpc.AgentInterruptedActivityRetryBackoff AgentInterruptedActivityToolCall = rpc.AgentInterruptedActivityToolCall AgentInterruptedCancelPhaseMidStream = rpc.AgentInterruptedCancelPhaseMidStream AgentInterruptedCancelPhasePreFirstToken = rpc.AgentInterruptedCancelPhasePreFirstToken AgentModelPolicyPreferred = rpc.AgentModelPolicyPreferred AgentModelPolicyRequired = rpc.AgentModelPolicyRequired AiCreditsStatusComplete = rpc.AiCreditsStatusComplete AiCreditsStatusPartial = rpc.AiCreditsStatusPartial AssistantMessageToolRequestCallerTypeProgram = rpc.AssistantMessageToolRequestCallerTypeProgram AssistantMessageToolRequestTypeCustom = rpc.AssistantMessageToolRequestTypeCustom AssistantMessageToolRequestTypeFunction = rpc.AssistantMessageToolRequestTypeFunction AssistantUsageAPIEndpointChatCompletions = rpc.AssistantUsageAPIEndpointChatCompletions AssistantUsageAPIEndpointResponses = rpc.AssistantUsageAPIEndpointResponses AssistantUsageAPIEndpointV1Messages = rpc.AssistantUsageAPIEndpointV1Messages AssistantUsageAPIEndpointWsResponses = rpc.AssistantUsageAPIEndpointWsResponses AssistantUsageTransportHTTP = rpc.AssistantUsageTransportHTTP AssistantUsageTransportWebsocket = rpc.AssistantUsageTransportWebsocket AssistedApprovalJudgeFailureReasonAbort = rpc.AssistedApprovalJudgeFailureReasonAbort AssistedApprovalJudgeFailureReasonEmptyResponse = rpc.AssistedApprovalJudgeFailureReasonEmptyResponse AssistedApprovalJudgeFailureReasonModelError = rpc.AssistedApprovalJudgeFailureReasonModelError AssistedApprovalJudgeFailureReasonParseError = rpc.AssistedApprovalJudgeFailureReasonParseError AssistedApprovalJudgeFailureReasonTimeout = rpc.AssistedApprovalJudgeFailureReasonTimeout AssistedApprovalRecommendationApprove = rpc.AssistedApprovalRecommendationApprove AssistedApprovalRecommendationError = rpc.AssistedApprovalRecommendationError AssistedApprovalRecommendationExcluded = rpc.AssistedApprovalRecommendationExcluded AssistedApprovalRecommendationRequireApproval = rpc.AssistedApprovalRecommendationRequireApproval AttachmentGitHubReferenceTypeDiscussion = rpc.AttachmentGitHubReferenceTypeDiscussion AttachmentGitHubReferenceTypeIssue = rpc.AttachmentGitHubReferenceTypeIssue AttachmentGitHubReferenceTypePr = rpc.AttachmentGitHubReferenceTypePr AttachmentTypeBlob = rpc.AttachmentTypeBlob AttachmentTypeDirectory = rpc.AttachmentTypeDirectory AttachmentTypeExtensionContext = rpc.AttachmentTypeExtensionContext AttachmentTypeFile = rpc.AttachmentTypeFile AttachmentTypeGitHubActionsJob = rpc.AttachmentTypeGitHubActionsJob AttachmentTypeGitHubCommit = rpc.AttachmentTypeGitHubCommit AttachmentTypeGitHubFile = rpc.AttachmentTypeGitHubFile AttachmentTypeGitHubFileDiff = rpc.AttachmentTypeGitHubFileDiff AttachmentTypeGitHubReference = rpc.AttachmentTypeGitHubReference AttachmentTypeGitHubRelease = rpc.AttachmentTypeGitHubRelease AttachmentTypeGitHubRepository = rpc.AttachmentTypeGitHubRepository AttachmentTypeGitHubSnippet = rpc.AttachmentTypeGitHubSnippet AttachmentTypeGitHubTreeComparison = rpc.AttachmentTypeGitHubTreeComparison AttachmentTypeGitHubURL = rpc.AttachmentTypeGitHubURL AttachmentTypeSelection = rpc.AttachmentTypeSelection AutoModeResolvedReasoningBucketHigh = rpc.AutoModeResolvedReasoningBucketHigh AutoModeResolvedReasoningBucketLow = rpc.AutoModeResolvedReasoningBucketLow AutoModeResolvedReasoningBucketMedium = rpc.AutoModeResolvedReasoningBucketMedium AutoModeSwitchResponseNo = rpc.AutoModeSwitchResponseNo AutoModeSwitchResponseYes = rpc.AutoModeSwitchResponseYes AutoModeSwitchResponseYesAlways = rpc.AutoModeSwitchResponseYesAlways AutopilotObjectiveChangedOperationCreate = rpc.AutopilotObjectiveChangedOperationCreate AutopilotObjectiveChangedOperationDelete = rpc.AutopilotObjectiveChangedOperationDelete AutopilotObjectiveChangedOperationUpdate = rpc.AutopilotObjectiveChangedOperationUpdate AutopilotObjectiveChangedStatusActive = rpc.AutopilotObjectiveChangedStatusActive AutopilotObjectiveChangedStatusCapReached = rpc.AutopilotObjectiveChangedStatusCapReached AutopilotObjectiveChangedStatusCompleted = rpc.AutopilotObjectiveChangedStatusCompleted AutopilotObjectiveChangedStatusPaused = rpc.AutopilotObjectiveChangedStatusPaused AutoTierSwitchFailureReasonPolicyRejected = rpc.AutoTierSwitchFailureReasonPolicyRejected AutoTierSwitchFailureReasonRequestFailed = rpc.AutoTierSwitchFailureReasonRequestFailed AutoTierSwitchFailureReasonSetupFailed = rpc.AutoTierSwitchFailureReasonSetupFailed AutoTierSwitchFailureReasonUnsupported = rpc.AutoTierSwitchFailureReasonUnsupported BinaryAssetReferenceTypeImage = rpc.BinaryAssetReferenceTypeImage BinaryAssetReferenceTypeResource = rpc.BinaryAssetReferenceTypeResource BinaryAssetTypeImage = rpc.BinaryAssetTypeImage BinaryAssetTypeResource = rpc.BinaryAssetTypeResource CitationLocationTypeBlock = rpc.CitationLocationTypeBlock CitationLocationTypeChar = rpc.CitationLocationTypeChar CitationLocationTypePage = rpc.CitationLocationTypePage CitationProviderAnthropic = rpc.CitationProviderAnthropic CitationProviderClient = rpc.CitationProviderClient CitationProviderOpenai = rpc.CitationProviderOpenai CompactionTriggerContextLimitRetry = rpc.CompactionTriggerContextLimitRetry CompactionTriggerManual = rpc.CompactionTriggerManual CompactionTriggerMemoryPressure = rpc.CompactionTriggerMemoryPressure CompactionTriggerModelSwitch = rpc.CompactionTriggerModelSwitch CompactionTriggerThreshold = rpc.CompactionTriggerThreshold CompletionReceiptStopReasonAgentStopBlockLimit = rpc.CompletionReceiptStopReasonAgentStopBlockLimit CompletionReceiptStopReasonNatural = rpc.CompletionReceiptStopReasonNatural CompletionReceiptStopReasonTerminalTool = rpc.CompletionReceiptStopReasonTerminalTool CompletionReceiptToolStatusDenied = rpc.CompletionReceiptToolStatusDenied CompletionReceiptToolStatusFailure = rpc.CompletionReceiptToolStatusFailure CompletionReceiptToolStatusRejected = rpc.CompletionReceiptToolStatusRejected CompletionReceiptToolStatusSuccess = rpc.CompletionReceiptToolStatusSuccess CompletionReceiptToolStatusTimeout = rpc.CompletionReceiptToolStatusTimeout ContextTierDefault = rpc.ContextTierDefault ContextTierLongContext = rpc.ContextTierLongContext ElicitationCompletedActionAccept = rpc.ElicitationCompletedActionAccept ElicitationCompletedActionCancel = rpc.ElicitationCompletedActionCancel ElicitationCompletedActionDecline = rpc.ElicitationCompletedActionDecline ElicitationRequestedModeForm = rpc.ElicitationRequestedModeForm ElicitationRequestedModeURL = rpc.ElicitationRequestedModeURL ElicitationRequestedSchemaTypeObject = rpc.ElicitationRequestedSchemaTypeObject ExitPlanModeActionAutopilot = rpc.ExitPlanModeActionAutopilot ExitPlanModeActionAutopilotFleet = rpc.ExitPlanModeActionAutopilotFleet ExitPlanModeActionExitOnly = rpc.ExitPlanModeActionExitOnly ExitPlanModeActionInteractive = rpc.ExitPlanModeActionInteractive ExtensionsLoadedExtensionSourcePlugin = rpc.ExtensionsLoadedExtensionSourcePlugin ExtensionsLoadedExtensionSourceProject = rpc.ExtensionsLoadedExtensionSourceProject ExtensionsLoadedExtensionSourceSession = rpc.ExtensionsLoadedExtensionSourceSession ExtensionsLoadedExtensionSourceUser = rpc.ExtensionsLoadedExtensionSourceUser ExtensionsLoadedExtensionStatusDisabled = rpc.ExtensionsLoadedExtensionStatusDisabled ExtensionsLoadedExtensionStatusFailed = rpc.ExtensionsLoadedExtensionStatusFailed ExtensionsLoadedExtensionStatusRunning = rpc.ExtensionsLoadedExtensionStatusRunning ExtensionsLoadedExtensionStatusStarting = rpc.ExtensionsLoadedExtensionStatusStarting FusionConversationScopeReview = rpc.FusionConversationScopeReview FusionConversationScopeRoot = rpc.FusionConversationScopeRoot FusionFollowUpActionReroute = rpc.FusionFollowUpActionReroute FusionFollowUpActionReusePrimary = rpc.FusionFollowUpActionReusePrimary FusionPatternCascade = rpc.FusionPatternCascade FusionPatternCritique = rpc.FusionPatternCritique FusionPatternSingle = rpc.FusionPatternSingle FusionPhaseActivityKindModelOutput = rpc.FusionPhaseActivityKindModelOutput FusionPhaseActivityKindToolCompleted = rpc.FusionPhaseActivityKindToolCompleted FusionPhaseActivityKindToolStarted = rpc.FusionPhaseActivityKindToolStarted FusionPhaseKindCritic = rpc.FusionPhaseKindCritic FusionPhaseKindDraft = rpc.FusionPhaseKindDraft FusionPhaseKindFollowUp = rpc.FusionPhaseKindFollowUp FusionPhaseKindJudge = rpc.FusionPhaseKindJudge FusionPhaseKindPrimary = rpc.FusionPhaseKindPrimary FusionPhaseKindRepair = rpc.FusionPhaseKindRepair FusionPhaseKindRevision = rpc.FusionPhaseKindRevision FusionPhaseStatusCancelled = rpc.FusionPhaseStatusCancelled FusionPhaseStatusFailed = rpc.FusionPhaseStatusFailed FusionPhaseStatusSucceeded = rpc.FusionPhaseStatusSucceeded FusionProjectionModeAppend = rpc.FusionProjectionModeAppend FusionProjectionModeNone = rpc.FusionProjectionModeNone FusionProjectionModeStaged = rpc.FusionProjectionModeStaged FusionTurnKindCompaction = rpc.FusionTurnKindCompaction FusionTurnKindUser = rpc.FusionTurnKindUser HandoffSourceTypeLocal = rpc.HandoffSourceTypeLocal HandoffSourceTypeRemote = rpc.HandoffSourceTypeRemote HumanResponseActorHostAutomation = rpc.HumanResponseActorHostAutomation HumanResponseActorHumanResponse = rpc.HumanResponseActorHumanResponse HumanResponseActorUnknown = rpc.HumanResponseActorUnknown HumanResponseRecordedResponseResponseKindAskUser = rpc.HumanResponseRecordedResponseResponseKindAskUser HumanResponseRecordedResponseResponseKindExitPlanMode = rpc.HumanResponseRecordedResponseResponseKindExitPlanMode HumanResponseRecordedResponseResponseKindUserInput = rpc.HumanResponseRecordedResponseResponseKindUserInput IndexedSearchStateDisabled = rpc.IndexedSearchStateDisabled IndexedSearchStateEnabled = rpc.IndexedSearchStateEnabled IndexedSearchStateFailed = rpc.IndexedSearchStateFailed IndexedSearchStateReady = rpc.IndexedSearchStateReady IndexedSearchStateStarting = rpc.IndexedSearchStateStarting InstructionUpdateAuthorityHost = rpc.InstructionUpdateAuthorityHost InstructionUpdateAuthorityManagedPolicy = rpc.InstructionUpdateAuthorityManagedPolicy InstructionUpdateAuthorityRuntime = rpc.InstructionUpdateAuthorityRuntime InstructionUpdateBoundaryAfterToolResults = rpc.InstructionUpdateBoundaryAfterToolResults InstructionUpdateBoundaryNextModelRequest = rpc.InstructionUpdateBoundaryNextModelRequest InstructionUpdateFallbackRebuildSystemPrompt = rpc.InstructionUpdateFallbackRebuildSystemPrompt InstructionUpdateFallbackReject = rpc.InstructionUpdateFallbackReject InstructionUpdateLifetimePersistent = rpc.InstructionUpdateLifetimePersistent InstructionUpdateLifetimeTurn = rpc.InstructionUpdateLifetimeTurn ManagedPluginProgressPhaseComplete = rpc.ManagedPluginProgressPhaseComplete ManagedPluginProgressPhaseInitializing = rpc.ManagedPluginProgressPhaseInitializing ManagedPluginProgressPhaseInstalling = rpc.ManagedPluginProgressPhaseInstalling ManagedPluginProgressPhaseUpdating = rpc.ManagedPluginProgressPhaseUpdating ManagedSettingsEnforcedActionBypassPermissionsBlocked = rpc.ManagedSettingsEnforcedActionBypassPermissionsBlocked ManagedSettingsEnforcedEscalationAllowAll = rpc.ManagedSettingsEnforcedEscalationAllowAll ManagedSettingsEnforcedEscalationApproveAll = rpc.ManagedSettingsEnforcedEscalationApproveAll ManagedSettingsEnforcedEscalationAssistedApproval = rpc.ManagedSettingsEnforcedEscalationAssistedApproval ManagedSettingsEnforcedEscalationServerWideMCPApproval = rpc.ManagedSettingsEnforcedEscalationServerWideMCPApproval ManagedSettingsEnforcedEscalationUnrestrictedPaths = rpc.ManagedSettingsEnforcedEscalationUnrestrictedPaths ManagedSettingsEnforcedEscalationUnrestrictedURLs = rpc.ManagedSettingsEnforcedEscalationUnrestrictedURLs ManagedSettingsResolvedSourceClient = rpc.ManagedSettingsResolvedSourceClient ManagedSettingsResolvedSourceDevice = rpc.ManagedSettingsResolvedSourceDevice ManagedSettingsResolvedSourceMixed = rpc.ManagedSettingsResolvedSourceMixed ManagedSettingsResolvedSourceNone = rpc.ManagedSettingsResolvedSourceNone ManagedSettingsResolvedSourcePolicyHelper = rpc.ManagedSettingsResolvedSourcePolicyHelper ManagedSettingsResolvedSourceServer = rpc.ManagedSettingsResolvedSourceServer MCPHeadersRefreshCompletedOutcomeError = rpc.MCPHeadersRefreshCompletedOutcomeError MCPHeadersRefreshCompletedOutcomeHeaders = rpc.MCPHeadersRefreshCompletedOutcomeHeaders MCPHeadersRefreshCompletedOutcomeNone = rpc.MCPHeadersRefreshCompletedOutcomeNone MCPHeadersRefreshCompletedOutcomeTimeout = rpc.MCPHeadersRefreshCompletedOutcomeTimeout MCPHeadersRefreshRequiredReasonAuthFailed = rpc.MCPHeadersRefreshRequiredReasonAuthFailed MCPHeadersRefreshRequiredReasonStartup = rpc.MCPHeadersRefreshRequiredReasonStartup MCPHeadersRefreshRequiredReasonTtlExpired = rpc.MCPHeadersRefreshRequiredReasonTtlExpired MCPOauthCompletionOutcomeCancelled = rpc.MCPOauthCompletionOutcomeCancelled MCPOauthCompletionOutcomeToken = rpc.MCPOauthCompletionOutcomeToken MCPOauthRecoveryCompletedOutcomeCancelled = rpc.MCPOauthRecoveryCompletedOutcomeCancelled MCPOauthRecoveryCompletedOutcomeFailed = rpc.MCPOauthRecoveryCompletedOutcomeFailed MCPOauthRecoveryCompletedOutcomeSucceeded = rpc.MCPOauthRecoveryCompletedOutcomeSucceeded MCPOauthRequestReasonInitial = rpc.MCPOauthRequestReasonInitial MCPOauthRequestReasonReauth = rpc.MCPOauthRequestReasonReauth MCPOauthRequestReasonRefresh = rpc.MCPOauthRequestReasonRefresh MCPOauthRequestReasonUpscope = rpc.MCPOauthRequestReasonUpscope MCPOauthRequiredStaticClientConfigGrantTypeClientCredentials = rpc.MCPOauthRequiredStaticClientConfigGrantTypeClientCredentials MCPServerSourceAccount = rpc.MCPServerSourceAccount MCPServerSourceBuiltin = rpc.MCPServerSourceBuiltin MCPServerSourceManaged = rpc.MCPServerSourceManaged MCPServerSourcePlugin = rpc.MCPServerSourcePlugin MCPServerSourceUser = rpc.MCPServerSourceUser MCPServerSourceWorkspace = rpc.MCPServerSourceWorkspace MCPServerStatusConnected = rpc.MCPServerStatusConnected MCPServerStatusDisabled = rpc.MCPServerStatusDisabled MCPServerStatusFailed = rpc.MCPServerStatusFailed MCPServerStatusNeedsAuth = rpc.MCPServerStatusNeedsAuth MCPServerStatusNotConfigured = rpc.MCPServerStatusNotConfigured MCPServerStatusPending = rpc.MCPServerStatusPending MCPServerStatusStopped = rpc.MCPServerStatusStopped MCPServerTransportHTTP = rpc.MCPServerTransportHTTP MCPServerTransportMemory = rpc.MCPServerTransportMemory MCPServerTransportSSE = rpc.MCPServerTransportSSE MCPServerTransportStdio = rpc.MCPServerTransportStdio ModelCallFailureBadRequestKindBodyless = rpc.ModelCallFailureBadRequestKindBodyless ModelCallFailureBadRequestKindStructuredError = rpc.ModelCallFailureBadRequestKindStructuredError ModelCallFailureKindAPI = rpc.ModelCallFailureKindAPI ModelCallFailureKindTransport = rpc.ModelCallFailureKindTransport ModelCallFailureSourceMCPSampling = rpc.ModelCallFailureSourceMCPSampling ModelCallFailureSourceSubagent = rpc.ModelCallFailureSourceSubagent ModelCallFailureSourceTopLevel = rpc.ModelCallFailureSourceTopLevel ModelCallFailureTransportHTTP = rpc.ModelCallFailureTransportHTTP ModelCallFailureTransportWebsocket = rpc.ModelCallFailureTransportWebsocket ModelCallFinalResultHTTP400 = rpc.ModelCallFinalResultHTTP400 ModelCallFinalResultHTTP413 = rpc.ModelCallFinalResultHTTP413 ModelCallFinalResultHTTP429 = rpc.ModelCallFinalResultHTTP429 ModelCallFinalResultHTTP4xx = rpc.ModelCallFinalResultHTTP4xx ModelCallFinalResultHTTP5xx = rpc.ModelCallFinalResultHTTP5xx ModelCallFinalResultOtherError = rpc.ModelCallFinalResultOtherError ModelCallFinalResultSuccess = rpc.ModelCallFinalResultSuccess ModelCallFinalResultTransportError = rpc.ModelCallFinalResultTransportError ModelCallFinishedOutcomeCancelled = rpc.ModelCallFinishedOutcomeCancelled ModelCallFinishedOutcomeError = rpc.ModelCallFinishedOutcomeError ModelCallFinishedOutcomeRejected = rpc.ModelCallFinishedOutcomeRejected ModelCallFinishedOutcomeSuccess = rpc.ModelCallFinishedOutcomeSuccess ModelCallRequestBodyCompressionFallbackDisabled = rpc.ModelCallRequestBodyCompressionFallbackDisabled ModelCallRequestBodyCompressionFallbackRetried = rpc.ModelCallRequestBodyCompressionFallbackRetried ModelCallRequestBodyEncodingGzip = rpc.ModelCallRequestBodyEncodingGzip ModelCallRequestBodyEncodingIdentity = rpc.ModelCallRequestBodyEncodingIdentity ModelCallRequestBodyEncodingZstd = rpc.ModelCallRequestBodyEncodingZstd ModelCallWebSocketFallbackErrorKindClosedByPeer = rpc.ModelCallWebSocketFallbackErrorKindClosedByPeer ModelCallWebSocketFallbackErrorKindClosedLocally = rpc.ModelCallWebSocketFallbackErrorKindClosedLocally ModelCallWebSocketFallbackErrorKindConfiguration = rpc.ModelCallWebSocketFallbackErrorKindConfiguration ModelCallWebSocketFallbackErrorKindConnectionRefused = rpc.ModelCallWebSocketFallbackErrorKindConnectionRefused ModelCallWebSocketFallbackErrorKindConnectionReset = rpc.ModelCallWebSocketFallbackErrorKindConnectionReset ModelCallWebSocketFallbackErrorKindDns = rpc.ModelCallWebSocketFallbackErrorKindDns ModelCallWebSocketFallbackErrorKindHTTPStatus = rpc.ModelCallWebSocketFallbackErrorKindHTTPStatus ModelCallWebSocketFallbackErrorKindNotConnected = rpc.ModelCallWebSocketFallbackErrorKindNotConnected ModelCallWebSocketFallbackErrorKindOther = rpc.ModelCallWebSocketFallbackErrorKindOther ModelCallWebSocketFallbackErrorKindProtocol = rpc.ModelCallWebSocketFallbackErrorKindProtocol ModelCallWebSocketFallbackErrorKindTimeout = rpc.ModelCallWebSocketFallbackErrorKindTimeout ModelCallWebSocketFallbackErrorKindTls = rpc.ModelCallWebSocketFallbackErrorKindTls ModelCallWebSocketFallbackReasonAPIError = rpc.ModelCallWebSocketFallbackReasonAPIError ModelCallWebSocketFallbackReasonConnectFailed = rpc.ModelCallWebSocketFallbackReasonConnectFailed ModelCallWebSocketFallbackReasonSendFailed = rpc.ModelCallWebSocketFallbackReasonSendFailed ModelCallWebSocketFallbackReasonTransportFailed = rpc.ModelCallWebSocketFallbackReasonTransportFailed ModelChangeSourceAgent = rpc.ModelChangeSourceAgent ModelChangeSourceAutomatic = rpc.ModelChangeSourceAutomatic ModelChangeSourceAutoTierRecommendation = rpc.ModelChangeSourceAutoTierRecommendation ModelChangeSourceChangeboardingShortcut = rpc.ModelChangeSourceChangeboardingShortcut ModelChangeSourceConfigCommand = rpc.ModelChangeSourceConfigCommand ModelChangeSourceManagedSettings = rpc.ModelChangeSourceManagedSettings ModelChangeSourceModelCommand = rpc.ModelChangeSourceModelCommand ModelChangeSourceModelPicker = rpc.ModelChangeSourceModelPicker ModelChangeSourcePlanMode = rpc.ModelChangeSourcePlanMode ModelChangeSourceRepoSettings = rpc.ModelChangeSourceRepoSettings ModelChangeSourceSDK = rpc.ModelChangeSourceSDK ModelChangeSourceSettingsCommand = rpc.ModelChangeSourceSettingsCommand ModelChangeSourceStartup = rpc.ModelChangeSourceStartup ModelDeselectedReasonProviderWithdrawn = rpc.ModelDeselectedReasonProviderWithdrawn ModelProviderKindCopilot = rpc.ModelProviderKindCopilot ModelProviderKindLoki = rpc.ModelProviderKindLoki OmittedBinaryOmittedReasonTooLarge = rpc.OmittedBinaryOmittedReasonTooLarge OmittedBinaryTypeImage = rpc.OmittedBinaryTypeImage OmittedBinaryTypeResource = rpc.OmittedBinaryTypeResource PermissionApprovalEvaluationEvaluationStageJudge = rpc.PermissionApprovalEvaluationEvaluationStageJudge PermissionApprovalEvaluationEvaluationStageNotReached = rpc.PermissionApprovalEvaluationEvaluationStageNotReached PermissionApprovalEvaluationEvaluationStagePreJudge = rpc.PermissionApprovalEvaluationEvaluationStagePreJudge PermissionApprovalEvaluationEvaluationStageReuse = rpc.PermissionApprovalEvaluationEvaluationStageReuse PermissionApprovalEvaluationEvaluationStageUnknown = rpc.PermissionApprovalEvaluationEvaluationStageUnknown PermissionApprovalEvaluationJudgeStatusCached = rpc.PermissionApprovalEvaluationJudgeStatusCached PermissionApprovalEvaluationJudgeStatusCompleted = rpc.PermissionApprovalEvaluationJudgeStatusCompleted PermissionApprovalEvaluationJudgeStatusFailed = rpc.PermissionApprovalEvaluationJudgeStatusFailed PermissionApprovalEvaluationJudgeStatusInherited = rpc.PermissionApprovalEvaluationJudgeStatusInherited PermissionApprovalEvaluationJudgeStatusNotCalled = rpc.PermissionApprovalEvaluationJudgeStatusNotCalled PermissionApprovalEvaluationJudgeStatusUnknown = rpc.PermissionApprovalEvaluationJudgeStatusUnknown PermissionApprovalEvaluationReasonCodeActionTooLong = rpc.PermissionApprovalEvaluationReasonCodeActionTooLong PermissionApprovalEvaluationReasonCodeArgumentBindingUnreviewable = rpc.PermissionApprovalEvaluationReasonCodeArgumentBindingUnreviewable PermissionApprovalEvaluationReasonCodeAuthorizationHistoryIncomplete = rpc.PermissionApprovalEvaluationReasonCodeAuthorizationHistoryIncomplete PermissionApprovalEvaluationReasonCodeContentExcluded = rpc.PermissionApprovalEvaluationReasonCodeContentExcluded PermissionApprovalEvaluationReasonCodeDynamicSource = rpc.PermissionApprovalEvaluationReasonCodeDynamicSource PermissionApprovalEvaluationReasonCodeExecutableTooLarge = rpc.PermissionApprovalEvaluationReasonCodeExecutableTooLarge PermissionApprovalEvaluationReasonCodeExtensionPermissionAccess = rpc.PermissionApprovalEvaluationReasonCodeExtensionPermissionAccess PermissionApprovalEvaluationReasonCodeInactive = rpc.PermissionApprovalEvaluationReasonCodeInactive PermissionApprovalEvaluationReasonCodeInherited = rpc.PermissionApprovalEvaluationReasonCodeInherited PermissionApprovalEvaluationReasonCodeInterpreterTooLarge = rpc.PermissionApprovalEvaluationReasonCodeInterpreterTooLarge PermissionApprovalEvaluationReasonCodeInterpreterWrappedScript = rpc.PermissionApprovalEvaluationReasonCodeInterpreterWrappedScript PermissionApprovalEvaluationReasonCodeInvalidWorkingDirectory = rpc.PermissionApprovalEvaluationReasonCodeInvalidWorkingDirectory PermissionApprovalEvaluationReasonCodeJudgeError = rpc.PermissionApprovalEvaluationReasonCodeJudgeError PermissionApprovalEvaluationReasonCodeJudgeVerdict = rpc.PermissionApprovalEvaluationReasonCodeJudgeVerdict PermissionApprovalEvaluationReasonCodeMalformedScriptActionManifest = rpc.PermissionApprovalEvaluationReasonCodeMalformedScriptActionManifest PermissionApprovalEvaluationReasonCodeMalformedScriptActionReview = rpc.PermissionApprovalEvaluationReasonCodeMalformedScriptActionReview PermissionApprovalEvaluationReasonCodeManagedApprovalRequired = rpc.PermissionApprovalEvaluationReasonCodeManagedApprovalRequired PermissionApprovalEvaluationReasonCodeNonUtf8 = rpc.PermissionApprovalEvaluationReasonCodeNonUtf8 PermissionApprovalEvaluationReasonCodeNotReached = rpc.PermissionApprovalEvaluationReasonCodeNotReached PermissionApprovalEvaluationReasonCodeNotRegularFile = rpc.PermissionApprovalEvaluationReasonCodeNotRegularFile PermissionApprovalEvaluationReasonCodePathNotAuthorized = rpc.PermissionApprovalEvaluationReasonCodePathNotAuthorized PermissionApprovalEvaluationReasonCodeSandboxBypass = rpc.PermissionApprovalEvaluationReasonCodeSandboxBypass PermissionApprovalEvaluationReasonCodeShellEnvironmentUnreviewable = rpc.PermissionApprovalEvaluationReasonCodeShellEnvironmentUnreviewable PermissionApprovalEvaluationReasonCodeTooLarge = rpc.PermissionApprovalEvaluationReasonCodeTooLarge PermissionApprovalEvaluationReasonCodeTooManySources = rpc.PermissionApprovalEvaluationReasonCodeTooManySources PermissionApprovalEvaluationReasonCodeUnknown = rpc.PermissionApprovalEvaluationReasonCodeUnknown PermissionApprovalEvaluationReasonCodeUnreadable = rpc.PermissionApprovalEvaluationReasonCodeUnreadable PermissionApprovalEvaluationReasonCodeUnrepresentablePath = rpc.PermissionApprovalEvaluationReasonCodeUnrepresentablePath PermissionApprovalEvaluationReasonCodeUnreviewableScriptInvocation = rpc.PermissionApprovalEvaluationReasonCodeUnreviewableScriptInvocation PermissionApprovalEvaluationReasonCodeUnsupportedCommandShape = rpc.PermissionApprovalEvaluationReasonCodeUnsupportedCommandShape PermissionApprovalEvaluationReasonCodeUnsupportedSource = rpc.PermissionApprovalEvaluationReasonCodeUnsupportedSource PermissionDecisionSourceAuthorizationCarryForward = rpc.PermissionDecisionSourceAuthorizationCarryForward PermissionMessageAuthorizationPolarityDenial = rpc.PermissionMessageAuthorizationPolarityDenial PermissionMessageAuthorizationPolarityGrant = rpc.PermissionMessageAuthorizationPolarityGrant PermissionModeAllowAll = rpc.PermissionModeAllowAll PermissionModeAssisted = rpc.PermissionModeAssisted PermissionModeManual = rpc.PermissionModeManual PermissionPromptRequestKindCommands = rpc.PermissionPromptRequestKindCommands PermissionPromptRequestKindCustomTool = rpc.PermissionPromptRequestKindCustomTool PermissionPromptRequestKindExtensionEnvAccess = rpc.PermissionPromptRequestKindExtensionEnvAccess PermissionPromptRequestKindExtensionManagement = rpc.PermissionPromptRequestKindExtensionManagement PermissionPromptRequestKindExtensionPermissionAccess = rpc.PermissionPromptRequestKindExtensionPermissionAccess PermissionPromptRequestKindHook = rpc.PermissionPromptRequestKindHook PermissionPromptRequestKindMCP = rpc.PermissionPromptRequestKindMCP PermissionPromptRequestKindMemory = rpc.PermissionPromptRequestKindMemory PermissionPromptRequestKindPath = rpc.PermissionPromptRequestKindPath PermissionPromptRequestKindRead = rpc.PermissionPromptRequestKindRead PermissionPromptRequestKindURL = rpc.PermissionPromptRequestKindURL PermissionPromptRequestKindWorkflow = rpc.PermissionPromptRequestKindWorkflow PermissionPromptRequestKindWrite = rpc.PermissionPromptRequestKindWrite PermissionPromptRequestPathAccessKindRead = rpc.PermissionPromptRequestPathAccessKindRead PermissionPromptRequestPathAccessKindShell = rpc.PermissionPromptRequestPathAccessKindShell PermissionPromptRequestPathAccessKindWrite = rpc.PermissionPromptRequestPathAccessKindWrite PermissionRecommendationApprove = rpc.PermissionRecommendationApprove PermissionRecoveryAttemptDispositionApproved = rpc.PermissionRecoveryAttemptDispositionApproved PermissionRecoveryAttemptDispositionBlocked = rpc.PermissionRecoveryAttemptDispositionBlocked PermissionRecoveryAttemptDispositionDeferred = rpc.PermissionRecoveryAttemptDispositionDeferred PermissionRecoveryAttemptDispositionDenied = rpc.PermissionRecoveryAttemptDispositionDenied PermissionRecoveryAttemptDispositionPrompted = rpc.PermissionRecoveryAttemptDispositionPrompted PermissionRecoveryAttemptDispositionSucceeded = rpc.PermissionRecoveryAttemptDispositionSucceeded PermissionRecoveryAttemptReasonAttemptsExhausted = rpc.PermissionRecoveryAttemptReasonAttemptsExhausted PermissionRecoveryAttemptReasonEquivalentAlternativeSucceeded = rpc.PermissionRecoveryAttemptReasonEquivalentAlternativeSucceeded PermissionRecoveryAttemptReasonPermissionApproved = rpc.PermissionRecoveryAttemptReasonPermissionApproved PermissionRecoveryAttemptReasonPermissionDenied = rpc.PermissionRecoveryAttemptReasonPermissionDenied PermissionRecoveryAttemptReasonPermissionRequired = rpc.PermissionRecoveryAttemptReasonPermissionRequired PermissionRecoveryAttemptReasonRepeatedAttempt = rpc.PermissionRecoveryAttemptReasonRepeatedAttempt PermissionRecoveryAttemptRelationAlternative = rpc.PermissionRecoveryAttemptRelationAlternative PermissionRecoveryAttemptRelationInitial = rpc.PermissionRecoveryAttemptRelationInitial PermissionRecoveryAttemptRelationRetry = rpc.PermissionRecoveryAttemptRelationRetry PermissionRecoveryOnBlockedAsk = rpc.PermissionRecoveryOnBlockedAsk PermissionRecoveryOnBlockedFail = rpc.PermissionRecoveryOnBlockedFail PermissionRecoveryReasonAttemptsExhausted = rpc.PermissionRecoveryReasonAttemptsExhausted PermissionRecoveryReasonEquivalentAlternativeSucceeded = rpc.PermissionRecoveryReasonEquivalentAlternativeSucceeded PermissionRecoveryReasonPermissionApproved = rpc.PermissionRecoveryReasonPermissionApproved PermissionRecoveryReasonPermissionDenied = rpc.PermissionRecoveryReasonPermissionDenied PermissionRecoveryReasonPermissionRequired = rpc.PermissionRecoveryReasonPermissionRequired PermissionRecoveryReasonRepeatedAttempt = rpc.PermissionRecoveryReasonRepeatedAttempt PermissionRecoveryStatusAwaitingApproval = rpc.PermissionRecoveryStatusAwaitingApproval PermissionRecoveryStatusBlocked = rpc.PermissionRecoveryStatusBlocked PermissionRecoveryStatusRecovering = rpc.PermissionRecoveryStatusRecovering PermissionRecoveryStatusResolved = rpc.PermissionRecoveryStatusResolved PermissionRequestKindCustomTool = rpc.PermissionRequestKindCustomTool PermissionRequestKindExtensionEnvAccess = rpc.PermissionRequestKindExtensionEnvAccess PermissionRequestKindExtensionManagement = rpc.PermissionRequestKindExtensionManagement PermissionRequestKindExtensionPermissionAccess = rpc.PermissionRequestKindExtensionPermissionAccess PermissionRequestKindHook = rpc.PermissionRequestKindHook PermissionRequestKindMCP = rpc.PermissionRequestKindMCP PermissionRequestKindMemory = rpc.PermissionRequestKindMemory PermissionRequestKindRead = rpc.PermissionRequestKindRead PermissionRequestKindShell = rpc.PermissionRequestKindShell PermissionRequestKindURL = rpc.PermissionRequestKindURL PermissionRequestKindWorkflow = rpc.PermissionRequestKindWorkflow PermissionRequestKindWrite = rpc.PermissionRequestKindWrite PermissionRequestMemoryActionStore = rpc.PermissionRequestMemoryActionStore PermissionRequestMemoryActionVote = rpc.PermissionRequestMemoryActionVote PermissionRequestMemoryDirectionDownvote = rpc.PermissionRequestMemoryDirectionDownvote PermissionRequestMemoryDirectionUpvote = rpc.PermissionRequestMemoryDirectionUpvote PermissionRequestMemoryScopeRepository = rpc.PermissionRequestMemoryScopeRepository PermissionRequestMemoryScopeUser = rpc.PermissionRequestMemoryScopeUser PermissionResultKindApproved = rpc.PermissionResultKindApproved PermissionResultKindApprovedForLocation = rpc.PermissionResultKindApprovedForLocation PermissionResultKindApprovedForSession = rpc.PermissionResultKindApprovedForSession PermissionResultKindApprovedReadOnlyForSession = rpc.PermissionResultKindApprovedReadOnlyForSession PermissionResultKindCancelled = rpc.PermissionResultKindCancelled PermissionResultKindDeniedByContentExclusionPolicy = rpc.PermissionResultKindDeniedByContentExclusionPolicy PermissionResultKindDeniedByPermissionRequestHook = rpc.PermissionResultKindDeniedByPermissionRequestHook PermissionResultKindDeniedByRules = rpc.PermissionResultKindDeniedByRules PermissionResultKindDeniedInteractivelyByUser = rpc.PermissionResultKindDeniedInteractivelyByUser PermissionResultKindDeniedNoApprovalRuleAndCouldNotRequestFromUser = rpc.PermissionResultKindDeniedNoApprovalRuleAndCouldNotRequestFromUser PermissionSandboxPathGrantAccessRead = rpc.PermissionSandboxPathGrantAccessRead PermissionSandboxPathGrantAccessReadWrite = rpc.PermissionSandboxPathGrantAccessReadWrite PersistedBinaryImageTypeImage = rpc.PersistedBinaryImageTypeImage PersistedBinaryImageTypeResource = rpc.PersistedBinaryImageTypeResource PersistedBinaryResultTypeImage = rpc.PersistedBinaryResultTypeImage PersistedBinaryResultTypeResource = rpc.PersistedBinaryResultTypeResource PlanChangedOperationCreate = rpc.PlanChangedOperationCreate PlanChangedOperationDelete = rpc.PlanChangedOperationDelete PlanChangedOperationUpdate = rpc.PlanChangedOperationUpdate ProviderMonthlyUsageScopeUnknown = rpc.ProviderMonthlyUsageScopeUnknown ProviderMonthlyUsageScopeUser = rpc.ProviderMonthlyUsageScopeUser ProviderMonthlyUsageStateAvailable = rpc.ProviderMonthlyUsageStateAvailable ProviderMonthlyUsageStateNoPolicy = rpc.ProviderMonthlyUsageStateNoPolicy ProviderMonthlyUsageStateUnknown = rpc.ProviderMonthlyUsageStateUnknown ProviderQuotaAccessStateAllowed = rpc.ProviderQuotaAccessStateAllowed ProviderQuotaAccessStateDenied = rpc.ProviderQuotaAccessStateDenied ProviderQuotaAccessStateNotRequired = rpc.ProviderQuotaAccessStateNotRequired ProviderQuotaAccessStateUnknown = rpc.ProviderQuotaAccessStateUnknown ProviderQuotaAcquisitionStatusFailed = rpc.ProviderQuotaAcquisitionStatusFailed ProviderQuotaAcquisitionStatusSucceeded = rpc.ProviderQuotaAcquisitionStatusSucceeded ProviderQuotaCapacityStateAvailable = rpc.ProviderQuotaCapacityStateAvailable ProviderQuotaCapacityStateExhausted = rpc.ProviderQuotaCapacityStateExhausted ProviderQuotaCapacityStateNotApplicable = rpc.ProviderQuotaCapacityStateNotApplicable ProviderQuotaCapacityStateNotRequired = rpc.ProviderQuotaCapacityStateNotRequired ProviderQuotaCapacityStateUnknown = rpc.ProviderQuotaCapacityStateUnknown ProviderQuotaCapacityStateUnlimited = rpc.ProviderQuotaCapacityStateUnlimited ProviderQuotaObservationKindAccountSnapshot = rpc.ProviderQuotaObservationKindAccountSnapshot ProviderQuotaObservationKindAdmissionState = rpc.ProviderQuotaObservationKindAdmissionState ProviderQuotaQuantityKindAdvisoryBalance = rpc.ProviderQuotaQuantityKindAdvisoryBalance ProviderQuotaQuantityKindAuthoritativeBudget = rpc.ProviderQuotaQuantityKindAuthoritativeBudget ProviderQuotaQuantityKindNone = rpc.ProviderQuotaQuantityKindNone ProviderQuotaUnitAiCredits = rpc.ProviderQuotaUnitAiCredits ProviderQuotaUnitRequests = rpc.ProviderQuotaUnitRequests ProviderQuotaUnitTokens = rpc.ProviderQuotaUnitTokens ProviderQuotaUnitUnknown = rpc.ProviderQuotaUnitUnknown ReasoningSummaryConcise = rpc.ReasoningSummaryConcise ReasoningSummaryDetailed = rpc.ReasoningSummaryDetailed ReasoningSummaryNone = rpc.ReasoningSummaryNone RecommendedAutoTierBalance = rpc.RecommendedAutoTierBalance RecommendedAutoTierEfficiency = rpc.RecommendedAutoTierEfficiency RecommendedAutoTierIntelligence = rpc.RecommendedAutoTierIntelligence RemediationActionAllowSandboxOutbound = rpc.RemediationActionAllowSandboxOutbound RemediationActionReviewSandboxPolicy = rpc.RemediationActionReviewSandboxPolicy RemediationActionRewindConversation = rpc.RemediationActionRewindConversation RemediationActionShowAccount = rpc.RemediationActionShowAccount RemediationActionSignIn = rpc.RemediationActionSignIn RemediationActionSwitchAccount = rpc.RemediationActionSwitchAccount ScheduleOriginModel = rpc.ScheduleOriginModel ScheduleOriginUser = rpc.ScheduleOriginUser SessionEventTypeAbort = rpc.SessionEventTypeAbort SessionEventTypeAgentInterrupted = rpc.SessionEventTypeAgentInterrupted SessionEventTypeAssistantFusionPhaseActivity = rpc.SessionEventTypeAssistantFusionPhaseActivity SessionEventTypeAssistantFusionPhaseCompleted = rpc.SessionEventTypeAssistantFusionPhaseCompleted SessionEventTypeAssistantFusionPhaseFailed = rpc.SessionEventTypeAssistantFusionPhaseFailed SessionEventTypeAssistantFusionPhaseStarted = rpc.SessionEventTypeAssistantFusionPhaseStarted SessionEventTypeAssistantIdle = rpc.SessionEventTypeAssistantIdle SessionEventTypeAssistantIntent = rpc.SessionEventTypeAssistantIntent SessionEventTypeAssistantMessage = rpc.SessionEventTypeAssistantMessage SessionEventTypeAssistantMessageDelta = rpc.SessionEventTypeAssistantMessageDelta SessionEventTypeAssistantMessageStart = rpc.SessionEventTypeAssistantMessageStart SessionEventTypeAssistantReasoning = rpc.SessionEventTypeAssistantReasoning SessionEventTypeAssistantReasoningDelta = rpc.SessionEventTypeAssistantReasoningDelta SessionEventTypeAssistantServerToolProgress = rpc.SessionEventTypeAssistantServerToolProgress SessionEventTypeAssistantStreamingDelta = rpc.SessionEventTypeAssistantStreamingDelta SessionEventTypeAssistantToolCallDelta = rpc.SessionEventTypeAssistantToolCallDelta SessionEventTypeAssistantTurnEnd = rpc.SessionEventTypeAssistantTurnEnd SessionEventTypeAssistantTurnRetry = rpc.SessionEventTypeAssistantTurnRetry SessionEventTypeAssistantTurnStart = rpc.SessionEventTypeAssistantTurnStart SessionEventTypeAssistantUsage = rpc.SessionEventTypeAssistantUsage SessionEventTypeAutoModeSwitchCompleted = rpc.SessionEventTypeAutoModeSwitchCompleted SessionEventTypeAutoModeSwitchRequested = rpc.SessionEventTypeAutoModeSwitchRequested SessionEventTypeCapabilitiesChanged = rpc.SessionEventTypeCapabilitiesChanged SessionEventTypeCommandCompleted = rpc.SessionEventTypeCommandCompleted SessionEventTypeCommandExecute = rpc.SessionEventTypeCommandExecute SessionEventTypeCommandQueued = rpc.SessionEventTypeCommandQueued SessionEventTypeCommandsChanged = rpc.SessionEventTypeCommandsChanged SessionEventTypeElicitationCompleted = rpc.SessionEventTypeElicitationCompleted SessionEventTypeElicitationRequested = rpc.SessionEventTypeElicitationRequested SessionEventTypeExitPlanModeCompleted = rpc.SessionEventTypeExitPlanModeCompleted SessionEventTypeExitPlanModeRequested = rpc.SessionEventTypeExitPlanModeRequested SessionEventTypeExternalToolCompleted = rpc.SessionEventTypeExternalToolCompleted SessionEventTypeExternalToolRequested = rpc.SessionEventTypeExternalToolRequested SessionEventTypeHookEnd = rpc.SessionEventTypeHookEnd SessionEventTypeHookProgress = rpc.SessionEventTypeHookProgress SessionEventTypeHookStart = rpc.SessionEventTypeHookStart SessionEventTypeHumanResponseRecorded = rpc.SessionEventTypeHumanResponseRecorded SessionEventTypeInstructionUpdate = rpc.SessionEventTypeInstructionUpdate SessionEventTypeMCPAppToolCallComplete = rpc.SessionEventTypeMCPAppToolCallComplete SessionEventTypeMCPHeadersRefreshCompleted = rpc.SessionEventTypeMCPHeadersRefreshCompleted SessionEventTypeMCPHeadersRefreshRequired = rpc.SessionEventTypeMCPHeadersRefreshRequired SessionEventTypeMCPOauthCompleted = rpc.SessionEventTypeMCPOauthCompleted SessionEventTypeMCPOauthRecoveryCompleted = rpc.SessionEventTypeMCPOauthRecoveryCompleted SessionEventTypeMCPOauthRequired = rpc.SessionEventTypeMCPOauthRequired SessionEventTypeMCPPromptsListChanged = rpc.SessionEventTypeMCPPromptsListChanged SessionEventTypeMCPResourcesListChanged = rpc.SessionEventTypeMCPResourcesListChanged SessionEventTypeMCPToolsListChanged = rpc.SessionEventTypeMCPToolsListChanged SessionEventTypeModelCallFailure = rpc.SessionEventTypeModelCallFailure SessionEventTypeModelCallFinalResult = rpc.SessionEventTypeModelCallFinalResult SessionEventTypeModelCallFinished = rpc.SessionEventTypeModelCallFinished SessionEventTypeModelCallStart = rpc.SessionEventTypeModelCallStart SessionEventTypePendingMessagesModified = rpc.SessionEventTypePendingMessagesModified SessionEventTypePermissionAssentDetected = rpc.SessionEventTypePermissionAssentDetected SessionEventTypePermissionCarriedForward = rpc.SessionEventTypePermissionCarriedForward SessionEventTypePermissionCompleted = rpc.SessionEventTypePermissionCompleted SessionEventTypePermissionContextualAuthorization = rpc.SessionEventTypePermissionContextualAuthorization SessionEventTypePermissionMessageAuthorization = rpc.SessionEventTypePermissionMessageAuthorization SessionEventTypePermissionMessageAuthorizationDegraded = rpc.SessionEventTypePermissionMessageAuthorizationDegraded SessionEventTypePermissionMessageAuthorizationRead = rpc.SessionEventTypePermissionMessageAuthorizationRead SessionEventTypePermissionRequested = rpc.SessionEventTypePermissionRequested SessionEventTypePromptCacheBreak = rpc.SessionEventTypePromptCacheBreak SessionEventTypeSamplingCompleted = rpc.SessionEventTypeSamplingCompleted SessionEventTypeSamplingRequested = rpc.SessionEventTypeSamplingRequested SessionEventTypeSandboxDecision = rpc.SessionEventTypeSandboxDecision SessionEventTypeSessionAutoModeResolved = rpc.SessionEventTypeSessionAutoModeResolved SessionEventTypeSessionAutopilotObjectiveChanged = rpc.SessionEventTypeSessionAutopilotObjectiveChanged SessionEventTypeSessionAutopilotStopped = rpc.SessionEventTypeSessionAutopilotStopped SessionEventTypeSessionAutoTierRecommendation = rpc.SessionEventTypeSessionAutoTierRecommendation SessionEventTypeSessionAutoTierSwitchFailed = rpc.SessionEventTypeSessionAutoTierSwitchFailed SessionEventTypeSessionBackgroundTasksChanged = rpc.SessionEventTypeSessionBackgroundTasksChanged SessionEventTypeSessionBinaryAsset = rpc.SessionEventTypeSessionBinaryAsset SessionEventTypeSessionCanvasClosed = rpc.SessionEventTypeSessionCanvasClosed SessionEventTypeSessionCanvasOpened = rpc.SessionEventTypeSessionCanvasOpened SessionEventTypeSessionCanvasRecorded = rpc.SessionEventTypeSessionCanvasRecorded SessionEventTypeSessionCanvasRegistryChanged = rpc.SessionEventTypeSessionCanvasRegistryChanged SessionEventTypeSessionCanvasRemoved = rpc.SessionEventTypeSessionCanvasRemoved SessionEventTypeSessionCompactionComplete = rpc.SessionEventTypeSessionCompactionComplete SessionEventTypeSessionCompactionStart = rpc.SessionEventTypeSessionCompactionStart SessionEventTypeSessionCompletionReceipt = rpc.SessionEventTypeSessionCompletionReceipt SessionEventTypeSessionContextChanged = rpc.SessionEventTypeSessionContextChanged SessionEventTypeSessionContextCleared = rpc.SessionEventTypeSessionContextCleared SessionEventTypeSessionCustomAgentsUpdated = rpc.SessionEventTypeSessionCustomAgentsUpdated SessionEventTypeSessionCustomNotification = rpc.SessionEventTypeSessionCustomNotification SessionEventTypeSessionError = rpc.SessionEventTypeSessionError SessionEventTypeSessionExtensionsAttachmentsPushed = rpc.SessionEventTypeSessionExtensionsAttachmentsPushed SessionEventTypeSessionExtensionsLoaded = rpc.SessionEventTypeSessionExtensionsLoaded SessionEventTypeSessionFusionCompleted = rpc.SessionEventTypeSessionFusionCompleted SessionEventTypeSessionFusionResolved = rpc.SessionEventTypeSessionFusionResolved SessionEventTypeSessionFusionRouteFailed = rpc.SessionEventTypeSessionFusionRouteFailed SessionEventTypeSessionFusionRouteStarted = rpc.SessionEventTypeSessionFusionRouteStarted SessionEventTypeSessionHandoff = rpc.SessionEventTypeSessionHandoff SessionEventTypeSessionIdle = rpc.SessionEventTypeSessionIdle SessionEventTypeSessionIndexedSearch = rpc.SessionEventTypeSessionIndexedSearch SessionEventTypeSessionInfo = rpc.SessionEventTypeSessionInfo SessionEventTypeSessionLimitsExhaustedCompleted = rpc.SessionEventTypeSessionLimitsExhaustedCompleted SessionEventTypeSessionLimitsExhaustedRequested = rpc.SessionEventTypeSessionLimitsExhaustedRequested SessionEventTypeSessionManagedPluginProgress = rpc.SessionEventTypeSessionManagedPluginProgress SessionEventTypeSessionManagedSettingsEnforced = rpc.SessionEventTypeSessionManagedSettingsEnforced SessionEventTypeSessionManagedSettingsResolved = rpc.SessionEventTypeSessionManagedSettingsResolved SessionEventTypeSessionMCPServerNeedsReconnect = rpc.SessionEventTypeSessionMCPServerNeedsReconnect SessionEventTypeSessionMCPServerRemoved = rpc.SessionEventTypeSessionMCPServerRemoved SessionEventTypeSessionMCPServersLoaded = rpc.SessionEventTypeSessionMCPServersLoaded SessionEventTypeSessionMCPServerStatusChanged = rpc.SessionEventTypeSessionMCPServerStatusChanged SessionEventTypeSessionMCPServerToolsLoaded = rpc.SessionEventTypeSessionMCPServerToolsLoaded SessionEventTypeSessionModeChanged = rpc.SessionEventTypeSessionModeChanged SessionEventTypeSessionModelChange = rpc.SessionEventTypeSessionModelChange SessionEventTypeSessionModelDeselected = rpc.SessionEventTypeSessionModelDeselected SessionEventTypeSessionModeNoticeDelivered = rpc.SessionEventTypeSessionModeNoticeDelivered SessionEventTypeSessionPermissionRecovery = rpc.SessionEventTypeSessionPermissionRecovery SessionEventTypeSessionPermissionsChanged = rpc.SessionEventTypeSessionPermissionsChanged SessionEventTypeSessionPlanChanged = rpc.SessionEventTypeSessionPlanChanged SessionEventTypeSessionQuotaObservation = rpc.SessionEventTypeSessionQuotaObservation SessionEventTypeSessionRemoteSteerableChanged = rpc.SessionEventTypeSessionRemoteSteerableChanged SessionEventTypeSessionResume = rpc.SessionEventTypeSessionResume SessionEventTypeSessionScheduleCancelled = rpc.SessionEventTypeSessionScheduleCancelled SessionEventTypeSessionScheduleCreated = rpc.SessionEventTypeSessionScheduleCreated SessionEventTypeSessionScheduleRearmed = rpc.SessionEventTypeSessionScheduleRearmed SessionEventTypeSessionSessionLimitsChanged = rpc.SessionEventTypeSessionSessionLimitsChanged SessionEventTypeSessionShutdown = rpc.SessionEventTypeSessionShutdown SessionEventTypeSessionSkillsLoaded = rpc.SessionEventTypeSessionSkillsLoaded SessionEventTypeSessionSnapshotRewind = rpc.SessionEventTypeSessionSnapshotRewind SessionEventTypeSessionStart = rpc.SessionEventTypeSessionStart SessionEventTypeSessionTaskComplete = rpc.SessionEventTypeSessionTaskComplete SessionEventTypeSessionTitleChanged = rpc.SessionEventTypeSessionTitleChanged SessionEventTypeSessionTodosChanged = rpc.SessionEventTypeSessionTodosChanged SessionEventTypeSessionToolsUpdated = rpc.SessionEventTypeSessionToolsUpdated SessionEventTypeSessionTruncation = rpc.SessionEventTypeSessionTruncation SessionEventTypeSessionUsageCheckpoint = rpc.SessionEventTypeSessionUsageCheckpoint SessionEventTypeSessionUsageInfo = rpc.SessionEventTypeSessionUsageInfo SessionEventTypeSessionWarning = rpc.SessionEventTypeSessionWarning SessionEventTypeSessionWorkspaceFileChanged = rpc.SessionEventTypeSessionWorkspaceFileChanged SessionEventTypeSkillContextDelivered = rpc.SessionEventTypeSkillContextDelivered SessionEventTypeSkillContextDeliveredRef = rpc.SessionEventTypeSkillContextDeliveredRef SessionEventTypeSkillInvoked = rpc.SessionEventTypeSkillInvoked SessionEventTypeSkillInvokedRef = rpc.SessionEventTypeSkillInvokedRef SessionEventTypeSubagentCompleted = rpc.SessionEventTypeSubagentCompleted SessionEventTypeSubagentConfigured = rpc.SessionEventTypeSubagentConfigured SessionEventTypeSubagentDeselected = rpc.SessionEventTypeSubagentDeselected SessionEventTypeSubagentFailed = rpc.SessionEventTypeSubagentFailed SessionEventTypeSubagentSelected = rpc.SessionEventTypeSubagentSelected SessionEventTypeSubagentStarted = rpc.SessionEventTypeSubagentStarted SessionEventTypeSystemMessage = rpc.SessionEventTypeSystemMessage SessionEventTypeSystemNotification = rpc.SessionEventTypeSystemNotification SessionEventTypeToolExecutionComplete = rpc.SessionEventTypeToolExecutionComplete // Deprecated: SessionEventTypeToolExecutionPartialResult identifies a deprecated event. SessionEventTypeToolExecutionPartialResult = rpc.SessionEventTypeToolExecutionPartialResult SessionEventTypeToolExecutionProgress = rpc.SessionEventTypeToolExecutionProgress SessionEventTypeToolExecutionStart = rpc.SessionEventTypeToolExecutionStart SessionEventTypeToolSearchActivated = rpc.SessionEventTypeToolSearchActivated SessionEventTypeToolShellOutput = rpc.SessionEventTypeToolShellOutput SessionEventTypeToolUserRequested = rpc.SessionEventTypeToolUserRequested SessionEventTypeUIEphemeralQuery = rpc.SessionEventTypeUIEphemeralQuery SessionEventTypeUserInputCompleted = rpc.SessionEventTypeUserInputCompleted SessionEventTypeUserInputRequested = rpc.SessionEventTypeUserInputRequested SessionEventTypeUserMessage = rpc.SessionEventTypeUserMessage SessionEventTypeWorkflowRunSettled = rpc.SessionEventTypeWorkflowRunSettled SessionEventTypeWorkflowRunStarted = rpc.SessionEventTypeWorkflowRunStarted SessionEventTypeWorkflowRunUpdated = rpc.SessionEventTypeWorkflowRunUpdated SessionLimitsExhaustedResponseActionAdd = rpc.SessionLimitsExhaustedResponseActionAdd SessionLimitsExhaustedResponseActionCancel = rpc.SessionLimitsExhaustedResponseActionCancel SessionLimitsExhaustedResponseActionSet = rpc.SessionLimitsExhaustedResponseActionSet SessionLimitsExhaustedResponseActionUnset = rpc.SessionLimitsExhaustedResponseActionUnset SessionModeAutopilot = rpc.SessionModeAutopilot SessionModeInteractive = rpc.SessionModeInteractive SessionModePlan = rpc.SessionModePlan ShutdownTypeError = rpc.ShutdownTypeError ShutdownTypeRoutine = rpc.ShutdownTypeRoutine SkillInvokedTriggerAgentInvoked = rpc.SkillInvokedTriggerAgentInvoked SkillInvokedTriggerContextLoad = rpc.SkillInvokedTriggerContextLoad SkillInvokedTriggerUserInvoked = rpc.SkillInvokedTriggerUserInvoked SkillSourceBuiltin = rpc.SkillSourceBuiltin SkillSourceCustom = rpc.SkillSourceCustom SkillSourceInherited = rpc.SkillSourceInherited SkillSourcePersonalAgents = rpc.SkillSourcePersonalAgents SkillSourcePersonalCopilot = rpc.SkillSourcePersonalCopilot SkillSourcePlugin = rpc.SkillSourcePlugin SkillSourceProject = rpc.SkillSourceProject SkillSourceSDK = rpc.SkillSourceSDK SubagentModelSelectionSourceAgentDefinitionDefault = rpc.SubagentModelSelectionSourceAgentDefinitionDefault SubagentModelSelectionSourceComplementaryDefault = rpc.SubagentModelSelectionSourceComplementaryDefault SubagentModelSelectionSourceConfiguredPreference = rpc.SubagentModelSelectionSourceConfiguredPreference SubagentModelSelectionSourceConfiguredRequired = rpc.SubagentModelSelectionSourceConfiguredRequired SubagentModelSelectionSourceExplicitOverride = rpc.SubagentModelSelectionSourceExplicitOverride SubagentModelSelectionSourceRuntimePolicy = rpc.SubagentModelSelectionSourceRuntimePolicy SubagentModelSelectionSourceSessionInheritance = rpc.SubagentModelSelectionSourceSessionInheritance SubagentTaskModelSourceCustomAgentDefinition = rpc.SubagentTaskModelSourceCustomAgentDefinition SubagentTaskModelSourceSubagentConfiguration = rpc.SubagentTaskModelSourceSubagentConfiguration SubagentTaskModelSourceTaskArgument = rpc.SubagentTaskModelSourceTaskArgument SubagentTaskModelSourceUnset = rpc.SubagentTaskModelSourceUnset SystemMessageRoleDeveloper = rpc.SystemMessageRoleDeveloper SystemMessageRoleSystem = rpc.SystemMessageRoleSystem SystemNotificationAgentCompletedStatusCompleted = rpc.SystemNotificationAgentCompletedStatusCompleted SystemNotificationAgentCompletedStatusFailed = rpc.SystemNotificationAgentCompletedStatusFailed SystemNotificationTypeAgentCompleted = rpc.SystemNotificationTypeAgentCompleted SystemNotificationTypeAgentIdle = rpc.SystemNotificationTypeAgentIdle SystemNotificationTypeInstructionDiscovered = rpc.SystemNotificationTypeInstructionDiscovered SystemNotificationTypeNewInboxMessage = rpc.SystemNotificationTypeNewInboxMessage SystemNotificationTypeShellCompleted = rpc.SystemNotificationTypeShellCompleted SystemNotificationTypeShellDetachedCompleted = rpc.SystemNotificationTypeShellDetachedCompleted SystemNotificationTypeUnclassified = rpc.SystemNotificationTypeUnclassified SystemNotificationTypeWorkflowCompleted = rpc.SystemNotificationTypeWorkflowCompleted SystemNotificationWorkflowCompletedStatusCancelled = rpc.SystemNotificationWorkflowCompletedStatusCancelled SystemNotificationWorkflowCompletedStatusCompleted = rpc.SystemNotificationWorkflowCompletedStatusCompleted SystemNotificationWorkflowCompletedStatusError = rpc.SystemNotificationWorkflowCompletedStatusError SystemNotificationWorkflowCompletedStatusHalted = rpc.SystemNotificationWorkflowCompletedStatusHalted SystemNotificationWorkflowCompletedStatusPaused = rpc.SystemNotificationWorkflowCompletedStatusPaused SystemNotificationWorkflowPauseInfoTypeCheckpoint = rpc.SystemNotificationWorkflowPauseInfoTypeCheckpoint SystemNotificationWorkflowPauseInfoTypeUser = rpc.SystemNotificationWorkflowPauseInfoTypeUser TaskBlockerKindPermissionRecovery = rpc.TaskBlockerKindPermissionRecovery TaskCompletionOutcomeBlocked = rpc.TaskCompletionOutcomeBlocked TaskCompletionOutcomeCompleted = rpc.TaskCompletionOutcomeCompleted TaskCompletionOutcomeContinue = rpc.TaskCompletionOutcomeContinue ToolExecutionCompleteContentResourceLinkIconThemeDark = rpc.ToolExecutionCompleteContentResourceLinkIconThemeDark ToolExecutionCompleteContentResourceLinkIconThemeLight = rpc.ToolExecutionCompleteContentResourceLinkIconThemeLight ToolExecutionCompleteContentTypeAudio = rpc.ToolExecutionCompleteContentTypeAudio ToolExecutionCompleteContentTypeImage = rpc.ToolExecutionCompleteContentTypeImage ToolExecutionCompleteContentTypeResource = rpc.ToolExecutionCompleteContentTypeResource ToolExecutionCompleteContentTypeResourceLink = rpc.ToolExecutionCompleteContentTypeResourceLink ToolExecutionCompleteContentTypeShellExit = rpc.ToolExecutionCompleteContentTypeShellExit ToolExecutionCompleteContentTypeTerminal = rpc.ToolExecutionCompleteContentTypeTerminal ToolExecutionCompleteContentTypeText = rpc.ToolExecutionCompleteContentTypeText ToolExecutionCompleteFileEditKindCreate = rpc.ToolExecutionCompleteFileEditKindCreate ToolExecutionCompleteFileEditKindDelete = rpc.ToolExecutionCompleteFileEditKindDelete ToolExecutionCompleteFileEditKindEdit = rpc.ToolExecutionCompleteFileEditKindEdit ToolExecutionCompleteToolDescriptionMetaUIVisibilityApp = rpc.ToolExecutionCompleteToolDescriptionMetaUIVisibilityApp ToolExecutionCompleteToolDescriptionMetaUIVisibilityModel = rpc.ToolExecutionCompleteToolDescriptionMetaUIVisibilityModel ToolExecutionStartToolDescriptionMetaUIVisibilityApp = rpc.ToolExecutionStartToolDescriptionMetaUIVisibilityApp ToolExecutionStartToolDescriptionMetaUIVisibilityModel = rpc.ToolExecutionStartToolDescriptionMetaUIVisibilityModel ToolShellOutputStreamStderr = rpc.ToolShellOutputStreamStderr ToolShellOutputStreamStdout = rpc.ToolShellOutputStreamStdout ToolShellOutputStreamTerminal = rpc.ToolShellOutputStreamTerminal UIEphemeralQueryPhaseAborted = rpc.UIEphemeralQueryPhaseAborted UIEphemeralQueryPhaseChunk = rpc.UIEphemeralQueryPhaseChunk UIEphemeralQueryPhaseCompleted = rpc.UIEphemeralQueryPhaseCompleted UIEphemeralQueryPhaseFailed = rpc.UIEphemeralQueryPhaseFailed UIEphemeralQueryPhaseStarted = rpc.UIEphemeralQueryPhaseStarted UserMessageAgentModeAutopilot = rpc.UserMessageAgentModeAutopilot UserMessageAgentModeInteractive = rpc.UserMessageAgentModeInteractive UserMessageAgentModePlan = rpc.UserMessageAgentModePlan UserMessageAgentModeShell = rpc.UserMessageAgentModeShell UserMessageDeliveryIdle = rpc.UserMessageDeliveryIdle UserMessageDeliveryQueued = rpc.UserMessageDeliveryQueued UserMessageDeliverySteering = rpc.UserMessageDeliverySteering UserToolSessionApprovalKindCommands = rpc.UserToolSessionApprovalKindCommands UserToolSessionApprovalKindCustomTool = rpc.UserToolSessionApprovalKindCustomTool UserToolSessionApprovalKindExtensionEnvAccess = rpc.UserToolSessionApprovalKindExtensionEnvAccess UserToolSessionApprovalKindExtensionManagement = rpc.UserToolSessionApprovalKindExtensionManagement UserToolSessionApprovalKindExtensionPermissionAccess = rpc.UserToolSessionApprovalKindExtensionPermissionAccess UserToolSessionApprovalKindMCP = rpc.UserToolSessionApprovalKindMCP UserToolSessionApprovalKindMemory = rpc.UserToolSessionApprovalKindMemory UserToolSessionApprovalKindRead = rpc.UserToolSessionApprovalKindRead UserToolSessionApprovalKindWorkflow = rpc.UserToolSessionApprovalKindWorkflow UserToolSessionApprovalKindWrite = rpc.UserToolSessionApprovalKindWrite VerbosityHigh = rpc.VerbosityHigh VerbosityLow = rpc.VerbosityLow VerbosityMedium = rpc.VerbosityMedium WorkflowPermissionOperationAuthor = rpc.WorkflowPermissionOperationAuthor WorkflowPermissionOperationRun = rpc.WorkflowPermissionOperationRun WorkflowRunSettledStatusCancelled = rpc.WorkflowRunSettledStatusCancelled WorkflowRunSettledStatusCompleted = rpc.WorkflowRunSettledStatusCompleted WorkflowRunSettledStatusError = rpc.WorkflowRunSettledStatusError WorkflowRunSettledStatusHalted = rpc.WorkflowRunSettledStatusHalted WorkflowRunSettledStatusPaused = rpc.WorkflowRunSettledStatusPaused WorkingDirectoryContextHostTypeADO = rpc.WorkingDirectoryContextHostTypeADO WorkingDirectoryContextHostTypeGitHub = rpc.WorkingDirectoryContextHostTypeGitHub WorkspaceFileChangedOperationCreate = rpc.WorkspaceFileChangedOperationCreate WorkspaceFileChangedOperationUpdate = rpc.WorkspaceFileChangedOperationUpdate )
Session-event constants are generated in the rpc package and re-exported here for source compatibility.
const SDKProtocolVersion = 3
SDKProtocolVersion is the SDK protocol version. This must match the version expected by the copilot-agent-runtime server.
var BuiltInToolsIsolated = []string{
"ask_user",
"task_complete",
"exit_plan_mode",
"task",
"read_agent",
"write_agent",
"list_agents",
"send_inbox",
"context_board",
"skill",
}
BuiltInToolsIsolated lists built-in tools that operate only within the bounds of a single session — no host filesystem access outside the session, no cross-session state, no host environment access, no network. Safe to enable in ModeEmpty scenarios (e.g. multi-tenant servers) without leaking host capabilities.
Contract: tools in this set MUST NOT be extended (even behind options or args) to read or write state outside the session boundary. Adding cross-session or host-state behavior to one of these tools is a breaking change that requires removing it from this set.
var ErrSkillNotFound = errors.New("skill not found")
ErrSkillNotFound is returned by SkillProvider.ReadSkill when a listed skill is no longer available. It can be wrapped; the SDK checks it with errors.Is.
var PermissionHandler = struct { // ApproveAll approves permission requests when managed settings are disabled. ApproveAll PermissionHandlerFunc }{ ApproveAll: func(request PermissionRequest, invocation PermissionInvocation) (rpc.PermissionDecision, error) { if invocation.ManagedSettingsEnabled { return nil, errors.New("approveAll cannot be used when managed settings are enabled") } if request.RequiresManagedApproval() { return &rpc.PermissionDecisionNoResult{}, nil } return &rpc.PermissionDecisionApproveOnce{}, nil }, }
PermissionHandler provides pre-built OnPermissionRequest implementations.
Bool returns a pointer to the given bool value. Use for option fields such as AutoStart, AutoRestart, or LogOptions.Ephemeral:
AutoStart: Bool(false) Ephemeral: Bool(true)
Float64 returns a pointer to the given float64 value. Use for setting thresholds: BackgroundCompactionThreshold: Float64(0.80)
func GetSDKProtocolVersion() int
GetSDKProtocolVersion returns the SDK protocol version.
Int returns a pointer to the given int value. Use for setting optional int parameters: MinLength: Int(1)
SendAndWait infers a JSON Schema for T using the same generator as DefineTool, sends a message, and unmarshals its final correlated root response at session idle. Go does not support generic methods, so this is a package-level function. Options must not specify ResponseSchema or immediate delivery. Streaming events remain text. Cancellation stops waiting, not the agent; errors are session-scoped. Provider schema restrictions apply. Unmarshaling is not full JSON Schema validation.
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AbortReason = rpc.AbortReason
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AgentInterruptedActivity = rpc.AgentInterruptedActivity
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AgentInterruptedCancelPhase = rpc.AgentInterruptedCancelPhase
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AgentInterruptedData = rpc.AgentInterruptedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AgentMode = rpc.SendAgentMode
AgentMode is the UI mode the agent is in for a given turn. See MessageOptions.AgentMode.
type AgentModelPolicy = rpc.AgentModelPolicy
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AgentStopHandler func(input AgentStopHookInput, invocation HookInvocation) (*AgentStopHookOutput, error)
AgentStopHandler handles agent-stop hook invocations.
type AgentStopHookInput struct {
AgentID string `json:"agentId,omitempty"`
AgentType string `json:"agentType,omitempty"`
ParentAgentID string `json:"parentAgentId,omitempty"`
SessionID string `json:"sessionId"`
Timestamp time.Time `json:"-"`
WorkingDirectory string `json:"cwd"`
StopReason string `json:"stopReason,omitempty"`
TranscriptPath string `json:"transcriptPath,omitempty"`
StopHookActive bool `json:"stop_hook_active,omitempty"`
}
AgentStopHookInput is the input for an agent-stop hook.
func (h AgentStopHookInput) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (h *AgentStopHookInput) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
type AgentStopHookOutput struct {
Decision string `json:"decision,omitempty"`
Reason string `json:"reason,omitempty"`
}
AgentStopHookOutput is the output for an agent-stop hook.
type AhpAuthenticationResult = rpc.HostAuthenticationResult
AhpAuthenticationResult accepts a custom credential for the exact configured identity until the required future RFC3339 ExpiresAt. A nil result rejects it. Experimental: AHP hosting may change or be removed.
type AhpHost struct {
HostID string
// URL is absent when no local listener was requested.
URL *string
Token *string
// EnvironmentID identifies the optional Mission Control registration.
EnvironmentID *string
// PID is absent for in-process listeners, not the owning runtime's PID.
PID *int64
// contains filtered or unexported fields
}
AhpHost is an experimental listener owned by one SDK connection. Reconnecting the client does not transfer this handle to its new connection. Experimental: AHP hosting may change or be removed.
Dispose stops the listener and joins runtime cleanup without deleting application sessions. Every call reaches the runtime, including repeated or concurrent calls.
ListSessions returns all live and dormant catalog sessions advertised by this host.
func (h *AhpHost) PublishSession(ctx context.Context, sessionID string) (*rpc.HostPublishSessionResult, error)
PublishSession durably advertises the exact attached session in the compute-scoped catalog. It does not invoke factories or transfer ownership.
SetAllowCreatingNewSessions changes subsequent remote admissions without disconnecting clients. Already-admitted creation may finish.
func (h *AhpHost) UnpublishSession(ctx context.Context, sessionID string) (*rpc.HostUnpublishSessionResult, error)
UnpublishSession withdraws a live or dormant application publication and revokes AHP attachments. It preserves local history, worktrees and ongoing work, returns false when absent, and rejects nonapplication publications without stopping the host.
type AhpHostAuthentication struct {
Mode AhpHostAuthenticationMode
RequireIdentity string
Authenticate func(context.Context, string) (*AhpAuthenticationResult, error)
}
AhpHostAuthentication explicitly selects github, custom, or none admission. Custom requires a stable nonempty RequireIdentity and Authenticate callback. The callback receives a decrypted admission token, never an inference credential; its context is cancelled when validation ends. Callbacks are captured at startup. Experimental: AHP hosting may change or be removed.
type AhpHostAuthenticationMode = rpc.HostAuthenticationMode
type AhpHostExit = rpc.HostExitedNotification
AhpHostExit reports termination of a connection-owned listener. Experimental: AHP hosting may change or be removed.
type AhpHostOptions struct {
// Authentication is required in every client mode, even for anonymous access.
Authentication AhpHostAuthentication
// ComputeID selects a durable catalog identity; defaults are runtime-owned.
// It must agree with GitHubEnvironment.ComputeID when both are supplied.
ComputeID *string
// Workspace is an absolute directory on the runtime host to serve through AHP.
// Nil uses the runtime's configured working directory; process and session working directories are unchanged.
Workspace *string
// LocalServer explicitly enables the local WebSocket listener.
LocalServer *rpc.HostLocalServerOptions
// GitHubEnvironment registers the host with Mission Control; Name, ComputeID,
// and github authentication are required.
GitHubEnvironment *rpc.HostGitHubEnvironmentOptions
// AllowCreatingNewSessions controls remote admissions. Nil selects the denied default.
AllowCreatingNewSessions *bool
CreateSession func(context.Context, AhpSessionCreateRequest) (*Session, error)
ResumeSession func(context.Context, AhpSessionResumeRequest) (*Session, error)
OnSessionReleased func(*Session) error
OnExit func(AhpHostExit) error
}
AhpHostOptions configures an experimental, in-process AHP listener. Factory contexts are cancelled when participation ends. A late returned session is still released exactly once; the SDK never disconnects or destroys it. Notification callbacks run asynchronously, with errors reported to the Go logger. At least one transport must be supplied. Both may be enabled. Experimental: AHP hosting may change or be removed.
type AhpSessionAuthentication = rpc.HostSessionAuthentication
AhpSessionAuthentication is the host-verified admission context, not an inference credential. Experimental: AHP hosting may change or be removed.
type AhpSessionAuthenticationCustom = rpc.HostSessionAuthenticationCustom
type AhpSessionAuthenticationGitHub = rpc.HostSessionAuthenticationGitHub
type AhpSessionAuthenticationNone = rpc.HostSessionAuthenticationNone
type AhpSessionCreateRequest struct {
Authentication AhpSessionAuthentication
Config *SessionConfig
}
AhpSessionCreateRequest contains the settings selected by the AHP host. Preserve Config when creating the session; add application prompts, tools and callbacks. Experimental: AHP hosting may change or be removed.
type AhpSessionResumeRequest struct {
Authentication AhpSessionAuthentication
SessionID string
Config *ResumeSessionConfig
}
AhpSessionResumeRequest identifies a durable application session to resume. Preserve Config, or return the exact retained original from the owning client. Experimental: AHP hosting may change or be removed.
type AiCreditsStatus = rpc.AiCreditsStatus
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AskUserVariant string
AskUserVariant selects the model-facing shape of the ask_user tool.
const ( // AskUserVariantLegacy uses the legacy user-input request implementation. AskUserVariantLegacy AskUserVariant = "legacy" // AskUserVariantElicitation uses the elicitation-based implementation. AskUserVariantElicitation AskUserVariant = "elicitation" )
type AssistantFusionPhaseActivityData = rpc.AssistantFusionPhaseActivityData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantFusionPhaseCompletedData = rpc.AssistantFusionPhaseCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantFusionPhaseFailedData = rpc.AssistantFusionPhaseFailedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantFusionPhaseStartedData = rpc.AssistantFusionPhaseStartedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantIdleData = rpc.AssistantIdleData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantIntentData = rpc.AssistantIntentData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantMessageData = rpc.AssistantMessageData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantMessageDeltaData = rpc.AssistantMessageDeltaData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantMessageReasoningBlocks = rpc.AssistantMessageReasoningBlocks
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantMessageServerTools = rpc.AssistantMessageServerTools
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantMessageStartData = rpc.AssistantMessageStartData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantMessageToolRequest = rpc.AssistantMessageToolRequest
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantMessageToolRequestCaller = rpc.AssistantMessageToolRequestCaller
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantMessageToolRequestCallerType = rpc.AssistantMessageToolRequestCallerType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantMessageToolRequestType = rpc.AssistantMessageToolRequestType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantReasoningData = rpc.AssistantReasoningData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantReasoningDeltaData = rpc.AssistantReasoningDeltaData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantServerToolProgressData = rpc.AssistantServerToolProgressData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantStreamingDeltaData = rpc.AssistantStreamingDeltaData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantToolCallDeltaData = rpc.AssistantToolCallDeltaData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantTurnEndData = rpc.AssistantTurnEndData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantTurnRetryData = rpc.AssistantTurnRetryData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantTurnStartData = rpc.AssistantTurnStartData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantUsageAPIEndpoint = rpc.AssistantUsageAPIEndpoint
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantUsageCopilotUsage = rpc.AssistantUsageCopilotUsage
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantUsageCopilotUsageTokenDetail = rpc.AssistantUsageCopilotUsageTokenDetail
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantUsageData = rpc.AssistantUsageData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistantUsageTransport = rpc.AssistantUsageTransport
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistedApprovalJudgeFailureReason = rpc.AssistedApprovalJudgeFailureReason
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AssistedApprovalRecommendation = rpc.AssistedApprovalRecommendation
Session-event types are generated in the rpc package and aliased here for source compatibility.
type Attachment = rpc.Attachment
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentBlob = rpc.AttachmentBlob
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentDirectory = rpc.AttachmentDirectory
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentExtensionContext = rpc.AttachmentExtensionContext
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentFile = rpc.AttachmentFile
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentFileLineRange = rpc.AttachmentFileLineRange
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentGitHubActionsJob = rpc.AttachmentGitHubActionsJob
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentGitHubCommit = rpc.AttachmentGitHubCommit
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentGitHubFile = rpc.AttachmentGitHubFile
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentGitHubFileDiff = rpc.AttachmentGitHubFileDiff
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentGitHubFileDiffSide = rpc.AttachmentGitHubFileDiffSide
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentGitHubReference = rpc.AttachmentGitHubReference
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentGitHubReferenceType = rpc.AttachmentGitHubReferenceType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentGitHubRelease = rpc.AttachmentGitHubRelease
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentGitHubRepository = rpc.AttachmentGitHubRepository
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentGitHubSnippet = rpc.AttachmentGitHubSnippet
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentGitHubTreeComparison = rpc.AttachmentGitHubTreeComparison
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentGitHubTreeComparisonSide = rpc.AttachmentGitHubTreeComparisonSide
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentGitHubURL = rpc.AttachmentGitHubURL
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentSelection = rpc.AttachmentSelection
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentSelectionDetails = rpc.AttachmentSelectionDetails
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentSelectionDetailsEnd = rpc.AttachmentSelectionDetailsEnd
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentSelectionDetailsStart = rpc.AttachmentSelectionDetailsStart
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttachmentType = rpc.AttachmentType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AttributedPermissionResult struct {
rpc.PermissionDecision
// DecisionContext describes how and where the decision was reached. When nil
// the SDK omits it from the wire, preserving legacy behavior.
DecisionContext *rpc.PermissionDecisionContext
}
AttributedPermissionResult pairs a permission decision with the context describing how it was reached, so the runtime can attribute auto-approval telemetry to the responding surface.
The embedded rpc.PermissionDecision carries the actual decision, while DecisionContext is informational only and never changes permission behavior. It satisfies rpc.PermissionDecision itself, so a PermissionHandlerFunc can return it wherever a plain decision is expected. Prefer constructing it through NewAttributedPermissionResult rather than by hand.
Experimental: AttributedPermissionResult is part of an experimental API and may change or be removed.
func NewAttributedPermissionResult(result rpc.PermissionDecision, decisionContext *rpc.PermissionDecisionContext) *AttributedPermissionResult
NewAttributedPermissionResult pairs a permission decision with the context describing how it was reached, so the runtime can attribute auto-approval telemetry to the responding surface.
The returned value satisfies rpc.PermissionDecision, so a PermissionHandlerFunc can return it directly. Passing an already-attributed result replaces the previous context rather than nesting it. If result is a rpc.PermissionDecisionNoResult (attributed or not), the SDK still suppresses the response.
Experimental: NewAttributedPermissionResult is part of an experimental API and may change or be removed.
type AutoModeResolvedReasoningBucket = rpc.AutoModeResolvedReasoningBucket
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AutoModeSwitchCompletedData = rpc.AutoModeSwitchCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AutoModeSwitchInvocation struct {
SessionID string
}
AutoModeSwitchInvocation provides context about an auto-mode-switch request.
type AutoModeSwitchRequest struct {
ErrorCode *string `json:"errorCode,omitempty"`
RetryAfterSeconds *float64 `json:"retryAfterSeconds,omitempty"`
}
AutoModeSwitchRequest represents a request to switch to auto mode after an eligible rate limit.
type AutoModeSwitchRequestHandler func(request AutoModeSwitchRequest, invocation AutoModeSwitchInvocation) (AutoModeSwitchResponse, error)
AutoModeSwitchRequestHandler handles auto-mode-switch requests from the agent.
type AutoModeSwitchRequestedData = rpc.AutoModeSwitchRequestedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AutoModeSwitchResponse = rpc.AutoModeSwitchResponse
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AutoTierSwitchFailureReason = rpc.AutoTierSwitchFailureReason
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AutopilotObjectiveChangedOperation = rpc.AutopilotObjectiveChangedOperation
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AutopilotObjectiveChangedStatus = rpc.AutopilotObjectiveChangedStatus
Session-event types are generated in the rpc package and aliased here for source compatibility.
type AzureProviderOptions struct {
// APIVersion is the Azure API version. When empty, the runtime uses the GA
// versionless v1 route.
APIVersion string `json:"apiVersion,omitempty"`
}
AzureProviderOptions contains Azure-specific provider configuration
type BearerTokenProvider func(args ProviderTokenArgs) (string, error)
BearerTokenProvider is a per-provider callback that resolves a bearer token on demand, returning the raw token string (without the "Bearer " prefix). The Copilot SDK itself takes no Azure dependency: the consumer supplies this callback backed by their own identity library (for example azidentity's DefaultAzureCredential.GetToken), and the runtime calls it once before each outbound model request. The runtime does no caching of its own, so the callback (or the identity library it wraps) owns token caching and refresh.
Experimental: BearerTokenProvider is part of the experimental managed-identity / bearer-token-provider surface and may change or be removed in future SDK or CLI releases.
type BinaryAssetReference = rpc.BinaryAssetReference
Session-event types are generated in the rpc package and aliased here for source compatibility.
type BinaryAssetReferenceType = rpc.BinaryAssetReferenceType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type BinaryAssetType = rpc.BinaryAssetType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CanvasDeclaration struct {
// ID is the canvas identifier, unique within the declaring connection.
ID string `json:"id"`
// DisplayName is the human-readable name shown in host UI and canvas pickers.
DisplayName string `json:"displayName"`
// Description is a short, single-sentence description shown to the agent in canvas catalogs.
Description string `json:"description"`
// InputSchema is the JSON Schema for the `input` payload accepted by `canvas.open`.
InputSchema map[string]any `json:"inputSchema,omitzero"`
// Actions are the agent-callable actions this canvas exposes.
Actions []rpc.CanvasAction `json:"actions,omitempty"`
}
CanvasDeclaration is the declarative metadata for a single canvas, sent over the wire on `session.create` / `session.resume`.
Experimental: CanvasDeclaration is part of an experimental wire-protocol surface and may change or be removed in future SDK or CLI releases.
type CanvasError struct {
// Code is the machine-readable error code.
Code string `json:"code"`
// Message is the human-readable message.
Message string `json:"message"`
}
CanvasError is a structured error returned from canvas handlers.
Wire envelope:
{ "code": "<code>", "message": "<message>" }
Experimental: CanvasError is part of an experimental wire-protocol surface and may change or be removed in future SDK or CLI releases.
func CanvasErrorNoHandler() *CanvasError
CanvasErrorNoHandler is the default error returned when a custom action has no handler.
func NewCanvasError(code, message string) *CanvasError
NewCanvasError constructs a new error envelope with the given code and message.
func (e *CanvasError) Error() string
Error implements the error interface.
type CanvasHandler interface {
OnOpen(ctx context.Context, c rpc.CanvasProviderOpenRequest) (rpc.CanvasProviderOpenResult, error)
OnClose(ctx context.Context, c rpc.CanvasProviderCloseRequest) error
// OnAction handles a non-lifecycle action declared by the canvas. The
// returned value is sent to the model as the invoke_canvas_action tool
// result. To return text and images, as tool handlers do, return a
// ToolResult with BinaryResultsForLLM; any other value is rendered to the
// model as JSON text.
OnAction(ctx context.Context, c rpc.CanvasProviderInvokeActionRequest) (any, error)
}
CanvasHandler is the provider-side canvas lifecycle handler.
A session installs a single CanvasHandler (via SessionConfig.CanvasHandler). The handler receives every inbound `canvas.open` / `canvas.close` / `canvas.action.invoke` JSON-RPC request the runtime issues for this session and decides — typically by inspecting CanvasProviderOpenRequest.CanvasID — which application-side canvas should handle the call.
The SDK does not maintain a per-canvas registry; multiplexing across declared canvases is the implementor's responsibility.
Embed CanvasHandlerDefaults to inherit no-op defaults for OnClose and a "no handler" error for OnAction.
Experimental: CanvasHandler is part of an experimental wire-protocol surface and may change or be removed in future SDK or CLI releases.
type CanvasHandlerDefaults struct{}
CanvasHandlerDefaults supplies default OnClose / OnAction implementations that consumers can inherit by embedding it in their CanvasHandler.
Example:
type myHandler struct {
copilot.CanvasHandlerDefaults
}
func (h *myHandler) OnOpen(ctx context.Context, c rpc.CanvasProviderOpenRequest) (rpc.CanvasProviderOpenResult, error) { ... }
Experimental: CanvasHandlerDefaults is part of an experimental wire-protocol surface and may change or be removed in future SDK or CLI releases.
func (CanvasHandlerDefaults) OnAction(ctx context.Context, c rpc.CanvasProviderInvokeActionRequest) (any, error)
OnAction returns CanvasErrorNoHandler() by default.
func (CanvasHandlerDefaults) OnClose(ctx context.Context, c rpc.CanvasProviderCloseRequest) error
OnClose returns nil by default.
type CanvasProviderIdentity struct {
// ID is an opaque, stable provider id used verbatim as the canvas
// extension id.
ID string `json:"id"`
// Name is an optional display name surfaced as the canvas extension name.
Name *string `json:"name,omitempty"`
}
CanvasProviderIdentity is the stable identity for a host/SDK connection that supplies built-in canvases.
When set on session create or resume, the runtime uses ID verbatim as the agent-facing canvas extension id, so host-provided canvases survive reconnect and CLI restart.
Experimental: CanvasProviderIdentity is part of an experimental wire-protocol surface and may change or be removed in future SDK or CLI releases.
type CanvasRegistryChangedCanvas = rpc.CanvasRegistryChangedCanvas
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CanvasRegistryChangedCanvasAction = rpc.CanvasRegistryChangedCanvasAction
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CapabilitiesChangedData = rpc.CapabilitiesChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CapabilitiesChangedUI = rpc.CapabilitiesChangedUI
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CapiSessionOptions struct {
// EnableWebSocketResponses controls whether the CAPI Responses API uses
// WebSocket transport. Enabled by default when the model advertises
// ws:/responses support; set to Bool(false) to force HTTP Responses transport.
EnableWebSocketResponses *bool `json:"enableWebSocketResponses,omitempty"`
// AutoTier selects the routing tier for model "auto" with V2 Auto.
// Requires a runtime that supports Auto tiers; it has no effect outside V2 Auto.
// When unset, the runtime uses its default on create and restores the last
// committed tier on cold resume. On resident resume, a different tier
// requests a safe switch that takes effect after resume succeeds and never
// disturbs a turn that is already running.
//
// To change the preference on a live session, use [Session.SetAutoTier].
AutoTier AutoTier `json:"autoTier,omitempty"`
}
CapiSessionOptions configures provider-scoped Copilot API (CAPI) session behavior.
WebSocket transport is the default for the CAPI Responses API whenever the model advertises the ws:/responses endpoint. Set EnableWebSocketResponses to Bool(false) to force the HTTP Responses transport, which is useful behind proxies where WebSockets fail. This is equivalent to setting the COPILOT_CLI_DISABLE_WEBSOCKET_RESPONSES environment variable. These options are provider-scoped under the capi namespace because a single session can host multiple providers, such as CAPI and BYOK, so transport choice is provider-level.
type CitableSource = rpc.CitableSource
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CitationLocation = rpc.CitationLocation
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CitationLocationBlock = rpc.CitationLocationBlock
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CitationLocationChar = rpc.CitationLocationChar
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CitationLocationPage = rpc.CitationLocationPage
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CitationLocationType = rpc.CitationLocationType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CitationProvider = rpc.CitationProvider
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CitationReference = rpc.CitationReference
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CitationSource = rpc.CitationSource
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CitationSpan = rpc.CitationSpan
Session-event types are generated in the rpc package and aliased here for source compatibility.
Session-event types are generated in the rpc package and aliased here for source compatibility.
type Client struct {
// RPC provides typed server-scoped RPC methods.
// This field is nil until the client is connected via Start().
RPC *rpc.ServerRPC
// contains filtered or unexported fields
}
Client manages the connection to the Copilot CLI server and provides session management.
The Client can either spawn a CLI server process or connect to an existing server. It handles JSON-RPC communication, session lifecycle, tool execution, and permission requests.
Example:
// Create a client with default options (spawns CLI server using stdio)
client := copilot.NewClient(nil)
// Or connect to an existing server
client := copilot.NewClient(&copilot.ClientOptions{
Connection: copilot.URIConnection{URL: "localhost:3000"},
})
if err := client.Start(); err != nil {
log.Fatal(err)
}
defer client.Stop()
func NewClient(options *ClientOptions) *Client
NewClient creates a new Copilot runtime client with the given options.
If options is nil, default options are used (spawns the bundled runtime over stdio). The client is not connected after creation; call Client.Start to connect, or simply call Client.CreateSession/Client.ResumeSession, which auto-start the runtime on first use.
Example:
// Default options: bundled runtime over stdio
client := copilot.NewClient(nil)
// Custom CLI path over stdio
client := copilot.NewClient(&copilot.ClientOptions{
Connection: copilot.StdioConnection{Path: "/usr/local/bin/copilot"},
LogLevel: "debug",
})
// Connect to an already-running runtime
client := copilot.NewClient(&copilot.ClientOptions{
Connection: copilot.URIConnection{URL: "localhost:8080"},
})
func (c *Client) CreateSessionWithMCPAuthRuntimeRefresh(ctx context.Context, config *SessionConfig, handler MCPAuthRuntimeRefreshHandler) (*Session, error)
CreateSessionWithMCPAuthRuntimeRefresh creates a session using the opt-in MCP auth handler instead of config.OnMCPAuthRequest. A nil handler uses the legacy callback. All other options and session lifecycle behavior match CreateSession.
DeleteSession permanently deletes a session and all its data from disk, including conversation history, planning state, and artifacts.
Unlike Session.Disconnect, which only releases in-memory resources and preserves session data for later resumption, DeleteSession is irreversible. The session cannot be resumed after deletion. If the session is in the local sessions map, it will be removed.
Example:
if err := client.DeleteSession(context.Background(), "session-123"); err != nil {
log.Fatal(err)
}
func (c *Client) ForceStop()
ForceStop forcefully stops the CLI server without graceful cleanup.
Use this when Client.Stop fails or takes too long. This method:
Event processing observes the stop signal before dispatching each remaining callback. Callbacks already being dispatched are not awaited and may finish after this method returns; an event handler can itself call ForceStop. Pending response waits fail when the session is retired, without waiting for an idle event or their context deadline. Registered session callbacks are released locally, including unadmitted event handler entries retained by a dispatch snapshot.
Example:
// If normal stop hangs, force stop
done := make(chan struct{})
go func() {
client.Stop()
close(done)
}()
select {
case <-done:
// Stopped successfully
case <-time.After(5 * time.Second):
client.ForceStop()
}
func (c *Client) GetAuthStatus(ctx context.Context) (*GetAuthStatusResponse, error)
GetAuthStatus returns current authentication status
GetForegroundSessionID returns the ID of the session currently displayed in the TUI.
This is only available when connecting to a server running in TUI+server mode (--ui-server). Returns nil if no foreground session is set.
Example:
sessionID, err := client.GetForegroundSessionID()
if err != nil {
log.Fatal(err)
}
if sessionID != nil {
fmt.Printf("TUI is displaying session: %s\n", *sessionID)
}
GetLastSessionID returns the ID of the most recently updated session.
This is useful for resuming the last conversation when the session ID was not stored. Returns nil if no sessions exist.
Example:
lastID, err := client.GetLastSessionID(context.Background())
if err != nil {
log.Fatal(err)
}
if lastID != nil {
session, err := client.ResumeSession(context.Background(), *lastID, &copilot.ResumeSessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
})
}
func (c *Client) GetSessionMetadata(ctx context.Context, sessionID string) (*SessionMetadata, error)
GetSessionMetadata returns metadata for a specific session by ID.
This provides an efficient O(1) lookup of a single session's metadata instead of listing all sessions. Returns nil if the session is not found.
Example:
metadata, err := client.GetSessionMetadata(context.Background(), "session-123")
if err != nil {
log.Fatal(err)
}
if metadata != nil {
fmt.Printf("Session started at: %s\n", metadata.StartTime)
}
func (c *Client) GetStatus(ctx context.Context) (*GetStatusResponse, error)
GetStatus returns CLI status including version and protocol information
ListModels returns available models with their metadata.
Results are cached after the first successful call to avoid rate limiting. The cache is cleared when the client disconnects.
func (c *Client) ListSessions(ctx context.Context, filter *SessionListFilter) ([]SessionMetadata, error)
ListSessions returns metadata about all sessions known to the server.
Returns a list of SessionMetadata for all available sessions, including their IDs, timestamps, optional summaries, and context information.
An optional filter can be provided to filter sessions by working directory, git root, repository, or branch.
Example:
sessions, err := client.ListSessions(context.Background(), nil)
if err != nil {
log.Fatal(err)
}
for _, session := range sessions {
fmt.Printf("Session: %s\n", session.SessionID)
}
Example with filter:
sessions, err := client.ListSessions(context.Background(), &SessionListFilter{Repository: "owner/repo"})
func (c *Client) On(handler SessionLifecycleHandler) func()
On subscribes to all session lifecycle events.
Lifecycle events are emitted when sessions are created, deleted, updated, or change foreground/background state (in TUI+server mode).
Returns a function that, when called, unsubscribes the handler.
Example:
unsubscribe := client.On(func(event copilot.SessionLifecycleEvent) {
fmt.Printf("Session %s: %s\n", event.SessionID, event.Type)
})
defer unsubscribe()
func (c *Client) OnEventType(eventType SessionLifecycleEventType, handler SessionLifecycleHandler) func()
OnEventType subscribes to a specific session lifecycle event type.
Returns a function that, when called, unsubscribes the handler.
Example:
unsubscribe := client.OnEventType(copilot.SessionLifecycleForeground, func(event copilot.SessionLifecycleEvent) {
fmt.Printf("Session %s is now in foreground\n", event.SessionID)
})
defer unsubscribe()
Ping sends a ping request to the server to verify connectivity.
The message parameter is optional and will be echoed back in the response. Returns a PingResponse containing the message and server timestamp, or an error.
Example:
resp, err := client.Ping(context.Background(), "health check")
if err != nil {
log.Printf("Server unreachable: %v", err)
} else {
log.Printf("Server responded at %s", resp.Timestamp)
}
func (c *Client) ResumeSession(ctx context.Context, sessionID string, config *ResumeSessionConfig) (*Session, error)
ResumeSession resumes an existing conversation session by its ID.
This is a convenience method that calls Client.ResumeSessionWithOptions. Example:
session, err := client.ResumeSession(context.Background(), "session-123", &copilot.ResumeSessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
})
func (c *Client) ResumeSessionWithMCPAuthRuntimeRefresh(ctx context.Context, sessionID string, config *ResumeSessionConfig, handler MCPAuthRuntimeRefreshHandler) (*Session, error)
ResumeSessionWithMCPAuthRuntimeRefresh resumes a session using the opt-in MCP auth handler instead of config.OnMCPAuthRequest. A nil handler uses the legacy callback. All other options and session lifecycle behavior match ResumeSessionWithOptions.
func (c *Client) ResumeSessionWithOptions(ctx context.Context, sessionID string, config *ResumeSessionConfig) (*Session, error)
ResumeSessionWithOptions resumes an existing conversation session with additional configuration.
This allows you to continue a previous conversation, maintaining all conversation history. The session must have been previously created and not deleted.
Example:
session, err := client.ResumeSessionWithOptions(context.Background(), "session-123", &copilot.ResumeSessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Tools: []copilot.Tool{myNewTool},
})
RuntimePort returns the TCP port the runtime is listening on. Returns 0 if the client is not connected or using stdio transport.
SetForegroundSessionID requests the TUI to switch to displaying the specified session.
This is only available when connecting to a server running in TUI+server mode (--ui-server).
Example:
if err := client.SetForegroundSessionID("session-123"); err != nil {
log.Fatal(err)
}
Start starts the CLI server (if not using an external server) and establishes a connection.
If connecting to an external server (via URIConnection), only establishes the connection. Otherwise, spawns the CLI server process and then connects.
This method is called automatically when creating a session if AutoStart is true (default).
Returns an error if the server fails to start or the connection fails.
Example:
client := copilot.NewClient(&copilot.ClientOptions{AutoStart: boolPtr(false)})
if err := client.Start(context.Background()); err != nil {
log.Fatal("Failed to start:", err)
}
// Now ready to create sessions
StartAhpHost starts a full AHP listener in the connected runtime, without a companion process. The listener ends when this connection closes. Cancellation abandons the wait; a listener that subsequently starts is disposed. Experimental: AHP hosting may change or be removed.
Stop stops the CLI server and closes all active sessions.
This method performs graceful cleanup:
Note: session data on disk is preserved, so sessions can be resumed later. To permanently remove session data before stopping, call Client.DeleteSession for each session first.
Returns an error that aggregates all errors encountered during cleanup.
Example:
if err := client.Stop(); err != nil {
log.Printf("Cleanup error: %v", err)
}
type ClientInfo struct {
// ApplicationName is the name of the application using the SDK.
ApplicationName string
// ApplicationVersion is the version of the application using the SDK.
ApplicationVersion string
// IntegrationName optionally identifies a specific integration within the
// application, such as an extension or plugin.
IntegrationName string
// IntegrationVersion is the optional version of the named integration.
IntegrationVersion string
}
ClientInfo identifies the integrating application on the `server.connect` handshake.
Declaring it lets the telemetry the runtime emits on the connection be attributed to a single, consistent surface instead of the runtime's own build. All fields are optional; an empty field is omitted from the handshake.
type ClientMode string
ClientMode controls the default surface presented to sessions created by the Client. The zero value is ModeCopilotCli, matching the legacy CLI defaults.
Set ClientOptions.Mode to ModeEmpty to opt in to multi-tenant safe defaults: no built-in tools by default (callers must specify SessionConfig.AvailableTools explicitly), no environment_context section in the system message, telemetry off, custom instructions and remote-custom agents disabled, etc.
const ( // ModeCopilotCli is the default mode; sessions inherit the full Copilot // CLI experience (all built-in tools, host environment_context, etc.). ModeCopilotCli ClientMode = "copilot-cli" // ModeEmpty is the multi-tenant safe-default mode. Sessions start with // no built-in tools, no environment context, and various features // (custom instructions, remote agents, telemetry, plugins) off by // default. Callers can opt back in field-by-field. ModeEmpty ClientMode = "empty" )
type ClientOptions struct {
// Connection describes how to connect to the Copilot runtime. When nil,
// COPILOT_SDK_DEFAULT_CONNECTION may select "inprocess" or "stdio";
// when unset, defaults to an empty [StdioConnection].
Connection RuntimeConnection
// WorkingDirectory is the working directory for the runtime process.
// If empty, inherits the current process's working directory.
WorkingDirectory string
// BaseDirectory is the base directory for Copilot data (session state,
// config, etc.). Sets the COPILOT_HOME environment variable on the
// spawned runtime. When empty, the runtime defaults to ~/.copilot.
// This does not affect where the Go SDK extracts the embedded CLI
// binary; use embeddedcli.Config.Dir to control that install/cache
// location.
// Ignored when connecting to an existing runtime via [URIConnection].
BaseDirectory string
// BuiltinPluginDirectories contains absolute paths to trusted plugin
// directories bundled by the host. When non-empty, Start replaces the
// runtime's complete trusted built-in plugin directory set before sessions
// can be created.
BuiltinPluginDirectories []string
// ExtensionLaunchProvider resolves launch profiles for extension entrypoints
// discovered by the runtime. When non-nil, Start registers the provider
// before any sessions can be created.
ExtensionLaunchProvider ExtensionLaunchProvider
// InstallationConfirmationHandler receives connection-global human reviews
// for experimental `installations.confirm` callbacks. It does not enable
// installation capabilities or perform any runtime registration RPC.
InstallationConfirmationHandler InstallationConfirmationHandler
// LogLevel for the runtime. When empty (the default), the runtime
// uses its own default level; the SDK does not pass --log-level.
// Recognized values: "none", "error", "warning", "info", "debug", "all".
LogLevel string
// Env are the environment variables for the runtime process (default:
// inherits from current process). Each entry is of the form "KEY=VALUE".
// If Env contains duplicate keys, only the last value for each key is used.
//
// For child-process transports ([StdioConnection] / [TCPConnection]) the
// per-connection Env, when set, takes precedence over this field; setting
// both is rejected. Env is not supported with [InProcessConnection] (the
// runtime shares this process's single environment block) and is rejected
// by [NewClient].
Env []string
// GitHubToken is the GitHub token to use for authentication.
// When provided, the token is passed to the runtime via environment
// variable. This takes priority over other authentication methods.
GitHubToken string
// UseLoggedInUser controls whether to use the logged-in user for
// authentication. When true, the runtime attempts to use stored OAuth
// tokens or gh CLI auth. When false, only explicit tokens (GitHubToken
// or environment variables) are used.
// Default: true (but defaults to false when GitHubToken is provided).
UseLoggedInUser *bool
// OnListModels is a custom handler for listing available models.
// When provided, [Client.ListModels] calls this handler instead of
// querying the runtime. Useful in BYOK mode to return models available
// from your custom provider.
OnListModels func(ctx context.Context) ([]ModelInfo, error)
// SessionFS configures a custom session filesystem provider.
// When provided, the client registers as the session filesystem provider
// on connection, routing session-scoped file I/O through per-session
// handlers.
SessionFS *SessionFSConfig
// RequestHandler registers a connection-level LLM inference callback. When
// non-nil, the client registers as the inference provider on connect, and
// the runtime routes its model-layer HTTP and WebSocket traffic through
// this handler instead of issuing the calls itself. Works for both CAPI
// and BYOK sessions.
RequestHandler *CopilotRequestHandler
// OnGitHubTelemetry registers a connection-level callback (experimental)
// that receives GitHub telemetry events the runtime forwards for sessions
// opened by this client. When non-nil, every session created or resumed by
// this client opts into telemetry forwarding (enableGitHubTelemetryForwarding).
OnGitHubTelemetry func(notification *rpc.GitHubTelemetryNotification)
// Telemetry configures OpenTelemetry integration for the runtime.
// When non-nil, COPILOT_OTEL_ENABLED=true is set and any populated
// fields are mapped to the corresponding environment variables.
Telemetry *TelemetryConfig
// SessionIdleTimeoutSeconds configures the server-wide session idle
// timeout in seconds. Sessions without activity for this duration are
// automatically cleaned up. Set to 0 or leave unset to disable.
// Ignored when connecting to an existing runtime via [URIConnection].
SessionIdleTimeoutSeconds int
// ClientInfo declares the integrating application's identity, forwarded to the
// runtime on the `server.connect` handshake. Declaring it lets the
// telemetry the runtime emits on this connection be attributed to a
// consistent surface (the application and its Copilot integration) instead of
// the runtime's own build. All fields are optional; leave it nil to keep the
// runtime's default attribution.
ClientInfo *ClientInfo
// Entra configures the host's Entra application for its sessions.
// Required for built-in Entra sign-in and token renewal; other authentication methods remain available.
Entra *rpc.EntraAuthConfig
// Mode controls the default tool surface and feature flags presented to
// sessions created by this client. The zero value ([ModeCopilotCli])
// matches legacy CLI defaults. Set to [ModeEmpty] to opt in to
// multi-tenant safe defaults — see [ClientMode] for details.
//
// When Mode is [ModeEmpty], NewClient requires either BaseDirectory,
// SessionFS, or a [URIConnection] so the runtime has persistent storage
// for session state.
Mode ClientMode
}
ClientOptions configures the Client.
type CloudSessionOptions struct {
Repository *CloudSessionRepository `json:"repository,omitempty"`
}
CloudSessionOptions configures creation of a remote session in the cloud.
type CloudSessionRepository struct {
Owner string `json:"owner"`
Name string `json:"name"`
Branch string `json:"branch,omitempty"`
}
CloudSessionRepository is GitHub repository metadata associated with a cloud session.
type CommandCompletedData = rpc.CommandCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CommandContext struct {
// SessionID is the session where the command was invoked.
SessionID string
// Command is the full command text (e.g. "/deploy production").
Command string
// CommandName is the command name without the leading / (e.g. "deploy").
CommandName string
// Args is the raw argument string after the command name.
Args string
}
CommandContext provides context about a slash-command invocation.
type CommandDefinition struct {
// Name is the command name (without leading /).
Name string
// Description is a human-readable description shown in command completion UI.
Description string
// Handler is invoked when the command is executed.
Handler CommandHandler
}
CommandDefinition registers a slash-command. Name is shown in the CLI TUI as /name for the user to invoke.
type CommandExecuteData = rpc.CommandExecuteData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CommandHandler func(ctx CommandContext) error
CommandHandler is invoked when a registered slash-command is executed.
type CommandQueuedData = rpc.CommandQueuedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CommandsChangedCommand = rpc.CommandsChangedCommand
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CommandsChangedData = rpc.CommandsChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CompactionCompleteCompactionTokensUsed = rpc.CompactionCompleteCompactionTokensUsed
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CompactionCompleteCompactionTokensUsedCopilotUsageTokenDetail = rpc.CompactionCompleteCompactionTokensUsedCopilotUsageTokenDetail
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CompactionTrigger = rpc.CompactionTrigger
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CompletionReceiptEventRange = rpc.CompletionReceiptEventRange
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CompletionReceiptFinalTool = rpc.CompletionReceiptFinalTool
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CompletionReceiptStopReason = rpc.CompletionReceiptStopReason
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CompletionReceiptToolStatus = rpc.CompletionReceiptToolStatus
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ContextTier = rpc.ContextTier
Session-event types are generated in the rpc package and aliased here for source compatibility.
type CopilotExpAssignmentResponse struct {
// Features lists the enabled feature names.
Features []string `json:"Features"`
// Flights holds the assigned flights keyed by flight name.
Flights map[string]string `json:"Flights"`
// Configs holds configuration entries carrying typed parameter values.
Configs []ExpConfigEntry `json:"Configs"`
// ParameterGroups is an opaque parameter-group payload passed through
// untouched. Optional.
ParameterGroups any `json:"ParameterGroups,omitempty"`
// FlightingVersion is the version of the flighting configuration. Optional.
FlightingVersion *int `json:"FlightingVersion,omitempty"`
// ImpressionID is the impression identifier for the assignment. Optional.
// Serialized on the wire as "ImpressionId".
ImpressionID *string `json:"ImpressionId,omitempty"`
// AssignmentContext is the assignment context string forwarded to CAPI and
// telemetry.
AssignmentContext string `json:"AssignmentContext"`
}
CopilotExpAssignmentResponse is ExP ("flight") assignment data, in the same JSON shape the Copilot CLI fetches from the experimentation service. Field names are PascalCase to match the on-the-wire contract consumed by the runtime.
func (r CopilotExpAssignmentResponse) MarshalJSON() ([]byte, error)
MarshalJSON normalizes the required collection fields so a zero-value response serializes them as JSON arrays/objects rather than null, which the runtime can otherwise treat as a malformed assignment payload and drop.
type CopilotRequestContext struct {
RequestID string
SessionID string
AgentID string
ParentAgentID string
InteractionType string
// AgentInvocationID is the runtime-provided logical invocation identity,
// unchanged across physical retries. Nil when the runtime omits it.
AgentInvocationID *string
// Transport is "http" (covering plain HTTP and SSE) or "websocket".
Transport string
Method string
URL string
Headers http.Header
// Context is cancelled when the runtime cancels this in-flight request.
Context context.Context
// contains filtered or unexported fields
}
CopilotRequestContext is the per-request context handed to every CopilotRequestHandler seam.
func RequestContextFrom(r *http.Request) *CopilotRequestContext
RequestContextFrom returns the CopilotRequestContext attached to an http.Request by the adapter, or nil if not present. Call this from a custom http.RoundTripper to access metadata such as SessionID and AgentID.
type CopilotRequestHandler struct {
// Transport forwards HTTP requests. When nil a shared default transport is
// used. RoundTrip is called directly, so redirects are not followed.
Transport http.RoundTripper
// OpenWebSocket returns a per-connection WebSocket handler. When nil a
// transparent [CopilotWebSocketForwarder] to the request URL is opened.
OpenWebSocket func(ctx *CopilotRequestContext) (CopilotWebSocketHandler, error)
}
CopilotRequestHandler is the idiomatic handler for intercepting or replacing LLM inference requests. HTTP requests are forwarded through Transport (an http.RoundTripper); supply a custom RoundTripper to mutate the request, post-process the response, or replace the call entirely. WebSocket requests are serviced by OpenWebSocket; supply one to return a custom handler.
The default behaviour (both fields nil) transparently forwards HTTP through a shared transport and opens a forwarding WebSocket connection to the runtime's original URL.
CopilotWebSocketCloseStatus is the terminal status for a callback-owned WebSocket connection.
type CopilotWebSocketForwarder struct {
URL string
Headers http.Header
// OnSendRequestMessage observes or transforms each runtime→upstream frame.
// The frame type (text vs binary) is available via the message's Binary
// field and may be changed in the returned message. Return nil to drop the
// frame.
OnSendRequestMessage func(msg CopilotWebSocketMessage) *CopilotWebSocketMessage
// OnSendResponseMessage observes or transforms each upstream→runtime frame.
// The frame type (text vs binary) is available via the message's Binary
// field and may be changed in the returned message. Return nil to drop the
// frame.
OnSendResponseMessage func(msg CopilotWebSocketMessage) *CopilotWebSocketMessage
// contains filtered or unexported fields
}
CopilotWebSocketForwarder is the default CopilotWebSocketHandler: it dials the real upstream and runs a receive loop forwarding upstream→runtime messages. Set OnSendRequestMessage / OnSendResponseMessage to observe, transform, or drop messages in either direction.
func NewCopilotWebSocketForwarder(url string, headers http.Header) *CopilotWebSocketForwarder
NewCopilotWebSocketForwarder creates a forwarding handler targeting url with the given handshake headers.
func (f *CopilotWebSocketForwarder) Close() error
func (f *CopilotWebSocketForwarder) Done() <-chan struct{}
func (f *CopilotWebSocketForwarder) Err() error
func (f *CopilotWebSocketForwarder) Open(ctx context.Context, resp WebSocketResponseWriter) error
func (f *CopilotWebSocketForwarder) SendRequestMessage(ctx context.Context, msg CopilotWebSocketMessage) error
type CopilotWebSocketHandler interface {
// Open establishes the connection and starts forwarding upstream→runtime
// messages into resp. It must not block. ctx is cancelled on teardown.
Open(ctx context.Context, resp WebSocketResponseWriter) error
// SendRequestMessage forwards one runtime→upstream message.
SendRequestMessage(ctx context.Context, msg CopilotWebSocketMessage) error
// Done is closed when the upstream connection completes (closed or errored).
Done() <-chan struct{}
// Err returns the terminal error after Done is closed, or nil on clean close.
Err() error
// Close tears down the connection.
Close() error
}
CopilotWebSocketHandler is a per-connection WebSocket handler returned by CopilotRequestHandler.OpenWebSocket. The default implementation is CopilotWebSocketForwarder; a full transport replacement implements this interface directly.
type CopilotWebSocketMessage struct {
Data []byte
Binary bool
// AgentInvocationID identifies this runtime request message's invocation,
// which may differ from the invocation that opened the connection.
// Nil when the runtime omits it, including upstream response messages.
AgentInvocationID *string
}
CopilotWebSocketMessage is a single WebSocket frame exchanged through the handler seam. Binary distinguishes a binary frame from a UTF-8 text frame.
func NewTextMessage(text string) CopilotWebSocketMessage
NewTextMessage creates a text-frame message from a UTF-8 string. Binary frames are constructed directly with CopilotWebSocketMessage{Data: ..., Binary: true}.
func (m CopilotWebSocketMessage) Text() string
Text decodes the frame payload as a UTF-8 string.
type CustomAgentConfig struct {
// Hooks contains declarative actions keyed by event name, active only for this agent.
Hooks map[string][]map[string]any `json:"hooks,omitempty"`
// Name is the unique name of the custom agent
Name string `json:"name"`
// DisplayName is the display name for UI purposes
DisplayName string `json:"displayName,omitempty"`
// Description of what the agent does
Description string `json:"description,omitempty"`
// Tools is the list of tool names the agent can use. Nil omits the field
// (all tools); an empty non-nil slice sends "tools": [] (no tools).
Tools []string `json:"tools,omitzero"`
// Prompt is the prompt content for the agent
Prompt string `json:"prompt"`
// MCPServers are MCP servers specific to this agent
MCPServers map[string]MCPServerConfig `json:"mcpServers,omitempty"`
// Infer indicates whether the agent should be available for model inference
Infer *bool `json:"infer,omitempty"`
// Skills is the list of skill names to preload into this agent's context at startup (opt-in; omit for none)
Skills []string `json:"skills,omitempty"`
// Model is the model identifier for this agent (e.g. "claude-haiku-4.5").
// When set, the runtime will attempt to use this model for the agent,
// falling back to the parent session model if unavailable unless ModelPolicy
// requires the authored model.
Model string `json:"model,omitempty"`
// ModelPolicy controls whether the authored model is preferred or required.
// When omitted, the model is preferred and may fall back to the parent.
ModelPolicy AgentModelPolicy `json:"modelPolicy,omitempty"`
// ReasoningEffort is the reasoning effort level for this agent's model.
// When empty, the runtime resolves model configuration, then inherits the
// parent effort only for the same model.
ReasoningEffort string `json:"reasoningEffort,omitempty"`
}
CustomAgentConfig configures a custom agent.
type CustomAgentsUpdatedAgent = rpc.CustomAgentsUpdatedAgent
Session-event types are generated in the rpc package and aliased here for source compatibility.
type DefaultAgentConfig struct {
// ExcludedTools is a list of tool names to exclude from the default agent.
// These tools remain available to custom sub-agents that reference them in their Tools list.
ExcludedTools []string `json:"excludedTools,omitempty"`
}
DefaultAgentConfig configures the default agent (the built-in agent that handles turns when no custom agent is selected). Use ExcludedTools to hide specific tools from the default agent while keeping them available to custom sub-agents.
type DisableBypassPermissionsMode string
DisableBypassPermissionsMode is the managed bypass-permissions policy.
The runtime may introduce additional fail-closed modes. Values are serialized as strings so callers can use newer modes without waiting for an SDK release.
const ( // DisableBypassPermissionsModeDisable turns off bypass-permissions mode. DisableBypassPermissionsModeDisable DisableBypassPermissionsMode = "disable" // DisableBypassPermissionsModeAllowAutoOnly permits only automatic bypass. DisableBypassPermissionsModeAllowAutoOnly DisableBypassPermissionsMode = "allow-auto-only" )
type ElicitationAction = rpc.UIElicitationResponseAction
ElicitationAction is the user response to an elicitation request.
const ( ElicitationActionAccept ElicitationAction = rpc.UIElicitationResponseActionAccept ElicitationActionCancel ElicitationAction = rpc.UIElicitationResponseActionCancel ElicitationActionDecline ElicitationAction = rpc.UIElicitationResponseActionDecline )
Elicitation action values.
type ElicitationCompletedAction = rpc.ElicitationCompletedAction
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ElicitationCompletedData = rpc.ElicitationCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ElicitationContext struct {
// SessionID is the identifier of the session that triggered the request.
SessionID string
// Message describes what information is needed from the user.
Message string
// RequestedSchema is a JSON Schema describing the form fields (form mode only).
RequestedSchema *ElicitationSchema
// Mode is "form" for structured input, "url" for browser redirect.
Mode *ElicitationRequestedMode
// ElicitationSource is the source that initiated the request (e.g. MCP server name).
ElicitationSource *string
// ElicitationSourceDisplayName is the trusted display label of a Connector-owned
// MCP server that initiated the request, such as "Work IQ".
ElicitationSourceDisplayName *string
// URL to open in the user's browser (url mode only).
URL *string
}
ElicitationContext describes an elicitation request from the server, combining the request data with session context. Mirrors the single-argument pattern of CommandContext.
type ElicitationFieldValue = any
ElicitationFieldValue is a primitive value submitted for an elicitation form field. Supported values are string, numeric types, bool, []string, and []any containing strings.
type ElicitationHandler func(ctx ElicitationContext) (ElicitationResult, error)
ElicitationHandler handles elicitation requests from the server (e.g. from MCP tools). It receives an ElicitationContext and must return an ElicitationResult. If the handler returns an error the SDK auto-cancels the request.
type ElicitationRequestedData = rpc.ElicitationRequestedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ElicitationRequestedMode = rpc.ElicitationRequestedMode
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ElicitationRequestedSchema = rpc.ElicitationRequestedSchema
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ElicitationRequestedSchemaType = rpc.ElicitationRequestedSchemaType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ElicitationResult struct {
// Action is the user response: accept, decline, or cancel.
Action ElicitationAction `json:"action"`
// Content holds form values submitted by the user when Action is accept.
Content map[string]ElicitationFieldValue `json:"content,omitzero"`
}
ElicitationResult is the user's response to an elicitation dialog.
type ElicitationSchema struct {
// Properties contains form field definitions keyed by field name.
Properties map[string]any `json:"properties"`
// Required lists field names that must be submitted.
Required []string `json:"required,omitzero"`
}
ElicitationSchema describes the form fields for an elicitation request.
type EmbeddedBlobResourceContents = rpc.EmbeddedBlobResourceContents
Session-event types are generated in the rpc package and aliased here for source compatibility.
type EmbeddedTextResourceContents = rpc.EmbeddedTextResourceContents
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ErrorOccurredHandler func(input ErrorOccurredHookInput, invocation HookInvocation) (*ErrorOccurredHookOutput, error)
ErrorOccurredHandler handles error-occurred hook invocations
type ErrorOccurredHookInput struct {
AgentID string `json:"agentId,omitempty"`
AgentType string `json:"agentType,omitempty"`
ParentAgentID string `json:"parentAgentId,omitempty"`
SessionID string `json:"sessionId"`
Timestamp time.Time `json:"-"`
WorkingDirectory string `json:"cwd"`
Error string `json:"error"`
ErrorContext string `json:"errorContext"` // "model_call", "tool_execution", "system", "user_input"
Recoverable bool `json:"recoverable"`
}
ErrorOccurredHookInput is the input for an error-occurred hook
func (h ErrorOccurredHookInput) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (h *ErrorOccurredHookInput) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds and Error from the CLI's error object (see hookErrorText).
type ErrorOccurredHookOutput struct {
SuppressOutput bool `json:"suppressOutput,omitempty"`
ErrorHandling string `json:"errorHandling,omitempty"` // "retry", "skip", "abort"
RetryCount int `json:"retryCount,omitempty"`
UserNotification string `json:"userNotification,omitempty"`
}
ErrorOccurredHookOutput is the output for an error-occurred hook
type ExitPlanModeAction = rpc.ExitPlanModeAction
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ExitPlanModeCompletedData = rpc.ExitPlanModeCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ExitPlanModeInvocation struct {
SessionID string
}
ExitPlanModeInvocation provides context about an exit-plan-mode request.
type ExitPlanModeRequest struct {
Summary string `json:"summary"`
PlanContent string `json:"planContent,omitempty"`
Actions []string `json:"actions"`
RecommendedAction string `json:"recommendedAction"`
}
ExitPlanModeRequest represents a request to exit plan mode and continue with a selected action.
type ExitPlanModeRequestHandler func(request ExitPlanModeRequest, invocation ExitPlanModeInvocation) (ExitPlanModeResult, error)
ExitPlanModeRequestHandler handles exit-plan-mode requests from the agent.
type ExitPlanModeRequestedData = rpc.ExitPlanModeRequestedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ExitPlanModeResult struct {
Approved bool `json:"approved"`
SelectedAction string `json:"selectedAction,omitempty"`
Feedback string `json:"feedback,omitempty"`
}
ExitPlanModeResult is the response to an exit-plan-mode request.
type ExpConfigEntry struct {
// ID identifies the configuration entry. Serialized on the wire as "Id".
ID string `json:"Id"`
// Parameters holds parameter values keyed by parameter name.
Parameters map[string]ExpFlagValue `json:"Parameters"`
}
ExpConfigEntry is a single configuration entry in a CopilotExpAssignmentResponse. Each entry carries an identifier and a bag of typed parameter values.
func (e ExpConfigEntry) MarshalJSON() ([]byte, error)
MarshalJSON normalizes the required Parameters map so an entry serializes it as a JSON object rather than null.
type ExpFlagValue any
ExpFlagValue is a single ExP (Experiment Platform) flag value. ExP assignments resolve to a string, number (float64/int), bool, or nil.
type ExtensionInfo struct {
// Source is the extension namespace/source, e.g. "github-app".
Source string `json:"source"`
// Name is the extension identifier within that source, e.g. "my-app".
Name string `json:"name"`
}
ExtensionInfo carries stable extension identity for session participants that provide canvases.
Experimental: ExtensionInfo is part of an experimental wire-protocol surface and may change or be removed in future SDK or CLI releases.
type ExtensionLaunchProfile = rpc.ExtensionLaunchProfile
ExtensionLaunchProfile describes how the runtime should launch an extension.
type ExtensionLaunchProvider = rpc.ExtensionLaunchProviderHandler
ExtensionLaunchProvider resolves launch profiles for extension entrypoints discovered by the runtime.
Experimental: this API may change or be removed.
type ExtensionLaunchProviderResolveRequest = rpc.ExtensionLaunchProviderResolveRequest
ExtensionLaunchProviderResolveRequest describes a discovered extension entrypoint that may need a host-provided launch profile.
type ExtensionLaunchProviderResolveResult = rpc.ExtensionLaunchProviderResolveResult
ExtensionLaunchProviderResolveResult contains the optional host-provided launch profile for an extension entrypoint.
type ExtensionsLoadedExtension = rpc.ExtensionsLoadedExtension
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ExtensionsLoadedExtensionSource = rpc.ExtensionsLoadedExtensionSource
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ExtensionsLoadedExtensionStatus = rpc.ExtensionsLoadedExtensionStatus
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ExternalToolCompletedData = rpc.ExternalToolCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ExternalToolRequestedData = rpc.ExternalToolRequestedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type FusionAttribution = rpc.FusionAttribution
Session-event types are generated in the rpc package and aliased here for source compatibility.
type FusionConversationScope = rpc.FusionConversationScope
Session-event types are generated in the rpc package and aliased here for source compatibility.
type FusionCritic = rpc.FusionCritic
Session-event types are generated in the rpc package and aliased here for source compatibility.
type FusionFollowUpAction = rpc.FusionFollowUpAction
Session-event types are generated in the rpc package and aliased here for source compatibility.
type FusionFollowUpRecommendation = rpc.FusionFollowUpRecommendation
Session-event types are generated in the rpc package and aliased here for source compatibility.
type FusionPattern = rpc.FusionPattern
Session-event types are generated in the rpc package and aliased here for source compatibility.
type FusionPhaseActivityKind = rpc.FusionPhaseActivityKind
Session-event types are generated in the rpc package and aliased here for source compatibility.
type FusionPhaseKind = rpc.FusionPhaseKind
Session-event types are generated in the rpc package and aliased here for source compatibility.
type FusionPhasePlanStep = rpc.FusionPhasePlanStep
Session-event types are generated in the rpc package and aliased here for source compatibility.
type FusionPhaseStatus = rpc.FusionPhaseStatus
Session-event types are generated in the rpc package and aliased here for source compatibility.
type FusionPhaseUsage = rpc.FusionPhaseUsage
Session-event types are generated in the rpc package and aliased here for source compatibility.
type FusionScores = rpc.FusionScores
Session-event types are generated in the rpc package and aliased here for source compatibility.
type FusionTurnKind = rpc.FusionTurnKind
Session-event types are generated in the rpc package and aliased here for source compatibility.
type GetAuthStatusResponse struct {
IsAuthenticated bool `json:"isAuthenticated"`
AuthType *string `json:"authType,omitempty"`
Host *string `json:"host,omitempty"`
Login *string `json:"login,omitempty"`
StatusMessage *string `json:"statusMessage,omitempty"`
}
GetAuthStatusResponse is the response from auth.getStatus
type GetStatusResponse struct {
Version string `json:"version"`
ProtocolVersion int `json:"protocolVersion"`
}
GetStatusResponse is the response from status.get
type GitHubMCPToolConfig struct {
EnableAllTools *bool `json:"enableAllTools,omitempty"`
AdditionalToolsets []string `json:"additionalToolsets,omitempty"`
AdditionalTools []string `json:"additionalTools,omitempty"`
EnableInsidersMode *bool `json:"enableInsidersMode,omitempty"`
DisableFormDeferral *bool `json:"disableFormDeferral,omitempty"`
}
GitHubMCPToolConfig configures the built-in GitHub MCP server.
DisableFormDeferral only applies to the built-in GitHub MCP server and only has an effect when MCP Apps and form-backed GitHub tools are enabled.
type GitHubRepoRef = rpc.GitHubRepoRef
Session-event types are generated in the rpc package and aliased here for source compatibility.
type GitHubToken struct {
// AccessToken is the GitHub access token.
AccessToken string
// TokenType is the OAuth token type. The runtime defaults it to "bearer".
TokenType *string
// ExpiresIn is the required positive number of seconds remaining when the
// callback completes. Production GitHub tokens typically last eight hours.
ExpiresIn int64
}
GitHubToken contains a GitHub access token returned by a provider.
Experimental: GitHubToken may change or be removed.
func (t GitHubToken) GoString() string
GoString returns a redacted Go-syntax description that never includes the access token.
func (t GitHubToken) String() string
String returns a redacted description that never includes the access token.
type GitHubTokenProvider func(args GitHubTokenProviderArgs) (*GitHubTokenProviderResult, error)
GitHubTokenProvider acquires session-scoped GitHub tokens on demand. Initial cancellation, errors, and invalid token responses reject session creation or resume instead of falling back to ambient authentication.
Experimental: GitHubTokenProvider may change or be removed.
type GitHubTokenProviderArgs struct {
// Host is the effective GitHub host for which a token is needed.
Host string
// SessionID identifies the session receiving the token. It is nil before a
// cloud session has been assigned an ID.
SessionID *string
// Reason indicates whether this is the initial token or a refresh.
Reason GitHubTokenRequestReason
}
GitHubTokenProviderArgs contains the context for a GitHub token request.
Experimental: GitHubTokenProviderArgs may change or be removed.
type GitHubTokenProviderResult struct {
Cancelled bool
Token *GitHubToken
}
GitHubTokenProviderResult is the result of a GitHub token request.
Experimental: GitHubTokenProviderResult may change or be removed.
func GitHubTokenCancelled() *GitHubTokenProviderResult
GitHubTokenCancelled returns a result indicating that token acquisition was cancelled.
func GitHubTokenResult(token *GitHubToken) *GitHubTokenProviderResult
GitHubTokenResult returns a successful token-provider result.
type GitHubTokenRequestReason = rpc.GitHubTokenAcquireReason
GitHubTokenRequestReason describes why the runtime needs a GitHub token.
Experimental: GitHubTokenRequestReason may change or be removed.
type HandoffRepository = rpc.HandoffRepository
Session-event types are generated in the rpc package and aliased here for source compatibility.
type HandoffSourceType = rpc.HandoffSourceType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type HeaderEntry = rpc.HeaderEntry
Session-event types are generated in the rpc package and aliased here for source compatibility.
type HookEndData = rpc.HookEndData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type HookEndError = rpc.HookEndError
Session-event types are generated in the rpc package and aliased here for source compatibility.
type HookInvocation struct {
SessionID string
}
HookInvocation provides context about a hook invocation
type HookProgressData = rpc.HookProgressData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type HookStartData = rpc.HookStartData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type HumanResponseActor = rpc.HumanResponseActor
Session-event types are generated in the rpc package and aliased here for source compatibility.
type HumanResponseRecordedData = rpc.HumanResponseRecordedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type HumanResponseRecordedResponse = rpc.HumanResponseRecordedResponse
Session-event types are generated in the rpc package and aliased here for source compatibility.
type HumanResponseRecordedResponseAskUser = rpc.HumanResponseRecordedResponseAskUser
Session-event types are generated in the rpc package and aliased here for source compatibility.
type HumanResponseRecordedResponseExitPlanMode = rpc.HumanResponseRecordedResponseExitPlanMode
Session-event types are generated in the rpc package and aliased here for source compatibility.
type HumanResponseRecordedResponseResponseKind = rpc.HumanResponseRecordedResponseResponseKind
Session-event types are generated in the rpc package and aliased here for source compatibility.
type HumanResponseRecordedResponseUserInput = rpc.HumanResponseRecordedResponseUserInput
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ImageGenerationConfig struct {
// Enabled opts in when true and disables image generation when false.
Enabled *bool `json:"enabled,omitempty"`
// Watermark requests a visible "Made with AI" label on generated and edited
// images. Overrides the user's imageGenerationWatermark preference (default
// false). Re-supply after cold resume. Does not enable image generation or
// enforce enterprise policy.
Watermark *bool `json:"watermark,omitempty"`
// SaveToDisk is experimental. It saves generated and edited images under the
// session-state directory's images folder and gives the model each path as a
// "saved_to:" line in the tool result. Defaults to true; set false to opt
// out. Subagents follow
// their parent's value unless they set their own. A failed save still returns
// the image. Sessions without a local session-state directory never save.
// Re-supply after cold resume. Does not enable image generation.
SaveToDisk *bool `json:"saveToDisk,omitempty"`
}
ImageGenerationConfig opts in to an authorized Copilot image model. Experimental: this API may change or be removed in a future release. Omission disables on create/cold resume and preserves resident resume state. Not persisted: re-supply after runtime restart. Policy, permissions, offline mode, and tool filters still apply. BYOK image generation is not supported.
type InProcessConnection struct {
// RunOnUiThread schedules the supplied native action exactly once on the UI
// thread (the process main thread on macOS), returning only after it completes.
// The action can block while native UI is open. No authentication data crosses
// this callback. Other in-process clients may share this process-wide capability.
//
// Required for OneAuth interactive authentication on macOS. This general-purpose
// scheduler may also be used for other runtime-owned native UI operations.
// Temporary OneAuth workaround; this API may be removed if no longer needed.
// See https://github.com/github/copilot-agent-runtime/issues/27032.
// Experimental.
RunOnUiThread func(action func() error) error
}
InProcessConnection hosts the Copilot runtime in-process by loading its native runtime library (a Rust cdylib) and driving JSON-RPC over the library's C ABI, instead of spawning a runtime child process.
Because the runtime is loaded into the calling process, per-client environment, working directory, and telemetry cannot be represented and are rejected by NewClient (see ClientOptions). Set those via the host process environment instead, or use a child-process transport (StdioConnection / TCPConnection).
Experimental: the in-process transport is experimental and its API and behavior may change in a future release. Build the application with the copilot_inprocess build tag to enable this transport.
type IndexedSearchState = rpc.IndexedSearchState
Session-event types are generated in the rpc package and aliased here for source compatibility.
type InfiniteSessionConfig struct {
// Enabled controls whether infinite sessions are enabled (default: true)
Enabled *bool `json:"enabled,omitempty"`
// BackgroundCompactionThreshold is the context utilization (0.0-1.0) at which
// background compaction starts. Default: 0.80
BackgroundCompactionThreshold *float64 `json:"backgroundCompactionThreshold,omitempty"`
// BufferExhaustionThreshold is the context utilization (0.0-1.0) at which
// the session blocks until compaction completes. Default: 0.95
BufferExhaustionThreshold *float64 `json:"bufferExhaustionThreshold,omitempty"`
}
InfiniteSessionConfig configures infinite sessions with automatic context compaction and workspace persistence. When enabled, sessions automatically manage context window limits through background compaction and persist state to a workspace directory.
InstallationConfirmationContext is cancelled when the runtime retires this JSON-RPC request, including via numeric $/cancelRequest, or when the original connection is closed or the client is stopped. It does not cancel outbound installation or OAuth RPCs.
Experimental: InstallationConfirmationContext may change or be removed.
type InstallationConfirmationDecision = rpc.InstallationDecision
InstallationConfirmationDecision is the explicit human decision returned by an installation confirmation handler.
Experimental: InstallationConfirmationDecision may change or be removed.
type InstallationConfirmationHandler interface {
ConfirmInstallation(request InstallationConfirmationRequest, context InstallationConfirmationContext) (InstallationConfirmationDecision, error)
}
InstallationConfirmationHandler collects a fresh human decision for the complete runtime review.
Match OperationID and PolicySessionID against the exact action registered by this client before displaying the review. Refuse unknown actions or incomplete reviews; never infer authority from the current session. The SDK echoes the original challenge and fingerprint, so the handler returns only a decision.
Experimental: InstallationConfirmationHandler may change or be removed.
type InstallationConfirmationHandlerFunc func(request InstallationConfirmationRequest, context InstallationConfirmationContext) (InstallationConfirmationDecision, error)
InstallationConfirmationHandlerFunc adapts a function to InstallationConfirmationHandler.
Experimental: InstallationConfirmationHandlerFunc may change or be removed.
func (f InstallationConfirmationHandlerFunc) ConfirmInstallation(request InstallationConfirmationRequest, context InstallationConfirmationContext) (InstallationConfirmationDecision, error)
ConfirmInstallation calls f(request, context).
type InstallationConfirmationRequest = rpc.InstallationConfirmationRequest
InstallationConfirmationRequest is the typed review request for one sealed installation operation on its original connection.
Experimental: InstallationConfirmationRequest may change or be removed.
type InstructionUpdateAuthority = rpc.InstructionUpdateAuthority
Session-event types are generated in the rpc package and aliased here for source compatibility.
type InstructionUpdateBoundary = rpc.InstructionUpdateBoundary
Session-event types are generated in the rpc package and aliased here for source compatibility.
type InstructionUpdateData = rpc.InstructionUpdateData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type InstructionUpdateFallback = rpc.InstructionUpdateFallback
Session-event types are generated in the rpc package and aliased here for source compatibility.
type InstructionUpdateLifetime = rpc.InstructionUpdateLifetime
Session-event types are generated in the rpc package and aliased here for source compatibility.
type LargeToolOutputConfig struct {
// Enabled controls whether large output handling is enabled. Default: true.
Enabled *bool `json:"enabled,omitempty"`
// MaxSizeBytes is the maximum size in bytes before output is written to a
// temp file. Default: 50KB.
MaxSizeBytes *int64 `json:"maxSizeBytes,omitempty"`
// OutputDirectory is the directory to write temp files to. Defaults to the OS
// temp directory.
OutputDirectory string `json:"outputDir,omitempty"`
}
LargeToolOutputConfig configures handling of large tool outputs. When a tool produces output exceeding the configured size, the output is written to a temp file and a reference is returned to the model instead of the full payload.
type LogOptions struct {
// Level sets the log severity. Valid values are [rpc.SessionLogLevelInfo] (default),
// [rpc.SessionLogLevelWarning], and [rpc.SessionLogLevelError].
Level rpc.SessionLogLevel
// Ephemeral marks the message as transient so it is not persisted
// to the session event log on disk. When nil the server decides the
// default; set to a non-nil value to explicitly control persistence.
Ephemeral *bool
}
type MCPAppToolCallCompleteData = rpc.MCPAppToolCallCompleteData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPAppToolCallCompleteError = rpc.MCPAppToolCallCompleteError
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPAppToolCallCompleteToolMeta = rpc.MCPAppToolCallCompleteToolMeta
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPAppToolCallCompleteToolMetaUI = rpc.MCPAppToolCallCompleteToolMetaUI
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPAuthHandler func(request MCPAuthRequest, invocation MCPAuthInvocation) (*MCPAuthResult, error)
MCPAuthHandler handles MCP OAuth requests from the runtime.
type MCPAuthInvocation struct {
SessionID string
}
MCPAuthInvocation provides context about an MCP auth handler invocation.
type MCPAuthRequest struct {
RequestID string `json:"requestId"`
ServerName string `json:"serverName"`
ServerURL string `json:"serverUrl"`
Reason MCPOauthRequestReason `json:"reason"`
WwwAuthenticateParams *MCPAuthWwwAuthenticateParams `json:"wwwAuthenticateParams,omitempty"`
ResourceMetadata *string `json:"resourceMetadata,omitempty"`
StaticClientConfig *MCPAuthStaticClientConfig `json:"staticClientConfig,omitempty"`
}
MCPAuthRequest describes an MCP OAuth request that the SDK host can satisfy with a token.
type MCPAuthResult struct {
Kind string
Token *MCPAuthToken
}
MCPAuthResult is the result returned by an MCP auth request handler.
func MCPAuthResultCancelled() *MCPAuthResult
MCPAuthResultCancelled returns a cancelled result for an MCP OAuth request.
func MCPAuthResultRuntimeRefresh() *MCPAuthResult
MCPAuthResultRuntimeRefresh requests noninteractive renewal for an advertised Refresh. Response acceptance is not token installation or reconnect completion.
func MCPAuthResultToken(token *MCPAuthToken) *MCPAuthResult
MCPAuthResultToken returns a token result for an MCP OAuth request.
type MCPAuthRuntimeRefreshHandler func(request MCPAuthRequest, invocation MCPAuthInvocation, runtimeRefreshSupported bool) (*MCPAuthResult, error)
MCPAuthRuntimeRefreshHandler opts into runtime-owned refresh without changing legacy request or invocation literals. runtimeRefreshSupported is false when omitted. Return MCPAuthResultRuntimeRefresh only for an advertised Refresh. Other requests retain the host's existing token or cancellation policy.
type MCPAuthStaticClientConfig struct {
ClientID string `json:"clientId"`
ClientSecret *string `json:"clientSecret,omitempty"`
GrantType *string `json:"grantType,omitempty"`
PublicClient *bool `json:"publicClient,omitempty"`
Scope *string `json:"scope,omitempty"`
}
MCPAuthStaticClientConfig is static OAuth client configuration supplied by an MCP server.
type MCPAuthToken struct {
AccessToken string `json:"accessToken"`
TokenType *string `json:"tokenType,omitempty"`
ExpiresIn *int64 `json:"expiresIn,omitempty"`
}
MCPAuthToken is host-provided OAuth token data for a pending MCP OAuth request.
type MCPAuthWwwAuthenticateParams struct {
ResourceMetadataURL *string `json:"resourceMetadataUrl,omitempty"`
Scope *string `json:"scope,omitempty"`
Error *string `json:"error,omitempty"`
}
MCPAuthWwwAuthenticateParams contains parsed parameters from an MCP server's WWW-Authenticate response.
type MCPHTTPServerConfig struct {
Tools []string `json:"tools,omitzero"`
Timeout int `json:"timeout,omitempty"`
URL string `json:"url"`
Headers map[string]string `json:"headers,omitzero"`
OAuthClientID *string `json:"oauthClientId,omitempty"`
OAuthScopes []string `json:"oauthScopes,omitzero"`
OAuthPublicClient *bool `json:"oauthPublicClient,omitempty"`
OAuthGrantType *rpc.MCPServerConfigHTTPOauthGrantType `json:"oauthGrantType,omitempty"`
}
MCPHTTPServerConfig configures a remote MCP server (HTTP or SSE).
See MCPStdioServerConfig for the semantics of the Tools field.
func (c MCPHTTPServerConfig) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, injecting the "type" discriminator.
type MCPHeadersRefreshCompletedData = rpc.MCPHeadersRefreshCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPHeadersRefreshCompletedOutcome = rpc.MCPHeadersRefreshCompletedOutcome
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPHeadersRefreshRequiredData = rpc.MCPHeadersRefreshRequiredData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPHeadersRefreshRequiredReason = rpc.MCPHeadersRefreshRequiredReason
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPOauthCompletedData = rpc.MCPOauthCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPOauthCompletionOutcome = rpc.MCPOauthCompletionOutcome
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPOauthHTTPResponse = rpc.MCPOauthHTTPResponse
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPOauthRecoveryCompletedData = rpc.MCPOauthRecoveryCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPOauthRecoveryCompletedOutcome = rpc.MCPOauthRecoveryCompletedOutcome
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPOauthRequestReason = rpc.MCPOauthRequestReason
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPOauthRequiredData = rpc.MCPOauthRequiredData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPOauthRequiredStaticClientConfig = rpc.MCPOauthRequiredStaticClientConfig
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPOauthRequiredStaticClientConfigGrantType = rpc.MCPOauthRequiredStaticClientConfigGrantType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPOauthWwwAuthenticateParams = rpc.MCPOauthWwwAuthenticateParams
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPPromptsListChangedData = rpc.MCPPromptsListChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPResourcesListChangedData = rpc.MCPResourcesListChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPServerConfig interface {
// contains filtered or unexported methods
}
MCPServerConfig is implemented by MCP server configuration types. Only MCPStdioServerConfig and MCPHTTPServerConfig implement this interface.
type MCPServerMetadata = rpc.MCPServerMetadata
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPServerSource = rpc.MCPServerSource
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPServerStatus = rpc.MCPServerStatus
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPServerTransport = rpc.MCPServerTransport
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPServersLoadedServer = rpc.MCPServersLoadedServer
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MCPStdioServerConfig struct {
Tools []string `json:"tools,omitzero"`
Timeout int `json:"timeout,omitempty"`
Command string `json:"command"`
Args []string `json:"args,omitzero"`
Env map[string]string `json:"env,omitzero"`
WorkingDirectory string `json:"cwd,omitempty"`
}
MCPStdioServerConfig configures a local/stdio MCP server.
The Tools field controls which tools from the server are exposed:
func (c MCPStdioServerConfig) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, injecting the "type" discriminator.
type MCPToolsListChangedData = rpc.MCPToolsListChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ManagedPermissionsContext = rpc.ManagedPermissionsContext
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ManagedPluginProgressPhase = rpc.ManagedPluginProgressPhase
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ManagedSettings struct {
// Permissions is the managed permission policy for the session.
Permissions *ManagedSettingsPermissions `json:"permissions,omitempty"`
}
ManagedSettings is host-injected enterprise managed settings for a session. The first supported contract is permissions-only; unknown sibling keys are rejected by the runtime. Serialized on the wire as managedSettings.
type ManagedSettingsEnforcedAction = rpc.ManagedSettingsEnforcedAction
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ManagedSettingsEnforcedEscalation = rpc.ManagedSettingsEnforcedEscalation
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ManagedSettingsPermissions struct {
// DisableBypassPermissionsMode restricts bypass-permissions mode for the
// session. See the DisableBypassPermissionsMode constants for known values.
// Newer values are forwarded unchanged so runtime policies remain fail-closed.
DisableBypassPermissionsMode DisableBypassPermissionsMode `json:"disableBypassPermissionsMode,omitempty"`
// DisableAssistedPermissionsMode prevents Assisted Permissions from being
// activated when true. Nil or false imposes no restriction.
DisableAssistedPermissionsMode *bool `json:"disableAssistedPermissionsMode,omitempty"`
// Deny lists operations that must always be denied. Unioned across layers.
Deny []string `json:"deny,omitzero"`
// Ask lists operations that must prompt for approval. Unioned across layers.
Ask []string `json:"ask,omitzero"`
// Allow lists operations permitted without prompting. Every declared allow
// list across managed layers must admit an operation for it to be allowed.
Allow []string `json:"allow,omitzero"`
// LimitTo is a closed-world host boundary expressed as Domain(hostname),
// Domain(IP), or Domain(*.example.com) rules. Schemes, ports, paths,
// queries, and fragments are rejected. Multiple managed layers intersect
// their lists. A present empty list denies all hosts.
LimitTo []string `json:"limitTo,omitzero"`
}
ManagedSettingsPermissions is the permissions-only managed policy injected via ManagedSettings. Rule strings use the same vocabulary the runtime accepts for fetched managed policy (e.g. "Read(**)", "Shell(git push *)"); malformed rules are rejected by the runtime at session creation.
type ManagedSettingsResolvedData = rpc.ManagedSettingsResolvedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ManagedSettingsResolvedSource = rpc.ManagedSettingsResolvedSource
Session-event types are generated in the rpc package and aliased here for source compatibility.
type MemoryConfiguration struct {
// Enabled controls whether the memory feature is enabled for this session.
Enabled bool `json:"enabled"`
// Mode selects where memories are placed.
// "system-prompt" (default) places memories in the system prompt.
// "user-prompt" places memories in generated user-role messages.
// Experimental: this option may change or be removed in a future release.
Mode MemoryMode `json:"mode,omitempty"`
}
MemoryConfiguration configures the memory feature for a session.
type MemoryMode = rpc.MemoryMode
MemoryMode selects where retrieved memories are included in the model conversation. Experimental: this type may change or be removed in a future release.
type MessageOptions struct {
// ResponseSchema is a per-run JSON Schema. Independent sends do not inherit it.
// Immediate steering inherits the active format and must not specify its own.
// Use RPC.Send for schema name, description and strictness options.
ResponseSchema map[string]any
// Prompt is the message to send
Prompt string
// Source identifies the message origin independently of Mode and AgentMode.
// The empty value omits source from the request, preserving runtime defaults.
Source MessageSource
// Attachments are file or directory attachments
Attachments []Attachment
// Mode is the message delivery mode (default: "enqueue")
Mode string
// AgentMode is the UI mode the agent was in when this message was sent
// (for example "plan" or "autopilot"). Defaults to the session's current
// mode when empty.
AgentMode AgentMode
// RequestHeaders are custom per-turn HTTP headers for outbound model requests.
RequestHeaders map[string]string
// DisplayPrompt, if provided, is shown in the timeline instead of Prompt.
DisplayPrompt string
}
MessageOptions configures a message to send
type MessageSource string
MessageSource identifies whether a message originates from a user, the system, or an agent.
const ( // MessageSourceUser identifies a user-originated message. MessageSourceUser MessageSource = "user" // MessageSourceSystem identifies a system-originated message. MessageSourceSystem MessageSource = "system" )
func MessageSourceAgent(id string) MessageSource
MessageSourceAgent identifies the agent that produced a message. The agent ID is opaque and is sent unchanged after the "agent-" prefix.
type ModelBilling struct {
Multiplier *float64 `json:"multiplier,omitempty"`
TokenPrices *rpc.ModelBillingTokenPrices `json:"tokenPrices,omitempty"`
}
ModelBilling contains model billing information
type ModelCallFailureBadRequestKind = rpc.ModelCallFailureBadRequestKind
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ModelCallFailureData = rpc.ModelCallFailureData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ModelCallFailureKind = rpc.ModelCallFailureKind
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ModelCallFailureRequestFingerprint = rpc.ModelCallFailureRequestFingerprint
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ModelCallFailureSource = rpc.ModelCallFailureSource
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ModelCallFailureTransport = rpc.ModelCallFailureTransport
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ModelCallFinalResult = rpc.ModelCallFinalResult
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ModelCallFinalResultData = rpc.ModelCallFinalResultData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ModelCallFinishedData = rpc.ModelCallFinishedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ModelCallFinishedOutcome = rpc.ModelCallFinishedOutcome
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ModelCallRequestBodyCompressionFallback = rpc.ModelCallRequestBodyCompressionFallback
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ModelCallRequestBodyEncoding = rpc.ModelCallRequestBodyEncoding
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ModelCallStartData = rpc.ModelCallStartData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ModelCallWebSocketFallbackErrorKind = rpc.ModelCallWebSocketFallbackErrorKind
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ModelCallWebSocketFallbackReason = rpc.ModelCallWebSocketFallbackReason
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ModelCapabilities struct {
Supports ModelSupports `json:"supports"`
Limits ModelLimits `json:"limits"`
}
ModelCapabilities contains model capabilities and limits
type ModelCapabilitiesOverride = rpc.ModelCapabilitiesOverride
Type aliases for model capabilities overrides, re-exported from the rpc package for ergonomic use without requiring a separate rpc import.
type ModelCapabilitiesOverrideLimits = rpc.ModelCapabilitiesOverrideLimits
Type aliases for model capabilities overrides, re-exported from the rpc package for ergonomic use without requiring a separate rpc import.
type ModelCapabilitiesOverrideLimitsVision = rpc.ModelCapabilitiesOverrideLimitsVision
Type aliases for model capabilities overrides, re-exported from the rpc package for ergonomic use without requiring a separate rpc import.
type ModelCapabilitiesOverrideSupports = rpc.ModelCapabilitiesOverrideSupports
Type aliases for model capabilities overrides, re-exported from the rpc package for ergonomic use without requiring a separate rpc import.
type ModelChangeSource = rpc.ModelChangeSource
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ModelDeselectedReason = rpc.ModelDeselectedReason
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ModelInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Capabilities ModelCapabilities `json:"capabilities"`
Policy *ModelPolicy `json:"policy,omitempty"`
Billing *ModelBilling `json:"billing,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
SupportedReasoningEfforts []string `json:"supportedReasoningEfforts,omitempty"`
DefaultReasoningEffort string `json:"defaultReasoningEffort,omitempty"`
}
ModelInfo contains information about an available model
type ModelLimits struct {
MaxPromptTokens *int `json:"max_prompt_tokens,omitempty"`
MaxContextWindowTokens *int `json:"max_context_window_tokens,omitempty"`
Vision *ModelVisionLimits `json:"vision,omitempty"`
}
ModelLimits contains model limits
ModelPolicy contains model policy state
type ModelProviderKind = rpc.ModelProviderKind
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ModelProviderRef = rpc.ModelProviderRef
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ModelSupports struct {
Vision bool `json:"vision"`
ReasoningEffort bool `json:"reasoningEffort"`
}
ModelSupports contains model support flags
type ModelVisionLimits struct {
SupportedMediaTypes []string `json:"supported_media_types"`
MaxPromptImages int `json:"max_prompt_images"`
MaxPromptImageSize int `json:"max_prompt_image_size"`
}
ModelVisionLimits contains vision-specific limits
type NamedProviderConfig struct {
// Name is the stable identifier referenced by ProviderModelConfig.Provider.
// Must not contain "/".
Name string `json:"name"`
// Type is the provider type: "openai", "azure", or "anthropic". Defaults to "openai".
Type string `json:"type,omitempty"`
// WireAPI is the API format (openai/azure only): "completions" or "responses". Defaults to "completions".
WireAPI string `json:"wireApi,omitempty"`
// ModelProvider is the product serving this provider's models, reported in
// telemetry as model_provider. Allowed values are "openai", "anthropic",
// "azure_openai", "ollama", "lm_studio", "foundry_local", and "llama_cpp";
// only affects telemetry.
ModelProvider string `json:"modelProvider,omitempty"`
// BaseURL is the API endpoint URL.
BaseURL string `json:"baseUrl"`
// APIKey is the API key. Optional for local providers like Ollama.
APIKey string `json:"apiKey,omitempty"`
// BearerToken for authentication. Sets the Authorization header directly.
// Takes precedence over APIKey when both are set.
BearerToken string `json:"bearerToken,omitempty"`
// Azure contains Azure-specific options.
Azure *AzureProviderOptions `json:"azure,omitempty"`
// Headers are custom HTTP headers included in all outbound provider requests.
Headers map[string]string `json:"headers,omitempty"`
// BearerTokenProvider resolves a bearer token on demand for this provider
// (managed-identity / on-demand auth). When set, the SDK strips the callback
// from the wire config and instead sends `hasBearerTokenProvider: true`; the
// runtime calls back over the session-scoped `providerToken.getToken` RPC
// before each outbound model request and applies the returned token as the
// Authorization header. Never serialized.
//
// When set alongside APIKey/BearerToken, this callback takes precedence: the
// runtime applies the token it returns as the Authorization: Bearer header for
// each request and does not send the static credential.
//
// Experimental: part of the experimental managed-identity / bearer-token-provider
// surface and may change or be removed in future SDK or CLI releases.
BearerTokenProvider BearerTokenProvider `json:"-"`
}
NamedProviderConfig is a named BYOK provider connection (transport + credentials), referenced by ProviderModelConfig entries via Name.
Unlike the singular Provider (which makes the whole session BYOK and bypasses Copilot API authentication), named providers are additive: they coexist with Copilot API auth so models from CAPI and one or more BYOK providers can be mixed within a single session and across sub-agents. Combining Providers and Models with Provider is rejected.
Experimental: NamedProviderConfig is part of an experimental multi-provider BYOK surface and may change or be removed in future SDK or CLI releases.
func (p NamedProviderConfig) MarshalJSON() ([]byte, error)
MarshalJSON serializes the named provider config, deriving the wire-only `hasBearerTokenProvider` flag from the presence of NamedProviderConfig.BearerTokenProvider. The non-serializable callback never crosses the RPC boundary; the runtime only learns that a token provider exists and forwards the provider name back when it needs a token.
type OmittedBinaryOmittedReason = rpc.OmittedBinaryOmittedReason
Session-event types are generated in the rpc package and aliased here for source compatibility.
type OmittedBinaryResult = rpc.OmittedBinaryResult
Session-event types are generated in the rpc package and aliased here for source compatibility.
type OmittedBinaryType = rpc.OmittedBinaryType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PendingMessagesModifiedData = rpc.PendingMessagesModifiedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionApprovalEvaluation = rpc.PermissionApprovalEvaluation
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionApprovalEvaluationEvaluationStage = rpc.PermissionApprovalEvaluationEvaluationStage
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionApprovalEvaluationJudgeStatus = rpc.PermissionApprovalEvaluationJudgeStatus
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionApprovalEvaluationReasonCode = rpc.PermissionApprovalEvaluationReasonCode
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionApproved = rpc.PermissionApproved
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionApprovedForLocation = rpc.PermissionApprovedForLocation
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionApprovedForSession = rpc.PermissionApprovedForSession
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionApprovedReadOnlyForSession = rpc.PermissionApprovedReadOnlyForSession
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionAssentDetectedData = rpc.PermissionAssentDetectedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionAssistedApproval = rpc.PermissionAssistedApproval
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionCancelled = rpc.PermissionCancelled
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionCarriedForwardData = rpc.PermissionCarriedForwardData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionCompletedData = rpc.PermissionCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionContextualAuthorizationData = rpc.PermissionContextualAuthorizationData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionDecisionContext = rpc.PermissionDecisionContext
PermissionDecisionContext describes how and where a permission decision was reached. Attach it to a decision with NewAttributedPermissionResult so the runtime can attribute auto-approval telemetry to the responding surface. It is informational only and never changes permission behavior.
Experimental: PermissionDecisionContext is part of an experimental API and may change or be removed.
type PermissionDecisionOutcome = rpc.PermissionDecisionOutcome
PermissionDecisionOutcome describes the disposition of a permission request as observed by the responding client.
type PermissionDecisionSource = rpc.PermissionDecisionSource
PermissionDecisionSource identifies the controlled reason or actor responsible for a permission response.
type PermissionDecisionSurface = rpc.PermissionDecisionSurface
PermissionDecisionSurface identifies the client surface that submitted a permission response.
type PermissionDeniedByContentExclusionPolicy = rpc.PermissionDeniedByContentExclusionPolicy
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionDeniedByPermissionRequestHook = rpc.PermissionDeniedByPermissionRequestHook
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionDeniedByRules = rpc.PermissionDeniedByRules
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionDeniedInteractivelyByUser = rpc.PermissionDeniedInteractivelyByUser
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser = rpc.PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionHandlerFunc func(request PermissionRequest, invocation PermissionInvocation) (rpc.PermissionDecision, error)
PermissionHandlerFunc executes a permission request. The handler should return a rpc.PermissionDecision. Returning an error causes the SDK to respond with rpc.PermissionDecisionUserNotAvailable.
Use the variant types directly:
&rpc.PermissionDecisionApproveOnce{}
&rpc.PermissionDecisionReject{Feedback: &feedback}
&rpc.PermissionDecisionUserNotAvailable{}
&rpc.PermissionDecisionNoResult{} // decline to respond; another client may answer
type PermissionHandlerInvocation struct {
PermissionInvocation
// PromptRequest is the derived user-facing prompt supplied by newer runtimes.
// Only commands, read, write, url, and workflow prompts can clear a raw
// managed-approval requirement after Assisted approval. Missing and other
// prompt kinds must remain conservative.
PromptRequest rpc.PermissionPromptRequest
}
PermissionHandlerInvocation provides the complete context for a permission request, including the optional derived prompt.
type PermissionHandlerWithPromptFunc func(request PermissionRequest, invocation PermissionHandlerInvocation) (rpc.PermissionDecision, error)
PermissionHandlerWithPromptFunc executes a permission request with the optional derived user-facing prompt supplied by newer runtimes.
PermissionInvocation provides context about a permission request.
This type retains its original two-field shape for source compatibility with existing positional composite literals.
type PermissionMessageAuthorizationData = rpc.PermissionMessageAuthorizationData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionMessageAuthorizationDegradedData = rpc.PermissionMessageAuthorizationDegradedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionMessageAuthorizationPolarity = rpc.PermissionMessageAuthorizationPolarity
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionMessageAuthorizationReadData = rpc.PermissionMessageAuthorizationReadData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionMode = rpc.PermissionMode
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequest = rpc.PermissionPromptRequest
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestCommands = rpc.PermissionPromptRequestCommands
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestCustomTool = rpc.PermissionPromptRequestCustomTool
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestExtensionEnvAccess = rpc.PermissionPromptRequestExtensionEnvAccess
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestExtensionManagement = rpc.PermissionPromptRequestExtensionManagement
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestExtensionPermissionAccess = rpc.PermissionPromptRequestExtensionPermissionAccess
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestHook = rpc.PermissionPromptRequestHook
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestKind = rpc.PermissionPromptRequestKind
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestMCP = rpc.PermissionPromptRequestMCP
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestMemory = rpc.PermissionPromptRequestMemory
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestPath = rpc.PermissionPromptRequestPath
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestPathAccessKind = rpc.PermissionPromptRequestPathAccessKind
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestRead = rpc.PermissionPromptRequestRead
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestURL = rpc.PermissionPromptRequestURL
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestWorkflow = rpc.PermissionPromptRequestWorkflow
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionPromptRequestWrite = rpc.PermissionPromptRequestWrite
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRecommendation = rpc.PermissionRecommendation
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRecoveryAttempt = rpc.PermissionRecoveryAttempt
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRecoveryAttemptDisposition = rpc.PermissionRecoveryAttemptDisposition
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRecoveryAttemptReason = rpc.PermissionRecoveryAttemptReason
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRecoveryAttemptRelation = rpc.PermissionRecoveryAttemptRelation
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRecoveryData = rpc.PermissionRecoveryData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRecoveryOnBlocked = rpc.PermissionRecoveryOnBlocked
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRecoveryReason = rpc.PermissionRecoveryReason
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRecoveryStatus = rpc.PermissionRecoveryStatus
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequest = rpc.PermissionRequest
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestCommand = rpc.PermissionRequestCommand
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestCustomTool = rpc.PermissionRequestCustomTool
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestExtensionEnvAccess = rpc.PermissionRequestExtensionEnvAccess
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestExtensionManagement = rpc.PermissionRequestExtensionManagement
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestExtensionPermissionAccess = rpc.PermissionRequestExtensionPermissionAccess
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestHook = rpc.PermissionRequestHook
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestKind = rpc.PermissionRequestKind
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestMCP = rpc.PermissionRequestMCP
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestMemory = rpc.PermissionRequestMemory
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestMemoryAction = rpc.PermissionRequestMemoryAction
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestMemoryDirection = rpc.PermissionRequestMemoryDirection
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestMemoryScope = rpc.PermissionRequestMemoryScope
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestRead = rpc.PermissionRequestRead
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestShell = rpc.PermissionRequestShell
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestShellCommand = rpc.PermissionRequestShellCommand
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestShellCommandSegment = rpc.PermissionRequestShellCommandSegment
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestShellPossibleURL = rpc.PermissionRequestShellPossibleURL
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestURL = rpc.PermissionRequestURL
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestWorkflow = rpc.PermissionRequestWorkflow
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestWrite = rpc.PermissionRequestWrite
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRequestedData = rpc.PermissionRequestedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionResponseCapability = rpc.PermissionResponseCapability
PermissionResponseCapability describes whether the responding client could ask a user for a permission decision.
type PermissionResult = rpc.PermissionResult
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionResultKind = rpc.PermissionResultKind
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionRule = rpc.PermissionRule
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionSandboxPathGrant = rpc.PermissionSandboxPathGrant
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionSandboxPathGrantAccess = rpc.PermissionSandboxPathGrantAccess
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionWriteFileContent = rpc.PermissionWriteFileContent
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PermissionWriteFileEdit = rpc.PermissionWriteFileEdit
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PersistedBinaryImage = rpc.PersistedBinaryImage
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PersistedBinaryImageType = rpc.PersistedBinaryImageType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PersistedBinaryResult = rpc.PersistedBinaryResult
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PersistedBinaryResultType = rpc.PersistedBinaryResultType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PingResponse struct {
Message string `json:"message"`
Timestamp time.Time `json:"timestamp"`
ProtocolVersion *int `json:"protocolVersion,omitempty"`
}
PingResponse is the response from a ping request
type PlanChangedOperation = rpc.PlanChangedOperation
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PossibleURL = rpc.PossibleURL
Session-event types are generated in the rpc package and aliased here for source compatibility.
type PostToolUseFailureHandler func(input PostToolUseFailureHookInput, invocation HookInvocation) (*PostToolUseFailureHookOutput, error)
PostToolUseFailureHandler handles post-tool-use-failure hook invocations.
type PostToolUseFailureHookInput struct {
AgentID string `json:"agentId,omitempty"`
AgentType string `json:"agentType,omitempty"`
ParentAgentID string `json:"parentAgentId,omitempty"`
SessionID string `json:"sessionId"`
Timestamp time.Time `json:"-"`
WorkingDirectory string `json:"cwd"`
ToolName string `json:"toolName"`
ToolArgs any `json:"toolArgs"`
// Error is the failure message from the tool's result.
Error string `json:"error"`
}
PostToolUseFailureHookInput is the input for a post-tool-use-failure hook.
Fires after a tool execution whose result was "failure". The CLI extracts the failure message from the tool result and passes it as the Error field (rather than passing the full result object).
func (h PostToolUseFailureHookInput) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (h *PostToolUseFailureHookInput) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
type PostToolUseFailureHookOutput struct {
AdditionalContext string `json:"additionalContext,omitempty"`
}
PostToolUseFailureHookOutput is the output for a post-tool-use-failure hook.
Only AdditionalContext is consumed by the host CLI — it is appended as hidden guidance to the model alongside the failed tool result.
type PostToolUseHandler func(input PostToolUseHookInput, invocation HookInvocation) (*PostToolUseHookOutput, error)
PostToolUseHandler handles post-tool-use hook invocations
type PostToolUseHookInput struct {
AgentID string `json:"agentId,omitempty"`
AgentType string `json:"agentType,omitempty"`
ParentAgentID string `json:"parentAgentId,omitempty"`
SessionID string `json:"sessionId"`
Timestamp time.Time `json:"-"`
WorkingDirectory string `json:"cwd"`
ToolName string `json:"toolName"`
ToolArgs any `json:"toolArgs"`
ToolResult any `json:"toolResult"`
}
PostToolUseHookInput is the input for a post-tool-use hook
func (h PostToolUseHookInput) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (h *PostToolUseHookInput) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
type PostToolUseHookOutput struct {
ModifiedResult any `json:"modifiedResult,omitempty"`
AdditionalContext string `json:"additionalContext,omitempty"`
SuppressOutput bool `json:"suppressOutput,omitempty"`
}
PostToolUseHookOutput is the output for a post-tool-use hook
type PreMCPToolCallHandler func(input PreMCPToolCallHookInput, invocation HookInvocation) (*PreMCPToolCallHookOutput, error)
PreMCPToolCallHandler handles pre-mcp-tool-call hook invocations
type PreMCPToolCallHookInput struct {
AgentID string `json:"agentId,omitempty"`
AgentType string `json:"agentType,omitempty"`
ParentAgentID string `json:"parentAgentId,omitempty"`
SessionID string `json:"sessionId"`
Timestamp time.Time `json:"-"`
WorkingDirectory string `json:"cwd"`
ServerName string `json:"serverName"`
ToolName string `json:"toolName"`
Arguments any `json:"arguments,omitempty"`
ToolCallID string `json:"toolCallId,omitempty"`
Meta any `json:"_meta,omitempty"`
}
PreMCPToolCallHookInput is the input for a pre-mcp-tool-call hook
func (h PreMCPToolCallHookInput) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (h *PreMCPToolCallHookInput) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
type PreMCPToolCallHookOutput struct {
MetaToUse any `json:"metaToUse"`
}
PreMCPToolCallHookOutput is the output for a pre-mcp-tool-call hook
type PreToolUseHandler func(input PreToolUseHookInput, invocation HookInvocation) (*PreToolUseHookOutput, error)
PreToolUseHandler handles pre-tool-use hook invocations
type PreToolUseHookInput struct {
AgentID string `json:"agentId,omitempty"`
AgentType string `json:"agentType,omitempty"`
ParentAgentID string `json:"parentAgentId,omitempty"`
SessionID string `json:"sessionId"`
Timestamp time.Time `json:"-"`
WorkingDirectory string `json:"cwd"`
ToolName string `json:"toolName"`
ToolArgs any `json:"toolArgs"`
}
PreToolUseHookInput is the input for a pre-tool-use hook
func (h PreToolUseHookInput) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (h *PreToolUseHookInput) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
type PreToolUseHookOutput struct {
PermissionDecision string `json:"permissionDecision,omitempty"` // "allow", "deny", "ask"
PermissionDecisionReason string `json:"permissionDecisionReason,omitempty"`
ModifiedArgs any `json:"modifiedArgs,omitempty"`
AdditionalContext string `json:"additionalContext,omitempty"`
SuppressOutput bool `json:"suppressOutput,omitempty"`
}
PreToolUseHookOutput is the output for a pre-tool-use hook
type PromptCacheBreakData = rpc.PromptCacheBreakData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ProviderConfig struct {
// Type is the provider type: "openai", "azure", or "anthropic". Defaults to "openai".
Type string `json:"type,omitempty"`
// WireAPI is the API format (openai/azure only): "completions" or "responses". Defaults to "completions".
WireAPI string `json:"wireApi,omitempty"`
// Transport for OpenAI Responses requests: "http" or "websockets". Defaults to "http".
// Set "websockets" to deliver Responses API requests over a persistent WebSocket
// connection instead of HTTP. Applies to OpenAI-compatible providers using WireAPI "responses".
Transport string `json:"transport,omitempty"`
// ModelProvider is the product serving the model, reported in telemetry as
// model_provider. Allowed values are "openai", "anthropic", "azure_openai",
// "ollama", "lm_studio", "foundry_local", and "llama_cpp"; only affects telemetry.
ModelProvider string `json:"modelProvider,omitempty"`
// BaseURL is the API endpoint URL
BaseURL string `json:"baseUrl"`
// APIKey is the API key. Optional for local providers like Ollama.
APIKey string `json:"apiKey,omitempty"`
// APIKeyCommand is run by the runtime before each provider request to obtain
// a fresh API key. Command failures fail the turn before sending a model request.
APIKeyCommand string `json:"apiKeyCommand,omitempty"`
// BearerToken for authentication. Sets the Authorization header directly.
// Use this for services requiring bearer token auth instead of API key.
// Takes precedence over APIKey when both are set.
BearerToken string `json:"bearerToken,omitempty"`
// Azure contains Azure-specific options
Azure *AzureProviderOptions `json:"azure,omitempty"`
// Headers are custom HTTP headers included in outbound provider requests.
Headers map[string]string `json:"headers,omitempty"`
// ModelID is the well-known model name used by the runtime to look up
// agent configuration (tools, prompts, reasoning behavior) and default
// token limits. Also used as the wire model when WireModel is not set.
// Falls back to SessionConfig.Model.
ModelID string `json:"modelId,omitempty"`
// WireModel is the model name sent to the provider API for inference. Use
// this when the provider's model name (e.g. an Azure deployment name or a
// custom fine-tune name) differs from ModelID.
// Falls back to ModelID, then SessionConfig.Model.
WireModel string `json:"wireModel,omitempty"`
// MaxPromptTokens overrides the resolved model's default max prompt tokens.
// The runtime triggers conversation compaction before sending a request
// when the prompt (system message, history, tool definitions, user
// message) would exceed this limit.
MaxPromptTokens int `json:"maxPromptTokens,omitempty"`
// MaxOutputTokens overrides the resolved model's default max output
// tokens. When hit, the model stops generating and returns a truncated
// response.
MaxOutputTokens int `json:"maxOutputTokens,omitempty"`
// BearerTokenProvider resolves a bearer token on demand for this provider
// (managed-identity / on-demand auth). When set, the SDK strips the callback
// from the wire config and instead sends `hasBearerTokenProvider: true`; the
// runtime calls back over the session-scoped `providerToken.getToken` RPC
// before each outbound model request and applies the returned token as the
// Authorization header. Never serialized.
//
// When set alongside APIKey, APIKeyCommand, or BearerToken, this callback
// takes precedence: the
// runtime applies the token it returns as the Authorization: Bearer header for
// each request without sending the static credential or running the command.
//
// Experimental: part of the experimental managed-identity / bearer-token-provider
// surface and may change or be removed in future SDK or CLI releases.
BearerTokenProvider BearerTokenProvider `json:"-"`
}
func (p ProviderConfig) MarshalJSON() ([]byte, error)
MarshalJSON serializes the provider config, deriving the wire-only `hasBearerTokenProvider` flag from the presence of ProviderConfig.BearerTokenProvider. The non-serializable callback never crosses the RPC boundary; the runtime only learns that a token provider exists and forwards the provider name back when it needs a token.
type ProviderModelConfig struct {
// ID is the provider-local model id, unique within its provider.
ID string `json:"id"`
// Provider is the name of the NamedProviderConfig that serves this model.
Provider string `json:"provider"`
// WireModel is the model name sent to the provider API for inference. Defaults to ID.
WireModel string `json:"wireModel,omitempty"`
// ModelID is the well-known base model id used for behavior/capability/config lookup. Defaults to ID.
ModelID string `json:"modelId,omitempty"`
// Name is the display name for model pickers. Defaults to the provider-qualified selection id.
Name string `json:"name,omitempty"`
// MaxPromptTokens is the maximum prompt/input tokens for the model.
MaxPromptTokens int `json:"maxPromptTokens,omitempty"`
// MaxContextWindowTokens is the maximum context window tokens for the model.
MaxContextWindowTokens int `json:"maxContextWindowTokens,omitempty"`
// MaxOutputTokens is the maximum output tokens for the model.
MaxOutputTokens int `json:"maxOutputTokens,omitempty"`
// Capabilities holds optional capability overrides for the synthesized model.
Capabilities *rpc.ModelCapabilitiesOverride `json:"capabilities,omitempty"`
}
ProviderModelConfig is a BYOK model definition that references a NamedProviderConfig by name and is added to the session's selectable model list. The session-wide selection id is the provider-qualified "provider/id".
Experimental: ProviderModelConfig is part of an experimental multi-provider BYOK surface and may change or be removed in future SDK or CLI releases.
type ProviderMonthlyUsage = rpc.ProviderMonthlyUsage
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ProviderMonthlyUsageScope = rpc.ProviderMonthlyUsageScope
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ProviderMonthlyUsageState = rpc.ProviderMonthlyUsageState
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ProviderQuotaAccessState = rpc.ProviderQuotaAccessState
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ProviderQuotaAcquisitionStatus = rpc.ProviderQuotaAcquisitionStatus
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ProviderQuotaBudgetMetadata = rpc.ProviderQuotaBudgetMetadata
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ProviderQuotaCapacityState = rpc.ProviderQuotaCapacityState
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ProviderQuotaObservationKind = rpc.ProviderQuotaObservationKind
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ProviderQuotaQuantityKind = rpc.ProviderQuotaQuantityKind
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ProviderQuotaState = rpc.ProviderQuotaState
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ProviderQuotaUnit = rpc.ProviderQuotaUnit
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ProviderTokenArgs struct {
// ProviderName is the name of the BYOK provider needing a token. For the
// singular, whole-session [ProviderConfig] this is the implicit provider name
// ("default"); for [NamedProviderConfig] entries it is
// [NamedProviderConfig.Name].
//
// The callback closes over its own token scope/audience; the runtime is
// provider-agnostic and forwards only the provider name.
ProviderName string
// SessionID is the id of the session that triggered this token request. A
// client-level shared callback registered for many sessions can use this to
// resolve the owning session and scope token acquisition or caching per
// session.
SessionID string
}
ProviderTokenArgs carries the context passed to a BearerTokenProvider callback when the runtime needs a fresh bearer token for a BYOK provider.
Experimental: ProviderTokenArgs is part of the experimental managed-identity / bearer-token-provider surface and may change or be removed in future SDK or CLI releases.
RPCError is the SDK's JSON-RPC transport error. Use errors.As to retrieve it from errors wrapped by SDK operations. It represents remote error responses and locally synthesized errors when an inline response callback fails; its type alone does not establish provenance.
Code and Message contain the JSON-RPC error code and message. Data contains the optional JSON value, which can be an object, array, or scalar. Omitted data is nil; explicit JSON null is the JSON text "null". Error() does not include Data.
RPCError is an alias of the transport error, preserving its identity and existing wrapping behavior. Its exported fields are part of the public API. The fields and Data bytes are shared with the error chain; copy before mutation.
type RawCitationLocation = rpc.RawCitationLocation
Session-event types are generated in the rpc package and aliased here for source compatibility.
type RawHumanResponseRecordedResponse = rpc.RawHumanResponseRecordedResponse
Session-event types are generated in the rpc package and aliased here for source compatibility.
type RawPermissionPromptRequest = rpc.RawPermissionPromptRequest
Session-event types are generated in the rpc package and aliased here for source compatibility.
type RawPermissionRequest = rpc.RawPermissionRequest
Session-event types are generated in the rpc package and aliased here for source compatibility.
type RawPermissionResult = rpc.RawPermissionResult
Session-event types are generated in the rpc package and aliased here for source compatibility.
type RawPersistedBinaryResult = rpc.RawPersistedBinaryResult
Session-event types are generated in the rpc package and aliased here for source compatibility.
type RawSessionEventData = rpc.RawSessionEventData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type RawSystemNotification = rpc.RawSystemNotification
Session-event types are generated in the rpc package and aliased here for source compatibility.
type RawSystemNotificationWorkflowPauseInfo = rpc.RawSystemNotificationWorkflowPauseInfo
Session-event types are generated in the rpc package and aliased here for source compatibility.
type RawToolExecutionCompleteContent = rpc.RawToolExecutionCompleteContent
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ReasoningSummary = rpc.ReasoningSummary
Session-event types are generated in the rpc package and aliased here for source compatibility.
type RecommendedAutoTier = rpc.RecommendedAutoTier
Session-event types are generated in the rpc package and aliased here for source compatibility.
type RemediationAction = rpc.RemediationAction
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ResponsesReasoning = rpc.ResponsesReasoning
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ResumeSessionConfig struct {
// ClientName identifies the application using the SDK.
// Included in the User-Agent header for API requests.
ClientName string
// GitHubTokenProvider acquires session-scoped GitHub tokens on demand. It
// cannot be combined with GitHubToken.
GitHubTokenProvider GitHubTokenProvider
// Model to use for this session. Can change the model when resuming.
Model string
// Tools exposes caller-implemented tools to the CLI. A Tool with a nil Handler
// is declaration-only; the consumer must resolve its calls via pending tool RPCs.
Tools []Tool
// SystemMessage configures system message customization
SystemMessage *SystemMessageConfig
// AvailableTools is a list of tool names to allow. When specified, only these tools will be available.
// Takes precedence over ExcludedTools.
AvailableTools []string
// ExcludedTools is a list of tool names to disable. All other tools remain available.
// Ignored if AvailableTools is specified.
ExcludedTools []string
// ExcludedBuiltInAgents is a list of built-in agent names to exclude from
// the session. Excluded built-in agents are hidden from discovery and cannot
// be selected or invoked unless a custom agent with the same name is
// configured.
ExcludedBuiltInAgents []string
// IncludedBuiltinSkills is the allowlist of runtime-bundled skill names.
// In ModeEmpty, nil excludes all built-in skills; a non-nil list opts the
// named built-ins back in. Skills from other sources remain eligible.
IncludedBuiltinSkills []string
// Provider configures a custom model provider
Provider *ProviderConfig
// Capi configures provider-scoped CAPI (Copilot API) session options.
Capi *CapiSessionOptions
// Providers configures named BYOK provider connections. Additive to Copilot
// API auth (unlike Provider); combine with Models. Cannot be combined with Provider.
//
// Experimental: Providers is part of an experimental multi-provider BYOK
// surface and may change or be removed in future SDK or CLI releases.
Providers []NamedProviderConfig
// Models adds BYOK model definitions to the session's selectable model list,
// each referencing a Providers entry by name.
//
// Experimental: Models is part of an experimental multi-provider BYOK
// surface and may change or be removed in future SDK or CLI releases.
Models []ProviderModelConfig
// EnableSessionTelemetry enables or disables internal session telemetry for this session.
// When false, disables session telemetry. When nil (the default) or true,
// telemetry is enabled for GitHub-authenticated sessions. When a custom
// Provider (BYOK) is configured, session telemetry is always disabled
// regardless of this setting. This is independent of the OpenTelemetry
// configuration in ClientOptions.Telemetry.
EnableSessionTelemetry *bool
// EnableCitations enables native model citations for supported providers.
//
// Experimental: EnableCitations is part of an experimental model capability
// surface and may change or be removed in future SDK or CLI releases.
EnableCitations *bool
// EnableFileChangeTracking opts in to capturing file changes for session
// rewind and cumulative session diff when the resumed session has a valid
// baseline. Earlier untracked changes cannot be reconstructed.
EnableFileChangeTracking *bool
// SessionLimits applies limits to this session's current accounting window.
//
// Experimental: SessionLimits is part of an experimental runtime accounting
// surface and may change or be removed in future SDK or CLI releases.
SessionLimits *rpc.SessionLimitsConfig
// Autopilot patches resident policy on warm resume; re-supply on cold resume.
// Does not change the session mode.
// Experimental: this policy may change in a future release.
Autopilot *rpc.AutopilotOptions
// EnableExperimentalMode controls whether the session enables experimental
// features. When nil, it defaults to false in [ModeEmpty]; otherwise the
// runtime decides.
EnableExperimentalMode *bool
// SkipCustomInstructions, when non-nil, controls whether the runtime loads
// custom instruction files. See also [ClientOptions.Mode] = [ModeEmpty].
SkipCustomInstructions *bool
// CustomAgentsLocalOnly, when non-nil, restricts custom agents to those
// defined locally. See also [ClientOptions.Mode] = [ModeEmpty].
CustomAgentsLocalOnly *bool
// exposed. See also [ClientOptions.Mode] = [ModeEmpty].
CoauthorEnabled *bool
// ManageScheduleEnabled, when non-nil, controls whether the
// `manage_schedule` tool is exposed. See also [ClientOptions.Mode] =
// [ModeEmpty].
ManageScheduleEnabled *bool
// ModelCapabilities overrides individual model capabilities resolved by the runtime.
// Only non-nil fields are applied over the runtime-resolved capabilities.
ModelCapabilities *rpc.ModelCapabilitiesOverride
// ReasoningEffort level for models that support it.
// Valid values: "low", "medium", "high", "xhigh", "max"
ReasoningEffort string
// ReasoningSummary mode for models that support configurable reasoning summaries.
// Use ReasoningSummaryNone to suppress summary output regardless of whether reasoning is enabled.
ReasoningSummary ReasoningSummary
// ContextTier pins the session to a context window tier for models that support it.
// Use ContextTierDefault or ContextTierLongContext for the currently known tiers.
ContextTier ContextTier
// OnPermissionRequest is an optional handler for permission requests from the server.
// When nil, permission requests are surfaced as events and left pending for the
// consumer to resolve via pending permission RPCs.
OnPermissionRequest PermissionHandlerFunc
// OnPermissionRequestWithPrompt receives the optional derived user-facing
// prompt supplied by newer runtimes. When both permission handlers are set,
// this handler takes precedence.
OnPermissionRequestWithPrompt PermissionHandlerWithPromptFunc
// OnMCPAuthRequest is an optional handler for MCP OAuth requests from MCP servers.
// See SessionConfig.OnMCPAuthRequest.
OnMCPAuthRequest MCPAuthHandler
// OnUserInputRequest handles legacy question-and-answer requests from the agent
// and enables the legacy ask_user tool.
OnUserInputRequest UserInputHandler
// AskUserVariant selects the model-facing shape of the ask_user tool.
// The zero value preserves legacy behavior. AskUserVariantElicitation also
// requires OnElicitationRequest so the host can answer structured forms.
AskUserVariant AskUserVariant
// Hooks configures hook handlers for session lifecycle events
Hooks *SessionHooks
// WorkingDirectory is the working directory for the session.
// Tool operations will be relative to this directory.
WorkingDirectory string
// AdditionalDirectories are directories the agent may access beyond WorkingDirectory.
// Relative paths are resolved against WorkingDirectory. Re-supply them when resuming.
AdditionalDirectories []string
// ConfigDirectory overrides the default configuration directory location.
ConfigDirectory string
// EnableConfigDiscovery enables runtime discovery of supported configuration.
// Explicitly supplied configuration takes precedence over discovered values.
// Nil leaves the runtime default unchanged; use Bool(false) to explicitly disable discovery.
EnableConfigDiscovery *bool
// SkipEmbeddingRetrieval, when non-nil, controls embedding-based retrieval
// for this session. Use in multitenant deployments to prevent cross-session
// information leakage through the shared embedding cache.
SkipEmbeddingRetrieval *bool
// EmbeddingCacheStorage controls how the embedding cache is stored for this session.
// "persistent" caches on disk and shares across sessions/restarts.
// "in-memory" caches in memory only and discards when the session ends.
EmbeddingCacheStorage *string
// OrganizationCustomInstructions provides organization-level custom instructions
// to include in the system prompt.
OrganizationCustomInstructions *string
// EnableOnDemandInstructionDiscovery, when non-nil, controls on-demand discovery
// of instruction files after successful file views.
EnableOnDemandInstructionDiscovery *bool
// EnableFileHooks, when non-nil, controls repository-origin file hooks from
// .github/hooks/ and trusted repository-configured roots. It does not control
// explicit HookDirectories or Hooks callbacks.
EnableFileHooks *bool
// EnableHostGitOperations, when non-nil, controls git operations on the host
// filesystem.
EnableHostGitOperations *bool
// EnableSessionStore, when non-nil, controls the cross-session store for search
// and retrieval across sessions.
EnableSessionStore *bool
// EnableSkills, when non-nil, controls skill loading.
EnableSkills *bool
// Streaming enables streaming of assistant message and reasoning chunks.
// When non-nil and true, assistant.message_delta and assistant.reasoning_delta
// events with deltaContent are sent as the response is generated.
// When nil, the runtime decides (currently defaults to non-streaming).
Streaming *bool
// IncludeSubAgentStreamingEvents includes sub-agent streaming events in the
// event stream. When true, streaming delta events from sub-agents (e.g.,
// assistant.message_delta, assistant.reasoning_delta, assistant.streaming_delta
// with agentId set) are forwarded to this connection. When false, only
// non-streaming sub-agent events and subagent.* lifecycle events are forwarded;
// streaming deltas from sub-agents are suppressed. When nil, defaults to true.
IncludeSubAgentStreamingEvents *bool
// MCPServers configures MCP servers for the session
MCPServers map[string]MCPServerConfig
// Diagnostics updates explicitly configured sources. Leave it nil on a
// resident resume to preserve the current settings.
Diagnostics *rpc.DiagnosticsConfiguration
// MCPOAuthTokenStorage controls how MCP OAuth tokens are stored for this session.
// When empty, the runtime default ("in-memory") is used.
MCPOAuthTokenStorage string
// AuthClientIDMetadataURL identifies the host for MCP OAuth authorization.
// When empty, no host identity is supplied.
AuthClientIDMetadataURL string
// CustomAgents configures custom agents for the session
CustomAgents []CustomAgentConfig
// DefaultAgent configures the default agent (the built-in agent that handles turns when no custom agent is selected).
DefaultAgent *DefaultAgentConfig
// Agent is the name of the custom agent to activate when the session starts.
// Must match the Name of one of the agents in CustomAgents.
Agent string
// SkillDirectories contains explicit discovery-only skill roots, not filesystem grants.
// Available without EnableConfigDiscovery, subject to skill/managed disables.
// Relative paths resolve once when supplied against the request's effective WorkingDirectory;
// retained roots do not move on cwd changes. Nil and omission are equivalent;
// an empty non-nil list clears only the explicit SDK contribution.
SkillDirectories []string
// SkillProvider supplies ephemeral SDK-hosted skills for this resumed
// session. Re-supply it on every resume; omitting it unbinds any previous
// provider.
//
// Experimental: this API may change or be removed in future SDK or CLI
// releases. Implementations must be safe for concurrent calls.
SkillProvider SkillProvider `json:"-"`
// AgentDirectories contains explicit discovery-only agent roots, separate from CustomAgents.
// No filesystem grant. Available without EnableConfigDiscovery, subject to source/managed
// disables. Relative paths resolve once when supplied against the request's effective
// WorkingDirectory; retained roots do not move. Nil and omission are equivalent;
// an empty non-nil list clears only the explicit SDK contribution.
AgentDirectories []string
// HookDirectories contains explicit discovery-only file-hook roots, separate from Hooks callbacks.
// No filesystem grant. Available without EnableConfigDiscovery or EnableFileHooks
// (repository-origin hooks only), subject to hook/managed disables. Relative paths resolve
// once when supplied against the request's effective WorkingDirectory; retained roots do not
// move. Nil and omission are equivalent; an empty non-nil list clears only the explicit SDK contribution.
HookDirectories []string
// PluginDirectories is a list of local filesystem paths to Open Plugins-format
// directories (https://open-plugins.com/) to load for this session.
// Relative paths resolve against WorkingDirectory (or the runtime cwd if unset).
// Treated as an explicit opt-in: plugin agents and rules load even when
// EnableConfigDiscovery is false.
PluginDirectories []string
// InstructionDirectories contains explicit discovery-only instruction roots using existing SDK formats.
// No filesystem grant. Available without EnableConfigDiscovery, subject to instruction/managed
// disables. Relative paths resolve once when supplied against the request's effective
// WorkingDirectory; retained roots do not move. Nil and omission are equivalent;
// an empty non-nil list clears only the explicit SDK contribution.
InstructionDirectories []string
// DisabledSkills is a list of skill names to disable
DisabledSkills []string
// DisabledMCPServers is a list of exact MCP server names to disable for this session.
// Disabled servers are not started or authenticated on create or cold resume.
// A resident resume cannot stop servers that are already running.
DisabledMCPServers []string
// SandboxConfig is applied when the session is constructed, before MCP servers start.
// Same shape as the sandboxConfig option of session options update;
// an identical later update is a no-op.
SandboxConfig *rpc.SandboxConfig
// InfiniteSessions configures infinite sessions for persistent workspaces and automatic compaction.
InfiniteSessions *InfiniteSessionConfig
// LargeOutput configures handling of large tool outputs. When a tool produces
// output exceeding the configured size, the output is written to a temp file
// and a reference is returned to the model instead of the full payload.
LargeOutput *LargeToolOutputConfig
// ToolSearch overrides the runtime's built-in tool-search behavior, which
// defers rarely used tools behind a searchable index. When nil, the runtime
// default applies.
ToolSearch *ToolSearchConfig
// ImageGeneration is the non-persisted image generation opt-in.
// Experimental: this API may change or be removed in a future release.
ImageGeneration *ImageGenerationConfig
// Memory configures the memory feature for the session. When omitted, the
// runtime default applies.
Memory *MemoryConfiguration
// GitHubToken is an optional per-session GitHub token used for authentication.
// When provided, the session authenticates as the token's owner instead of
// using the global client-level auth.
GitHubToken string `json:"-"`
// SuppressResumeEvent, when true, skips emitting the session.resume event.
// Useful for reconnecting to a session without triggering resume-related side effects.
SuppressResumeEvent bool
// ContinuePendingWork, when non-nil, controls whether the runtime continues any
// tool calls or permission prompts that were still pending when the session was
// last suspended. Nil leaves the runtime default unchanged; use Bool(false) to
// explicitly treat pending work as interrupted on resume. Completed tool results
// already durably recorded by the runtime are preserved.
//
// For permission requests, the runtime re-emits permission.requested so the
// registered OnPermissionRequest handler can re-prompt; for external tool calls,
// the consumer is expected to supply the result via the corresponding low-level
// RPC method.
ContinuePendingWork *bool
// AllowTranscriptRecovery controls whether resume repairs a damaged transcript.
// Nil uses the runtime default (true) in all modes. Set false to reject recovery.
// Recovery may discard a torn tail; inspect Session.TranscriptRecovery().
AllowTranscriptRecovery *bool
// OnEvent is an optional event handler registered before the session.resume RPC
// is issued, ensuring early events are delivered. See SessionConfig.OnEvent.
OnEvent SessionEventHandler
// CreateSessionFSProvider supplies a handler for session filesystem operations.
// This takes effect only when ClientOptions.SessionFS is configured.
CreateSessionFSProvider func(session *Session) SessionFSProvider
// Commands registers slash-commands for this session. See SessionConfig.Commands.
Commands []CommandDefinition
// OnElicitationRequest is a handler for elicitation requests from the server.
// See SessionConfig.OnElicitationRequest.
OnElicitationRequest ElicitationHandler
// OnExitPlanModeRequest is a handler for exit-plan-mode requests from the server.
// See SessionConfig.OnExitPlanModeRequest.
OnExitPlanModeRequest ExitPlanModeRequestHandler
// OnAutoModeSwitchRequest is a handler for auto-mode-switch requests from the server.
// See SessionConfig.OnAutoModeSwitchRequest.
OnAutoModeSwitchRequest AutoModeSwitchRequestHandler
// EnableMCPApps enables MCP Apps (SEP-1865) UI passthrough on resume.
// See SessionConfig.EnableMCPApps.
//
// Experimental: EnableMCPApps is part of an experimental wire-protocol
// surface (SEP-1865) and may change or be removed in a future release.
EnableMCPApps bool
// GitHubMCPToolConfig configures the built-in GitHub MCP server.
// DisableFormDeferral only applies to that server and only has an effect
// when MCP Apps and form-backed GitHub tools are enabled.
GitHubMCPToolConfig *GitHubMCPToolConfig
// Canvases declares canvases this session provides. Sent over the wire on
// `session.resume`. See SessionConfig.Canvases.
Canvases []CanvasDeclaration
// OpenCanvases declares canvas instances the caller knows were open before
// this resume so the runtime can re-attach them. Sent over the wire on
// `session.resume` as `openCanvases`.
OpenCanvases []rpc.OpenCanvasInstance
// RequestCanvasRenderer asks the host to enable canvas rendering for this session.
RequestCanvasRenderer *bool
// RequestExtensions asks the host to surface declared canvases as agent-visible extensions.
RequestExtensions *bool
// ExtensionSDKPath optionally overrides the bundled `@github/copilot-sdk` drop
// injected into extension subprocesses. See SessionConfig.ExtensionSDKPath.
ExtensionSDKPath *string
// CanvasHandler receives inbound canvas.* requests for this session. See SessionConfig.CanvasHandler.
CanvasHandler CanvasHandler `json:"-"`
// ExtensionInfo identifies the stable extension providing this session's canvases.
ExtensionInfo *ExtensionInfo
// CanvasProvider is the stable identity for a host/SDK connection that
// supplies built-in canvases. See SessionConfig.CanvasProvider.
CanvasProvider *CanvasProviderIdentity
// ExpAssignments injects ExP assignment ("flight") data on resume. See
// SessionConfig.ExpAssignments. Re-supply on resume so the runtime
// re-applies the assignments after a CLI process restart.
//
// Internal: ExpAssignments is part of the SDK's internal API surface,
// intended for trusted out-of-process integrators, and is not intended for
// general external use.
ExpAssignments *CopilotExpAssignmentResponse
// FeatureFlags contains host-resolved feature-flag values to apply on resume.
// See SessionConfig.FeatureFlags.
FeatureFlags map[string]bool
// EnableManagedSettings injects the same opt-in flag on resume. See
// SessionConfig.EnableManagedSettings. Re-supply on resume so the runtime
// re-applies the managed-settings self-fetch after a CLI process restart.
EnableManagedSettings *bool
// ExcludedManagedSettings excludes setting paths as on SessionConfig.
// Omitting it restores full enforcement on warm and cold resume.
ExcludedManagedSettings []string
// EnforceManagedModelDefaults re-applies managed model lock enforcement on
// resume. See SessionConfig.EnforceManagedModelDefaults.
EnforceManagedModelDefaults *bool
// InteractiveUser re-supplies that a human drives this session. It is not
// persisted and is ignored if the session is already active in the runtime.
InteractiveUser *bool
// ManagedSettings re-injects host-provided managed settings on resume. See
// SessionConfig.ManagedSettings. It must be re-supplied on resume: it
// replaces the prior injected layer, and omitting it clears that layer so
// warm and cold resume behave identically.
ManagedSettings *ManagedSettings
}
ResumeSessionConfig configures options when resuming a session
type RuntimeConnection interface {
// contains filtered or unexported methods
}
RuntimeConnection describes how a Client connects to the Copilot runtime.
Construct one with a StdioConnection, TCPConnection, URIConnection, or InProcessConnection literal and pass it via ClientOptions.Connection. When ClientOptions.Connection is nil, COPILOT_SDK_DEFAULT_CONNECTION may select "inprocess" or "stdio"; when unset, the default is an empty StdioConnection.
type SamplingCompletedData = rpc.SamplingCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SamplingRequestedData = rpc.SamplingRequestedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SandboxDecisionData = rpc.SandboxDecisionData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ScheduleOrigin = rpc.ScheduleOrigin
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SectionOverride struct {
// Action is the operation to perform: "replace", "remove", "append", "prepend", or "transform".
Action SectionOverrideAction `json:"action,omitempty"`
// Content for the override. Optional for all actions. Ignored for "remove".
Content string `json:"content,omitempty"`
// Transform is a callback invoked when Action is "transform".
// The runtime calls this with the current section content and uses the returned string.
// Excluded from JSON serialization; the SDK registers it as an RPC callback internally.
Transform SectionTransformFn `json:"-"`
}
SectionOverride defines an override operation for a single system message section.
type SectionOverrideAction string
SectionOverrideAction represents the action to perform on a system message section.
const ( // SectionActionReplace replaces section content entirely. SectionActionReplace SectionOverrideAction = "replace" // SectionActionRemove removes the section. SectionActionRemove SectionOverrideAction = "remove" // SectionActionAppend appends to existing section content. SectionActionAppend SectionOverrideAction = "append" // SectionActionPrepend prepends to existing section content. SectionActionPrepend SectionOverrideAction = "prepend" // SectionActionPreserve is a no-op marker that opts an individually-addressable // section out of a group-level "remove" (e.g. keep "tone" when removing the // "identity" group). SectionActionPreserve SectionOverrideAction = "preserve" )
SectionTransformFn is a callback that receives the current content of a system message section and returns the transformed content. Used with the "transform" action to read-then-write modify sections at runtime.
type Session struct {
// SessionID is the unique identifier for this session.
SessionID string
// RPC provides typed session-scoped RPC methods.
RPC *rpc.SessionRPC
// contains filtered or unexported fields
}
Session represents a single conversation session with the Copilot CLI.
A session maintains conversation state, handles events, and manages tool execution. Sessions are created via Client.CreateSession or resumed via Client.ResumeSession.
The session provides methods to send messages, subscribe to events, retrieve conversation history, and manage the session lifecycle. All methods are safe for concurrent use.
Example usage:
session, err := client.CreateSession(copilot.SessionConfig{
Model: "gpt-4",
})
if err != nil {
log.Fatal(err)
}
defer session.Disconnect()
// Subscribe to events
unsubscribe := session.On(func(event copilot.SessionEvent) {
if d, ok := event.Data.(*copilot.AssistantMessageData); ok {
fmt.Println("Assistant:", d.Content)
}
})
defer unsubscribe()
// Send a message
messageID, err := session.Send(copilot.MessageOptions{
Prompt: "Hello, world!",
})
Abort aborts the currently processing message in this session.
Use this to cancel a long-running request. The session remains valid and can continue to be used for new messages.
Returns an error if the session has been disconnected or the connection fails.
Example:
// Start a long-running request in a goroutine
go func() {
session.Send(context.Background(), copilot.MessageOptions{
Prompt: "Write a very long story...",
})
}()
// Abort after 5 seconds
time.Sleep(5 * time.Second)
if err := session.Abort(context.Background()); err != nil {
log.Printf("Failed to abort: %v", err)
}
func (s *Session) Capabilities() SessionCapabilities
Capabilities returns the session capabilities reported by the server.
Disconnect closes this session and releases all in-memory resources (event handlers, tool handlers, permission handlers).
The caller should ensure the session is idle (e.g., Session.SendAndWait has returned) before disconnecting. If the session is not idle, in-flight event handlers or tool handlers may observe failures.
Session state on disk (conversation history, planning state, artifacts) is preserved, so the conversation can be resumed later by calling Client.ResumeSession with the session ID. To permanently remove all session data including files on disk, use Client.DeleteSession instead.
After calling this method, the session object can no longer be used.
Returns an error if the connection fails.
Example:
// Clean up when done — session can still be resumed later
if err := session.Disconnect(); err != nil {
log.Printf("Failed to disconnect session: %v", err)
}
func (s *Session) GetEvents(ctx context.Context) ([]SessionEvent, error)
GetEvents retrieves all events from this session's history.
This returns the complete conversation history including user messages, assistant responses, tool executions, and other session events in chronological order.
Returns an error if the session has been disconnected or the connection fails.
Example:
events, err := session.GetEvents(context.Background())
if err != nil {
log.Printf("Failed to get events: %v", err)
return
}
for _, event := range events {
if d, ok := event.Data.(*copilot.AssistantMessageData); ok {
fmt.Println("Assistant:", d.Content)
}
}
Log sends a log message to the session timeline. The message appears in the session event stream and is visible to SDK consumers and (for non-ephemeral messages) persisted to the session event log on disk.
Pass nil for opts to use defaults (info level, non-ephemeral).
Example:
// Simple info message
session.Log(ctx, "Processing started")
// Warning with options
session.Log(ctx, "Rate limit approaching", &copilot.LogOptions{Level: rpc.SessionLogLevelWarning})
// Ephemeral message (not persisted)
session.Log(ctx, "Working...", &copilot.LogOptions{Ephemeral: copilot.Bool(true)})
func (s *Session) On(handler SessionEventHandler) func()
On subscribes to events from this session.
Events include assistant messages, tool executions, errors, and session state changes. Multiple handlers can be registered and will all receive events. Handlers are called synchronously in the order they were registered.
The returned function can be called to unsubscribe the handler. It is safe to call the unsubscribe function multiple times. Unsubscribing also removes an entry from dispatch snapshots if it has not started. Registration after the session closes is logged and returns a no-op unsubscribe.
Example:
unsubscribe := session.On(func(event copilot.SessionEvent) {
switch d := event.Data.(type) {
case *copilot.AssistantMessageData:
fmt.Println("Assistant:", d.Content)
case *copilot.SessionErrorData:
fmt.Println("Error:", d.Message)
}
})
// Later, to stop receiving events:
unsubscribe()
func (s *Session) OpenCanvases() []rpc.OpenCanvasInstance
OpenCanvases returns the open-canvas snapshot last reported by the runtime. The snapshot is populated from session.resume and live session.canvas.opened and session.canvas.closed events. The returned slice is a copy and is safe to mutate by the caller.
Send sends a message to this session and waits for the response.
The message is processed asynchronously. Subscribe to events via Session.On to receive streaming responses and other session events.
Parameters:
Returns the message ID of the response, which can be used to correlate events, or an error if the session has been disconnected or the connection fails.
Example:
messageID, err := session.Send(context.Background(), copilot.MessageOptions{
Prompt: "Explain this code",
Attachments: []copilot.Attachment{
&copilot.AttachmentFile{DisplayName: "main.go", Path: "./main.go"},
},
})
if err != nil {
log.Printf("Failed to send message: %v", err)
}
func (s *Session) SendAndWait(ctx context.Context, options MessageOptions) (*SessionEvent, error)
SendAndWait sends a message and waits for its response to complete.
Supported local runtimes correlate completion and the response with this message. Unsupported runtimes retain the legacy non-Autopilot session.idle or request-correlated session.autopilot_stopped wait. Autopilot completion does not wait for or stop attached shells.
Events are still delivered to handlers registered via Session.On while waiting. Synchronous handlers registered before this call process the terminal event, when present, before it returns successfully, unless the session retires. This does not wait for asynchronous work started by a handler. Sub-agent events with a non-empty AgentID do not complete the wait or supply its reply.
Parameters:
Returns the final assistant message event, or nil if none was received. Returns an error if the request is aborted, the timeout is reached, the session is closed, or the connection fails.
Example:
response, err := session.SendAndWait(context.Background(), copilot.MessageOptions{
Prompt: "What is 2+2?",
}) // Use default 60s timeout
if err != nil {
log.Printf("Failed: %v", err)
}
if response != nil {
if d, ok := response.Data.(*AssistantMessageData); ok {
fmt.Println(d.Content)
}
}
SendPrompt is a convenience wrapper for Session.Send that takes a plain prompt string instead of a MessageOptions struct. Equivalent to:
session.Send(ctx, copilot.MessageOptions{Prompt: prompt})
SendPromptAndWait is a convenience wrapper for Session.SendAndWait that takes a plain prompt string instead of a MessageOptions struct. Equivalent to:
session.SendAndWait(ctx, copilot.MessageOptions{Prompt: prompt})
func (s *Session) SetAutoTier(ctx context.Context, autoTier *AutoTier) (*rpc.ModelSwitchAutoTierResult, error)
SetAutoTier changes the Auto routing preference without changing the selected model.
The runtime does not apply the preference immediately. It records the request and commits it only when a later user turn using the "auto" model successfully obtains a usable model from the provider. A rpc.ModelSwitchAutoTierStatusPending status therefore confirms that the request was accepted, not that it took effect.
Watch for the outcome through the session.model_change event on success, or the ephemeral session.auto_tier_switch_failed event on failure. You can also read the current committed and in-flight state at any time with session.RPC.Model.GetCurrent.
Only the most recent request survives: issuing a new request replaces any earlier one that has not yet been claimed by a turn.
Pass nil to return to the provider's default Auto routing.
Experimental: SetAutoTier is part of an experimental Auto routing surface and may change or be removed.
Example:
tier := copilot.AutoTierIntelligence
result, err := session.SetAutoTier(context.Background(), &tier)
if err != nil {
log.Printf("Failed to set auto tier: %v", err)
}
SetModel changes the model for this session. The new model takes effect for the next message. Conversation history is preserved.
Example:
if err := session.SetModel(context.Background(), "gpt-5.4", nil); err != nil {
log.Printf("Failed to set model: %v", err)
}
if err := session.SetModel(context.Background(), "claude-sonnet-4.6", &SetModelOptions{ReasoningEffort: new("high")}); err != nil {
log.Printf("Failed to set model: %v", err)
}
SetTools atomically replaces the externally implemented tools supplied by this client connection for the live session. Built-in tools, MCP/plugin tools, extension-discovered tools, subagent tools, and tools supplied by other connections are unchanged.
The tools use the same Tool definitions and handlers as Client.CreateSession and Client.ResumeSession. The slice is a complete replacement for this connection: pass an empty slice to remove every tool this connection previously supplied. Tools with nil handlers are declaration-only.
Handlers switch after the runtime accepts the replacement. Calls already running finish on the handlers that started them. If the runtime rejects the replacement, the previous handlers remain installed. Concurrent SetTools calls on the same session are sent and applied in call order; an earlier failure does not block later calls. If ctx is done before the request is sent, for example while an earlier SetTools call is still in flight, nothing is sent. Once the request is sent, ctx only bounds the wait: an accepted replacement still installs its handlers unless the session has since closed.
The agent sees the new tools from its next model request, which can fall within a turn in progress. A model request already in flight was made with the previous tools, so the agent can still call a tool you removed. This session doesn't answer that call, and it can stay pending until the turn is aborted. If a running turn might still call a tool you remove, replace tools while the session is idle.
Experimental: SetTools wraps the experimental session.tools.set RPC and may change or be removed.
func (s *Session) TranscriptRecovery() *TranscriptRecoveryReport
TranscriptRecovery returns the report from session.resume, or nil if no transcript repair was reported. The returned value is independent of session state.
UI returns the interactive UI API for showing elicitation dialogs. Methods on the returned SessionUI will error if the host does not support elicitation (check Capabilities().UI.Elicitation first).
WorkspacePath returns the path to the session workspace directory when infinite sessions are enabled. Contains checkpoints/, plan.md, and files/ subdirectories. Returns empty string if infinite sessions are disabled.
type SessionAutoModeResolvedData = rpc.SessionAutoModeResolvedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionAutoTierRecommendationData = rpc.SessionAutoTierRecommendationData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionAutoTierSwitchFailedData = rpc.SessionAutoTierSwitchFailedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionAutopilotObjectiveChangedData = rpc.SessionAutopilotObjectiveChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionAutopilotStoppedData = rpc.SessionAutopilotStoppedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionBackgroundTasksChangedData = rpc.SessionBackgroundTasksChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionBinaryAssetData = rpc.SessionBinaryAssetData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionCanvasClosedData = rpc.SessionCanvasClosedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionCanvasOpenedData = rpc.SessionCanvasOpenedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionCanvasRecordedData = rpc.SessionCanvasRecordedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionCanvasRegistryChangedData = rpc.SessionCanvasRegistryChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionCanvasRemovedData = rpc.SessionCanvasRemovedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionCanvasUnavailableData = rpc.SessionCanvasUnavailableData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionCapabilities struct {
UI *UICapabilities `json:"ui,omitempty"`
}
SessionCapabilities describes what features the host supports.
type SessionCompactionCompleteData = rpc.SessionCompactionCompleteData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionCompactionStartData = rpc.SessionCompactionStartData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionCompletionReceiptData = rpc.SessionCompletionReceiptData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionConfig struct {
// SessionID is an optional custom session ID
SessionID string
// Name names the session at creation, as session.name.set would, and is
// validated the same way: non-empty, no leading or trailing whitespace, at
// most 100 UTF-16 units, no control characters, and no double quotes. A name
// also makes the session persist from the start, so it can be listed and
// resumed without ever running a turn. Local sessions only: cloud creation
// rejects it.
Name string
// ClientName identifies the application using the SDK.
// Included in the User-Agent header for API requests.
ClientName string
// Model to use for this session
Model string
// ReasoningEffort level for models that support it.
// Valid values: "low", "medium", "high", "xhigh", "max"
// Only applies to models where capabilities.supports.reasoningEffort is true.
ReasoningEffort string
// ReasoningSummary mode for models that support configurable reasoning summaries.
// Use ReasoningSummaryNone to suppress summary output regardless of whether reasoning is enabled.
ReasoningSummary ReasoningSummary
// ContextTier pins the session to a context window tier for models that support it.
// Use ContextTierDefault or ContextTierLongContext for the currently known tiers.
ContextTier ContextTier
// ConfigDirectory overrides the default configuration directory location.
// When specified, the session will use this directory for storing config and state.
ConfigDirectory string
// EnableConfigDiscovery enables runtime discovery of supported configuration.
// Explicitly supplied configuration takes precedence over discovered values.
// Nil leaves the runtime default unchanged; use Bool(false) to explicitly disable discovery.
EnableConfigDiscovery *bool
// TrustWorkingDirectory trusts the working directory for this session
// ("session") or persistently for the user ("user"). Empty leaves trust unchanged.
TrustWorkingDirectory WorkingDirectoryTrust
// SkipEmbeddingRetrieval, when non-nil, controls embedding-based retrieval
// for this session. Use in multitenant deployments to prevent cross-session
// information leakage through the shared embedding cache.
SkipEmbeddingRetrieval *bool
// EmbeddingCacheStorage controls how the embedding cache is stored for this session.
// "persistent" caches on disk and shares across sessions/restarts.
// "in-memory" caches in memory only and discards when the session ends.
EmbeddingCacheStorage *string
// OrganizationCustomInstructions provides organization-level custom instructions
// to include in the system prompt. Allows hosts to inject organization-specific
// guidance without relying on filesystem-based instruction discovery.
OrganizationCustomInstructions *string
// EnableOnDemandInstructionDiscovery, when non-nil, controls on-demand discovery
// of instruction files (AGENTS.md, .github/copilot-instructions.md, etc.) after
// successful file views.
EnableOnDemandInstructionDiscovery *bool
// EnableFileHooks, when non-nil, controls repository-origin file hooks from
// .github/hooks/ and trusted repository-configured roots. It does not control
// explicit HookDirectories or Hooks callbacks.
EnableFileHooks *bool
// EnableHostGitOperations, when non-nil, controls git operations on the host
// filesystem (branch detection, file status, commit history). When false, no
// git context is surfaced in the system prompt.
EnableHostGitOperations *bool
// EnableSessionStore, when non-nil, controls the cross-session store for search
// and retrieval. When false, session content is not written to or read from the
// shared session store.
EnableSessionStore *bool
// EnableSkills, when non-nil, controls skill loading (including builtin skills
// and discovered skill directories). When false, no skills are loaded regardless
// of SkillDirectories or EnableConfigDiscovery settings.
EnableSkills *bool
// IncludedBuiltinSkills is the allowlist of runtime-bundled skill names.
// In ModeEmpty, nil excludes all built-in skills; a non-nil list opts the
// named built-ins back in. Skills from other sources remain eligible.
IncludedBuiltinSkills []string
// Tools exposes caller-implemented tools to the CLI. A Tool with a nil Handler
// is declaration-only; the consumer must resolve its calls via pending tool RPCs.
Tools []Tool
// SystemMessage configures system message customization
SystemMessage *SystemMessageConfig
// AvailableTools is a list of tool names to allow. When specified, only these tools will be available.
// Takes precedence over ExcludedTools.
AvailableTools []string
// ExcludedTools is a list of tool names to disable. All other tools remain available.
// Ignored if AvailableTools is specified.
ExcludedTools []string
// ExcludedBuiltInAgents is a list of built-in agent names to exclude from
// the session. Excluded built-in agents are hidden from discovery and cannot
// be selected or invoked unless a custom agent with the same name is
// configured.
ExcludedBuiltInAgents []string
// OnPermissionRequest is an optional handler for permission requests from the server.
// When nil, permission requests are surfaced as events and left pending for the
// consumer to resolve via pending permission RPCs.
OnPermissionRequest PermissionHandlerFunc
// OnPermissionRequestWithPrompt receives the optional derived user-facing
// prompt supplied by newer runtimes. When both permission handlers are set,
// this handler takes precedence.
OnPermissionRequestWithPrompt PermissionHandlerWithPromptFunc
// OnMCPAuthRequest is an optional handler for MCP OAuth requests from MCP servers.
// When provided, the SDK can satisfy MCP server OAuth requests with host-provided
// token data or cancellation.
OnMCPAuthRequest MCPAuthHandler
// GitHubTokenProvider acquires session-scoped GitHub tokens on demand. It
// cannot be combined with GitHubToken.
GitHubTokenProvider GitHubTokenProvider
// OnUserInputRequest handles legacy question-and-answer requests from the agent
// and enables the legacy ask_user tool.
OnUserInputRequest UserInputHandler
// AskUserVariant selects the model-facing shape of the ask_user tool.
// The zero value preserves legacy behavior. AskUserVariantElicitation also
// requires OnElicitationRequest so the host can answer structured forms.
AskUserVariant AskUserVariant
// Hooks configures hook handlers for session lifecycle events
Hooks *SessionHooks
// WorkingDirectory is the working directory for the session.
// Tool operations will be relative to this directory.
WorkingDirectory string
// AdditionalDirectories are directories the agent may access beyond WorkingDirectory.
// Relative paths are resolved against WorkingDirectory. Re-supply them when resuming.
AdditionalDirectories []string
// Streaming enables streaming of assistant message and reasoning chunks.
// When non-nil and true, assistant.message_delta and assistant.reasoning_delta
// events with deltaContent are sent as the response is generated.
// When nil, the runtime decides (currently defaults to non-streaming).
Streaming *bool
// IncludeSubAgentStreamingEvents includes sub-agent streaming events in the
// event stream. When true, streaming delta events from sub-agents (e.g.,
// assistant.message_delta, assistant.reasoning_delta, assistant.streaming_delta
// with agentId set) are forwarded to this connection. When false, only
// non-streaming sub-agent events and subagent.* lifecycle events are forwarded;
// streaming deltas from sub-agents are suppressed. When nil, defaults to true.
IncludeSubAgentStreamingEvents *bool
// Provider configures a custom model provider (BYOK)
Provider *ProviderConfig
// Capi configures provider-scoped CAPI (Copilot API) session options.
Capi *CapiSessionOptions
// Providers configures named BYOK provider connections. Additive to Copilot
// API auth (unlike Provider); combine with Models. Cannot be combined with Provider.
//
// Experimental: Providers is part of an experimental multi-provider BYOK
// surface and may change or be removed in future SDK or CLI releases.
Providers []NamedProviderConfig
// Models adds BYOK model definitions to the session's selectable model list,
// each referencing a Providers entry by name.
//
// Experimental: Models is part of an experimental multi-provider BYOK
// surface and may change or be removed in future SDK or CLI releases.
Models []ProviderModelConfig
// EnableSessionTelemetry enables or disables internal session telemetry for this session.
// When false, disables session telemetry. When nil (the default) or true,
// telemetry is enabled for GitHub-authenticated sessions. When a custom
// Provider (BYOK) is configured, session telemetry is always disabled
// regardless of this setting. This is independent of the OpenTelemetry
// configuration in ClientOptions.Telemetry.
EnableSessionTelemetry *bool
// EnableCitations enables native model citations for supported providers.
//
// Experimental: EnableCitations is part of an experimental model capability
// surface and may change or be removed in future SDK or CLI releases.
EnableCitations *bool
// EnableFileChangeTracking opts in to capturing file changes from the first
// turn for session rewind and cumulative session diff.
EnableFileChangeTracking *bool
// SessionLimits applies limits to this session's current accounting window.
//
// Experimental: SessionLimits is part of an experimental runtime accounting
// surface and may change or be removed in future SDK or CLI releases.
SessionLimits *rpc.SessionLimitsConfig
// Autopilot configures continuation without changing the session mode.
// Omitted fields use defaults on create and preserve resident values on warm resume.
// Experimental: this policy may change in a future release.
Autopilot *rpc.AutopilotOptions
// EnableExperimentalMode controls whether the session enables experimental
// features. When nil, it defaults to false in [ModeEmpty]; otherwise the
// runtime decides.
EnableExperimentalMode *bool
// SkipCustomInstructions, when non-nil, controls whether the runtime loads
// custom instruction files. See also [ClientOptions.Mode] = [ModeEmpty].
SkipCustomInstructions *bool
// RefreshCustomInstructions, when true, invalidates the process-wide custom-instruction
// discovery cache before constructing this new session. Nil or false retains the cache.
// Other sessions in this runtime may observe updated instructions on later turns
// or discovery. It does not watch files or enable disabled instruction loading.
RefreshCustomInstructions *bool
// CustomAgentsLocalOnly, when non-nil, restricts custom agents to those
// defined locally. See also [ClientOptions.Mode] = [ModeEmpty].
CustomAgentsLocalOnly *bool
// exposed. See also [ClientOptions.Mode] = [ModeEmpty].
CoauthorEnabled *bool
// ManageScheduleEnabled, when non-nil, controls whether the
// `manage_schedule` tool is exposed. See also [ClientOptions.Mode] =
// [ModeEmpty].
ManageScheduleEnabled *bool
// ModelCapabilities overrides individual model capabilities resolved by the runtime.
// Only non-nil fields are applied over the runtime-resolved capabilities.
ModelCapabilities *rpc.ModelCapabilitiesOverride
// MCPServers configures MCP servers for the session
MCPServers map[string]MCPServerConfig
// Diagnostics enables explicitly configured session diagnostic sources.
// Diagnostics can contain MCP payloads, tool arguments, paths, and server
// stderr, so hosts must not upload or export them automatically.
Diagnostics *rpc.DiagnosticsConfiguration
// MCPOAuthTokenStorage controls how MCP OAuth tokens are stored for this session.
// When empty, the runtime default ("in-memory") is used.
MCPOAuthTokenStorage string
// AuthClientIDMetadataURL identifies the host for MCP OAuth authorization.
// When empty, no host identity is supplied.
AuthClientIDMetadataURL string
// CustomAgents configures custom agents for the session
CustomAgents []CustomAgentConfig
// DefaultAgent configures the default agent (the built-in agent that handles turns when no custom agent is selected).
// Use ExcludedTools to hide tools from the default agent while keeping them available to sub-agents.
DefaultAgent *DefaultAgentConfig
// Agent is the name of the custom agent to activate when the session starts.
// Must match the Name of one of the agents in CustomAgents.
Agent string
// SkillDirectories contains explicit discovery-only skill roots, not filesystem grants.
// Available without EnableConfigDiscovery, subject to skill/managed disables.
// Relative paths resolve once when supplied against the request's effective WorkingDirectory;
// retained roots do not move on cwd changes. Nil and omission are equivalent;
// an empty non-nil list clears only the explicit SDK contribution.
SkillDirectories []string
// SkillProvider supplies ephemeral SDK-hosted skills for this session. The
// provider is never serialized or persisted; re-supply it when resuming.
//
// Experimental: this API may change or be removed in future SDK or CLI
// releases. Implementations must be safe for concurrent calls.
SkillProvider SkillProvider `json:"-"`
// AgentDirectories contains explicit discovery-only agent roots, separate from CustomAgents.
// No filesystem grant. Available without EnableConfigDiscovery, subject to source/managed
// disables. Relative paths resolve once when supplied against the request's effective
// WorkingDirectory; retained roots do not move. Nil and omission are equivalent;
// an empty non-nil list clears only the explicit SDK contribution.
AgentDirectories []string
// HookDirectories contains explicit discovery-only file-hook roots, separate from Hooks callbacks.
// No filesystem grant. Available without EnableConfigDiscovery or EnableFileHooks
// (repository-origin hooks only), subject to hook/managed disables. Relative paths resolve
// once when supplied against the request's effective WorkingDirectory; retained roots do not
// move. Nil and omission are equivalent; an empty non-nil list clears only the explicit SDK contribution.
HookDirectories []string
// PluginDirectories is a list of local filesystem paths to Open Plugins-format
// directories (https://open-plugins.com/) to load for this session.
// Relative paths resolve against WorkingDirectory (or the runtime cwd if unset).
// Treated as an explicit opt-in: plugin agents and rules load even when
// EnableConfigDiscovery is false.
PluginDirectories []string
// InstructionDirectories contains explicit discovery-only instruction roots using existing SDK formats.
// No filesystem grant. Available without EnableConfigDiscovery, subject to instruction/managed
// disables. Relative paths resolve once when supplied against the request's effective
// WorkingDirectory; retained roots do not move. Nil and omission are equivalent;
// an empty non-nil list clears only the explicit SDK contribution.
InstructionDirectories []string
// DisabledSkills is a list of skill names to disable
DisabledSkills []string
// DisabledMCPServers is a list of exact MCP server names to disable for this session.
// Disabled servers are not started or authenticated on create or cold resume.
// A resident resume cannot stop servers that are already running.
DisabledMCPServers []string
// SandboxConfig is applied when the session is constructed, before MCP servers start.
// Same shape as the sandboxConfig option of session options update;
// an identical later update is a no-op.
SandboxConfig *rpc.SandboxConfig
// InfiniteSessions configures infinite sessions for persistent workspaces and automatic compaction.
// When enabled (default), sessions automatically manage context limits and persist state.
InfiniteSessions *InfiniteSessionConfig
// LargeOutput configures handling of large tool outputs. When a tool produces
// output exceeding the configured size, the output is written to a temp file
// and a reference is returned to the model instead of the full payload.
LargeOutput *LargeToolOutputConfig
// ToolSearch overrides the runtime's built-in tool-search behavior, which
// defers rarely used tools behind a searchable index. When nil, the runtime
// default applies.
ToolSearch *ToolSearchConfig
// ImageGeneration is the non-persisted image generation opt-in.
// Experimental: this API may change or be removed in a future release.
ImageGeneration *ImageGenerationConfig
// Memory configures the memory feature for the session. When omitted, the
// runtime default applies.
Memory *MemoryConfiguration
// OnEvent is an optional event handler that is registered on the session before
// the session.create RPC is issued. This guarantees that early events emitted
// by the CLI during session creation (e.g. session.start) are delivered to the
// handler. Equivalent to calling session.On(handler) immediately after creation,
// but executes earlier in the lifecycle so no events are missed.
OnEvent SessionEventHandler
// CreateSessionFSProvider supplies a handler for session filesystem operations.
// This takes effect only when ClientOptions.SessionFS is configured.
CreateSessionFSProvider func(session *Session) SessionFSProvider
// Commands registers slash-commands for this session. Each command appears as
// /name in the CLI TUI for the user to invoke. The Handler is called when the
// command is executed.
Commands []CommandDefinition
// OnElicitationRequest is a handler for elicitation requests from the server.
// When provided, the server may call back to this client for form-based UI dialogs
// (e.g. from MCP tools). Also enables the elicitation capability on the session.
OnElicitationRequest ElicitationHandler
// OnExitPlanModeRequest is a handler for exit-plan-mode requests from the server.
// When provided, enables exitPlanMode.request callbacks for the session.
OnExitPlanModeRequest ExitPlanModeRequestHandler
// OnAutoModeSwitchRequest is a handler for auto-mode-switch requests from the server.
// When provided, enables autoModeSwitch.request callbacks for the session.
OnAutoModeSwitchRequest AutoModeSwitchRequestHandler
// EnableMCPApps enables MCP Apps (SEP-1865) UI passthrough on this session.
//
// Experimental: EnableMCPApps is part of an experimental wire-protocol
// surface (SEP-1865) and may change or be removed in a future release.
//
// When true AND the runtime has MCP Apps enabled (via the MCP_APPS feature
// flag or COPILOT_MCP_APPS=true environment override), the runtime adds the
// mcp-apps capability to the session, which causes it to advertise the
// extensions.io.modelcontextprotocol/ui extension to MCP servers (so they
// expose _meta.ui.resourceUri on tools) and to expose the
// session.rpc.mcp.apps.{listTools,callTool,readResource,setHostContext,
// getHostContext,diagnose} JSON-RPC methods.
//
// If the runtime gate is off, the opt-in is silently dropped server-side
// (the runtime logs a warning); the session is created normally but the
// MCP Apps surface is unavailable. Inspect the runtime's
// capabilities.ui.mcpApps on the create/resume response to detect this.
//
// SDK consumers MUST set this to true only when they have an iframe renderer
// that can display ui:// MCP App bundles. Setting it without a renderer will
// cause MCP servers to register UI-enabled tool variants the consumer cannot
// display.
EnableMCPApps bool
// GitHubMCPToolConfig configures the built-in GitHub MCP server.
// DisableFormDeferral only applies to that server and only has an effect
// when MCP Apps and form-backed GitHub tools are enabled.
GitHubMCPToolConfig *GitHubMCPToolConfig
// GitHubToken is an optional per-session GitHub token used for authentication.
// When provided, the session authenticates as the token's owner instead of
// using the global client-level auth.
GitHubToken string `json:"-"`
// Cloud creates a remote session in the cloud instead of a local session.
// The optional repository is associated with the cloud session.
Cloud *CloudSessionOptions
// Canvases declares canvases this session provides. Sent over the wire on
// `session.create`. CanvasHandler must be set when this is non-empty (the
// SDK does not enforce this — declarations without a handler will surface
// canvas RPCs that return a canvas_handler_unset error envelope).
Canvases []CanvasDeclaration
// RequestCanvasRenderer asks the host to enable canvas rendering for this session.
RequestCanvasRenderer *bool
// RequestExtensions asks the host to surface declared canvases as agent-visible extensions.
RequestExtensions *bool
// ExtensionSDKPath optionally overrides the bundled `@github/copilot-sdk` drop
// injected into extension subprocesses. When set to an absolute path containing
// a valid `copilot-sdk/` folder (with `index.js` and `extension.js` at the
// root), the host injects the override into every forked extension; invalid or
// missing paths fall back to the bundled SDK silently.
ExtensionSDKPath *string
// CanvasHandler receives inbound canvas.open / canvas.close / canvas.action.invoke
// requests for this session. The SDK does not maintain a per-canvas registry;
// the handler must dispatch on CanvasProviderOpenRequest.CanvasID itself.
CanvasHandler CanvasHandler `json:"-"`
// ExtensionInfo identifies the stable extension providing this session's canvases.
ExtensionInfo *ExtensionInfo
// CanvasProvider is the stable identity for a host/SDK connection that
// supplies built-in canvases, so they survive reconnect and CLI restart.
CanvasProvider *CanvasProviderIdentity
// ExpAssignments injects ExP assignment ("flight") data for this session,
// in the same JSON shape the Copilot CLI fetches from the experimentation
// service (CopilotExpAssignmentResponse). When supplied, the runtime feeds
// it into the same feature-flag path as CLI-fetched assignments and stamps
// it onto telemetry and the CAPI request header. When absent, the session
// does not block on ExP. Malformed payloads are dropped by the runtime
// (fail-open).
//
// Internal: ExpAssignments is part of the SDK's internal API surface,
// intended for trusted out-of-process integrators, and is not intended for
// general external use.
ExpAssignments *CopilotExpAssignmentResponse
// FeatureFlags contains feature-flag values resolved by the host for this session.
// Re-supply them when resuming after a runtime restart.
FeatureFlags map[string]bool
// EnableManagedSettings, when set to true, opts the runtime into
// self-fetching enterprise managed settings (bypass-permissions policy) at
// session bootstrap using the session's GitHubToken. Requires GitHubToken to
// be set; if omitted, the runtime is expected to reject session creation
// (fail-closed). Unset behaves exactly as before.
EnableManagedSettings *bool
// ExcludedManagedSettings contains exact dotted setting paths excluded from
// fetched, device, and policy-helper policy. Host-injected policy and availability
// checks are unaffected. Not persisted; re-supply on resume.
ExcludedManagedSettings []string
// EnforceManagedModelDefaults, when true, enforces locked managed model
// controls for this session. Conflicting changes are rejected; overridable
// managed defaults remain mutable.
EnforceManagedModelDefaults *bool
// InteractiveUser declares that a human drives this session's conversation,
// enabling user-message analysis telemetry for user-authored messages.
// Automated messages remain excluded. Defaults to false for SDK sessions.
// Ignored for cloud sessions.
InteractiveUser *bool
// ManagedSettings supplies host-injected enterprise managed settings for
// the session. Unlike EnableManagedSettings (which asks the runtime to
// self-fetch account/org and device policy), this provides the managed
// policy directly. The runtime validates it with the same
// managed-permission parser it uses for fetched policy and composes it
// restrictively with any self-fetched (server) and device-managed (MDM)
// layers. It is startup-only and not persisted: re-supply it on resume,
// where it replaces the prior injected layer (omitting it clears the
// layer). It may be combined with EnableManagedSettings. Requires a runtime
// whose RPC schema includes managedSettings.
ManagedSettings *ManagedSettings
}
SessionConfig configures a new session
type SessionContext struct {
// WorkingDirectory is the working directory where the session was created
WorkingDirectory string `json:"cwd"`
// GitRoot is the git repository root (if in a git repo)
GitRoot string `json:"gitRoot,omitempty"`
// Repository is the GitHub repository in "owner/repo" format
Repository string `json:"repository,omitempty"`
// Branch is the current git branch
Branch string `json:"branch,omitempty"`
}
SessionContext contains working directory context for a session
type SessionContextChangedData = rpc.SessionContextChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionContextClearedData = rpc.SessionContextClearedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionCustomAgentsUpdatedData = rpc.SessionCustomAgentsUpdatedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionCustomNotificationData = rpc.SessionCustomNotificationData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionEndHandler func(input SessionEndHookInput, invocation HookInvocation) (*SessionEndHookOutput, error)
SessionEndHandler handles session-end hook invocations
type SessionEndHookInput struct {
AgentID string `json:"agentId,omitempty"`
AgentType string `json:"agentType,omitempty"`
ParentAgentID string `json:"parentAgentId,omitempty"`
SessionID string `json:"sessionId"`
Timestamp time.Time `json:"-"`
WorkingDirectory string `json:"cwd"`
Reason string `json:"reason"` // "complete", "error", "abort", "timeout", "user_exit"
FinalMessage string `json:"finalMessage,omitempty"`
Error string `json:"error,omitempty"`
}
SessionEndHookInput is the input for a session-end hook
func (h SessionEndHookInput) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (h *SessionEndHookInput) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds and Error from the CLI's error object (see hookErrorText).
type SessionEndHookOutput struct {
SuppressOutput bool `json:"suppressOutput,omitempty"`
CleanupActions []string `json:"cleanupActions,omitempty"`
SessionSummary string `json:"sessionSummary,omitempty"`
}
SessionEndHookOutput is the output for a session-end hook
type SessionErrorData = rpc.SessionErrorData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionEvent = rpc.SessionEvent
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionEventData = rpc.SessionEventData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionEventHandler func(event SessionEvent)
SessionEventHandler is a callback for session events
type SessionEventType = rpc.SessionEventType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionExtensionsAttachmentsPushedData = rpc.SessionExtensionsAttachmentsPushedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionExtensionsLoadedData = rpc.SessionExtensionsLoadedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionFSBinaryProvider interface {
ReadFileBytes(path string) ([]byte, error)
WriteFileBytes(path string, content []byte, mode *int) error
}
SessionFSBinaryProvider is an optional interface for exact file bytes. Declare capabilities.binary only when the provider implements both methods.
type SessionFSCapabilities struct {
// Sqlite indicates whether the provider supports SQLite query/exists operations.
Sqlite bool
// Binary indicates whether the provider supports exact binary file reads and writes.
Binary bool
}
SessionFSCapabilities declares optional provider capabilities.
type SessionFSConfig struct {
// InitialWorkingDirectory is the initial working directory for sessions.
InitialWorkingDirectory string
// SessionStatePath is the path within each session's filesystem where the runtime stores
// session-scoped files such as events, checkpoints, and temp files.
SessionStatePath string
// Conventions identifies the path conventions used by this filesystem provider.
Conventions rpc.SessionFSSetProviderConventions
// Capabilities declares optional provider capabilities such as SQLite support.
Capabilities *SessionFSCapabilities
}
SessionFSConfig configures a custom session filesystem provider.
type SessionFSFileInfo struct {
IsFile bool
IsDirectory bool
Size int64
Mtime time.Time
Birthtime time.Time
}
SessionFSFileInfo holds file metadata returned by SessionFSProvider.Stat.
type SessionFSProvider interface {
// ReadFile reads the full content of a file. Return os.ErrNotExist (or wrap it)
// if the file does not exist.
ReadFile(path string) (string, error)
// WriteFile writes content to a file, creating it and parent directories if needed.
// mode is an optional POSIX-style permission mode. Pass nil to use the OS default.
// Return a *SessionFSWriteFailure if the failed write changed the target.
WriteFile(path string, content string, mode *int) error
// AppendFile appends content to a file, creating it and parent directories if needed.
// mode is an optional POSIX-style permission mode. Pass nil to use the OS default.
AppendFile(path string, content string, mode *int) error
// Exists checks whether the given path exists.
Exists(path string) (bool, error)
// Stat returns metadata about a file or directory.
// Return os.ErrNotExist if the path does not exist.
Stat(path string) (*SessionFSFileInfo, error)
// Mkdir creates a directory. If recursive is true, create parent directories as needed.
// mode is an optional POSIX-style permission mode (e.g., 0o755). Pass nil to use the OS default.
MakeDirectory(path string, recursive bool, mode *int) error
// Readdir lists the names of entries in a directory.
// Return os.ErrNotExist if the directory does not exist.
ReadDirectory(path string) ([]string, error)
// ReaddirWithTypes lists entries with type information.
// Return os.ErrNotExist if the directory does not exist.
ReadDirectoryWithTypes(path string) ([]rpc.SessionFSReaddirWithTypesEntry, error)
// Rm removes a file or directory. If recursive is true, remove contents too.
// If force is true, do not return an error when the path does not exist.
Remove(path string, recursive bool, force bool) error
// Rename moves/renames a file or directory.
Rename(src string, dest string) error
}
SessionFSProvider is the interface that SDK users implement to provide a session filesystem. Methods use idiomatic Go error handling: return an error for failures (the adapter maps os.ErrNotExist → ENOENT automatically).
To add SQLite support, also implement SessionFSSqliteProvider on the same type.
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)
}
SessionFSSqliteProvider is an optional interface that a SessionFSProvider may also implement to support per-session SQLite databases. The adapter checks for this interface at runtime using a type assertion. If the provider does not implement it, SQLite requests return an "unsupported" error.
Providers are already session-scoped (created per session by the factory), so these methods do not take a session ID parameter.
type SessionFSSqliteQueryResult struct {
Columns []string `json:"columns"`
Rows []map[string]any `json:"rows"`
RowsAffected int64 `json:"rowsAffected"`
LastInsertRowid *int64 `json:"lastInsertRowid,omitempty"`
}
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.
type SessionFSSqliteTransactionFailure struct {
// Class is the failure classification reported to the runtime.
Class rpc.SessionFSSqliteTransactionErrorClass
// Message describes the failure.
Message string
}
SessionFSSqliteTransactionFailure classifies a SQLite transaction failure for 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.
func (e *SessionFSSqliteTransactionFailure) Error() string
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
// 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)
}
SessionFSSqliteTransactionProvider is an optional interface that a SessionFSSqliteProvider may also implement to support atomic transactions.
type SessionFSWriteFailure struct {
Err error
}
SessionFSWriteFailure reports that a failed WriteFile changed its target. Wrap the original error so its cause remains available to errors.Is and errors.As.
func (e *SessionFSWriteFailure) Error() string
func (e *SessionFSWriteFailure) Unwrap() error
type SessionFusionCompletedData = rpc.SessionFusionCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionFusionResolvedData = rpc.SessionFusionResolvedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionFusionRouteFailedData = rpc.SessionFusionRouteFailedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionFusionRouteStartedData = rpc.SessionFusionRouteStartedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionHandoffData = rpc.SessionHandoffData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionHooks struct {
OnPreToolUse PreToolUseHandler
OnPostToolUse PostToolUseHandler
OnPostToolUseFailure PostToolUseFailureHandler
OnUserPromptSubmitted UserPromptSubmittedHandler
OnUserPromptTransformed UserPromptTransformedHandler
OnSessionStart SessionStartHandler
OnSessionEnd SessionEndHandler
OnErrorOccurred ErrorOccurredHandler
OnAgentStop AgentStopHandler
OnSubagentStart SubagentStartHandler
OnSubagentStop SubagentStopHandler
OnPreMCPToolCall PreMCPToolCallHandler
}
SessionHooks configures hook handlers for a session
type SessionIdleData = rpc.SessionIdleData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionIndexedSearchData = rpc.SessionIndexedSearchData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionInfoData = rpc.SessionInfoData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionLifecycleEvent struct {
Type SessionLifecycleEventType `json:"type"`
SessionID string `json:"sessionId"`
Metadata *SessionLifecycleEventMetadata `json:"metadata,omitempty"`
}
SessionLifecycleEvent represents a session lifecycle notification
type SessionLifecycleEventMetadata struct {
StartTime time.Time `json:"startTime"`
ModifiedTime time.Time `json:"modifiedTime"`
Summary *string `json:"summary,omitempty"`
}
SessionLifecycleEventMetadata contains optional metadata for lifecycle events
type SessionLifecycleEventType string
SessionLifecycleEventType represents the type of session lifecycle event
const ( SessionLifecycleCreated SessionLifecycleEventType = "session.created" SessionLifecycleDeleted SessionLifecycleEventType = "session.deleted" SessionLifecycleUpdated SessionLifecycleEventType = "session.updated" SessionLifecycleForeground SessionLifecycleEventType = "session.foreground" SessionLifecycleBackground SessionLifecycleEventType = "session.background" )
type SessionLifecycleHandler func(event SessionLifecycleEvent)
SessionLifecycleHandler is a callback for session lifecycle events
type SessionLimitsConfig = rpc.SessionLimitsConfig
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionLimitsExhaustedCompletedData = rpc.SessionLimitsExhaustedCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionLimitsExhaustedRequestedData = rpc.SessionLimitsExhaustedRequestedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionLimitsExhaustedResponse = rpc.SessionLimitsExhaustedResponse
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionLimitsExhaustedResponseAction = rpc.SessionLimitsExhaustedResponseAction
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionListFilter struct {
// WorkingDirectory filters by exact working directory match
WorkingDirectory string `json:"cwd,omitempty"`
// GitRoot filters by git root
GitRoot string `json:"gitRoot,omitempty"`
// Repository filters by repository (owner/repo format)
Repository string `json:"repository,omitempty"`
// Branch filters by branch
Branch string `json:"branch,omitempty"`
}
SessionListFilter contains filter options for listing sessions
type SessionMCPServerNeedsReconnectData = rpc.SessionMCPServerNeedsReconnectData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionMCPServerRemovedData = rpc.SessionMCPServerRemovedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionMCPServerStatusChangedData = rpc.SessionMCPServerStatusChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionMCPServerToolsLoadedData = rpc.SessionMCPServerToolsLoadedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionMCPServersLoadedData = rpc.SessionMCPServersLoadedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionManagedPluginProgressData = rpc.SessionManagedPluginProgressData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionManagedSettingsEnforcedData = rpc.SessionManagedSettingsEnforcedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionManagedSettingsResolvedData = rpc.SessionManagedSettingsResolvedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionMetadata struct {
SessionID string `json:"sessionId"`
StartTime time.Time `json:"startTime"`
ModifiedTime time.Time `json:"modifiedTime"`
Summary *string `json:"summary,omitempty"`
IsRemote bool `json:"isRemote"`
Context *SessionContext `json:"context,omitempty"`
}
SessionMetadata contains metadata about a session
type SessionMode = rpc.SessionMode
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionModeChangedData = rpc.SessionModeChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionModeNoticeDeliveredData = rpc.SessionModeNoticeDeliveredData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionModelChangeData = rpc.SessionModelChangeData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionModelDeselectedData = rpc.SessionModelDeselectedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionPermissionRecoveryData = rpc.SessionPermissionRecoveryData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionPermissionsChangedData = rpc.SessionPermissionsChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionPlanChangedData = rpc.SessionPlanChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionQuotaObservationData = rpc.SessionQuotaObservationData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionRemoteSteerableChangedData = rpc.SessionRemoteSteerableChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionResumeData = rpc.SessionResumeData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionScheduleCancelledData = rpc.SessionScheduleCancelledData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionScheduleCreatedData = rpc.SessionScheduleCreatedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionScheduleRearmedData = rpc.SessionScheduleRearmedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionSessionLimitsChangedData = rpc.SessionSessionLimitsChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionShutdownData = rpc.SessionShutdownData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionSkillsLoadedData = rpc.SessionSkillsLoadedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionSnapshotRewindData = rpc.SessionSnapshotRewindData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionStartData = rpc.SessionStartData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionStartHandler func(input SessionStartHookInput, invocation HookInvocation) (*SessionStartHookOutput, error)
SessionStartHandler handles session-start hook invocations
type SessionStartHookInput struct {
AgentID string `json:"agentId,omitempty"`
AgentType string `json:"agentType,omitempty"`
ParentAgentID string `json:"parentAgentId,omitempty"`
SessionID string `json:"sessionId"`
Timestamp time.Time `json:"-"`
WorkingDirectory string `json:"cwd"`
Source string `json:"source"` // "startup", "resume", "new"
InitialPrompt string `json:"initialPrompt,omitempty"`
}
SessionStartHookInput is the input for a session-start hook
func (h SessionStartHookInput) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (h *SessionStartHookInput) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
type SessionStartHookOutput struct {
AdditionalContext string `json:"additionalContext,omitempty"`
ModifiedConfig map[string]any `json:"modifiedConfig,omitempty"`
}
SessionStartHookOutput is the output for a session-start hook
type SessionTaskCompleteData = rpc.SessionTaskCompleteData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionTitleChangedData = rpc.SessionTitleChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionTodosChangedData = rpc.SessionTodosChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionToolsUpdatedData = rpc.SessionToolsUpdatedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionTruncationData = rpc.SessionTruncationData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionUI struct {
// contains filtered or unexported fields
}
SessionUI provides convenience methods for showing elicitation dialogs to the user. Obtained via Session.UI. Methods error if the host does not support elicitation.
Confirm shows a confirmation dialog and returns the user's boolean answer. Returns false if the user declines or cancels.
func (ui *SessionUI) Elicitation(ctx context.Context, message string, requestedSchema ElicitationSchema) (*ElicitationResult, error)
Elicitation shows a generic elicitation dialog with a custom schema.
type SessionUsageCheckpointData = rpc.SessionUsageCheckpointData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionUsageInfoData = rpc.SessionUsageInfoData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionWarningData = rpc.SessionWarningData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SessionWorkspaceFileChangedData = rpc.SessionWorkspaceFileChangedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SetModelOptions struct {
// ReasoningEffort sets the reasoning effort level for the new model (e.g., "low", "medium", "high", "xhigh", "max").
ReasoningEffort *string
// ReasoningSummary sets the reasoning summary mode for the new model.
// Use ReasoningSummaryNone to suppress summary output regardless of whether reasoning is enabled.
ReasoningSummary *ReasoningSummary
// ContextTier explicitly selects a context window tier for models that support it.
// Leave nil to use normal model behavior with no explicit tier.
ContextTier *ContextTier
// ModelCapabilities overrides individual model capabilities resolved by the runtime.
// Only non-nil fields are applied over the runtime-resolved capabilities.
ModelCapabilities *rpc.ModelCapabilitiesOverride
// AutoTier stages an Auto routing preference atomically with selecting the
// "auto" model. Leave nil to leave the current preference alone.
//
// The runtime rejects this option when the model is anything other than
// "auto". Use [Session.SetAutoTier] to change the preference without
// changing the selected model.
//
// Experimental: AutoTier is part of an experimental Auto routing surface and
// may change or be removed.
AutoTier *AutoTier
// ResetAutoTier returns to the provider's default Auto routing as part of
// this switch. It is mutually exclusive with AutoTier.
//
// Experimental: ResetAutoTier is part of an experimental Auto routing surface
// and may change or be removed.
ResetAutoTier bool
}
SetModelOptions configures optional parameters for SetModel.
type ShutdownAgentMetric = rpc.ShutdownAgentMetric
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ShutdownCodeChanges = rpc.ShutdownCodeChanges
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ShutdownModelMetric = rpc.ShutdownModelMetric
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ShutdownModelMetricRequests = rpc.ShutdownModelMetricRequests
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ShutdownModelMetricTokenDetail = rpc.ShutdownModelMetricTokenDetail
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ShutdownModelMetricUsage = rpc.ShutdownModelMetricUsage
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ShutdownTokenDetail = rpc.ShutdownTokenDetail
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ShutdownType = rpc.ShutdownType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SkillContextDeliveredData = rpc.SkillContextDeliveredData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SkillContextDeliveredRefData = rpc.SkillContextDeliveredRefData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SkillInvokedData = rpc.SkillInvokedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SkillInvokedRefData = rpc.SkillInvokedRefData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SkillInvokedTrigger = rpc.SkillInvokedTrigger
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SkillProvider interface {
// ListSkills returns catalog metadata for skills provided by this session.
// Return nil, nil to publish an empty catalog.
ListSkills(ctx context.Context) ([]rpc.SkillProviderDescriptor, error)
// ReadSkill returns the SKILL.md markdown for name. Return an error wrapping
// [ErrSkillNotFound] when the skill no longer exists. The markdown is
// ignored whenever a non-nil error is returned.
ReadSkill(ctx context.Context, name string) (string, error)
}
SkillProvider supplies session-scoped skills from the SDK host.
Experimental: this API may change or be removed in future SDK or CLI releases. Implementations must be safe for concurrent calls.
type SkillSource = rpc.SkillSource
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SkillsLoadedSkill = rpc.SkillsLoadedSkill
Session-event types are generated in the rpc package and aliased here for source compatibility.
type StdioConnection struct {
// Path is the runtime executable. When empty, the bundled runtime is used.
Path string
// Args are extra command-line arguments inserted before SDK-managed args.
Args []string
// Env are the environment variables for the runtime process, each of the
// form "KEY=VALUE". When set, these take precedence over
// [ClientOptions.Env]; setting both is rejected. When nil, the client-level
// env (or the current process environment) is used.
Env []string
}
StdioConnection spawns a runtime child process and communicates over its stdin/stdout pipes. This is the default when no connection is configured.
type SubagentCompletedData = rpc.SubagentCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SubagentConfiguredData = rpc.SubagentConfiguredData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SubagentDeselectedData = rpc.SubagentDeselectedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SubagentFailedData = rpc.SubagentFailedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SubagentModelSelectionSource = rpc.SubagentModelSelectionSource
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SubagentSelectedData = rpc.SubagentSelectedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SubagentStartHandler func(input SubagentStartHookInput, invocation HookInvocation) (*SubagentStartHookOutput, error)
SubagentStartHandler handles subagent-start hook invocations.
type SubagentStartHookInput struct {
AgentID string `json:"agentId,omitempty"`
AgentType string `json:"agentType,omitempty"`
ParentAgentID string `json:"parentAgentId,omitempty"`
SessionID string `json:"sessionId"`
Timestamp time.Time `json:"-"`
WorkingDirectory string `json:"cwd"`
TranscriptPath string `json:"transcriptPath"`
AgentName string `json:"agentName"`
AgentDisplayName string `json:"agentDisplayName,omitempty"`
AgentDescription string `json:"agentDescription,omitempty"`
}
SubagentStartHookInput is the input before a subagent's first turn.
func (h SubagentStartHookInput) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (h *SubagentStartHookInput) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
type SubagentStartHookOutput struct {
AdditionalContext string `json:"additionalContext,omitempty"`
}
SubagentStartHookOutput provides context prepended to the subagent's initial prompt.
type SubagentStartedData = rpc.SubagentStartedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SubagentStopHandler func(input SubagentStopHookInput, invocation HookInvocation) (*SubagentStopHookOutput, error)
SubagentStopHandler handles subagent-stop hook invocations.
type SubagentStopHookInput struct {
ParentAgentID string `json:"parentAgentId,omitempty"`
SessionID string `json:"sessionId"`
Timestamp time.Time `json:"-"`
WorkingDirectory string `json:"cwd"`
TranscriptPath string `json:"transcriptPath"`
AgentID string `json:"agentId,omitempty"`
AgentType string `json:"agentType"`
AgentName string `json:"agentName"`
AgentDisplayName string `json:"agentDisplayName,omitempty"`
AgentDescription string `json:"agentDescription,omitempty"`
StopReason string `json:"stopReason"`
Response string `json:"response"`
}
SubagentStopHookInput is the input after a subagent completes a turn.
func (h SubagentStopHookInput) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (h *SubagentStopHookInput) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
type SubagentStopHookOutput struct {
Decision string `json:"decision,omitempty"`
Reason string `json:"reason,omitempty"`
ModifiedResponse *string `json:"modifiedResponse,omitempty"`
}
SubagentStopHookOutput can block a subagent's completion or replace its response. Decision must be "block" with a nonempty Reason, "allow", or empty to allow. Reason without a block decision and unsupported decisions fail the subagent.
type SubagentTaskModelSource = rpc.SubagentTaskModelSource
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemMessageAppendConfig struct {
// Mode is optional, defaults to "append"
Mode string `json:"mode,omitempty"`
// Content provides additional instructions appended after SDK-managed sections
Content string `json:"content,omitempty"`
}
SystemMessageAppendConfig is append mode: use CLI foundation with optional appended content.
type SystemMessageConfig struct {
Mode string `json:"mode,omitempty"`
Content string `json:"content,omitempty"`
Sections map[string]SectionOverride `json:"sections,omitempty"`
}
SystemMessageConfig represents system message configuration for session creation.
In Go, use one struct and set fields appropriate for the desired mode.
type SystemMessageContentBlock = rpc.SystemMessageContentBlock
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemMessageData = rpc.SystemMessageData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemMessageMetadata = rpc.SystemMessageMetadata
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemMessageReplaceConfig struct {
// Mode must be "replace"
Mode string `json:"mode"`
// Content is the complete system message (required)
Content string `json:"content"`
}
SystemMessageReplaceConfig is replace mode: use caller-provided system message entirely. Removes all SDK guardrails including security restrictions.
type SystemMessageRole = rpc.SystemMessageRole
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotification = rpc.SystemNotification
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationAgentCompleted = rpc.SystemNotificationAgentCompleted
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationAgentCompletedStatus = rpc.SystemNotificationAgentCompletedStatus
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationAgentIdle = rpc.SystemNotificationAgentIdle
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationData = rpc.SystemNotificationData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationInstructionDiscovered = rpc.SystemNotificationInstructionDiscovered
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationNewInboxMessage = rpc.SystemNotificationNewInboxMessage
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationShellCompleted = rpc.SystemNotificationShellCompleted
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationShellDetachedCompleted = rpc.SystemNotificationShellDetachedCompleted
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationType = rpc.SystemNotificationType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationUnclassified = rpc.SystemNotificationUnclassified
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationWorkflowCompleted = rpc.SystemNotificationWorkflowCompleted
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationWorkflowCompletedStatus = rpc.SystemNotificationWorkflowCompletedStatus
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationWorkflowPauseInfo = rpc.SystemNotificationWorkflowPauseInfo
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationWorkflowPauseInfoCheckpoint = rpc.SystemNotificationWorkflowPauseInfoCheckpoint
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationWorkflowPauseInfoType = rpc.SystemNotificationWorkflowPauseInfoType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type SystemNotificationWorkflowPauseInfoUser = rpc.SystemNotificationWorkflowPauseInfoUser
Session-event types are generated in the rpc package and aliased here for source compatibility.
type TCPConnection struct {
// Port is the TCP port the runtime listens on. 0 (the default) lets the
// runtime pick a free port; the chosen port is then available via
// [Client.RuntimePort] after [Client.Start] returns.
Port int
// ConnectionToken is an optional shared secret sent in the `connect`
// handshake. When empty, a UUID is generated automatically so the
// loopback listener is safe by default.
ConnectionToken string
// Path is the runtime executable. When empty, the bundled runtime is used.
Path string
// Args are extra command-line arguments inserted before SDK-managed args.
Args []string
// Env are the environment variables for the runtime process, each of the
// form "KEY=VALUE". When set, these take precedence over
// [ClientOptions.Env]; setting both is rejected. When nil, the client-level
// env (or the current process environment) is used.
Env []string
}
TCPConnection spawns a runtime child process that listens on a TCP socket and connects to it.
type TaskBlocker = rpc.TaskBlocker
Session-event types are generated in the rpc package and aliased here for source compatibility.
type TaskBlockerKind = rpc.TaskBlockerKind
Session-event types are generated in the rpc package and aliased here for source compatibility.
type TaskCompleteData = rpc.TaskCompleteData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type TaskCompletionOutcome = rpc.TaskCompletionOutcome
Session-event types are generated in the rpc package and aliased here for source compatibility.
type TelemetryConfig struct {
// OTLPEndpoint is the OTLP HTTP endpoint URL for trace/metric export.
// Sets OTEL_EXPORTER_OTLP_ENDPOINT.
OTLPEndpoint string
// OTLPProtocol is the OTLP HTTP protocol for all signals.
// Sets OTEL_EXPORTER_OTLP_PROTOCOL.
OTLPProtocol string
// FilePath is the file path for JSON-lines trace output.
// Sets COPILOT_OTEL_FILE_EXPORTER_PATH.
FilePath string
// ExporterType is the exporter backend type: "otlp-http" or "file".
// Sets COPILOT_OTEL_EXPORTER_TYPE.
ExporterType string
// SourceName is the instrumentation scope name.
// Sets COPILOT_OTEL_SOURCE_NAME.
SourceName string
// CaptureContent controls whether to capture message content (prompts, responses).
// Sets OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT.
CaptureContent *bool
}
TelemetryConfig configures OpenTelemetry integration for the Copilot CLI process.
type Tool struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Parameters map[string]any `json:"parameters,omitzero"`
OverridesBuiltInTool bool `json:"overridesBuiltInTool,omitempty"`
SkipPermission bool `json:"skipPermission,omitempty"`
// IsTerminal reports that a successful call to this tool ends the agent
// turn: the runtime halts instead of feeding the result back to the model
// for another round. A failed call leaves the loop running so the model can
// read the error and retry.
IsTerminal bool `json:"isTerminal,omitempty"`
// Defer controls whether the tool may be deferred (loaded lazily via tool
// search) rather than always pre-loaded. When empty, the runtime decides.
Defer ToolDefer `json:"defer,omitempty"`
// Metadata is opaque, host-defined metadata associated with the tool
// definition. Keys are namespaced and not part of the stable public API;
// values are not interpreted and may be recognized to inform host-specific
// behavior. Unknown keys are preserved and round-tripped untouched.
Metadata map[string]any `json:"metadata,omitempty"`
// Namespace optionally groups this tool with related tools for model tool
// discovery. Where the model provider supports native tool namespaces,
// deferred tools sharing a namespace are presented to the model as one
// group; elsewhere the tool stays flat. Name remains the tool's unique
// invocation name either way.
//
// Experimental: this field may change or be removed.
Namespace *ToolNamespace `json:"namespace,omitempty"`
// Handler is optional. When nil, the SDK exposes the tool declaration but does
// not automatically invoke it.
Handler ToolHandler `json:"-"`
}
func DefineTool[T any, U any](name, description string, handler func(T, ToolInvocation) (U, error)) Tool
DefineTool creates a Tool with automatic JSON schema generation from a typed handler function. The handler receives typed arguments (automatically unmarshaled from JSON) and the raw ToolInvocation. The handler can return any value - strings pass through directly, other types are JSON-serialized.
Example:
type GetWeatherParams struct {
City string `json:"city" jsonschema:"city name"`
Unit string `json:"unit" jsonschema:"temperature unit (celsius or fahrenheit)"`
}
tool := copilot.DefineTool("get_weather", "Get weather for a city",
func(params GetWeatherParams, inv copilot.ToolInvocation) (any, error) {
return fmt.Sprintf("Weather in %s: 22°%s", params.City, params.Unit), nil
})
type ToolBinaryResult struct {
Data string `json:"data"`
MIMEType string `json:"mimeType"`
Type string `json:"type"`
Description string `json:"description,omitempty"`
}
ToolBinaryResult represents binary payloads returned by tools.
type ToolDefer string
ToolDefer controls whether a tool may be deferred (loaded lazily via tool search) rather than always pre-loaded.
type ToolExecutionCompleteContent = rpc.ToolExecutionCompleteContent
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteContentAudio = rpc.ToolExecutionCompleteContentAudio
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteContentImage = rpc.ToolExecutionCompleteContentImage
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteContentResource = rpc.ToolExecutionCompleteContentResource
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteContentResourceDetails = rpc.ToolExecutionCompleteContentResourceDetails
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteContentResourceLink = rpc.ToolExecutionCompleteContentResourceLink
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteContentResourceLinkIcon = rpc.ToolExecutionCompleteContentResourceLinkIcon
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteContentResourceLinkIconTheme = rpc.ToolExecutionCompleteContentResourceLinkIconTheme
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteContentShellExit = rpc.ToolExecutionCompleteContentShellExit
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteContentTerminal = rpc.ToolExecutionCompleteContentTerminal
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteContentText = rpc.ToolExecutionCompleteContentText
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteContentType = rpc.ToolExecutionCompleteContentType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteData = rpc.ToolExecutionCompleteData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteError = rpc.ToolExecutionCompleteError
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteFileEdit = rpc.ToolExecutionCompleteFileEdit
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteFileEditKind = rpc.ToolExecutionCompleteFileEditKind
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteResult = rpc.ToolExecutionCompleteResult
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteShellExecution = rpc.ToolExecutionCompleteShellExecution
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteToolDescription = rpc.ToolExecutionCompleteToolDescription
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteToolDescriptionMeta = rpc.ToolExecutionCompleteToolDescriptionMeta
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteToolDescriptionMetaUI = rpc.ToolExecutionCompleteToolDescriptionMetaUI
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteToolDescriptionMetaUIVisibility = rpc.ToolExecutionCompleteToolDescriptionMetaUIVisibility
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteUIResource = rpc.ToolExecutionCompleteUIResource
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteUIResourceMeta = rpc.ToolExecutionCompleteUIResourceMeta
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteUIResourceMetaUI = rpc.ToolExecutionCompleteUIResourceMetaUI
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteUIResourceMetaUICsp = rpc.ToolExecutionCompleteUIResourceMetaUICsp
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteUIResourceMetaUIPermissions = rpc.ToolExecutionCompleteUIResourceMetaUIPermissions
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteUIResourceMetaUIPermissionsCamera = rpc.ToolExecutionCompleteUIResourceMetaUIPermissionsCamera
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite = rpc.ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation = rpc.ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone = rpc.ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionPartialResultData = rpc.ToolExecutionPartialResultData
Deprecated: ToolExecutionPartialResultData is deprecated.
type ToolExecutionProgressData = rpc.ToolExecutionProgressData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionStartData = rpc.ToolExecutionStartData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionStartShellToolInfo = rpc.ToolExecutionStartShellToolInfo
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionStartToolDescription = rpc.ToolExecutionStartToolDescription
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionStartToolDescriptionMeta = rpc.ToolExecutionStartToolDescriptionMeta
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionStartToolDescriptionMetaUI = rpc.ToolExecutionStartToolDescriptionMetaUI
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionStartToolDescriptionMetaUIVisibility = rpc.ToolExecutionStartToolDescriptionMetaUIVisibility
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionUsage = rpc.ToolExecutionUsage
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolExecutionUsageTokenDetails = rpc.ToolExecutionUsageTokenDetails
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolHandler func(invocation ToolInvocation) (ToolResult, error)
ToolHandler executes a tool invocation. The handler should return a ToolResult. Returning an error marks the tool execution as a failure.
type ToolInvocation struct {
SessionID string
ToolCallID string
ToolName string
Arguments any
// AvailableTools is a snapshot of the session's currently initialized
// tools. The SDK populates it only when this invocation targets the
// built-in tool-search tool ("tool_search_tool"), so a tool-search
// override can rank/filter the live catalog -- including MCP tools
// configured in settings -- without issuing its own RPC. It is nil for
// every other tool invocation.
AvailableTools []rpc.CurrentToolMetadata
// TraceContext carries the W3C Trace Context propagated from the CLI's
// execute_tool span. Pass this to OpenTelemetry-aware code so that
// child spans created inside the handler are parented to the CLI span.
// It is cancelled when the external tool request completes or the session
// disconnects, so background work must derive its own lifetime if it should
// outlive the invocation.
TraceContext context.Context
// AgentID is the sub-agent instance that issued this call (the AgentID of
// its session events). It is empty for a root-agent call, and for every
// call when the runtime does not attribute sub-agent tool calls.
//
// Experimental: this field may change or be removed.
AgentID string
// RequestID is the runtime request id of this call: the key
// session.tools.handlePendingToolCall and session.tools.listPendingRequests use.
// A root-agent call stays answerable after the session is resumed with
// pending work continued; a sub-agent's call can be answered only while that
// sub-agent is still running.
//
// Experimental: this field may change or be removed.
RequestID string
}
ToolInvocation describes a tool call initiated by Copilot
type ToolNamespace struct {
// Name is the namespace name: 1-64 ASCII letters, digits, underscores, or
// hyphens.
Name string `json:"name"`
// Description is an optional model-visible explanation of the tools in
// this namespace.
Description string `json:"description,omitempty"`
}
ToolNamespace groups related tools for model tool discovery.
Experimental: this type may change or be removed.
type ToolResult struct {
TextResultForLLM string `json:"textResultForLlm"`
BinaryResultsForLLM []ToolBinaryResult `json:"binaryResultsForLlm,omitempty"`
ResultType string `json:"resultType"`
Error string `json:"error,omitempty"`
SessionLog string `json:"sessionLog,omitempty"`
ToolTelemetry map[string]any `json:"toolTelemetry,omitempty"`
// ToolReferences lists names of tools returned by a tool-search tool.
ToolReferences []string `json:"toolReferences,omitempty"`
}
ToolResult represents the result of a tool invocation.
func ConvertMCPCallToolResult(value any) (ToolResult, bool)
ConvertMCPCallToolResult converts an MCP CallToolResult value (a map or struct with a "content" array and optional "isError" bool) into a ToolResult. Returns the converted ToolResult and true if the value matched the expected shape, or a zero ToolResult and false otherwise.
type ToolSearchActivatedData = rpc.ToolSearchActivatedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolSearchConfig struct {
// Controls whether tool search is enabled.
Enabled *bool `json:"enabled,omitempty"`
// DeferThreshold is the tool count above which MCP and external tools are
// deferred behind tool search. When nil, the runtime default (30) applies.
DeferThreshold *int `json:"deferThreshold,omitempty"`
}
ToolSearchConfig allows to configure tool search behavior. Tool search defers tools to keep the model's active tool set small. To override the tool-search tool's implementation, register a Tool named "tool_search_tool" with OverridesBuiltInTool set to true.
type ToolSet struct {
// contains filtered or unexported fields
}
ToolSet builds a list of source-qualified tool filter patterns (`builtin:*`, `mcp:<name>`, `custom:*`, ...) for use with SessionConfig.AvailableTools or SessionConfig.ExcludedTools.
Tools are classified by the runtime at registration time (not from name parsing), so AddBuiltIn("foo") matches only tools the runtime registered as built-in, even if an MCP server or custom-agent extension happens to register a tool with the same wire name.
ToolSet's zero value is ready to use. Convert to []string via ToolSet.ToSlice before passing to SessionConfig fields, e.g. `(&ToolSet{}).AddBuiltIn(...).ToSlice()`.
AddBuiltIn adds one or more built-in tool patterns. Pass a specific tool name (e.g. "bash") or "*" to match all built-in tools.
AddCustom adds a custom-tool pattern. Matches tools registered via SessionConfig.Tools or via custom agents.
type ToolShellOutputData = rpc.ToolShellOutputData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolShellOutputStream = rpc.ToolShellOutputStream
Session-event types are generated in the rpc package and aliased here for source compatibility.
type ToolUserRequestedData = rpc.ToolUserRequestedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type TranscriptRecoveryReport struct {
PlannedBackupPath string `json:"plannedBackupPath"`
InvalidLineNumbers []int `json:"invalidLineNumbers"`
SessionStartMoved bool `json:"sessionStartMoved"`
}
TranscriptRecoveryReport describes the repair performed while resuming a session.
type UICapabilities struct {
// Elicitation indicates whether the host supports interactive elicitation dialogs.
Elicitation bool `json:"elicitation,omitempty"`
// MCPApps indicates whether the runtime has accepted the session's MCP Apps
// (SEP-1865) opt-in. True when the consumer set EnableMCPApps=true on
// create/resume AND the runtime's MCP_APPS feature flag (or
// COPILOT_MCP_APPS=true env override) is on. Otherwise false, indicating
// the runtime silently dropped the opt-in.
//
// Experimental: MCPApps is part of an experimental wire-protocol surface
// (SEP-1865) and may change or be removed in a future release.
MCPApps bool `json:"mcpApps,omitempty"`
}
UICapabilities describes host UI feature support.
type UIEphemeralQueryData = rpc.UIEphemeralQueryData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UIEphemeralQueryPhase = rpc.UIEphemeralQueryPhase
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UIInputOptions struct {
// Title label for the input field.
Title string
// Description text shown below the field.
Description string
// MinLength is the minimum character length.
MinLength *int
// MaxLength is the maximum character length.
MaxLength *int
// Format is a semantic format hint: "email", "uri", "date", or "date-time".
Format string
// Default is the pre-populated value.
Default string
}
UIInputOptions configures a text input field for the Input convenience method.
type URIConnection struct {
// URL of the runtime. Accepts "port", "host:port", or a full URL such
// as "http://host:port".
URL string
// ConnectionToken authenticates the connection; must match what the
// remote runtime expects.
ConnectionToken string
}
URIConnection connects to an already-running runtime at the given URL. The SDK does not spawn a process in this mode.
type UsageAccountingIdentity = rpc.UsageAccountingIdentity
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UsageGetMetricsResult = rpc.UsageGetMetricsResult
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UsageMetricsAgentMetric = rpc.UsageMetricsAgentMetric
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UsageMetricsCodeChanges = rpc.UsageMetricsCodeChanges
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UsageMetricsModelMetric = rpc.UsageMetricsModelMetric
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UsageMetricsModelMetricRequests = rpc.UsageMetricsModelMetricRequests
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UsageMetricsModelMetricTokenDetail = rpc.UsageMetricsModelMetricTokenDetail
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UsageMetricsModelMetricUsage = rpc.UsageMetricsModelMetricUsage
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UsageMetricsProviderModelMetric = rpc.UsageMetricsProviderModelMetric
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UsageMetricsTokenDetail = rpc.UsageMetricsTokenDetail
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserInputCompletedData = rpc.UserInputCompletedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserInputHandler func(request UserInputRequest, invocation UserInputInvocation) (UserInputResponse, error)
UserInputHandler handles user input requests from the agent The handler should return a UserInputResponse. Returning an error fails the request.
type UserInputInvocation struct {
SessionID string
}
UserInputInvocation provides context about a user input request
UserInputRequest represents a request for user input from the agent
type UserInputRequestedData = rpc.UserInputRequestedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
UserInputResponse represents the user's response to an input request
type UserMessageAgentMode = rpc.UserMessageAgentMode
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserMessageData = rpc.UserMessageData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserMessageDelivery = rpc.UserMessageDelivery
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserPromptSubmittedHandler func(input UserPromptSubmittedHookInput, invocation HookInvocation) (*UserPromptSubmittedHookOutput, error)
UserPromptSubmittedHandler handles user-prompt-submitted hook invocations
type UserPromptSubmittedHookInput struct {
AgentID string `json:"agentId,omitempty"`
AgentType string `json:"agentType,omitempty"`
ParentAgentID string `json:"parentAgentId,omitempty"`
SessionID string `json:"sessionId"`
Timestamp time.Time `json:"-"`
WorkingDirectory string `json:"cwd"`
Prompt string `json:"prompt"`
}
UserPromptSubmittedHookInput is the input for a user-prompt-submitted hook
func (h UserPromptSubmittedHookInput) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (h *UserPromptSubmittedHookInput) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
type UserPromptSubmittedHookOutput struct {
ModifiedPrompt string `json:"modifiedPrompt,omitempty"`
AdditionalContext string `json:"additionalContext,omitempty"`
SuppressOutput bool `json:"suppressOutput,omitempty"`
Decision string `json:"decision,omitempty"`
Reason string `json:"reason,omitempty"`
}
UserPromptSubmittedHookOutput is the output for a user-prompt-submitted hook.
A Decision of "block" refuses the prompt: no model turn runs, no user message is recorded, and the session emits an ephemeral session.warning (warningType "policy_blocked") carrying Reason. The runtime blocks only when a reason is present, and an empty Reason is omitted from the output, so a block needs a non-empty Reason.
type UserPromptTransformedHandler func(input UserPromptTransformedHookInput, invocation HookInvocation) (*UserPromptTransformedHookOutput, error)
UserPromptTransformedHandler handles user-prompt-transformed hook invocations.
type UserPromptTransformedHookInput struct {
AgentID string `json:"agentId,omitempty"`
AgentType string `json:"agentType,omitempty"`
ParentAgentID string `json:"parentAgentId,omitempty"`
SessionID string `json:"sessionId"`
Timestamp time.Time `json:"-"`
WorkingDirectory string `json:"cwd"`
Prompt string `json:"prompt"`
TransformedPrompt string `json:"transformedPrompt"`
}
UserPromptTransformedHookInput is the input for a user-prompt-transformed hook.
func (h UserPromptTransformedHookInput) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.
func (h *UserPromptTransformedHookInput) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.
type UserPromptTransformedHookOutput struct {
ModifiedTransformedPrompt *string `json:"modifiedTransformedPrompt,omitempty"`
}
UserPromptTransformedHookOutput is the output for a user-prompt-transformed hook.
type UserToolSessionApproval = rpc.UserToolSessionApproval
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserToolSessionApprovalCommands = rpc.UserToolSessionApprovalCommands
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserToolSessionApprovalCustomTool = rpc.UserToolSessionApprovalCustomTool
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserToolSessionApprovalExtensionEnvAccess = rpc.UserToolSessionApprovalExtensionEnvAccess
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserToolSessionApprovalExtensionManagement = rpc.UserToolSessionApprovalExtensionManagement
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserToolSessionApprovalExtensionPermissionAccess = rpc.UserToolSessionApprovalExtensionPermissionAccess
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserToolSessionApprovalKind = rpc.UserToolSessionApprovalKind
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserToolSessionApprovalMCP = rpc.UserToolSessionApprovalMCP
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserToolSessionApprovalMemory = rpc.UserToolSessionApprovalMemory
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserToolSessionApprovalRead = rpc.UserToolSessionApprovalRead
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserToolSessionApprovalWorkflow = rpc.UserToolSessionApprovalWorkflow
Session-event types are generated in the rpc package and aliased here for source compatibility.
type UserToolSessionApprovalWrite = rpc.UserToolSessionApprovalWrite
Session-event types are generated in the rpc package and aliased here for source compatibility.
Session-event types are generated in the rpc package and aliased here for source compatibility.
type WebSocketResponseWriter interface {
// SendText forwards an upstream text message to the runtime.
SendText(data []byte) error
// SendBinary forwards an upstream binary message to the runtime.
SendBinary(data []byte) error
}
WebSocketResponseWriter forwards upstream→runtime WebSocket messages back into the runtime response. A CopilotWebSocketHandler receives one in CopilotWebSocketHandler.Open.
type WorkflowPermissionOperation = rpc.WorkflowPermissionOperation
Session-event types are generated in the rpc package and aliased here for source compatibility.
type WorkflowPermissionPhase = rpc.WorkflowPermissionPhase
Session-event types are generated in the rpc package and aliased here for source compatibility.
type WorkflowRunSettledData = rpc.WorkflowRunSettledData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type WorkflowRunSettledStatus = rpc.WorkflowRunSettledStatus
Session-event types are generated in the rpc package and aliased here for source compatibility.
type WorkflowRunStartedData = rpc.WorkflowRunStartedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type WorkflowRunUpdatedData = rpc.WorkflowRunUpdatedData
Session-event types are generated in the rpc package and aliased here for source compatibility.
type WorkingDirectoryContext = rpc.WorkingDirectoryContext
Session-event types are generated in the rpc package and aliased here for source compatibility.
type WorkingDirectoryContextHostType = rpc.WorkingDirectoryContextHostType
Session-event types are generated in the rpc package and aliased here for source compatibility.
type WorkingDirectoryTrust string
WorkingDirectoryTrust selects the scope of a working-directory trust grant.
const ( // WorkingDirectoryTrustSession trusts the directory for this session only. WorkingDirectoryTrustSession WorkingDirectoryTrust = "session" // WorkingDirectoryTrustUser persists trust in the user's profile. WorkingDirectoryTrustUser WorkingDirectoryTrust = "user" )
type WorkspaceFileChangedOperation = rpc.WorkspaceFileChangedOperation
Session-event types are generated in the rpc package and aliased here for source compatibility.