copilot

package module
v2.0.2-preview.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 39 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Copilot CLI SDK for Go

A Go SDK for programmatic access to the GitHub Copilot CLI.

Prerequisites

To use the SDK, you'll need:

  • Go 1.26.0 or later
  • A matching native runtime package, embedded with the bundler below or supplied through COPILOT_CLI_PATH

Installation

go get github.com/microsoft/copilot-sdk/go/v2
go get -tool github.com/microsoft/copilot-sdk/go/v2/cmd/bundler
go tool bundler

Run the Sample

Try the interactive chat sample (from the repo root):

cd nodejs
npm ci
export COPILOT_CLI_PATH="$(npm run --silent prepare:runtime -- --print-path)"
cd ../go/samples
go run chat.go

The manual permission/tool-result resume sample can be run from the same directory:

go run ./manual_tool_resume

Print an edited permission request without starting the CLI:

go run chat.go --permission-envelope

The output retains unknown fields, explicit nulls, and large integers.

Run both permission-envelope and MCP refresh callbacks on an isolated JSON-RPC session, without the CLI:

go run chat.go --permission-envelope-mcp-refresh

The output contains the original futureDetails value and the correlated runtimeRefresh response.

Quick Start

For experimental in-process AHP hosting, use client.StartAhpHost(ctx, &copilot.AhpHostOptions{...}). Select at least one explicit transport: LocalServer: &rpc.HostLocalServerOptions{} enables a local listener; GitHubEnvironment: &rpc.HostGitHubEnvironmentOptions{Name: "My host", ComputeID: "my-compute"} registers a Mission Control environment. Both can be enabled. Import rpc from github.com/microsoft/copilot-sdk/go/v2/rpc. No transport is enabled by default. Local hostname, port, and WebSocket connection-token settings belong inside LocalServer. Set top-level Authentication: copilot.AhpHostAuthentication{Mode: "github"}, {Mode: "none"}, or {Mode: "custom", RequireIdentity: "owner", Authenticate: validator} in every client mode. Mission Control requires github; none does not disable the independent WebSocket connection token. The custom validator takes (context.Context, string) (the decrypted admission token) and returns (*copilot.AhpAuthenticationResult, error): return nil to reject, or the exact configured Identity and a mandatory future RFC3339 ExpiresAt. Its context is cancelled when validation ends; late results cannot grant access. Create/resume requests expose trusted, tagged Authentication alongside Config, never inside it. Admission tokens are not GitHub or inference credentials; use Config.Inference.Providers for BYOK inference independently of host admission. The returned handle's URL, Token, PID, and EnvironmentID are optional pointers; Mission Control-only hosting has no local URL. These APIs are experimental. Call host.ListSessions(ctx) to read the complete advertised catalog of live and dormant sessions. Set top-level ComputeID to reuse the durable catalog across local and Mission Control hosting; it must agree with GitHubEnvironment.ComputeID when both are supplied. The runtime persists an omitted local-only identity. Publication survives host shutdown; dormant application sessions require your resume callback. Use the generated client.RPC.Environments namespace for environment list/get/delete operations. See runtime-supervised AHP hosting for creation and resume callbacks, resident-session publication, ownership, and shared-snapshot E2Es.

package main

import (
	"context"
	"fmt"
	"log"

	copilot "github.com/microsoft/copilot-sdk/go/v2"
)

func main() {
	// Create client
	client := copilot.NewClient(&copilot.ClientOptions{Mode: copilot.ModeCodingAgent, Observability: copilot.ClientObservabilityOptions{

		// Start the client
		LogLevel: "error"},
	})

	if err := client.Start(context.Background()); err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	session, err := client.CreateSession(context.Background(), &copilot.CreateSessionOptions{Model: "gpt-5", Permissions: copilot.SessionPermissionOptions{OnRequest: copilot.PermissionHandler.ApproveAll}})
	if err != nil {
		log.Fatal(err)
	}
	defer session.Disconnect()

	// Set up event handler
	done := make(chan bool)
	session.On(func(event copilot.SessionEvent) {
		switch d := event.Data.(type) {
		case *copilot.AssistantMessageData:
			fmt.Println(d.Content)
		case *copilot.SessionIdleData:
			close(done)
		}
	})

	// Send a message
	_, err = session.Send(context.Background(), copilot.MessageOptions{
		Prompt: "What is 2+2?",
	})
	if err != nil {
		log.Fatal(err)
	}

	// Wait for completion
	<-done
}

When targeting MCP tools configured through MCP.Servers, remember the runtime tool name is <server-key>-<tool-name>. For Tools.AvailableTools and Tools.ExcludedTools, prefer the source-qualified form mcp:<server-key>-<tool-name>. For CustomAgents[].Tools and DefaultAgent.ExcludedTools, use <server-key>-<tool-name> directly.

Untyped JSON numbers

Only ContentExclusionValidatePoliciesResult decodes untyped JSON numbers as json.Number to preserve policy values without precision loss. Existing RPC results, requests, callbacks, and session events keep their existing numeric representation, including float64 for untyped numbers. Typed numeric fields keep their declared Go types. Use json.Number.Int64() or json.Number.Float64() when you need a numeric conversion, and handle the returned error.

JSON-RPC errors

Use errors.As to inspect a runtime error without parsing its message, including errors wrapped by SDK operations:

var rpcErr *copilot.RPCError
if errors.As(err, &rpcErr) {
    fmt.Printf("RPC error %d: %s\n", rpcErr.Code, rpcErr.Message)
    if rpcErr.Data != nil {
        // Decode into an application-specific type when the payload schema is known.
        var details map[string]json.RawMessage
        if err := json.Unmarshal(rpcErr.Data, &details); err != nil {
            // The payload may be an array or scalar rather than an object.
            log.Printf("Error data is not an object: %v", err)
        }
    }
}

This example uses the standard errors, encoding/json, fmt, and log packages. RPCError.Data is a json.RawMessage containing the original JSON value: objects, arrays, strings, numbers, and booleans are preserved. Omitted data is nil; explicit JSON null is the non-nil JSON text null. Empty values, zero, and false are not treated as absent. Ordinary connection and local precondition failures do not match *copilot.RPCError. The transport also uses this type for locally synthesized inline-response callback failures, so matching it does not prove that the runtime sent an error response.

RPCError aliases the existing transport error, so error identity, wrapping, and Error() messages are unchanged. The error string does not include the payload; accessing or logging it is an explicit application choice. Avoid logging it indiscriminately: server-provided data may contain sensitive information. Its fields and data bytes are shared with the wrapped error; copy them before mutation.

Skill providers (experimental)

Use CreateSessionOptions.Skills.Provider or ResumeSessionOptions.Skills.Provider to serve session-scoped skills from your application instead of from SKILL.md files on disk. The provider is ephemeral: it is not serialized or persisted, so re-supply it on every resume. Resuming without a provider unbinds any previous provider for that session.

type memorySkillProvider struct{}

func (memorySkillProvider) ListSkills(ctx context.Context) ([]rpc.SkillProviderDescriptor, error) {
    return []rpc.SkillProviderDescriptor{{
        Name:        "review",
        Description: "Review code using the host application's policy",
    }}, nil
}

func (memorySkillProvider) ReadSkill(ctx context.Context, name string) (string, error) {
    if name != "review" {
        return "", copilot.ErrSkillNotFound
    }
    return "Review the changes and call out policy violations.", nil
}

session, err := client.CreateSession(ctx, &copilot.CreateSessionOptions{
	Skills: copilot.SessionSkillOptions{
		Provider: memorySkillProvider{},
		// Required only when ClientOptions.Mode is ModeEmpty.
		// Enabled: copilot.Bool(true),
	},
})

ReadSkill returns an error for which errors.Is(err, copilot.ErrSkillNotFound) is true when a listed skill no longer exists. Other errors are reported to the runtime as generic provider failures so provider error text is not exposed to the model.

Skill providers are not supported for cloud sessions. Creating a cloud session with a provider fails before the client connects with: Skill providers are not supported for cloud sessions.

Provider methods can be called concurrently by the runtime, including from sub-agents that inherit the root session binding. Implementations must be safe for concurrent calls and should observe the context.Context. The context is cancelled when the runtime abandons the request: the call times out, the session disconnects or is deleted, or a resume replaces the provider. It is also cancelled when the connection closes or the client is force-stopped.

Supporting files (experimental)

To give a provider skill supporting files, such as scripts, references, templates, and assets, set its descriptor's Directory to the absolute path of the folder that holds them:

var _ = rpc.SkillProviderDescriptor{
	Name:        "release-notes",
	Description: "Writes release notes in the team's format.",
	Directory:   copilot.String("/srv/skills/release-notes"),
}

When the skill is activated, the runtime lists the folder's files for the model. See Supporting files for details.

Installation confirmation (experimental)

Set ClientOptions.Installations.ConfirmationHandler to receive the runtime's installations.confirm callback through Installations.ConfirmationHandler. The handler receives the generated InstallationConfirmationRequest and an InstallationConfirmationContext, a context.Context cancelled when the review is retired or the original connection closes. It returns only an explicit InstallationConfirmationDecision: confirm, decline or cancel. The SDK echoes the original challenge and review fingerprint; it never infers approval.

Match OperationID and PolicySessionID against the original action on this exact connection before presenting the complete review. Missing legacy session metadata does not select a default session. Refuse unknown operations or incomplete reviews. Concurrent reviews are independent and do not block other RPCs on the connection.

The callback context follows the runtime's numeric $/cancelRequest, including runtime-enforced expiry, and is also cancelled for loss of the original connection or client stop. Any separately spawned UI work must observe that single context. Dropping an outbound installation or OAuth future does not cancel that operation.

Call client.RPC.MCP.PrepareInstall(...) before ApplyInstall(...). Register its inert runtime-issued OperationID, original expiry and captured session on this client before applying. Removal uses PlanUninstall(...) then ApplyUninstall(...); its OperationID identifies the operation, while PlanHandle is the one-use removal input. Never interchange them. The Installations namespace exposes List, Recover, Status and Cancel. Control uncertain work using its original connection and operation ID, without selecting a replacement session or replaying apply.

Owned OAuth uses session.RPC.MCP.Oauth().PrepareLogin(...) to return LoginID before browser, network or cached-reconnect work. Keep that ID with the original session and ExpectedInstallationID for Login(...) and CancelLogin(...). Preparation freezes reauthentication and display options. Dropping the login future is not a substitute for CancelLogin(...). Manual MCP OAuth retains its direct Login(...) path.

These methods require a matching runtime and available owned-lifecycle support. Capability negotiation does not promise availability; preserve typed refusals instead of falling back to raw configuration writes. Generated presence and transport tests do not establish live OAuth, activation or cross-process recovery.

Network callbacks (experimental)

Set ClientOptions.Network to a NetworkConfig when the SDK host should take over parts of the runtime's networking, for example when the runtime runs in WSL or a container and should use VS Code's proxy settings and the host's Kerberos tickets. Registration happens during Start (including the auto-start in CreateSession and ResumeSession), before sessions can be created. Without this option, or for a callback you leave nil, the runtime handles that part itself.

  • ResolveProxy(ctx, request) decides the proxies for every request the runtime would otherwise route by ambient proxy settings: proxy environment variables, NO_PROXY and operating-system proxy settings are not consulted unless it returns "". The NetworkResolveProxyRequest's URL is the request target as a PAC script sees it: without credentials or fragment, and for https and wss also without path and query. Return a PAC-style list such as PROXY proxy.example:8080; HTTPS proxy.example:443; DIRECT (the format of Electron's session.resolveProxy); return "DIRECT" for a direct connection, or "" to let the runtime resolve the proxy itself, as if no callback were registered. Entry types the runtime doesn't support, such as SOCKS and QUIC, are skipped. If the callback returns an error, the request fails rather than connecting directly. Requests to loopback targets, and requests with an explicitly configured proxy, never consult it. The runtime caches answers, including "", for 5 seconds and waits at most 10 seconds for the callback.
  • AuthenticateNegotiate(ctx, request) supplies the Kerberos token for a proxy's Negotiate challenge instead of the runtime's native credential lookup. The NetworkAuthenticateNegotiateRequest's Spn is a service principal in the platform-independent service/host[@REALM] form; validate it before issuing credentials. Return a fresh base64 SPNEGO token without the Negotiate prefix, or "" when credentials are unavailable, which fails the request unless the proxy also offers Basic and AuthenticateBasic supplies credentials. The runtime waits at most 30 seconds for the callback (less when the request's own deadline is sooner). Tokens are not cached and must not be logged or persisted. The callback supplies the initial SPNEGO token only; exchanges requiring continuation tokens are not supported. Proxies chosen by ResolveProxy are authenticated the same way.
  • AuthenticateBasic(ctx, request) supplies credentials for a proxy's Basic challenge on requests the runtime tunnels through the proxy (https and wss targets). The NetworkAuthenticateBasicRequest names the challenging Proxy (http://host:port or https://host:port), the proxy's optional Realm, which is untrusted text, and PreviousRejected, which is true when the proxy rejected the credentials the connection sent last. Return a NetworkAuthenticateBasicResult with Username and Password (nil means an empty password), or nil when credentials are unavailable, which fails the request with the proxy's challenge, as does an empty user name. The user name must not contain a colon, and neither the user name nor the password may contain control characters; the runtime fails the request otherwise. The runtime remembers the answer for that proxy and uses it for later connections, until the proxy rejects it; then it calls again with PreviousRejected set, so return different credentials, for example by asking the user, or nil. A later connection sends the answer without waiting for a challenge, unless the runtime may try Negotiate with that proxy first. A connection submits at most three sets of credentials. While a call is pending, other requests through that proxy wait for its answer. When a proxy offers both Negotiate and Basic, the runtime prefers Negotiate and answers with Basic when Negotiate is unavailable or the proxy rejects it. The runtime does not time the callback out: a request whose own deadline passes stops waiting, but the answer is still remembered. Credentials must not be logged or persisted.

A returned error, or a panic, is reported to the runtime as a callback failure. Each callback's ctx is cancelled when the runtime stops waiting (it cancels the request, for example after its timeout, or the connection closes); the SDK then stops waiting for the callback and ignores any later result, so a lookup that can hang should abandon its work once the context is done. If that happens before the callback starts, the callback is not called at all.

By default the callbacks serve only requests made for sessions this client creates or resumes. With Scope: copilot.NetworkScopeRuntime they also serve the runtime's shared background traffic, such as catalog refreshes and telemetry; only one connection at a time can hold that scope, so startup fails if another client holds it. The registration ends when the connection closes; a failed Start, including one whose context is cancelled, closes it.

client := copilot.NewClient(&copilot.ClientOptions{ Mode: copilot.ModeCodingAgent,
    Network: &copilot.NetworkConfig{
        Scope: copilot.NetworkScopeRuntime,
        ResolveProxy: func(ctx context.Context, request copilot.NetworkResolveProxyRequest) (string, error) {
            return lookUpProxy(ctx, request.URL) // for example "PROXY proxy.example:8080; DIRECT"
        },
        AuthenticateNegotiate: func(ctx context.Context, request copilot.NetworkAuthenticateNegotiateRequest) (string, error) {
            return acquireSPNEGOToken(ctx, request.Spn) // host-side credential lookup
        },
        AuthenticateBasic: func(ctx context.Context, request copilot.NetworkAuthenticateBasicRequest) (*copilot.NetworkAuthenticateBasicResult, error) {
            return lookUpProxyCredentials(ctx, request.Proxy, request.PreviousRejected) // nil when unavailable
        },
    },
})

Distributing your application with an embedded GitHub Copilot CLI

The SDK supports bundling, using Go's embed package, the Copilot CLI binary within your application's distribution. This allows you to bundle a specific CLI version and avoid external dependencies on the user's system. The bundler downloads the matching github-copilot-<version>-<platform>.tgz asset from github/copilot-cli for stable/prerelease runtimes or microsoft/copilot-sdk for unstable runtimes, verifying it against the release's SHA256SUMS.txt.

Follow these steps to embed the CLI:

  1. Run go get -tool github.com/microsoft/copilot-sdk/go/v2/cmd/bundler. This is a one-time setup step per project.
  2. Run go tool bundler in your build environment just before building your application.

When your application calls copilot.NewClient, the SDK extracts and loads the embedded runtime.

If the user cache cannot be determined, Unix uses <temp>/copilot-sdk-cache-<uid> with owner-only permissions (0700), checking ownership and permissions before reuse. No HOME is required. The selected temporary base is trusted, like COPILOT_HOME or embeddedcli.Config.Directory; the application must keep these locations protected from replacement by other users. Other platforms retain the existing temporary-directory fallback. Legacy shared Unix caches are not reused, so the first fallback install is cold.

The bundler includes the native runtime library for the in-process transport without a build tag.

In-process transport

SDK v2 defaults to loading the native runtime into the application process. It keeps framed JSON-RPC over the C ABI, but provides no crash isolation or sandbox.

Build normally:

go build
client := copilot.NewClient(&copilot.ClientOptions{Mode: copilot.ModeCodingAgent, Runtime: copilot.InProcessConnection{},
})
if err := client.Start(context.Background()); err != nil {
	log.Fatal(err)
}
defer client.Stop()

Resolution and requirements:

  • Supported native hosts are macOS, Linux, and Windows on amd64 or arm64.
  • For native-free subprocess or external-server applications, build with go build -tags copilot_no_inprocess to exclude FFI and its native dependencies. Then explicitly select SpawnedStdioConnection, SpawnedTCPConnection, or TCPConnection, or set COPILOT_SDK_DEFAULT_CONNECTION=stdio. In-process selection, including the omitted connection's default, fails with this tag; there is no automatic fallback. Without it, Linux builds can require glibc even with CGO_ENABLED=0, preventing startup in glibc-free images such as scratch or Alpine.
  • With no override, ClientOptions.Runtime == nil selects in-process. Set COPILOT_SDK_DEFAULT_CONNECTION=stdio or use SpawnedStdioConnection{} to retain a subprocess. An explicit connection always takes precedence.
  • Set COPILOT_CLI_PATH only when using an externally provisioned compatible runtime package; otherwise the bundled runtime is used. No PATH lookup is performed.
  • Embedded runtime versions are isolated in separate cache directories. Start fails loudly if the native runtime is unavailable.
  • Managed child-process start fails if the embedded copilot-runtime and runtime.node pair is unavailable; explicit paths and COPILOT_CLI_PATH remain direct overrides.
  • Linux in-process bundles include both glibc and musl runtime packages and select the matching package automatically at startup.
  • Only one native runtime version may be loaded per process.

Observability.Telemetry configures per-runtime startup, including in-process. Omitted settings inherit the environment; policy takes precedence. In-process runtimes do not expose child-process settings:

  • Env — set variables in the host process environment instead.
  • WorkingDirectory — the runtime shares the host process's working directory. Set CreateSessionOptions.WorkingDirectory instead.

FFI uses purego. Linux CGO_ENABLED=0 builds require glibc; Alpine/musl in-process builds require CGO_ENABLED=1 with a musl C toolchain.

API Reference

Client
  • NewClient(options *ClientOptions) *Client - Create a new client
  • Start(ctx context.Context) error - Start the CLI server
  • Stop() error - Gracefully stop the CLI server. For an owned stdio process, requests runtime shutdown, closes stdin, and waits up to 10 seconds for host cleanup (including telemetry) and natural exit before falling back to a forced termination.
  • ForceStop() - Forcefully stop without graceful RPC cleanup. Retires local event subscriptions and session callbacks, including entries held by dispatch snapshots or unsubscribe handles. Pending response waits fail without waiting for idle or their context deadlines; already-dispatched handlers are not joined. Late event registration is logged and returns a no-op unsubscribe, and a late tool-replacement acknowledgment cannot restore retired handlers.
  • A plain SendAndWait that has already received its terminal idle or error preserves that result when local session retirement races the wait. An earlier event handler may also call Disconnect on the terminal event without losing that result. Without retirement, the wait still lets earlier synchronous handlers finish; a forced stop does not join those handlers or complete waits whose terminal dispatch they are still blocking.
  • CreateSession(ctx context.Context, config *CreateSessionOptions) (*Session, error) - Create a new session
  • ResumeSession(ctx context.Context, sessionID string, config *ResumeSessionOptions) (*Session, error) - Resume an existing session
  • ListSessions(ctx context.Context, filter *SessionListFilter) ([]SessionMetadata, error) - List sessions (with optional filter)
  • DeleteSession(ctx context.Context, sessionID string) error - Delete a session permanently
  • GetLastSessionID(ctx context.Context) (*string, error) - Get the ID of the most recently updated session
  • Ping(ctx context.Context, message string) (*PingResponse, error) - Ping the server
  • RuntimePort() int - TCP port the runtime is listening on (0 if stdio)
  • GetForegroundSessionID(ctx context.Context) (*string, error) - Get the session ID currently displayed in TUI (TUI+server mode only)
  • SetForegroundSessionID(ctx context.Context, sessionID string) error - Request TUI to display a specific session (TUI+server mode only)
  • On(handler SessionLifecycleHandler) func() - Subscribe to all lifecycle events; returns unsubscribe function
  • OnEventType(eventType SessionLifecycleEventType, handler SessionLifecycleHandler) func() - Subscribe to specific lifecycle event type

Session Lifecycle Events:

// Subscribe to all lifecycle events
unsubscribe := client.On(func(event copilot.SessionLifecycleEvent) {
	fmt.Printf("Session %s: %s\n", event.SessionID, event.Type)
})
defer unsubscribe()

// Subscribe to specific event type
unsubscribeForeground := client.OnEventType(copilot.SessionLifecycleForeground, func(event copilot.SessionLifecycleEvent) {
	fmt.Printf("Session %s is now in foreground\n", event.SessionID)
})
defer unsubscribeForeground()

Event types: SessionLifecycleCreated, SessionLifecycleDeleted, SessionLifecycleUpdated, SessionLifecycleForeground, SessionLifecycleBackground

ClientOptions:

  • Mode (ClientMode, required): Select ModeCodingAgent for CLI-like behavior or ModeEmpty to opt into features explicitly. NewClient panics if options or mode are omitted. Feature settings live in typed groups on ClientOptions, CreateSessionOptions, and ResumeSessionOptions; dotted names below identify those fields. This API uses grouped create/resume RPC payloads and requires protocol 4 runtimes.

  • Runtime (RuntimeConnection): How the SDK connects to the runtime. Construct via one of:

    • SpawnedStdioConnection{Path, Args, Env, WorkingDirectory} — spawn a runtime over stdio
    • SpawnedTCPConnection{Port, ConnectionToken, Path, Args, Env, WorkingDirectory} — spawn a runtime that listens on TCP
    • TCPConnection{Host, Port, ConnectionToken} — connect to an already-running runtime (no process spawned)
    • InProcessConnection{} — the default if Connection is nil. Host the runtime in-process via the native FFI library. See In-process transport.

    When Path is empty for stdio/tcp, the SDK uses COPILOT_CLI_PATH when set, then the bundled copilot-runtime and adjacent runtime.node.

    ForDefault(&OwnedRuntimeOptions{...}) synchronously resolves COPILOT_SDK_DEFAULT_CONNECTION at invocation (inprocess when unset, or stdio) without starting a runtime. A nil Runtime uses the same default at construction. SpawnedStdioConnection and SpawnedTCPConnection alone accept Env and WorkingDirectory.

  • Owned runtimes accept BaseDirectory and SessionIdleTimeoutSeconds. BaseDirectory selects Copilot data and sets child-process COPILOT_HOME; empty uses ~/.copilot. TCPConnection omits both settings and rejects non-default GitHub.Token, GitHub.UseLoggedInUser, Observability.LogLevel and Observability.Telemetry. Embedded CLI extraction remains controlled by embeddedcli.Config.Dir.

  • Extensions.LaunchProvider (ExtensionLaunchProvider): Experimental connection-level resolver for extension launch profiles. Start installs the reverse-RPC handler and registers the provider before sessions can be created.

  • Network (*NetworkConfig): Experimental. Network callbacks through which the SDK host resolves the runtime's proxies (ResolveProxy), supplies Kerberos tokens for proxies' Negotiate challenges (AuthenticateNegotiate) and supplies credentials for proxies' Basic challenges (AuthenticateBasic). Start installs the network.resolveProxy, network.authenticateNegotiate and network.authenticateBasic handlers for the configured callbacks and registers them with the optional Scope (NetworkScopeConnection by default, or NetworkScopeRuntime) before sessions can be created. See Network callbacks.

  • Installations.ConfirmationHandler (InstallationConfirmationHandler): Experimental connection-global human review for installations.confirm. Receives the typed request, a per-request cancellation context and a separate connection-closed signal, then returns an explicit decision. Does not enable installation capabilities.

  • Observability.LogLevel (string): Log level. When empty (default), the runtime uses its own default level (the SDK does not pass --log-level).

  • Child-process Env ([]string): Environment variables (nil inherits from the process; an empty slice supplies an empty environment).

    For the native standalone runtime, include "COPILOT_TELEMETRY_DISABLED=true" in child-process Env before startup to disable Copilot-owned GitHub and Entra authentication telemetry process-wide, including sessionless events. Authentication, GitHub.OnTelemetry forwarding, and user-configured OpenTelemetry export remain unchanged. This is separate from GitHub.TelemetryEnabled: copilot.Bool(false), which disables only a session's pipeline. The value must be exactly "true"; changing it requires a process restart. COPILOT_GITHUB_TELEMETRY_DISABLED remains native-runtime/GitHub-only. In-process connections have no Env setting; set the variable in the host process environment before starting the runtime instead.

  • GitHub.Token (string): GitHub token for authentication. When provided, takes priority over other auth methods.

  • GitHub.UseLoggedInUser (*bool): Whether to use logged-in user for authentication (default: true, but false when GitHub.Token is provided). Cannot be used with TCPConnection.

  • Observability.Telemetry (*TelemetryConfig): OpenTelemetry configuration for the runtime. Providing this enables telemetry — no separate flag needed. See Telemetry below.

  • SessionFS (*SessionFSConfig): Custom session filesystem provider configuration. For the view tool to read provider-only images, set Capabilities.Binary and return a provider implementing SessionFSBinaryProvider (ReadFileBytes and WriteFileBytes) from State.CreateSessionFSProvider. Image reads do not fall back to local files. Binary reads and writes are limited to 50,330,880 bytes before encoding or decoding.

CreateSessionOptions:

  • Model (string): Model to use ("gpt-5", "claude-sonnet-4.5", etc.). Required when using custom provider.
  • Inference.ReasoningEffort (string): Reasoning effort level for models that support it ("low", "medium", "high", "xhigh", "max"). Use ListModels() to check which models support this option.
  • SessionID (string): Custom session ID
  • Tools.Definitions ([]Tool): Custom tools exposed to the CLI
  • SystemMessage (*SystemMessageConfig): System message configuration. Supports three modes:
    • append (default): Appends Content after the SDK-managed prompt
    • replace: Replaces the entire prompt with Content
    • customize: Selectively override individual sections via Sections map (keys: SectionPreamble, SectionIdentity, SectionTone, SectionToolEfficiency, SectionEnvironmentContext, SectionCodeChangeRules, SectionGuidelines, SectionSafety, SectionToolInstructions, SectionCustomInstructions, SectionRuntimeInstructions, SectionLastInstructions; values: SectionOverride with Action and optional Content)
  • Inference.Providers ([]NamedProviderConfig): Named BYOK connections. See Custom Providers.
  • Events.Streaming (*bool): Enable streaming delta events (nil = runtime default)
  • State.InfiniteSessions (*InfiniteSessionConfig): Automatic context compaction configuration
  • Execution.Autopilot (*rpc.AutopilotOptions, experimental): Autopilot policy, also accepted by ResumeSessionOptions and options update. ContinuationEnabled defaults to true and does not change session mode; MaxContinues limits continuations outside an active objective (non-negative integer, default five, zero allows none). Updates and warm resumes preserve omitted fields; an empty object changes nothing. Re-supply on cold resume.
  • WorkingDirectory (string): Working directory for the session (default: runtime process working directory)
  • State.EnableCrossSessionStore (*bool): Enables the cross-session store for search and retrieval across sessions. When unset in ModeCodingAgent, the runtime default applies (enabled). In ModeEmpty, defaults to disabled.
  • GitHub.TokenProvider (GitHubTokenProvider): Acquires session-scoped GitHub tokens on demand. Return GitHubTokenResult with an ExpiresIn value that leaves more than one hour after the runtime validates the token (production GitHub tokens typically use 8 * 60 * 60 seconds), or GitHubTokenCancelled. Cannot be combined with GitHub.Token.
  • Permissions.OnRequest (PermissionHandlerFunc): Optional handler called before each tool execution to approve or deny it. When nil, permission requests are emitted as events and left pending for manual resolution. copilot.PermissionHandler.ApproveAll approves requests when managed settings are disabled and returns an error when GitHub.FetchManagedSettings is true. Custom handlers can inspect RequiresManagedApproval() for human-facing confirmation logic. See Permission Handling section.
  • Permissions.OnRequestWithPrompt (PermissionHandlerWithPromptFunc): Optional compatibility-preserving alternative that also receives the derived user-facing prompt. Takes precedence when both permission handlers are set. See Permission Handling section.
  • Interaction.OnUserInputRequest (UserInputHandler): Handler for legacy question-and-answer requests from the agent. Enables the legacy ask_user tool. See User Input Requests section.
  • Interaction.OnAttributedUserInputRequest (AttributedUserInputHandler): Same as Interaction.OnUserInputRequest, but its result can say a person answered. Takes precedence when both are set. See Reporting a person's answers.
  • Interaction.OnShellAuthenticationRequest (ShellAuthenticationHandler): Handler for passwords and other answers that shell commands run by the agent ask for, such as sudo -A, ssh, and git over HTTPS. The answer goes only to the program that asked; the model never sees it. Without a handler, those commands fail as they do without a terminal. See Shell password prompts.
  • Interaction.AskUserVariant (AskUserVariant): Selects the model-facing shape of the ask_user tool. The zero value preserves legacy behavior; use AskUserVariantElicitation with Interaction.OnElicitationRequest or Interaction.OnAttributedElicitationRequest.
  • GitHub.InteractiveUser (*bool): Declares that a person types this session's messages, as in an editor chat panel. Enables the runtime's user-message analysis telemetry for user-authored messages; automated messages stay excluded. Nil or false keeps the SDK default of off. Ignored for cloud sessions.
  • Permissions.Mode (rpc.PermissionMode): Applies manual, assisted, or allow-all before the session's first turn, before CreateSession returns. Uses the same checks as session.RPC.Permissions.SetMode; Session.PermissionModeResult() reports whether it was applied and the authoritative mode. Not supported for cloud sessions.
  • Hooks.Handlers (*SessionHooks): Hook handlers for session lifecycle events. See Session Hooks section.
  • Interaction.Commands ([]CommandDefinition): Slash-commands registered for this session. See Commands section.
  • Interaction.OnElicitationRequest (ElicitationHandler): Handler for elicitation requests from the server. See Elicitation Requests section.
  • Interaction.OnAttributedElicitationRequest (AttributedElicitationHandler) and Interaction.OnAttributedExitPlanModeRequest (AttributedExitPlanModeRequestHandler): Same as Interaction.OnElicitationRequest and Interaction.OnExitPlanModeRequest, but their results can say a person answered. Each takes precedence over its plain handler when both are set. See Reporting a person's answers.

ResumeSessionOptions:

  • Permissions.OnRequest (PermissionHandlerFunc): Optional handler called before each tool execution to approve or deny it. See Permission Handling section.
  • Permissions.OnRequestWithPrompt (PermissionHandlerWithPromptFunc): Optional alternative that also receives the derived user-facing prompt. Takes precedence when both permission handlers are set.
  • Tools.Definitions ([]Tool): Tools to expose when resuming
  • Inference.ReasoningEffort (string): Reasoning effort level for models that support it
  • Inference.Providers ([]NamedProviderConfig): Named BYOK connections. See Custom Providers.
  • Events.Streaming (*bool): Enable streaming delta events (nil = runtime default)
  • Interaction.Commands ([]CommandDefinition): Slash-commands. See Commands section.
  • Interaction.OnElicitationRequest (ElicitationHandler): Elicitation handler. See Elicitation Requests section.
  • Interaction.OnAttributedUserInputRequest, Interaction.OnAttributedExitPlanModeRequest, and Interaction.OnAttributedElicitationRequest: Re-supply the attributed prompt handlers on resume. See CreateSessionOptions.
  • Interaction.AskUserVariant (AskUserVariant): Selects the model-facing shape of the ask_user tool on cold resume. Re-supply AskUserVariantElicitation with Interaction.OnElicitationRequest or Interaction.OnAttributedElicitationRequest; the zero value preserves legacy behavior.
  • GitHub.InteractiveUser (*bool): Re-supplies the interactive-user declaration on cold resume. It is ignored when resuming a session that is already active.
  • Permissions.Mode (rpc.PermissionMode): Applied before resumed pending work continues. If it is refused (for example by managed policy), continued work runs under the mode session.PermissionModeResult() reports. See CreateSessionOptions.Permissions.Mode.
  • GitHub.TokenProvider (GitHubTokenProvider): Replaces the session-scoped token provider when resuming. Cannot be combined with GitHub.Token.
session, err := client.CreateSession(ctx, &copilot.CreateSessionOptions{GitHub: copilot.SessionGitHubOptions{TokenProvider: func(args copilot.GitHubTokenProviderArgs) (*copilot.GitHubTokenProviderResult, error) {
	token, err := acquireToken(args.Host)
	if err != nil {
		return nil, err
	}
	return copilot.GitHubTokenResult(&copilot.GitHubToken{
		AccessToken: token,
		ExpiresIn:   8 * 60 * 60,
	}), nil
}},
})

Initial acquisition runs during session creation or resume. Cancellation, provider errors, and invalid token responses reject that operation instead of falling back to ambient authentication. Idle sessions refresh only before their next credential-consuming operation; there is no background refresh timer.

Session
  • Send(ctx context.Context, options MessageOptions) (string, error) - Send a message
  • On(handler SessionEventHandler) func() - Subscribe to events (returns unsubscribe function)
  • Abort(ctx context.Context) error - Abort the currently processing message
  • SetTools(ctx context.Context, tools []Tool) error - Replace this client's live custom tools and handlers for the session. See changing tools for shared behavior and active-turn limitations.
  • GetEvents(ctx context.Context) ([]SessionEvent, error) - Get event history
  • Disconnect() error - Disconnect the session (releases in-memory resources, preserves disk state)
  • UI() *SessionUI - Interactive UI API for elicitation dialogs
  • Capabilities() SessionCapabilities - Host capabilities (e.g. elicitation support)
Message source

Set MessageOptions.Source to copilot.MessageSourceAgent(id) for messages from an identified agent. Use copilot.MessageSourceSystem for application-internal context, not as a substitute for agent provenance. Use copilot.MessageSourceUser for explicit user provenance, or leave it empty to omit source from the request and preserve the runtime's default behavior.

_, err := session.Send(ctx, copilot.MessageOptions{
	Prompt: "Review complete. The build passed.",
	Source: copilot.MessageSourceAgent("reviewer"),
	Mode:   "enqueue",
})

MessageSourceAgent returns a MessageSource containing agent- followed by the unchanged ID, so "reviewer" becomes "agent-reviewer". It does not trim whitespace, change case, or remove an existing prefix.

Use copilot.MessageSourceAutomation(id) for a turn sent on behalf of an automation the user configured, such as a recurring check-in; it becomes automation-<id>. An automation turn defines the session's task like a user message but carries no human authority; see Message provenance.

Source is independent of delivery Mode and AgentMode; it does not replace the session's SystemMessage configuration. SendAndWait accepts the same options and waits for response completion, returning nil if no assistant message arrives. Sub-agent events remain visible to listeners but do not complete the wait or supply its reply.

Helper Functions
  • Bool(v bool) *bool - Helper to create bool pointers (e.g. for Events.Streaming)
  • Int(v int) *int - Helper to create int pointers for MinLength, MaxLength
  • String(v string) *string - Helper to create string pointers
  • Float64(v float64) *float64 - Helper to create float64 pointers
System Message Customization

Control the system prompt using SystemMessage in session config:

session, err := client.CreateSession(ctx, &copilot.CreateSessionOptions{SystemMessage: &copilot.SystemMessageConfig{
	Content: "Always check for security vulnerabilities before suggesting changes.",
},
})

The SDK auto-injects environment context, tool instructions, and security guardrails. The default CLI persona is preserved, and your Content is appended after SDK-managed sections. To change the persona or fully redefine the prompt, use Mode: "replace" or Mode: "customize".

Customize Mode

Use Mode: "customize" to selectively override individual sections of the prompt while preserving the rest:

session, err := client.CreateSession(ctx, &copilot.CreateSessionOptions{SystemMessage: &copilot.SystemMessageConfig{
	Mode: "customize",
	Sections: map[string]copilot.SectionOverride{
		// Replace the tone/style section
		copilot.SectionTone: {Action: "replace", Content: "Respond in a warm, professional tone. Be thorough in explanations."},
		// Remove coding-specific rules
		copilot.SectionCodeChangeRules: {Action: "remove"},
		// Append to existing guidelines
		copilot.SectionGuidelines: {Action: "append", Content: "\n* Always cite data sources"},
	},
	// Additional instructions appended after all sections
	Content: "Focus on financial analysis and reporting.",
},
})

Available section constants: SectionPreamble, SectionIdentity, SectionTone, SectionToolEfficiency, SectionEnvironmentContext, SectionCodeChangeRules, SectionGuidelines, SectionSafety, SectionToolInstructions, SectionCustomInstructions, SectionRuntimeInstructions, SectionLastInstructions.

SectionIdentity and SectionToolInstructions are section groups that target a collection of related sub-sections as a unit. Use SectionPreamble to target just the identity preamble without affecting its sibling sub-sections.

SectionLastInstructions (last_instructions) includes configured subagent-model guidance when the task tool is available. Removing or replacing this section also removes that guidance; a SectionOverride.Transform callback receives the complete section, including the guidance, and its returned content is authoritative. Append, prepend, and preserve retain their usual section semantics. These overrides change prompt prose only, not configured subagent models, tool availability, or runtime dispatch policy. SectionRuntimeInstructions is a separate section: removing it does not remove SectionLastInstructions.

Each section override supports five static actions:

  • replace — Replace the section content entirely
  • remove — Remove the section from the prompt
  • append — Add content after the existing section
  • prepend — Add content before the existing section
  • preserve — No-op that opts an individually-addressable section out of a group-level remove

A sixth operation, transform, computes the new content from the current content. Set the Transform callback on a SectionOverride instead of Action; it takes precedence over Action and Content. The SDK calls it with the section's current content and uses the string it returns. Transform callbacks apply in customize mode only. If the callback returns an error, the section keeps its current content.

session, err := client.CreateSession(ctx, &copilot.CreateSessionOptions{SystemMessage: &copilot.SystemMessageConfig{
	Mode: "customize",
	Sections: map[string]copilot.SectionOverride{
		copilot.SectionGuidelines: {
			Transform: func(current string) (string, error) {
				return current + "\n* Always cite data sources", nil
			},
		},
	},
},
})

Unknown section IDs are handled gracefully: content from replace/append/prepend overrides is appended to additional instructions, and remove overrides are silently ignored.

Auto routing tiers

The canonical values are AutoTierEfficiency, AutoTierBalance, AutoTierIntelligence, and AutoTierFast, which send efficiency, balance, intelligence, and fast on the wire. Fast is an integrator-only latency preset, not a fourth first-party GitHub Copilot preference. The SDK forwards the requested value without deciding eligibility or inspecting client identity. An externally supplied older runtime returns its native runtime or JSON-RPC error; the SDK does not downgrade or silently ignore the request.

Omitting the tier on create uses the runtime default rather than Balance. A cold resume restores the persisted tier unless the resume request supplies an explicit override.

Change 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, so a pending status confirms acceptance rather than effect. Only the most recent request survives.

Watch for the outcome through the session.model_change event on success or the ephemeral session.auto_tier_switch_failed event on failure. A failed activation leaves the incumbent effective tier unchanged. Read the authoritative committed, pending, and activating preferences at any time through the session's model.getCurrent RPC method.

tier := copilot.AutoTierIntelligence
result, err := session.SetAutoTier(ctx, &tier)
if err != nil {
	return err
}
if result.Status == rpc.ModelSwitchAutoTierStatusPending {
	// Accepted, but not yet in effect.
}

// Return to the provider's default Auto routing.
_, err = session.SetAutoTier(ctx, nil)

SetModel accepts the same preference through SetModelOptions.AutoTier, which stages the tier atomically with selecting auto. Set ResetAutoTier instead to return to provider-default routing; the two options are mutually exclusive.

For Copilot Fusion, use the CLI's names: model "fusion" with CapiSessionOptions.FusionTier on create or resume, SetModelOptions.FusionTier on SetModel, or session.SetFusionTier. The tiers are FusionTierStandard, FusionTierHigh, and FusionTierMax. The routing identifiers these replace (balance, hydrafusion, and hydrafusion-max, and the hydrafusion and hydrafusion-max model IDs) remain accepted but are deprecated. See Copilot Fusion names.

See Auto tier persistence for the full lifecycle rules.

Image Support

The SDK supports image attachments via the Attachments field in MessageOptions. You can attach images by providing their file path, or by passing base64-encoded data directly using a blob attachment:

// File attachment — runtime reads from disk
_, err = session.Send(context.Background(), copilot.MessageOptions{
	Prompt: "What's in this image?",
	Attachments: []copilot.Attachment{
		&copilot.AttachmentFile{
			DisplayName: "image.jpg",
			Path:        "/path/to/image.jpg",
		},
	},
})

// Blob attachment — provide base64 data directly
mimeType := "image/png"
_, err = session.Send(context.Background(), copilot.MessageOptions{
	Prompt: "What's in this image?",
	Attachments: []copilot.Attachment{
		&copilot.AttachmentBlob{
			Data:     &base64ImageData,
			MIMEType: mimeType,
		},
	},
})

Supported image formats are PNG, JPEG, WebP, and GIF. Images in other formats, such as BMP or TIFF, are not sent to the model. The agent's view tool can also read images directly from the filesystem, so you can also ask questions like:

_, err = session.Send(context.Background(), copilot.MessageOptions{
	Prompt: "What does the most recent jpg in this directory portray?",
})

Tools

Expose your own functionality to Copilot by attaching tools to a session.

Use DefineTool for type-safe tools with automatic JSON schema generation:

type LookupIssueParams struct {
    ID string `json:"id" jsonschema:"Issue identifier"`
}

lookupIssue := copilot.DefineTool("lookup_issue", "Fetch issue details from our tracker",
    func(params LookupIssueParams, inv copilot.ToolInvocation) (any, error) {
        // params is automatically unmarshaled from the LLM's arguments
        issue, err := fetchIssue(params.ID)
        if err != nil {
            return nil, err
        }
        return issue.Summary, nil
    })

session, _ := client.CreateSession(context.Background(), &copilot.CreateSessionOptions{Model: "gpt-5", Tools: copilot.SessionToolOptions{Definitions: []copilot.Tool{lookupIssue}}})
Using Tool struct directly

For more control over the JSON schema, use the Tool struct directly:

lookupIssue := copilot.Tool{
	Name:        "lookup_issue",
	Description: "Fetch issue details from our tracker",
	Parameters: map[string]any{
		"type": "object",
		"properties": map[string]any{
			"id": map[string]any{
				"type":        "string",
				"description": "Issue identifier",
			},
		},
		"required": []string{"id"},
	},
	Handler: func(invocation copilot.ToolInvocation) (copilot.ToolResult, error) {
		args := invocation.Arguments.(map[string]any)
		issue, err := fetchIssue(args["id"].(string))
		if err != nil {
			return copilot.ToolResult{}, err
		}
		return copilot.ToolResult{
			TextResultForLLM: issue.Summary,
			ResultType:       "success",
			SessionLog:       fmt.Sprintf("Fetched issue %s", issue.ID),
		}, nil
	},
}

session, _ := client.CreateSession(context.Background(), &copilot.CreateSessionOptions{Model: "gpt-5", Tools: copilot.SessionToolOptions{Definitions: []copilot.Tool{lookupIssue}}})

When the model selects a tool, the SDK automatically runs your handler (in parallel with other calls) and responds to the CLI's tool.call with the handler's result.

Overriding Built-in Tools

If you register a tool with the same name as a built-in CLI tool (e.g. edit_file, read_file), the SDK will throw an error unless you explicitly opt in by setting OverridesBuiltInTool = true. This flag signals that you intend to replace the built-in tool with your custom implementation.

editFile := copilot.DefineTool("edit_file", "Custom file editor with project-specific validation",
	func(params EditFileParams, inv copilot.ToolInvocation) (any, error) {
		// your logic
		return nil, nil
	})
editFile.OverridesBuiltInTool = true

An explicit apply_patch override can declare a root string schema by using a string parameter with DefineTool. The model sees a required input property, but the runtime restores the scalar patch text before dispatch. Both the typed parameter and ToolInvocation.Arguments receive a string, not an {"input": ...} object. This example returns trimmed patch text; replace the handler body with your own patch implementation:

import "strings"

applyPatch := copilot.DefineTool("apply_patch", "Apply a patch",
    func(patch string, inv copilot.ToolInvocation) (string, error) {
        return strings.TrimSpace(patch), nil
    })
applyPatch.OverridesBuiltInTool = true

String-schema apply_patch overrides cannot contain JSON Schema references; use an object schema if references are needed.

Skipping Permission Prompts

Set SkipPermission = true on a tool to allow it to execute without triggering a permission prompt:

safeLookup := copilot.DefineTool("safe_lookup", "A read-only lookup that needs no confirmation",
	func(params LookupParams, inv copilot.ToolInvocation) (any, error) {
		// your logic
	})
safeLookup.SkipPermission = true

Deferring Tools

Set Defer to control whether a tool may be loaded lazily via tool search rather than always pre-loaded. Use copilot.ToolDeferAuto to allow the tool to be deferred and surfaced through tool search, or copilot.ToolDeferNever to force it to always be pre-loaded. Defaults to copilot.ToolDeferAuto.

lookupIssue := copilot.DefineTool("lookup_issue", "Fetch issue details",
	func(params LookupParams, inv copilot.ToolInvocation) (any, error) {
		// your logic
		return nil, nil
	})
lookupIssue.Defer = copilot.ToolDeferAuto

Structured output (experimental)

Use the package-level generic helper (Go does not support generic methods):

type Inventory struct {
    Count int    `json:"count"`
    Color string `json:"color"`
}

inventory, err := copilot.SendAndWait[Inventory](ctx, session, copilot.MessageOptions{
    Prompt: "Call get_inventory, then report the widget count and color.",
})

This derives the schema using the same jsonschema-go generator as DefineTool and unmarshals the final JSON into Inventory. Unmarshaling is not full JSON Schema validation. For an explicit schema, set MessageOptions.ResponseSchema on session.Send or session.SendAndWait; the latter returns the message event. The generic helper rejects an explicit schema or immediate delivery.

The schema lasts for one run, including tools, steering, and stop-hook corrections. Independent sends and subagents do not inherit it; streaming stays text. Structured waits select the last correlated root assistant message without tool requests at non-autopilot idle or the matching root session.autopilot_stopped. All SendAndWait variants accept this authoritative Autopilot terminal without waiting for or stopping attached shells. Its RequestID must match the original send ID; continuation messages do not change ownership. Missing, unrelated, or subagent terminals cannot complete the wait. session.idle remains whole-session quiescence; assistant.idle and session.task_complete alone are not completion. Concurrent waits retain their own results, though queued work can delay idle. Aborted runs, session errors after the run starts, and missing final output fail. Context cancellation stops waiting, not agent work.

Provider schema restrictions apply, and supplied schemas are forwarded unchanged. Low-level session.RPC.Send and session.RPC.SendMessages expose the full rpc.ResponseFormat options, including name, description, and strictness.

Streaming

Enable streaming to receive assistant response chunks as they're generated:

package main

import (
	"context"
	"fmt"
	"log"

	copilot "github.com/microsoft/copilot-sdk/go/v2"
)

func main() {
	client := copilot.NewClient(&copilot.ClientOptions{Mode: copilot.ModeCodingAgent})

	if err := client.Start(context.Background()); err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	session, err := client.CreateSession(context.Background(), &copilot.CreateSessionOptions{Model: "gpt-5", Events: copilot.SessionEventOptions{Streaming: copilot.Bool(true)}})
	if err != nil {
		log.Fatal(err)
	}
	defer session.Disconnect()

	done := make(chan bool)

	session.On(func(event copilot.SessionEvent) {
		switch d := event.Data.(type) {
		case *copilot.AssistantMessageDeltaData:
			// Streaming message chunk - print incrementally
			fmt.Print(d.DeltaContent)
		case *copilot.AssistantReasoningDeltaData:
			// Streaming reasoning chunk (if model supports reasoning)
			fmt.Print(d.DeltaContent)
		case *copilot.AssistantMessageData:
			// Final message - complete content
			fmt.Println("\n--- Final message ---")
			fmt.Println(d.Content)
		case *copilot.AssistantReasoningData:
			// Final reasoning content (if model supports reasoning)
			fmt.Println("--- Reasoning ---")
			fmt.Println(d.Content)
		case *copilot.SessionIdleData:
			close(done)
		}
	})

	_, err = session.Send(context.Background(), copilot.MessageOptions{
		Prompt: "Tell me a short story",
	})
	if err != nil {
		log.Fatal(err)
	}

	<-done
}

When Streaming: copilot.Bool(true):

  • assistant.message_delta events are sent with DeltaContent containing incremental text
  • assistant.reasoning_delta events are sent with DeltaContent for reasoning/chain-of-thought (model-dependent)
  • Accumulate DeltaContent values to build the full response progressively
  • The final assistant.message and assistant.reasoning events contain the complete content

Note: assistant.message and assistant.reasoning (final events) are always sent regardless of streaming setting.

Infinite Sessions

By default, sessions use infinite sessions which automatically manage context window limits through background compaction and persist state to a workspace directory.

// Default: infinite sessions enabled with default thresholds
session, _ := client.CreateSession(context.Background(), &copilot.CreateSessionOptions{Model: "gpt-5"})

// Access the workspace path for checkpoints and files
fmt.Println(session.WorkspacePath())
// => ~/.copilot/session-state/{sessionId}/

// Custom thresholds
customSession, _ := client.CreateSession(context.Background(), &copilot.CreateSessionOptions{Model: "gpt-5", State: copilot.SessionStateOptions{InfiniteSessions: &copilot.InfiniteSessionConfig{
	Enabled:                       copilot.Bool(true),
	BackgroundCompactionThreshold: copilot.Float64(0.80), // Start compacting at 80% context usage
	BufferExhaustionThreshold:     copilot.Float64(0.95), // Block at 95% until compaction completes
}},
})

// Disable infinite sessions
disabledSession, _ := client.CreateSession(context.Background(), &copilot.CreateSessionOptions{Model: "gpt-5", State: copilot.SessionStateOptions{InfiniteSessions: &copilot.InfiniteSessionConfig{
	Enabled: copilot.Bool(false),
}},
})

When enabled, sessions emit compaction events:

  • session.compaction_start - Background compaction started
  • session.compaction_complete - Compaction finished (includes token counts)

Memory

Sessions can opt in to the memory feature, which lets the agent persist and recall information across turns. Provide a MemoryConfiguration on session create or resume; when omitted, the runtime default applies. In ModeCodingAgent client mode the SDK leaves State.Memory unset so the runtime applies its own default, while ModeEmpty defaults State.Memory to disabled unless you set it explicitly. For more background, see About GitHub Copilot Memory.

// Enable memory for a session
session, _ := client.CreateSession(context.Background(), &copilot.CreateSessionOptions{Model: "gpt-5", State: copilot.SessionStateOptions{Memory: &copilot.MemoryConfiguration{
	Enabled: true,
}},
})

// Disable memory for a session
memoryOffSession, _ := client.CreateSession(context.Background(), &copilot.CreateSessionOptions{Model: "gpt-5", State: copilot.SessionStateOptions{Memory: &copilot.MemoryConfiguration{
	Enabled: false,
}},
})

Custom Providers

The SDK supports custom OpenAI-compatible API providers (BYOK - Bring Your Own Key), including local providers like Ollama. When using a custom provider, you must specify the Model explicitly.

NamedProviderConfig:

  • Type (string): Provider type - "openai", "azure", "anthropic", or "google" (default: "openai"). "google" (experimental) uses Google's native Gemini Interactions API.
  • BaseURL (string): API endpoint URL (required)
  • APIKey (string): API key (optional for local providers like Ollama)
  • BearerToken (string): Bearer token for authentication (takes precedence over APIKey)
  • WireAPI (string): API format for OpenAI/Azure - "completions" or "responses" (default: "completions")
  • Azure.APIVersion (string): Azure API version; when empty, the runtime uses the GA versionless v1 route

Example with Ollama:

defaultProvider := copilot.String("byok")
session, err := client.CreateSession(context.Background(), &copilot.CreateSessionOptions{GitHub: copilot.SessionGitHubOptions{Capi: &copilot.CapiSessionOptions{Enabled: copilot.Bool(false)}}, Model: "deepseek-coder-v2:16b", Inference: // Required when using custom provider
copilot.SessionInferenceOptions{DefaultProvider: &defaultProvider, Providers: []copilot.NamedProviderConfig{{Name: "byok",
	Type:    "openai",
	BaseURL: "http://localhost:11434/v1", // Ollama endpoint
	// APIKey not required for Ollama
}}},
})

Example with custom OpenAI-compatible API:

defaultProvider := copilot.String("byok")
session, err := client.CreateSession(context.Background(), &copilot.CreateSessionOptions{GitHub: copilot.SessionGitHubOptions{Capi: &copilot.CapiSessionOptions{Enabled: copilot.Bool(false)}}, Model: "gpt-4", Inference: copilot.SessionInferenceOptions{DefaultProvider: &defaultProvider, Providers: []copilot.NamedProviderConfig{{Name: "byok",
	Type:    "openai",
	BaseURL: "https://my-api.example.com/v1",
	APIKey:  os.Getenv("MY_API_KEY"),
}}},
})

Example with Azure OpenAI:

defaultProvider := copilot.String("byok")
session, err := client.CreateSession(context.Background(), &copilot.CreateSessionOptions{GitHub: copilot.SessionGitHubOptions{Capi: &copilot.CapiSessionOptions{Enabled: copilot.Bool(false)}}, Model: "gpt-4", Inference: copilot.SessionInferenceOptions{DefaultProvider: &defaultProvider, Providers: []copilot.NamedProviderConfig{{Name: "byok",
	Type:    "azure",                                // Must be "azure" for Azure endpoints, NOT "openai"
	BaseURL: "https://my-resource.openai.azure.com", // Just the host, no path
	APIKey:  os.Getenv("AZURE_OPENAI_KEY"),
	Azure: &copilot.AzureProviderOptions{
		APIVersion: "2024-10-21",
	},
}}},
})

Important notes:

  • When using a custom provider, the Model parameter is required. The SDK will return an error if no model is specified.
  • For Azure OpenAI endpoints (*.openai.azure.com), you must use Type: "azure", not Type: "openai".
  • The BaseURL should be just the host (e.g., https://my-resource.openai.azure.com). Do not include /openai/v1 in the URL - the SDK handles path construction automatically.

Telemetry

The SDK supports OpenTelemetry for distributed tracing. Provide a Observability.Telemetry config to enable trace export and W3C Trace Context propagation.

client := copilot.NewClient(&copilot.ClientOptions{Mode: copilot.ModeCodingAgent, Observability: copilot.ClientObservabilityOptions{Telemetry: &copilot.TelemetryConfig{
	OTLPEndpoint: "http://localhost:4318",
}},
})

TelemetryConfig fields:

  • OTLPEndpoint (string): OTLP HTTP endpoint URL
  • OTLPProtocol (string): OTLP HTTP protocol for all signals ("http/json" or "http/protobuf")
  • FilePath (string): File path for JSON-lines trace output
  • ExporterType (string): "otlp-http" or "file"
  • SourceName (string): Instrumentation scope name
  • CaptureContent (bool): Whether to capture message content

Trace context (traceparent/tracestate) is propagated between the SDK and CLI on CreateSession, ResumeSession, and Send calls, and inbound when the CLI invokes tool handlers. The SDK injects and extracts it with the global OpenTelemetry propagator, which drops trace context until your application installs one, so set a W3C Trace Context propagator at startup:

import (
    "go.opentelemetry.io/otel"
    "go.opentelemetry.io/otel/propagation"
)

otel.SetTextMapPropagator(propagation.TraceContext{})

In a tool handler, ToolInvocation.TraceContext is a context.Context with the CLI's execute_tool span restored. Start your spans from it, for example with otel.Tracer("my-app").Start(inv.TraceContext, "my-tool"), so they are parented to that span.

Dependency: go.opentelemetry.io/otel

Permission Handling

Permission handlers are optional when you create or resume a session. The selected handler returns a decision before each tool executes. With no handler, permission requests remain pending as events for manual resolution.

Use Permissions.OnRequestWithPrompt when the callback needs optional derived prompt context as invocation.PromptRequest, matching PermissionRequestedData.PromptRequest. Both callbacks expose ProgramToolCallID (nil for ordinary requests); positional PermissionInvocation literals need updating. The raw request's managed-approval marker remains managed-policy provenance and enforces one-shot restrictions. Only derived commands, read, write, url, and workflow prompts can clear the human requirement after Assisted approval; for missing or other prompt kinds, keep the raw marker authoritative.

Set config.Permissions.OnRequestWithEnvelope before CreateSession or ResumeSession for lossless forwarding. The handler receives a *copilot.PermissionRequestEnvelope and PermissionHandlerInvocation; envelope.Request retains the concrete typed variant. It overrides the config's permission handlers; a nil handler retains their existing behavior without changing the config.

Set config.MCP.OnAuthRuntimeRefresh alongside the permission handler to compose both callbacks. Enable config.Interaction.AutoModeRecovery with config.Interaction.OnAutoModeSwitchRequest for recovery-aware decisions. Each nil handler retains the corresponding config callbacks without changing the config.

Pass the envelope itself as rpc.SessionPermissionsManagedReviewRequiredRequest.Request, not envelope.Request. The envelope owns the original JSON and initial typed state, so it remains usable after the callback returns.

Typed edits preserve untouched unknown fields, nulls, and numeric precision in objects and same-length arrays (by index). Nil optional fields are removed; resized arrays and scalars replace originals. Call envelope.Replace(request) to replace the entire payload and discard original unknown fields.

Legacy callbacks and plain typed values keep their original field layout and encoding; they do not retain unknown JSON.

Approve All (simplest)

Use the built-in PermissionHandler.ApproveAll helper when managed settings are disabled:

session, err := client.CreateSession(context.Background(), &copilot.CreateSessionOptions{Model: "gpt-5", Permissions: copilot.SessionPermissionOptions{OnRequest: copilot.PermissionHandler.ApproveAll},
})

When GitHub.FetchManagedSettings is true for the session, ApproveAll returns an error. Use a custom handler for managed sessions; request-level RequiresManagedApproval() remains available for human-facing confirmation logic.

Custom Permission Handler

Provide your own PermissionHandlerWithPromptFunc to inspect each request and the optional derived prompt. Check the raw managed requirement before any automatic approval, and clear it only from a supported derived prompt:

import (
    "fmt"

    copilot "github.com/microsoft/copilot-sdk/go/v2"
    "github.com/microsoft/copilot-sdk/go/v2/rpc"
)

session, err := client.CreateSession(context.Background(), &copilot.CreateSessionOptions{Model: "gpt-5", Permissions: copilot.SessionPermissionOptions{OnRequestWithPrompt: func(request copilot.PermissionRequest, invocation copilot.PermissionHandlerInvocation) (rpc.PermissionDecision, error) {
	assistedApprovalClearsManagedRequirement := false
	switch prompt := invocation.PromptRequest.(type) {
	case *rpc.PermissionPromptRequestCommands:
		assistedApprovalClearsManagedRequirement = prompt.ManagedApprovalRequired == nil || !*prompt.ManagedApprovalRequired
	case *rpc.PermissionPromptRequestRead:
		assistedApprovalClearsManagedRequirement = prompt.ManagedApprovalRequired == nil || !*prompt.ManagedApprovalRequired
	case *rpc.PermissionPromptRequestWrite:
		assistedApprovalClearsManagedRequirement = prompt.ManagedApprovalRequired == nil || !*prompt.ManagedApprovalRequired
	case *rpc.PermissionPromptRequestURL:
		assistedApprovalClearsManagedRequirement = prompt.ManagedApprovalRequired == nil || !*prompt.ManagedApprovalRequired
	case *rpc.PermissionPromptRequestWorkflow:
		assistedApprovalClearsManagedRequirement = prompt.ManagedApprovalRequired == nil || !*prompt.ManagedApprovalRequired
	}
	if request.RequiresManagedApproval() && !assistedApprovalClearsManagedRequirement {
		return &rpc.PermissionDecisionNoResult{}, nil
	}

	// Type-switch on the discriminated PermissionRequest variants to
	// access per-kind fields:
	if shell, ok := request.(*copilot.PermissionRequestShell); ok {
		feedback := fmt.Sprintf("Refusing shell: %s", shell.FullCommandText)
		return &rpc.PermissionDecisionReject{Feedback: &feedback}, nil
	}
	return &rpc.PermissionDecisionApproveOnce{}, nil
}},
})
Permission Decisions

The handler returns an rpc.PermissionDecision — a sealed interface implemented by every decision variant:

Variant Meaning
&rpc.PermissionDecisionApproveOnce{} Allow this single request
&rpc.PermissionDecisionReject{...} Deny the request (set Feedback to forward a message to the LLM)
&rpc.PermissionDecisionUserNotAvailable{} Deny because no user is available to confirm
&rpc.PermissionDecisionNoResult{} Decline to respond, allowing another connected client to answer instead

Richer decisions (PermissionDecisionApproveForSession, PermissionDecisionApproveForLocation, PermissionDecisionApprovePermanently) carry per-kind approval payloads — instantiate the variant struct directly.

Resuming Sessions

You may pass either config permission handler when resuming a session:

session, err := client.ResumeSession(context.Background(), sessionID, &copilot.ResumeSessionOptions{Permissions: copilot.SessionPermissionOptions{OnRequest: copilot.PermissionHandler.ApproveAll},
})

AllowTranscriptRecovery controls transcript repair on resume. A nil value omits the wire field and uses the runtime default (true) in all modes. Set copilot.Bool(false) to reject recovery. session.TranscriptRecovery() returns repair details or nil. The report's InvalidLineNumbers includes any discarded torn-tail lines. On rejection, use errors.As(err, &rpcErr) with var rpcErr *copilot.RPCError to inspect rpcErr.Code and rpcErr.Data (invalidLineNumbers, sessionStartMoved); the original error message remains available. Disabling recovery still permits adding a missing newline after an intact final record; it rejects torn tails.

Per-Tool Skip Permission

To let a specific custom tool bypass the permission prompt entirely, set SkipPermission = true on the tool. See Skipping Permission Prompts under Tools.

User Input Requests

Enable the legacy question-and-answer ask_user tool by providing an Interaction.OnUserInputRequest handler:

session, err := client.CreateSession(context.Background(), &copilot.CreateSessionOptions{Model: "gpt-5", Interaction: copilot.SessionInteractionOptions{OnUserInputRequest: func(request copilot.UserInputRequest, invocation copilot.UserInputInvocation) (copilot.UserInputResponse, error) {
	// request.Question - The question to ask
	// request.Choices - Optional slice of choices for multiple choice
	// request.AllowFreeform - Whether freeform input is allowed (default: true)
	// request.RequestID - Runtime ID of the pending request, for RPC.UI.HandlePendingUserInput (empty on older runtimes)

	fmt.Printf("Agent asks: %s\n", request.Question)
	if len(request.Choices) > 0 {
		fmt.Printf("Choices: %v\n", request.Choices)
	}

	// Return the user's response
	return copilot.UserInputResponse{
		Answer:      "User's answer here",
		WasFreeform: true, // Whether the answer was freeform (not from choices)
	}, nil
}},
})

Reporting a person's answers

When a person answers a prompt in your UI, register the attributed handler for that prompt and set DecisionContext on its result so Assisted Permissions can treat the answer as the person's own authority. Use OnAttributedUserInputRequest (AttributedUserInputResponse), OnAttributedExitPlanModeRequest (AttributedExitPlanModeResult), and OnAttributedElicitationRequest (AttributedElicitationResult); each result embeds the plain result. For permission handlers, use copilot.NewAttributedPermissionResult:

interactive := copilot.PermissionResponseCapabilityInteractive
personAnswered := &copilot.PermissionDecisionContext{
    Source:             copilot.PermissionDecisionSourceHumanResponse,
    ResponseCapability: &interactive,
    Surface:            copilot.PermissionDecisionSurfaceSDK,
    Outcome:            copilot.PermissionDecisionOutcomePromptedUser,
}

session, err := client.CreateSession(context.Background(), &copilot.CreateSessionOptions{
    Model: "gpt-5", Interaction: copilot.SessionInteractionOptions{
    OnAttributedUserInputRequest: func(request copilot.UserInputRequest, invocation copilot.UserInputInvocation) (copilot.AttributedUserInputResponse, error) {
        return copilot.AttributedUserInputResponse{
            UserInputResponse: copilot.UserInputResponse{Answer: "Only src/app.ts", WasFreeform: true},
            DecisionContext:   personAnswered,
        }, nil
    },
    OnAttributedExitPlanModeRequest: func(request copilot.ExitPlanModeRequest, invocation copilot.ExitPlanModeInvocation) (copilot.AttributedExitPlanModeResult, error) {
        return copilot.AttributedExitPlanModeResult{
            ExitPlanModeResult: copilot.ExitPlanModeResult{Approved: true, SelectedAction: "interactive"},
            DecisionContext:    personAnswered,
        }, nil
    },
    OnAttributedElicitationRequest: func(ctx copilot.ElicitationContext) (copilot.AttributedElicitationResult, error) {
        return copilot.AttributedElicitationResult{
            ElicitationResult: copilot.ElicitationResult{Action: copilot.ElicitationActionDecline},
            DecisionContext:   personAnswered,
        }, nil
    },
}})

Label a person's declines and dismissals too; the runtime decides which answers carry authority. It accepts the label only from the connection that owns the session, so other connections' answers still settle, without it. Leave automated answers unlabeled: a nil DecisionContext sends no label. Each attributed handler enables its prompt just like the plain one. When a config sets both, the attributed handler answers and the plain one is not called.

Session Hooks

Hook into session lifecycle events by providing handlers in the Hooks.Handlers configuration:

session, err := client.CreateSession(context.Background(), &copilot.CreateSessionOptions{Model: "gpt-5", Hooks: copilot.SessionHookOptions{Handlers: &copilot.SessionHooks{
	// Called before each tool execution
	OnPreToolUse: func(input copilot.PreToolUseHookInput, invocation copilot.HookInvocation) (*copilot.PreToolUseHookOutput, error) {
		fmt.Printf("About to run tool: %s\n", input.ToolName)
		// Return permission decision and optionally modify args
		return &copilot.PreToolUseHookOutput{
			PermissionDecision: "allow",        // "allow", "deny", or "ask"
			ModifiedArgs:       input.ToolArgs, // Optionally modify tool arguments
			AdditionalContext:  "Extra context for the model",
		}, nil
	},

	// Called after each tool execution
	OnPostToolUse: func(input copilot.PostToolUseHookInput, invocation copilot.HookInvocation) (*copilot.PostToolUseHookOutput, error) {
		fmt.Printf("Tool %s completed\n", input.ToolName)
		return &copilot.PostToolUseHookOutput{
			AdditionalContext: "Post-execution notes",
		}, nil
	},

	// Called when a tool execution result was a failure. OnPostToolUse only
	// fires on success, so register OnPostToolUseFailure to observe failed
	// tool calls. The CLI extracts the failure message and passes it as
	// input.Error.
	OnPostToolUseFailure: func(input copilot.PostToolUseFailureHookInput, invocation copilot.HookInvocation) (*copilot.PostToolUseFailureHookOutput, error) {
		fmt.Printf("Tool %s failed: %s\n", input.ToolName, input.Error)
		return &copilot.PostToolUseFailureHookOutput{
			AdditionalContext: fmt.Sprintf("Retry guidance for %s", input.ToolName),
		}, nil
	},

	// Called when user submits a prompt
	OnUserPromptSubmitted: func(input copilot.UserPromptSubmittedHookInput, invocation copilot.HookInvocation) (*copilot.UserPromptSubmittedHookOutput, error) {
		fmt.Printf("User prompt: %s\n", input.Prompt)
		return &copilot.UserPromptSubmittedHookOutput{
			ModifiedPrompt: input.Prompt, // Optionally modify the prompt
		}, nil
	},

	// Called when session starts
	OnSessionStart: func(input copilot.SessionStartHookInput, invocation copilot.HookInvocation) (*copilot.SessionStartHookOutput, error) {
		fmt.Printf("Session started from: %s\n", input.Source) // "startup", "resume", "new"
		return &copilot.SessionStartHookOutput{
			AdditionalContext: "Session initialization context",
		}, nil
	},

	// Called when session ends
	OnSessionEnd: func(input copilot.SessionEndHookInput, invocation copilot.HookInvocation) (*copilot.SessionEndHookOutput, error) {
		fmt.Printf("Session ended: %s\n", input.Reason)
		return nil, nil
	},

	// Called before a subagent's first turn; context is prepended to its prompt
	OnSubagentStart: func(input copilot.SubagentStartHookInput, invocation copilot.HookInvocation) (*copilot.SubagentStartHookOutput, error) {
		fmt.Printf("Starting subagent %s\n", input.AgentName)
		return &copilot.SubagentStartHookOutput{
			AdditionalContext: "Focus on the requested file.",
		}, nil
	},

	// Called after a subagent finishes a turn
	OnSubagentStop: func(input copilot.SubagentStopHookInput, invocation copilot.HookInvocation) (*copilot.SubagentStopHookOutput, error) {
		fmt.Printf("Subagent %s finished: %s\n", input.AgentType, input.StopReason)
		return &copilot.SubagentStopHookOutput{
			ModifiedResponse: copilot.String("Verified: " + input.Response),
		}, nil
	},

	// Called when an error occurs
	OnErrorOccurred: func(input copilot.ErrorOccurredHookInput, invocation copilot.HookInvocation) (*copilot.ErrorOccurredHookOutput, error) {
		fmt.Printf("Error in %s: %s\n", input.ErrorContext, input.Error)
		return &copilot.ErrorOccurredHookOutput{
			ErrorHandling: "retry", // "retry", "skip", or "abort"
		}, nil
	},
}},
})

Available hooks:

  • OnPreToolUse - Intercept tool calls before execution. Can allow/deny or modify arguments.
  • OnPostToolUse - Process tool results after successful execution. Can modify results or add context.
  • OnPostToolUseFailure - Observe failed tool executions and inject extra context to guide the model's next step.
  • OnUserPromptSubmitted - Intercept user prompts. Can modify the prompt before processing, or return Decision: "block" with a non-empty Reason to refuse it: no model turn runs, no user message is recorded, and the session emits an ephemeral session.warning (warningType: "policy_blocked") carrying the reason.
  • OnSessionStart - Run logic when a session starts or resumes.
  • OnSessionEnd - Cleanup or logging when session ends.
  • OnSubagentStart - Observe a subagent before its first turn and optionally prepend AdditionalContext to its prompt.
  • OnSubagentStop - Observe a completed subagent turn. Return Decision: "block" with a non-empty Reason to request another turn, or ModifiedResponse: copilot.String("replacement") to replace its response (including an intentional empty string).
  • OnAgentStop - Intercept the parent agent's stop; distinct from OnSubagentStop.
  • OnErrorOccurred - Handle errors with retry/skip/abort strategies.

Subagent hook inputs identify the parent session in SessionID and HookInvocation.SessionID. Both include a time.Time timestamp, WorkingDirectory (cwd), TranscriptPath, and AgentName. AgentDisplayName and AgentDescription may be empty. Stop inputs additionally include an optional AgentID, AgentType, StopReason ("end_turn"), and the subagent's Response. Registering either hook alone enables hook callbacks for both new and resumed sessions.

Commands

Register slash-commands that users can invoke from the CLI TUI. When a user types /deploy production, the SDK dispatches to your handler and responds via the RPC layer.

session, err := client.CreateSession(ctx, &copilot.CreateSessionOptions{Permissions: copilot.SessionPermissionOptions{OnRequest: copilot.PermissionHandler.ApproveAll}, Interaction: copilot.SessionInteractionOptions{Commands: []copilot.CommandDefinition{
	{
		Name:        "deploy",
		Description: "Deploy the app to production",
		Handler: func(ctx copilot.CommandContext) error {
			fmt.Printf("Deploying with args: %s\n", ctx.Args)
			// ctx.SessionID, ctx.Command, ctx.CommandName, ctx.Args
			return nil
		},
	},
	{
		Name:        "rollback",
		Description: "Rollback the last deployment",
		Handler: func(ctx copilot.CommandContext) error {
			return nil
		},
	},
}},
})

Commands are also available when resuming sessions:

session, err := client.ResumeSession(ctx, sessionID, &copilot.ResumeSessionOptions{Permissions: copilot.SessionPermissionOptions{OnRequest: copilot.PermissionHandler.ApproveAll}, Interaction: copilot.SessionInteractionOptions{Commands: []copilot.CommandDefinition{
	{Name: "status", Description: "Show status", Handler: statusHandler},
}},
})

If a handler returns an error, the SDK sends the error message back to the server. Unknown commands automatically receive an error response.

UI Elicitation

The SDK provides convenience methods to ask the user questions via elicitation dialogs. These are gated by host capabilities — check session.Capabilities().UI.Elicitation before calling.

ui := session.UI()

// Confirmation dialog — returns bool
confirmed, err := ui.Confirm(ctx, "Deploy to production?")

// Selection dialog — returns (selected string, ok bool, error)
choice, ok, err := ui.Select(ctx, "Pick an environment", []string{"staging", "production"})

// Text input — returns (text, ok bool, error)
name, ok, err := ui.Input(ctx, "Enter the release name", &copilot.UIInputOptions{
	Title:       "Release Name",
	Description: "A short name for the release",
	MinLength:   copilot.Int(1),
	MaxLength:   copilot.Int(50),
})

// Full custom elicitation with a schema
result, err := ui.Elicitation(ctx, "Configure deployment", copilot.ElicitationSchema{
	Properties: map[string]any{
		"target": map[string]any{"type": "string", "enum": []string{"staging", "production"}},
		"force":  map[string]any{"type": "boolean"},
	},
	Required: []string{"target"},
})
// result.Action is "accept", "decline", or "cancel"
// result.Content has the form values when Action is "accept"

Elicitation Requests (Server→Client)

When the server (or an MCP tool) needs to ask the end-user a question, it sends an elicitation.requested event. Register a handler to respond:

session, err := client.CreateSession(ctx, &copilot.CreateSessionOptions{Permissions: copilot.SessionPermissionOptions{OnRequest: copilot.PermissionHandler.ApproveAll}, Interaction: copilot.SessionInteractionOptions{OnElicitationRequest: func(ctx copilot.ElicitationContext) (copilot.ElicitationResult, error) {
	// ctx.SessionID — session that triggered the request
	// ctx.Message — what's being asked
	// ctx.RequestedSchema — form schema (if mode is "form")
	// ctx.Mode — "form" or "url"
	// ctx.ElicitationSource — e.g. MCP server name
	// ctx.URL — browser URL (if mode is "url")

	// Return the user's response
	return copilot.ElicitationResult{
		Action:  copilot.ElicitationActionAccept,
		Content: map[string]any{"confirmed": true},
	}, nil
}},
})

When Interaction.OnElicitationRequest is provided, the SDK automatically:

  • Sends requestElicitation: true in the create/resume payload
  • Routes elicitation.requested events to your handler
  • Auto-cancels the request if your handler returns an error (so the server doesn't hang)

Transport Modes

In-process (default)

Loads the native Rust runtime into the application process. See in-process transport for requirements and shared-process limitations.

client := copilot.NewClient(&copilot.ClientOptions{Mode: copilot.ModeCodingAgent}) // Hosts the runtime in-process by default
stdio

Select copilot.SpawnedStdioConnection{} to run a subprocess communicating over stdin/stdout pipes.

TCP

Communicates with CLI via TCP socket. Useful for distributed scenarios.

Environment Variables

  • COPILOT_CLI_PATH - Path to the Copilot CLI executable

Development

Tests require a supported Node.js version. From the repository root:

cd nodejs
npm ci
cd test/harness
npm ci
cd go
./test.sh

License

MIT

Documentation

Overview

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(&copilot.ClientOptions{Mode: copilot.ModeCodingAgent})
if err := client.Start(); err != nil {
    log.Fatal(err)
}
defer client.Stop()

session, err := client.CreateSession(&copilot.CreateSessionOptions{
    OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
    Model: "gpt-5.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.

Index

Constants

View Source
const (
	// GitHubTokenRequestReasonInitial indicates the session needs its initial token.
	GitHubTokenRequestReasonInitial = rpc.GitHubTokenAcquireReasonInitial
	// GitHubTokenRequestReasonRefresh indicates the session needs a refreshed token.
	GitHubTokenRequestReasonRefresh = rpc.GitHubTokenAcquireReasonRefresh
)
View Source
const (
	AhpHostAuthenticationModeGitHub = rpc.HostAuthenticationModeGitHub
	AhpHostAuthenticationModeCustom = rpc.HostAuthenticationModeCustom
	AhpHostAuthenticationModeNone   = rpc.HostAuthenticationModeNone
)
View Source
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
)
View Source
const (
	// NetworkScopeConnection serves only requests made for sessions this client
	// creates or resumes.
	NetworkScopeConnection = rpc.NetworkScopeConnection
	// NetworkScopeRuntime also serves the runtime's shared background traffic.
	// Only one connection at a time can hold this scope.
	NetworkScopeRuntime = rpc.NetworkScopeRuntime
)
View Source
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.

View Source
const (
	PermissionResponseCapabilityHeadless    = rpc.PermissionResponseCapabilityHeadless
	PermissionResponseCapabilityInteractive = rpc.PermissionResponseCapabilityInteractive
	PermissionResponseCapabilityNone        = rpc.PermissionResponseCapabilityNone
)
View Source
const (
	PermissionDecisionOutcomeAutoApproved    = rpc.PermissionDecisionOutcomeAutoApproved
	PermissionDecisionOutcomeAutopilotDenied = rpc.PermissionDecisionOutcomeAutopilotDenied
	PermissionDecisionOutcomePromptedUser    = rpc.PermissionDecisionOutcomePromptedUser
)
View Source
const (
	PermissionDecisionSourceAssistedApproval   = rpc.PermissionDecisionSourceAssistedApproval
	PermissionDecisionSourceHostPolicy         = rpc.PermissionDecisionSourceHostPolicy
	PermissionDecisionSourceHumanResponse      = rpc.PermissionDecisionSourceHumanResponse
	PermissionDecisionSourceUnattendedFallback = rpc.PermissionDecisionSourceUnattendedFallback
)
View Source
const (
	PermissionDecisionSurfaceAcp        = rpc.PermissionDecisionSurfaceAcp
	PermissionDecisionSurfaceCopilotApp = rpc.PermissionDecisionSurfaceCopilotApp
	PermissionDecisionSurfacePromptMode = rpc.PermissionDecisionSurfacePromptMode
	PermissionDecisionSurfaceSDK        = rpc.PermissionDecisionSurfaceSDK
	PermissionDecisionSurfaceTui        = rpc.PermissionDecisionSurfaceTui
)
View Source
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"
)
View Source
const (
	// MemoryModeSystemPrompt includes memories in the system prompt (the default).
	MemoryModeSystemPrompt = rpc.MemoryModeSystemPrompt
	// MemoryModeUserPrompt includes memories in user messages.
	MemoryModeUserPrompt = rpc.MemoryModeUserPrompt
)
View Source
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
)
View Source
const (
	// FusionTierStandard selects Copilot Fusion Standard.
	FusionTierStandard = rpc.FusionTierStandard
	// FusionTierHigh selects Copilot Fusion High.
	FusionTierHigh = rpc.FusionTierHigh
	// FusionTierMax selects Copilot Fusion Max.
	FusionTierMax = rpc.FusionTierMax
)
View Source
const (
	AgentModeInteractive = rpc.SendAgentModeInteractive
	AgentModePlan        = rpc.SendAgentModePlan
	AgentModeAutopilot   = rpc.SendAgentModeAutopilot
	AgentModeShell       = rpc.SendAgentModeShell
)

AgentMode values supported by the runtime.

View Source
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
	AiCreditsStatusUnavailable                                           = rpc.AiCreditsStatusUnavailable
	AssistantMessageToolRequestCallerTypeProgram                         = rpc.AssistantMessageToolRequestCallerTypeProgram
	AssistantMessageToolRequestTypeCustom                                = rpc.AssistantMessageToolRequestTypeCustom
	AssistantMessageToolRequestTypeFunction                              = rpc.AssistantMessageToolRequestTypeFunction
	AssistantUsageAPIEndpointChatCompletions                             = rpc.AssistantUsageAPIEndpointChatCompletions
	AssistantUsageAPIEndpointInteractions                                = rpc.AssistantUsageAPIEndpointInteractions
	AssistantUsageAPIEndpointResponses                                   = rpc.AssistantUsageAPIEndpointResponses
	AssistantUsageAPIEndpointV1Messages                                  = rpc.AssistantUsageAPIEndpointV1Messages
	AssistantUsageAPIEndpointWsResponses                                 = rpc.AssistantUsageAPIEndpointWsResponses
	AssistantUsageTransportHTTP                                          = rpc.AssistantUsageTransportHTTP
	AssistantUsageTransportWebsocket                                     = rpc.AssistantUsageTransportWebsocket
	AssistedApprovalAssessmentStatusCompleted                            = rpc.AssistedApprovalAssessmentStatusCompleted
	AssistedApprovalAssessmentStatusExcluded                             = rpc.AssistedApprovalAssessmentStatusExcluded
	AssistedApprovalAssessmentStatusFailed                               = rpc.AssistedApprovalAssessmentStatusFailed
	AssistedApprovalAssessmentStatusNotRun                               = rpc.AssistedApprovalAssessmentStatusNotRun
	AssistedApprovalAssessmentStatusUnavailable                          = rpc.AssistedApprovalAssessmentStatusUnavailable
	AssistedApprovalCompletedRecommendationApprove                       = rpc.AssistedApprovalCompletedRecommendationApprove
	AssistedApprovalCompletedRecommendationRequireApproval               = rpc.AssistedApprovalCompletedRecommendationRequireApproval
	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
	AttachmentTypeSessionReference                                       = rpc.AttachmentTypeSessionReference
	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
	ExtensionsLoadedExtensionStatusDormant                               = rpc.ExtensionsLoadedExtensionStatusDormant
	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
	HumanResponseAskUserActionCancel                                     = rpc.HumanResponseAskUserActionCancel
	HumanResponseAskUserActionDecline                                    = rpc.HumanResponseAskUserActionDecline
	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
	ModelCallProductStateErrorInputItemConnectionMismatch                = rpc.ModelCallProductStateErrorInputItemConnectionMismatch
	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
	ModelCallWebSocketFallbackReasonConnectionUnavailable                = rpc.ModelCallWebSocketFallbackReasonConnectionUnavailable
	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
	OmittedBinaryOmittedReasonAssetUnavailable                           = rpc.OmittedBinaryOmittedReasonAssetUnavailable
	OmittedBinaryOmittedReasonTooLarge                                   = rpc.OmittedBinaryOmittedReasonTooLarge
	OmittedBinaryOmittedReasonUnsupportedFormat                          = rpc.OmittedBinaryOmittedReasonUnsupportedFormat
	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
	PermissionApprovalEvaluationReasonCodeExecutableUnavailable          = rpc.PermissionApprovalEvaluationReasonCodeExecutableUnavailable
	PermissionApprovalEvaluationReasonCodeExtensionPermissionAccess      = rpc.PermissionApprovalEvaluationReasonCodeExtensionPermissionAccess
	PermissionApprovalEvaluationReasonCodeInactive                       = rpc.PermissionApprovalEvaluationReasonCodeInactive
	PermissionApprovalEvaluationReasonCodeInherited                      = rpc.PermissionApprovalEvaluationReasonCodeInherited
	PermissionApprovalEvaluationReasonCodeInterpreterTooLarge            = rpc.PermissionApprovalEvaluationReasonCodeInterpreterTooLarge
	PermissionApprovalEvaluationReasonCodeInterpreterUnavailable         = rpc.PermissionApprovalEvaluationReasonCodeInterpreterUnavailable
	PermissionApprovalEvaluationReasonCodeInterpreterWrappedScript       = rpc.PermissionApprovalEvaluationReasonCodeInterpreterWrappedScript
	PermissionApprovalEvaluationReasonCodeInvalidWorkingDirectory        = rpc.PermissionApprovalEvaluationReasonCodeInvalidWorkingDirectory
	PermissionApprovalEvaluationReasonCodeJudgeContextTooLarge           = rpc.PermissionApprovalEvaluationReasonCodeJudgeContextTooLarge
	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
	PermissionApprovalEvaluationReasonCodeUnavailable                    = rpc.PermissionApprovalEvaluationReasonCodeUnavailable
	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
	PermissionRecoveryAttemptReasonResponderUnavailable                  = rpc.PermissionRecoveryAttemptReasonResponderUnavailable
	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
	PermissionRecoveryReasonResponderUnavailable                         = rpc.PermissionRecoveryReasonResponderUnavailable
	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
	ProviderMonthlyUsageStateUnavailable                                 = rpc.ProviderMonthlyUsageStateUnavailable
	ProviderMonthlyUsageStateUnknown                                     = rpc.ProviderMonthlyUsageStateUnknown
	ProviderQuotaAccessStateAllowed                                      = rpc.ProviderQuotaAccessStateAllowed
	ProviderQuotaAccessStateDenied                                       = rpc.ProviderQuotaAccessStateDenied
	ProviderQuotaAccessStateNotRequired                                  = rpc.ProviderQuotaAccessStateNotRequired
	ProviderQuotaAccessStateUnavailable                                  = rpc.ProviderQuotaAccessStateUnavailable
	ProviderQuotaAccessStateUnknown                                      = rpc.ProviderQuotaAccessStateUnknown
	ProviderQuotaAcquisitionStatusFailed                                 = rpc.ProviderQuotaAcquisitionStatusFailed
	ProviderQuotaAcquisitionStatusSucceeded                              = rpc.ProviderQuotaAcquisitionStatusSucceeded
	ProviderQuotaAcquisitionStatusUnavailable                            = rpc.ProviderQuotaAcquisitionStatusUnavailable
	ProviderQuotaCapacityStateAvailable                                  = rpc.ProviderQuotaCapacityStateAvailable
	ProviderQuotaCapacityStateExhausted                                  = rpc.ProviderQuotaCapacityStateExhausted
	ProviderQuotaCapacityStateNotApplicable                              = rpc.ProviderQuotaCapacityStateNotApplicable
	ProviderQuotaCapacityStateNotRequired                                = rpc.ProviderQuotaCapacityStateNotRequired
	ProviderQuotaCapacityStateUnavailable                                = rpc.ProviderQuotaCapacityStateUnavailable
	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
	SessionEventTypeAutoModeRecoveryConsentCompleted                     = rpc.SessionEventTypeAutoModeRecoveryConsentCompleted
	SessionEventTypeAutoModeRecoveryConsentRequested                     = rpc.SessionEventTypeAutoModeRecoveryConsentRequested
	SessionEventTypeAutoModeRecoveryOutcome                              = rpc.SessionEventTypeAutoModeRecoveryOutcome
	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
	SessionEventTypeIdeAddFileReference                                  = rpc.SessionEventTypeIdeAddFileReference
	SessionEventTypeIdeConnectionChanged                                 = rpc.SessionEventTypeIdeConnectionChanged
	SessionEventTypeIdeElicitationComplete                               = rpc.SessionEventTypeIdeElicitationComplete
	SessionEventTypeIdeSelectionChanged                                  = rpc.SessionEventTypeIdeSelectionChanged
	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
	SessionEventTypeSessionCanvasUnavailable                             = rpc.SessionEventTypeSessionCanvasUnavailable
	SessionEventTypeSessionCompactionComplete                            = rpc.SessionEventTypeSessionCompactionComplete
	SessionEventTypeSessionCompactionStart                               = rpc.SessionEventTypeSessionCompactionStart
	SessionEventTypeSessionCompactionSummarized                          = rpc.SessionEventTypeSessionCompactionSummarized
	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
	SessionEventTypeSessionJournalLink                                   = rpc.SessionEventTypeSessionJournalLink
	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
	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
	SkillSourceMCP                                                       = rpc.SkillSourceMCP
	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
	TaskBlockerReasonAttemptsExhausted                                   = rpc.TaskBlockerReasonAttemptsExhausted
	TaskBlockerReasonEquivalentAlternativeSucceeded                      = rpc.TaskBlockerReasonEquivalentAlternativeSucceeded
	TaskBlockerReasonPermissionApproved                                  = rpc.TaskBlockerReasonPermissionApproved
	TaskBlockerReasonPermissionDenied                                    = rpc.TaskBlockerReasonPermissionDenied
	TaskBlockerReasonPermissionRecoveryRunLimit                          = rpc.TaskBlockerReasonPermissionRecoveryRunLimit
	TaskBlockerReasonPermissionRequired                                  = rpc.TaskBlockerReasonPermissionRequired
	TaskBlockerReasonRepeatedAttempt                                     = rpc.TaskBlockerReasonRepeatedAttempt
	TaskBlockerReasonResponderUnavailable                                = rpc.TaskBlockerReasonResponderUnavailable
	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
	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.

View Source
const SDKProtocolVersion = 4

SDKProtocolVersion is the SDK protocol version. This must match the version expected by the Copilot runtime server.

Variables

View Source
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.

View Source
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.

View Source
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.

Functions

func Bool

func Bool(v bool) *bool

Bool returns a pointer to the given bool value. Use for optional bool fields such as LogOptions.Ephemeral:

Ephemeral: Bool(true)

func Float64

func Float64(v float64) *float64

Float64 returns a pointer to the given float64 value. Use for setting thresholds: BackgroundCompactionThreshold: Float64(0.80)

func GetSDKProtocolVersion

func GetSDKProtocolVersion() int

GetSDKProtocolVersion returns the SDK protocol version.

func Int

func Int(v int) *int

Int returns a pointer to the given int value. Use for setting optional int parameters: MinLength: Int(1)

func SendAndWait

func SendAndWait[T any](ctx context.Context, session *Session, options MessageOptions) (T, error)

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.

func String

func String(v string) *string

String returns a pointer to the given string value. Use for setting optional string parameters in RPC calls.

Types

type AbortData

type AbortData = rpc.AbortData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AbortReason

type AbortReason = rpc.AbortReason

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AgentInterruptedActivity

type AgentInterruptedActivity = rpc.AgentInterruptedActivity

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AgentInterruptedCancelPhase

type AgentInterruptedCancelPhase = rpc.AgentInterruptedCancelPhase

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AgentInterruptedData

type AgentInterruptedData = rpc.AgentInterruptedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AgentMode

type AgentMode = rpc.SendAgentMode

AgentMode is the UI mode the agent is in for a given turn. See MessageOptions.AgentMode.

type AgentModelPolicy

type AgentModelPolicy = rpc.AgentModelPolicy

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AgentStopHandler

type AgentStopHandler func(input AgentStopHookInput, invocation HookInvocation) (*AgentStopHookOutput, error)

AgentStopHandler handles agent-stop hook invocations.

type AgentStopHookInput

type AgentStopHookInput struct {
	Traceparent      string    `json:"traceparent,omitempty"`
	Tracestate       string    `json:"tracestate,omitempty"`
	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 (AgentStopHookInput) MarshalJSON

func (h AgentStopHookInput) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.

func (*AgentStopHookInput) UnmarshalJSON

func (h *AgentStopHookInput) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.

type AgentStopHookOutput

type AgentStopHookOutput struct {
	Decision string `json:"decision,omitempty"`
	Reason   string `json:"reason,omitempty"`
}

AgentStopHookOutput is the output for an agent-stop hook.

type AhpAuthenticationResult

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

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.

func (*AhpHost) Dispose

func (h *AhpHost) Dispose(ctx context.Context) error

Dispose stops the listener and joins runtime cleanup without deleting application sessions. Every call reaches the runtime, including repeated or concurrent calls.

func (*AhpHost) ListSessions

func (h *AhpHost) ListSessions(ctx context.Context) (*rpc.HostListSessionsResult, error)

ListSessions returns all live and dormant catalog sessions advertised by this host.

func (*AhpHost) PublishSession

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.

func (*AhpHost) SetAllowCreatingNewSessions

func (h *AhpHost) SetAllowCreatingNewSessions(ctx context.Context, allowed bool) error

SetAllowCreatingNewSessions changes subsequent remote admissions without disconnecting clients. Already-admitted creation may finish.

func (*AhpHost) UnpublishSession

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

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

type AhpHostAuthenticationMode = rpc.HostAuthenticationMode

type AhpHostExit

type AhpHostExit = rpc.HostExitedNotification

AhpHostExit reports termination of a connection-owned listener. Experimental: AHP hosting may change or be removed.

type AhpHostOptions

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

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

type AhpSessionAuthenticationCustom = rpc.HostSessionAuthenticationCustom

type AhpSessionAuthenticationGitHub

type AhpSessionAuthenticationGitHub = rpc.HostSessionAuthenticationGitHub

type AhpSessionAuthenticationNone

type AhpSessionAuthenticationNone = rpc.HostSessionAuthenticationNone

type AhpSessionCreateRequest

type AhpSessionCreateRequest struct {
	Authentication AhpSessionAuthentication
	Config         *CreateSessionOptions
}

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

type AhpSessionResumeRequest struct {
	Authentication AhpSessionAuthentication
	SessionID      string
	Config         *ResumeSessionOptions
}

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

type AiCreditsStatus = rpc.AiCreditsStatus

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AskUserVariant

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

type AssistantFusionPhaseActivityData = rpc.AssistantFusionPhaseActivityData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantFusionPhaseCompletedData

type AssistantFusionPhaseCompletedData = rpc.AssistantFusionPhaseCompletedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantFusionPhaseFailedData

type AssistantFusionPhaseFailedData = rpc.AssistantFusionPhaseFailedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantFusionPhaseStartedData

type AssistantFusionPhaseStartedData = rpc.AssistantFusionPhaseStartedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantIdleData

type AssistantIdleData = rpc.AssistantIdleData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantIntentData

type AssistantIntentData = rpc.AssistantIntentData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantMessageData

type AssistantMessageData = rpc.AssistantMessageData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantMessageDeltaData

type AssistantMessageDeltaData = rpc.AssistantMessageDeltaData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantMessageReasoningBlocks

type AssistantMessageReasoningBlocks = rpc.AssistantMessageReasoningBlocks

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantMessageServerTools

type AssistantMessageServerTools = rpc.AssistantMessageServerTools

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantMessageStartData

type AssistantMessageStartData = rpc.AssistantMessageStartData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantMessageToolRequest

type AssistantMessageToolRequest = rpc.AssistantMessageToolRequest

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantMessageToolRequestCaller

type AssistantMessageToolRequestCaller = rpc.AssistantMessageToolRequestCaller

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantMessageToolRequestCallerType

type AssistantMessageToolRequestCallerType = rpc.AssistantMessageToolRequestCallerType

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantMessageToolRequestType

type AssistantMessageToolRequestType = rpc.AssistantMessageToolRequestType

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantReasoningData

type AssistantReasoningData = rpc.AssistantReasoningData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantReasoningDeltaData

type AssistantReasoningDeltaData = rpc.AssistantReasoningDeltaData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantServerToolProgressData

type AssistantServerToolProgressData = rpc.AssistantServerToolProgressData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantStreamingDeltaData

type AssistantStreamingDeltaData = rpc.AssistantStreamingDeltaData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantToolCallDeltaData

type AssistantToolCallDeltaData = rpc.AssistantToolCallDeltaData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantTurnEndData

type AssistantTurnEndData = rpc.AssistantTurnEndData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantTurnRetryData

type AssistantTurnRetryData = rpc.AssistantTurnRetryData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantTurnStartData

type AssistantTurnStartData = rpc.AssistantTurnStartData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantUsageAPIEndpoint

type AssistantUsageAPIEndpoint = rpc.AssistantUsageAPIEndpoint

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantUsageCopilotUsage

type AssistantUsageCopilotUsage = rpc.AssistantUsageCopilotUsage

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantUsageCopilotUsageTokenDetail

type AssistantUsageCopilotUsageTokenDetail = rpc.AssistantUsageCopilotUsageTokenDetail

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantUsageData

type AssistantUsageData = rpc.AssistantUsageData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistantUsageTransport

type AssistantUsageTransport = rpc.AssistantUsageTransport

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistedApprovalAssessment

type AssistedApprovalAssessment = rpc.AssistedApprovalAssessment

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistedApprovalAssessmentCompleted

type AssistedApprovalAssessmentCompleted = rpc.AssistedApprovalAssessmentCompleted

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistedApprovalAssessmentExcluded

type AssistedApprovalAssessmentExcluded = rpc.AssistedApprovalAssessmentExcluded

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistedApprovalAssessmentFailed

type AssistedApprovalAssessmentFailed = rpc.AssistedApprovalAssessmentFailed

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistedApprovalAssessmentNotRun

type AssistedApprovalAssessmentNotRun = rpc.AssistedApprovalAssessmentNotRun

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistedApprovalAssessmentStatus

type AssistedApprovalAssessmentStatus = rpc.AssistedApprovalAssessmentStatus

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistedApprovalAssessmentUnavailable

type AssistedApprovalAssessmentUnavailable = rpc.AssistedApprovalAssessmentUnavailable

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistedApprovalCompletedRecommendation

type AssistedApprovalCompletedRecommendation = rpc.AssistedApprovalCompletedRecommendation

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistedApprovalJudgeFailureReason

type AssistedApprovalJudgeFailureReason = rpc.AssistedApprovalJudgeFailureReason

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AssistedApprovalRecommendation

type AssistedApprovalRecommendation = rpc.AssistedApprovalRecommendation

Session-event types are generated in the rpc package and aliased here for source compatibility.

type Attachment

type Attachment = rpc.Attachment

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentBlob

type AttachmentBlob = rpc.AttachmentBlob

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentDirectory

type AttachmentDirectory = rpc.AttachmentDirectory

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentExtensionContext

type AttachmentExtensionContext = rpc.AttachmentExtensionContext

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentFile

type AttachmentFile = rpc.AttachmentFile

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentFileLineRange

type AttachmentFileLineRange = rpc.AttachmentFileLineRange

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentGitHubActionsJob

type AttachmentGitHubActionsJob = rpc.AttachmentGitHubActionsJob

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentGitHubCommit

type AttachmentGitHubCommit = rpc.AttachmentGitHubCommit

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentGitHubFile

type AttachmentGitHubFile = rpc.AttachmentGitHubFile

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentGitHubFileDiff

type AttachmentGitHubFileDiff = rpc.AttachmentGitHubFileDiff

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentGitHubFileDiffSide

type AttachmentGitHubFileDiffSide = rpc.AttachmentGitHubFileDiffSide

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentGitHubReference

type AttachmentGitHubReference = rpc.AttachmentGitHubReference

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentGitHubReferenceType

type AttachmentGitHubReferenceType = rpc.AttachmentGitHubReferenceType

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentGitHubRelease

type AttachmentGitHubRelease = rpc.AttachmentGitHubRelease

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentGitHubRepository

type AttachmentGitHubRepository = rpc.AttachmentGitHubRepository

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentGitHubSnippet

type AttachmentGitHubSnippet = rpc.AttachmentGitHubSnippet

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentGitHubTreeComparison

type AttachmentGitHubTreeComparison = rpc.AttachmentGitHubTreeComparison

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentGitHubTreeComparisonSide

type AttachmentGitHubTreeComparisonSide = rpc.AttachmentGitHubTreeComparisonSide

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentGitHubURL

type AttachmentGitHubURL = rpc.AttachmentGitHubURL

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentSelection

type AttachmentSelection = rpc.AttachmentSelection

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentSelectionDetails

type AttachmentSelectionDetails = rpc.AttachmentSelectionDetails

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentSelectionDetailsEnd

type AttachmentSelectionDetailsEnd = rpc.AttachmentSelectionDetailsEnd

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentSelectionDetailsStart

type AttachmentSelectionDetailsStart = rpc.AttachmentSelectionDetailsStart

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentSessionReference

type AttachmentSessionReference = rpc.AttachmentSessionReference

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttachmentType

type AttachmentType = rpc.AttachmentType

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AttributedElicitationHandler

type AttributedElicitationHandler func(ctx ElicitationContext) (AttributedElicitationResult, error)

AttributedElicitationHandler is an ElicitationHandler whose results can say who answered. Register it with SessionInteractionOptions.OnAttributedElicitationRequest. If it returns an error, the SDK cancels the request without a label.

Experimental: AttributedElicitationHandler is part of an experimental API and may change or be removed.

type AttributedElicitationResult

type AttributedElicitationResult struct {
	ElicitationResult
	// DecisionContext says who answered and how. When a person answered, set
	// Source [PermissionDecisionSourceHumanResponse], ResponseCapability
	// [PermissionResponseCapabilityInteractive] and Outcome
	// [PermissionDecisionOutcomePromptedUser] so Assisted Permissions can
	// count the answer as the person's own authority. Leave it nil for
	// automated answers; nil sends no decisionContext. The SDK sends it
	// beside the elicitation result, not inside it.
	DecisionContext *PermissionDecisionContext `json:"decisionContext,omitempty"`
}

AttributedElicitationResult is an ElicitationResult that can say who answered. Return it from an AttributedElicitationHandler.

Experimental: AttributedElicitationResult is part of an experimental API and may change or be removed.

type AttributedExitPlanModeRequestHandler

type AttributedExitPlanModeRequestHandler func(request ExitPlanModeRequest, invocation ExitPlanModeInvocation) (AttributedExitPlanModeResult, error)

AttributedExitPlanModeRequestHandler is an ExitPlanModeRequestHandler whose results can say who reviewed the plan. Register it with SessionInteractionOptions.OnAttributedExitPlanModeRequest.

Experimental: AttributedExitPlanModeRequestHandler is part of an experimental API and may change or be removed.

type AttributedExitPlanModeResult

type AttributedExitPlanModeResult struct {
	ExitPlanModeResult
	// DecisionContext says who answered and how. When a person answered, set
	// Source [PermissionDecisionSourceHumanResponse], ResponseCapability
	// [PermissionResponseCapabilityInteractive] and Outcome
	// [PermissionDecisionOutcomePromptedUser] so Assisted Permissions can
	// count the review as the person's own. Leave it nil for automated
	// answers; nil sends no decisionContext.
	DecisionContext *PermissionDecisionContext `json:"decisionContext,omitempty"`
}

AttributedExitPlanModeResult is an ExitPlanModeResult that can say who reviewed the plan. Return it from an AttributedExitPlanModeRequestHandler.

Experimental: AttributedExitPlanModeResult is part of an experimental API and may change or be removed.

type AttributedPermissionResult

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 saying who decided and how.

The embedded rpc.PermissionDecision carries the actual decision. A DecisionContext whose Source is PermissionDecisionSourceHumanResponse makes the runtime record the decision as the person's: it sets permission.completed.decisionSource and gives the decision Assisted Permissions authority. The runtime accepts that only from the session's owning connection; from any other connection the decision applies without that authority. Other fields attribute the decision in telemetry. 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

func NewAttributedPermissionResult(result rpc.PermissionDecision, decisionContext *rpc.PermissionDecisionContext) *AttributedPermissionResult

NewAttributedPermissionResult pairs a permission decision with the context saying who decided and how; see AttributedPermissionResult for what the runtime does with it.

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 AttributedUserInputHandler

type AttributedUserInputHandler func(request UserInputRequest, invocation UserInputInvocation) (AttributedUserInputResponse, error)

AttributedUserInputHandler is a UserInputHandler whose answers can say who answered. Register it with SessionInteractionOptions.OnAttributedUserInputRequest.

Experimental: AttributedUserInputHandler is part of an experimental API and may change or be removed.

type AttributedUserInputResponse

type AttributedUserInputResponse struct {
	UserInputResponse
	// DecisionContext says who answered and how. When a person answered, set
	// Source [PermissionDecisionSourceHumanResponse], ResponseCapability
	// [PermissionResponseCapabilityInteractive] and Outcome
	// [PermissionDecisionOutcomePromptedUser] so Assisted Permissions can
	// count the answer as the person's own authority. Leave it nil for
	// automated answers; nil sends no decisionContext.
	DecisionContext *PermissionDecisionContext
}

AttributedUserInputResponse is a UserInputResponse that can say who answered. Return it from an AttributedUserInputHandler.

Experimental: AttributedUserInputResponse is part of an experimental API and may change or be removed.

type AutoModeRecoveryConsentCompletedData

type AutoModeRecoveryConsentCompletedData = rpc.AutoModeRecoveryConsentCompletedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AutoModeRecoveryConsentRequestedData

type AutoModeRecoveryConsentRequestedData = rpc.AutoModeRecoveryConsentRequestedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AutoModeRecoveryContext

type AutoModeRecoveryContext struct {
	RequestID     string `json:"requestId"`
	OriginalModel string `json:"originalModel"`
	// AllowAlways indicates whether this offer permits remembering consent.
	// Currently true only for per-model rate limits.
	AllowAlways          bool    `json:"allowAlways"`
	InteractionID        *string `json:"interactionId,omitempty"`
	OriginatingMessageID *string `json:"originatingMessageId,omitempty"`
}

AutoModeRecoveryContext identifies an offer to recover the active request using Auto.

type AutoModeRecoveryOutcomeData

type AutoModeRecoveryOutcomeData = rpc.AutoModeRecoveryOutcomeData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AutoModeResolvedReasoningBucket

type AutoModeResolvedReasoningBucket = rpc.AutoModeResolvedReasoningBucket

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AutoModeSwitchCompletedData

type AutoModeSwitchCompletedData = rpc.AutoModeSwitchCompletedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AutoModeSwitchInvocation

type AutoModeSwitchInvocation struct {
	SessionID string
}

AutoModeSwitchInvocation provides context about an auto-mode-switch request.

type AutoModeSwitchRequest

type AutoModeSwitchRequest struct {
	ErrorCode         *string  `json:"errorCode,omitempty"`
	RetryAfterSeconds *float64 `json:"retryAfterSeconds,omitempty"`
	// AutoModeRecovery identifies an active-request recovery offer; nil is an ordinary switch.
	AutoModeRecovery *AutoModeRecoveryContext `json:"autoModeRecovery,omitempty"`
}

AutoModeSwitchRequest describes an Auto switch offer.

type AutoModeSwitchRequestHandler

type AutoModeSwitchRequestHandler func(request AutoModeSwitchRequest, invocation AutoModeSwitchInvocation) (AutoModeSwitchResponse, error)

AutoModeSwitchRequestHandler handles auto-mode-switch requests from the agent.

type AutoModeSwitchRequestedData

type AutoModeSwitchRequestedData = rpc.AutoModeSwitchRequestedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AutoModeSwitchResponse

type AutoModeSwitchResponse = rpc.AutoModeSwitchResponse

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AutoTier

type AutoTier = rpc.AutoTier

AutoTier selects the routing tier for model "auto" with V2 Auto.

type AutoTierSwitchFailureReason

type AutoTierSwitchFailureReason = rpc.AutoTierSwitchFailureReason

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AutopilotObjectiveChangedOperation

type AutopilotObjectiveChangedOperation = rpc.AutopilotObjectiveChangedOperation

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AutopilotObjectiveChangedStatus

type AutopilotObjectiveChangedStatus = rpc.AutopilotObjectiveChangedStatus

Session-event types are generated in the rpc package and aliased here for source compatibility.

type AzureProviderOptions

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

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

type BinaryAssetReference = rpc.BinaryAssetReference

Session-event types are generated in the rpc package and aliased here for source compatibility.

type BinaryAssetReferenceType

type BinaryAssetReferenceType = rpc.BinaryAssetReferenceType

Session-event types are generated in the rpc package and aliased here for source compatibility.

type BinaryAssetType

type BinaryAssetType = rpc.BinaryAssetType

Session-event types are generated in the rpc package and aliased here for source compatibility.

type BlockedPermissionAction

type BlockedPermissionAction = rpc.BlockedPermissionAction

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CanvasDeclaration

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

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

func CanvasErrorNoHandler() *CanvasError

CanvasErrorNoHandler is the default error returned when a custom action has no handler.

func NewCanvasError

func NewCanvasError(code, message string) *CanvasError

NewCanvasError constructs a new error envelope with the given code and message.

func (*CanvasError) Error

func (e *CanvasError) Error() string

Error implements the error interface.

type CanvasHandler

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 sessionOptions.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

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

OnAction returns CanvasErrorNoHandler() by default.

func (CanvasHandlerDefaults) OnClose

OnClose returns nil by default.

type CanvasProviderIdentity

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

type CanvasRegistryChangedCanvas = rpc.CanvasRegistryChangedCanvas

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CanvasRegistryChangedCanvasAction

type CanvasRegistryChangedCanvasAction = rpc.CanvasRegistryChangedCanvasAction

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CapabilitiesChangedData

type CapabilitiesChangedData = rpc.CapabilitiesChangedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CapabilitiesChangedUI

type CapabilitiesChangedUI = rpc.CapabilitiesChangedUI

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CapiSessionOptions

type CapiSessionOptions struct {
	// Enabled controls Copilot API models independently of GitHub identity.
	Enabled *bool `json:"enabled,omitempty"`
	// 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].
	//
	// For Copilot Fusion, prefer FusionTier. The balance, hydrafusion and
	// hydrafusion-max identifiers it replaces remain accepted but are deprecated.
	AutoTier AutoTier `json:"autoTier,omitempty"`

	// FusionTier selects the Copilot Fusion tier for model "fusion" or "auto",
	// matching the CLI's --fusion-tier. The runtime resolves the tier to the Auto
	// routing preference it stands for and then applies it exactly like AutoTier,
	// so session.RPC.Model.GetCurrent and session.model_change events report that
	// preference as AutoTier. It cannot be combined with AutoTier.
	//
	// To change the tier on a live session, use [Session.SetFusionTier].
	//
	// Experimental: FusionTier is part of an experimental Auto routing surface
	// and may change or be removed.
	FusionTier FusionTier `json:"fusionTier,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

type CitableSource = rpc.CitableSource

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CitationLocation

type CitationLocation = rpc.CitationLocation

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CitationLocationBlock

type CitationLocationBlock = rpc.CitationLocationBlock

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CitationLocationChar

type CitationLocationChar = rpc.CitationLocationChar

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CitationLocationPage

type CitationLocationPage = rpc.CitationLocationPage

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CitationLocationType

type CitationLocationType = rpc.CitationLocationType

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CitationProvider

type CitationProvider = rpc.CitationProvider

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CitationReference

type CitationReference = rpc.CitationReference

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CitationSource

type CitationSource = rpc.CitationSource

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CitationSpan

type CitationSpan = rpc.CitationSpan

Session-event types are generated in the rpc package and aliased here for source compatibility.

type Citations

type Citations = rpc.Citations

Session-event types are generated in the rpc package and aliased here for source compatibility.

type Client

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 hosts the native runtime in-process by default, or uses an explicit subprocess or external-server connection. It handles JSON-RPC communication, session lifecycle, tool execution, and permission requests.

Example:

// Create a client with default transport (hosts the runtime in-process)
client := copilot.NewClient(&copilot.ClientOptions{Mode: copilot.ModeCodingAgent})

// Or connect to an existing server
client := copilot.NewClient(&copilot.ClientOptions{
    Mode: copilot.ModeCodingAgent,
    Runtime: copilot.TCPConnection{Host: "localhost", Port: 3000},
})

if err := client.Start(); err != nil {
    log.Fatal(err)
}
defer client.Stop()

func NewClient

func NewClient(options *ClientOptions) *Client

NewClient creates a new Copilot runtime client with the given options.

Options and ClientOptions.Mode are required. 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 transport: bundled runtime in-process
client := copilot.NewClient(&copilot.ClientOptions{Mode: copilot.ModeCodingAgent})

// Custom CLI path over stdio
client := copilot.NewClient(&copilot.ClientOptions{
    Mode: copilot.ModeCodingAgent,
    Runtime: copilot.SpawnedStdioConnection{Path: "/usr/local/bin/copilot"},
    Observability: copilot.ClientObservabilityOptions{LogLevel: "debug"},
})

// Connect to an already-running runtime
client := copilot.NewClient(&copilot.ClientOptions{
    Mode: copilot.ModeCodingAgent,
    Runtime: copilot.TCPConnection{Host: "localhost", Port: 8080},
})

func (*Client) CreateSession

func (c *Client) CreateSession(ctx context.Context, input *CreateSessionOptions) (*Session, error)

func (*Client) DeleteSession

func (c *Client) DeleteSession(ctx context.Context, sessionID string) error

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 (*Client) ForceStop

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:

  • Clears all sessions immediately without destroying them
  • Force closes the connection
  • Kills the CLI process (if spawned by this client)

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 (*Client) GetAuthStatus

func (c *Client) GetAuthStatus(ctx context.Context) (*GetAuthStatusResponse, error)

GetAuthStatus returns current authentication status, starting the client if needed.

func (*Client) GetForegroundSessionID

func (c *Client) GetForegroundSessionID(ctx context.Context) (*string, error)

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)
}

func (*Client) GetLastSessionID

func (c *Client) GetLastSessionID(ctx context.Context) (*string, error)

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.ResumeSessionOptions{
        OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
    })
}

func (*Client) GetSessionMetadata

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 (*Client) GetStatus

func (c *Client) GetStatus(ctx context.Context) (*GetStatusResponse, error)

GetStatus returns CLI status including version and protocol information, starting the client if needed.

func (*Client) ListModels

func (c *Client) ListModels(ctx context.Context) ([]Model, error)

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. It starts the client if needed, unless a custom OnListModels handler is configured.

func (*Client) ListSessions

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 (*Client) On

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 (*Client) OnEventType

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()

func (*Client) Ping

func (c *Client) Ping(ctx context.Context, message string) (*PingResponse, error)

Ping sends a ping request to the server to verify connectivity. It starts the client if needed.

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 (*Client) ResumeSession

func (c *Client) ResumeSession(ctx context.Context, sessionID string, input *ResumeSessionOptions) (*Session, error)

ResumeSession resumes an existing conversation with its history and configuration.

func (*Client) RuntimePort

func (c *Client) RuntimePort() int

RuntimePort returns the TCP port the runtime is listening on. Returns 0 if the client is not connected or using stdio transport.

func (*Client) SetForegroundSessionID

func (c *Client) SetForegroundSessionID(ctx context.Context, sessionID string) error

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)
}

func (*Client) Start

func (c *Client) Start(ctx context.Context) error

Start starts the runtime host (unless using an external server) and establishes a connection.

If connecting to an external server (via TCPConnection), only establishes the connection. Otherwise, starts an in-process host or the explicitly selected subprocess.

Management helpers call this method automatically when the client is not connected. Operations called while Start is in progress wait for it and fail with its error if it fails.

Returns an error if the server fails to start or the connection fails.

Example:

client := copilot.NewClient(&copilot.ClientOptions{Mode: copilot.ModeCodingAgent})
if err := client.Start(context.Background()); err != nil {
    log.Fatal("Failed to start:", err)
}
// Now ready to create sessions

func (*Client) StartAhpHost

func (c *Client) StartAhpHost(ctx context.Context, options *AhpHostOptions) (*AhpHost, error)

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.

func (*Client) Stop

func (c *Client) Stop() error

Stop stops the CLI server and closes all active sessions.

This method performs graceful cleanup:

  1. Closes all active sessions (releases in-memory resources); detach requests share one 10 second timeout, so an unresponsive runtime cannot hold the remaining steps back
  2. Requests runtime shutdown for SDK-owned CLI processes
  3. Closes owned stdio input and waits up to 10 seconds for host cleanup and exit
  4. Terminates any remaining owned CLI process and closes the JSON-RPC connection

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 ClientExtensionOptions

type ClientExtensionOptions struct {
	// LaunchProvider resolves launch profiles for extension entrypoints
	// discovered by the runtime. When non-nil, Start registers the provider
	// before any sessions can be created.
	LaunchProvider ExtensionLaunchProvider
}

ClientExtensionOptions configures client extensions.

type ClientGitHubOptions

type ClientGitHubOptions struct {
	// Token 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.
	Token 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 such as
	// GitHubToken are used; environment variable tokens (COPILOT_GITHUB_TOKEN,
	// GH_TOKEN, GITHUB_TOKEN) are ignored.
	// Default: true (but defaults to false when GitHubToken is provided).
	UseLoggedInUser *bool
	// OnTelemetry 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).
	OnTelemetry func(notification *rpc.GitHubTelemetryNotification)
}

ClientGitHubOptions configures client github.

type ClientInfo

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 ClientInstallationOptions

type ClientInstallationOptions struct {
	// ConfirmationHandler receives connection-global human reviews
	// for experimental `installations.confirm` callbacks. It does not enable
	// installation capabilities or perform any runtime registration RPC.
	ConfirmationHandler InstallationConfirmationHandler
}

ClientInstallationOptions configures client installations.

type ClientMode

type ClientMode string

ClientMode controls the default surface presented to sessions created by the Client. A mode must be explicitly selected in ClientOptions.

Set [clientOptions.Mode] to ModeEmpty to opt in to multi-tenant safe defaults: no built-in tools by default (callers must specify [sessionOptions.AvailableTools] explicitly), no environment_context section in the system message, telemetry off, custom instructions and remote-custom agents disabled, etc.

const (
	// ModeCodingAgent selects coding-agent defaults; sessions inherit the full Copilot
	// CLI experience (all built-in tools, host environment_context, etc.).
	ModeCodingAgent ClientMode = "coding-agent"
	// 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 ClientModelOptions

type ClientModelOptions struct {
	// 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) ([]Model, error)
	// 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
}

ClientModelOptions configures client models.

type ClientObservabilityOptions

type ClientObservabilityOptions struct {
	// 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
	// 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
}

ClientObservabilityOptions configures client observability.

type ClientOptions

type ClientOptions struct {
	// InternalTestOptions is unsupported SDK test infrastructure configuration.
	// Only applies to runtimes owned by this client.
	InternalTestOptions *InternalTestOptions
	Runtime             RuntimeConnection
	Plugins             ClientPluginOptions
	Extensions          ClientExtensionOptions
	// Network lets the SDK host resolve the runtime's proxies and answer
	// Negotiate (Kerberos) proxy challenges. When it configures a
	// callback, Start installs the `network.resolveProxy` and
	// `network.authenticateNegotiate` handlers
	// for the configured callbacks and registers them before any sessions can be
	// created. See [NetworkConfig].
	//
	// Experimental: Network is part of an experimental API and may change or be
	// removed.
	Network       *NetworkConfig
	Installations ClientInstallationOptions
	Observability ClientObservabilityOptions
	GitHub        ClientGitHubOptions
	Models        ClientModelOptions
	// 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
	// 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.
	//
	// Experimental: this API may change or be removed.
	Entra *EntraAuthOptions
	// Mode controls the default tool surface and feature flags presented to
	// sessions created by this client. Specify [ModeCodingAgent] for coding-agent
	// defaults or [ModeEmpty] to opt in to multi-tenant safe defaults — see [ClientMode] for details.
	//
	// When Mode is [ModeEmpty], NewClient requires an owned runtime's BaseDirectory,
	// SessionFS, or a [TCPConnection] so the runtime has persistent storage
	// for session state.
	Mode ClientMode
}

ClientOptions groups options by the feature they configure.

type ClientPluginOptions

type ClientPluginOptions struct {
	// BuiltinDirectories 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.
	BuiltinDirectories []string
}

ClientPluginOptions configures client plugins.

type CloudSessionOptions

type CloudSessionOptions struct {
	Repository *CloudSessionRepository `json:"repository,omitempty"`
}

CloudSessionOptions configures creation of a remote session in the cloud.

type CloudSessionRepository

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

type CommandCompletedData = rpc.CommandCompletedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CommandContext

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

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

type CommandExecuteData = rpc.CommandExecuteData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CommandHandler

type CommandHandler func(ctx CommandContext) error

CommandHandler is invoked when a registered slash-command is executed.

type CommandQueuedData

type CommandQueuedData = rpc.CommandQueuedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CommandsChangedCommand

type CommandsChangedCommand = rpc.CommandsChangedCommand

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CommandsChangedData

type CommandsChangedData = rpc.CommandsChangedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CompactionCompleteCompactionTokensUsed

type CompactionCompleteCompactionTokensUsed = rpc.CompactionCompleteCompactionTokensUsed

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CompactionCompleteCompactionTokensUsedCopilotUsageTokenDetail

type CompactionCompleteCompactionTokensUsedCopilotUsageTokenDetail = rpc.CompactionCompleteCompactionTokensUsedCopilotUsageTokenDetail

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CompactionTrigger

type CompactionTrigger = rpc.CompactionTrigger

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CompletionReceiptEventRange

type CompletionReceiptEventRange = rpc.CompletionReceiptEventRange

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CompletionReceiptFinalTool

type CompletionReceiptFinalTool = rpc.CompletionReceiptFinalTool

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CompletionReceiptStopReason

type CompletionReceiptStopReason = rpc.CompletionReceiptStopReason

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CompletionReceiptToolStatus

type CompletionReceiptToolStatus = rpc.CompletionReceiptToolStatus

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ContextTier

type ContextTier = rpc.ContextTier

Session-event types are generated in the rpc package and aliased here for source compatibility.

type CopilotExpAssignmentResponse

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 (CopilotExpAssignmentResponse) MarshalJSON

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

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

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

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.

type CopilotWebSocketCloseStatus

type CopilotWebSocketCloseStatus struct {
	Description string
	ErrorCode   string
	Err         error
}

CopilotWebSocketCloseStatus is the terminal status for a callback-owned WebSocket connection.

type CopilotWebSocketForwarder

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

func NewCopilotWebSocketForwarder(url string, headers http.Header) *CopilotWebSocketForwarder

NewCopilotWebSocketForwarder creates a forwarding handler targeting url with the given handshake headers.

func (*CopilotWebSocketForwarder) Close

func (f *CopilotWebSocketForwarder) Close() error

func (*CopilotWebSocketForwarder) Done

func (f *CopilotWebSocketForwarder) Done() <-chan struct{}

func (*CopilotWebSocketForwarder) Err

func (*CopilotWebSocketForwarder) Open

func (*CopilotWebSocketForwarder) SendRequestMessage

func (f *CopilotWebSocketForwarder) SendRequestMessage(ctx context.Context, msg CopilotWebSocketMessage) error

type CopilotWebSocketHandler

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

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

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 (CopilotWebSocketMessage) Text

Text decodes the frame payload as a UTF-8 string.

type CreateSessionFilesystemOptions

type CreateSessionFilesystemOptions struct {
	// TrustWorkingDirectory trusts the working directory for this session
	// ("session") or persistently for the user ("user"). Empty leaves trust unchanged.
	TrustWorkingDirectory WorkingDirectoryTrust
	// AdditionalDirectories are directories the agent may access beyond WorkingDirectory.
	// Relative paths are resolved against WorkingDirectory. Re-supply them when resuming.
	AdditionalDirectories []string
	// TrackFileChanges opts in to capturing file changes from the first
	// turn for session rewind and cumulative session diff.
	TrackFileChanges *bool
}

CreateSessionFilesystemOptions adds operation-specific settings.

type CreateSessionInstructionOptions

type CreateSessionInstructionOptions struct {
	// OrganizationText 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.
	OrganizationText *string
	// OnDemandDiscovery, when non-nil, controls on-demand discovery
	// of instruction files (AGENTS.md, .github/copilot-instructions.md, etc.) after
	// successful file views.
	OnDemandDiscovery *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
	// Directories 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.
	Directories []string
}

CreateSessionInstructionOptions adds operation-specific settings.

type CreateSessionOptions

type CreateSessionOptions struct {
	Inference SessionInferenceOptions
	// 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
	// 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
	Filesystem            CreateSessionFilesystemOptions
	State                 SessionStateOptions
	Instructions          CreateSessionInstructionOptions
	Hooks                 SessionHookOptions
	Git                   SessionGitOptions
	Skills                SessionSkillOptions
	Tools                 SessionToolOptions
	// SystemMessage configures system message customization
	SystemMessage *SystemMessageConfig
	Agents        SessionAgentOptions
	Permissions   SessionPermissionOptions
	MCP           SessionMCPOptions
	GitHub        SessionGitHubOptions
	Interaction   SessionInteractionOptions
	// WorkingDirectory is the working directory for the session.
	// Tool operations will be relative to this directory.
	WorkingDirectory string
	Events           SessionEventOptions
	Execution        SessionExecutionOptions
	Experiments      SessionExperimentOptions
	// 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
	Plugins     SessionPluginOptions
	// 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   SessionCanvasOptions
	Extensions SessionExtensionOptions
	Policy     SessionPolicyOptions
}

CreateSessionOptions groups options by the feature they configure.

type CustomAgentConfig

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

type CustomAgentsUpdatedAgent = rpc.CustomAgentsUpdatedAgent

Session-event types are generated in the rpc package and aliased here for source compatibility.

type DefaultAgentConfig

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

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

type ElicitationAction = rpc.UIElicitationResponseAction

ElicitationAction is the user response to an elicitation request.

Elicitation action values.

type ElicitationCompletedAction

type ElicitationCompletedAction = rpc.ElicitationCompletedAction

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ElicitationCompletedData

type ElicitationCompletedData = rpc.ElicitationCompletedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ElicitationContext

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
	// 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

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

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

type ElicitationRequestedData = rpc.ElicitationRequestedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ElicitationRequestedMode

type ElicitationRequestedMode = rpc.ElicitationRequestedMode

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ElicitationRequestedSchema

type ElicitationRequestedSchema = rpc.ElicitationRequestedSchema

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ElicitationRequestedSchemaType

type ElicitationRequestedSchemaType = rpc.ElicitationRequestedSchemaType

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ElicitationResult

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

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

type EmbeddedBlobResourceContents = rpc.EmbeddedBlobResourceContents

Session-event types are generated in the rpc package and aliased here for source compatibility.

type EmbeddedTextResourceContents

type EmbeddedTextResourceContents = rpc.EmbeddedTextResourceContents

Session-event types are generated in the rpc package and aliased here for source compatibility.

type EntraAuthOptions

type EntraAuthOptions struct {
	ClientID string
	// MatsAppName identifies this host in OneAuth MATS telemetry.
	// When nil or blank, MATS telemetry is disabled.
	MatsAppName *string
	// OneAuthApplicationID overrides the native application descriptor.
	// When nil or blank, the runtime uses ClientID; it does not isolate accounts.
	OneAuthApplicationID *string
	// TokenProvider selects/revalidates identities and acquires resource tokens.
	// When nil, the runtime uses its built-in Entra sign-in.
	//
	// Experimental: this API may change or be removed.
	TokenProvider EntraTokenProvider
}

EntraAuthOptions configures the host application and optional host-owned acquisition.

Experimental: this API may change or be removed.

type EntraTokenProvider

EntraTokenProvider acquires the requested identity or resource token. Renewal must be silent and account-pinned. The context ends when this request or its original connection is cancelled. Unavailability never opens runtime sign-in.

Experimental: this API may change or be removed.

type ErrorOccurredHandler

type ErrorOccurredHandler func(input ErrorOccurredHookInput, invocation HookInvocation) (*ErrorOccurredHookOutput, error)

ErrorOccurredHandler handles error-occurred hook invocations

type ErrorOccurredHookInput

type ErrorOccurredHookInput struct {
	Traceparent      string    `json:"traceparent,omitempty"`
	Tracestate       string    `json:"tracestate,omitempty"`
	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 (ErrorOccurredHookInput) MarshalJSON

func (h ErrorOccurredHookInput) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.

func (*ErrorOccurredHookInput) UnmarshalJSON

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

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

type ExitPlanModeAction = rpc.ExitPlanModeAction

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ExitPlanModeCompletedData

type ExitPlanModeCompletedData = rpc.ExitPlanModeCompletedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ExitPlanModeInvocation

type ExitPlanModeInvocation struct {
	SessionID string
}

ExitPlanModeInvocation provides context about an exit-plan-mode request.

type ExitPlanModeRequest

type ExitPlanModeRequest struct {
	Summary           string   `json:"summary"`
	PlanContent       string   `json:"planContent,omitempty"`
	Actions           []string `json:"actions"`
	RecommendedAction string   `json:"recommendedAction"`
	// RequestID is the runtime request ID of the pending `exit_plan_mode.requested`
	// event. Pass it as RequestID to the session's RPC.UI.HandlePendingExitPlanMode
	// (or the trusted handleHumanExitPlanMode path) to correlate an out-of-band
	// answer. It is empty when the runtime predates this field.
	RequestID string `json:"requestId,omitempty"`
}

ExitPlanModeRequest represents a request to exit plan mode and continue with a selected action.

type ExitPlanModeRequestHandler

type ExitPlanModeRequestHandler func(request ExitPlanModeRequest, invocation ExitPlanModeInvocation) (ExitPlanModeResult, error)

ExitPlanModeRequestHandler handles exit-plan-mode requests from the agent.

type ExitPlanModeRequestedData

type ExitPlanModeRequestedData = rpc.ExitPlanModeRequestedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ExitPlanModeResult

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

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 (ExpConfigEntry) MarshalJSON

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

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

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

type ExtensionLaunchProfile = rpc.ExtensionLaunchProfile

ExtensionLaunchProfile describes how the runtime should launch an extension.

type ExtensionLaunchProvider

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

type ExtensionLaunchProviderResolveRequest = rpc.ExtensionLaunchProviderResolveRequest

ExtensionLaunchProviderResolveRequest describes a discovered extension entrypoint that may need a host-provided launch profile.

type ExtensionLaunchProviderResolveResult

type ExtensionLaunchProviderResolveResult = rpc.ExtensionLaunchProviderResolveResult

ExtensionLaunchProviderResolveResult contains the optional host-provided launch profile for an extension entrypoint.

type ExtensionsLoadedExtension

type ExtensionsLoadedExtension = rpc.ExtensionsLoadedExtension

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ExtensionsLoadedExtensionSource

type ExtensionsLoadedExtensionSource = rpc.ExtensionsLoadedExtensionSource

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ExtensionsLoadedExtensionStatus

type ExtensionsLoadedExtensionStatus = rpc.ExtensionsLoadedExtensionStatus

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ExternalToolCompletedData

type ExternalToolCompletedData = rpc.ExternalToolCompletedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ExternalToolRequestedData

type ExternalToolRequestedData = rpc.ExternalToolRequestedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type FusionAttribution

type FusionAttribution = rpc.FusionAttribution

Session-event types are generated in the rpc package and aliased here for source compatibility.

type FusionConversationScope

type FusionConversationScope = rpc.FusionConversationScope

Session-event types are generated in the rpc package and aliased here for source compatibility.

type FusionCritic

type FusionCritic = rpc.FusionCritic

Session-event types are generated in the rpc package and aliased here for source compatibility.

type FusionFollowUpAction

type FusionFollowUpAction = rpc.FusionFollowUpAction

Session-event types are generated in the rpc package and aliased here for source compatibility.

type FusionFollowUpRecommendation

type FusionFollowUpRecommendation = rpc.FusionFollowUpRecommendation

Session-event types are generated in the rpc package and aliased here for source compatibility.

type FusionPattern

type FusionPattern = rpc.FusionPattern

Session-event types are generated in the rpc package and aliased here for source compatibility.

type FusionPhaseActivityKind

type FusionPhaseActivityKind = rpc.FusionPhaseActivityKind

Session-event types are generated in the rpc package and aliased here for source compatibility.

type FusionPhaseKind

type FusionPhaseKind = rpc.FusionPhaseKind

Session-event types are generated in the rpc package and aliased here for source compatibility.

type FusionPhasePlanStep

type FusionPhasePlanStep = rpc.FusionPhasePlanStep

Session-event types are generated in the rpc package and aliased here for source compatibility.

type FusionPhaseStatus

type FusionPhaseStatus = rpc.FusionPhaseStatus

Session-event types are generated in the rpc package and aliased here for source compatibility.

type FusionPhaseUsage

type FusionPhaseUsage = rpc.FusionPhaseUsage

Session-event types are generated in the rpc package and aliased here for source compatibility.

type FusionScores

type FusionScores = rpc.FusionScores

Session-event types are generated in the rpc package and aliased here for source compatibility.

type FusionTier

type FusionTier = rpc.FusionTier

FusionTier selects a Copilot Fusion tier, matching the CLI's --fusion-tier. The runtime resolves each tier to the Auto routing preference it stands for.

Experimental: FusionTier is part of an experimental Auto routing surface and may change or be removed.

type FusionTurnKind

type FusionTurnKind = rpc.FusionTurnKind

Session-event types are generated in the rpc package and aliased here for source compatibility.

type GetAuthStatusResponse

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

type GetStatusResponse struct {
	Version         string               `json:"version"`
	ProtocolVersion int                  `json:"protocolVersion"`
	HostDiagnostics *rpc.HostDiagnostics `json:"hostDiagnostics,omitempty"`
}

GetStatusResponse is the response from status.get

type GitHubMCPToolConfig

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

type GitHubRepoRef = rpc.GitHubRepoRef

Session-event types are generated in the rpc package and aliased here for source compatibility.

type GitHubToken

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 number of seconds remaining when the callback
	// completes. More than one hour must still remain after the runtime
	// validates the token. 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 (GitHubToken) GoString

func (t GitHubToken) GoString() string

GoString returns a redacted Go-syntax description that never includes the access token.

func (GitHubToken) String

func (t GitHubToken) String() string

String returns a redacted description that never includes the access token.

type GitHubTokenProvider

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

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

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

func GitHubTokenCancelled() *GitHubTokenProviderResult

GitHubTokenCancelled returns a result indicating that token acquisition was cancelled.

func GitHubTokenResult

func GitHubTokenResult(token *GitHubToken) *GitHubTokenProviderResult

GitHubTokenResult returns a successful token-provider result.

type GitHubTokenRequestReason

type GitHubTokenRequestReason = rpc.GitHubTokenAcquireReason

GitHubTokenRequestReason describes why the runtime needs a GitHub token.

Experimental: GitHubTokenRequestReason may change or be removed.

type HandoffRepository

type HandoffRepository = rpc.HandoffRepository

Session-event types are generated in the rpc package and aliased here for source compatibility.

type HandoffSourceType

type HandoffSourceType = rpc.HandoffSourceType

Session-event types are generated in the rpc package and aliased here for source compatibility.

type HeaderEntry

type HeaderEntry = rpc.HeaderEntry

Session-event types are generated in the rpc package and aliased here for source compatibility.

type HookEndData

type HookEndData = rpc.HookEndData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type HookEndError

type HookEndError = rpc.HookEndError

Session-event types are generated in the rpc package and aliased here for source compatibility.

type HookInvocation

type HookInvocation struct {
	SessionID string
}

HookInvocation provides context about a hook invocation

type HookProgressData

type HookProgressData = rpc.HookProgressData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type HookStartData

type HookStartData = rpc.HookStartData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type HumanResponseActor

type HumanResponseActor = rpc.HumanResponseActor

Session-event types are generated in the rpc package and aliased here for source compatibility.

type HumanResponseAskUserAction

type HumanResponseAskUserAction = rpc.HumanResponseAskUserAction

Session-event types are generated in the rpc package and aliased here for source compatibility.

type HumanResponseRecordedData

type HumanResponseRecordedData = rpc.HumanResponseRecordedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type HumanResponseRecordedResponse

type HumanResponseRecordedResponse = rpc.HumanResponseRecordedResponse

Session-event types are generated in the rpc package and aliased here for source compatibility.

type HumanResponseRecordedResponseAskUser

type HumanResponseRecordedResponseAskUser = rpc.HumanResponseRecordedResponseAskUser

Session-event types are generated in the rpc package and aliased here for source compatibility.

type HumanResponseRecordedResponseExitPlanMode

type HumanResponseRecordedResponseExitPlanMode = rpc.HumanResponseRecordedResponseExitPlanMode

Session-event types are generated in the rpc package and aliased here for source compatibility.

type HumanResponseRecordedResponseResponseKind

type HumanResponseRecordedResponseResponseKind = rpc.HumanResponseRecordedResponseResponseKind

Session-event types are generated in the rpc package and aliased here for source compatibility.

type HumanResponseRecordedResponseUserInput

type HumanResponseRecordedResponseUserInput = rpc.HumanResponseRecordedResponseUserInput

Session-event types are generated in the rpc package and aliased here for source compatibility.

type IdeAddFileReferenceData

type IdeAddFileReferenceData = rpc.IdeAddFileReferenceData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type IdeConnectedInfo

type IdeConnectedInfo = rpc.IdeConnectedInfo

Session-event types are generated in the rpc package and aliased here for source compatibility.

type IdeConnectionChangedData

type IdeConnectionChangedData = rpc.IdeConnectionChangedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type IdeConnectionState

type IdeConnectionState = rpc.IdeConnectionState

Session-event types are generated in the rpc package and aliased here for source compatibility.

type IdeElicitationCompleteData

type IdeElicitationCompleteData = rpc.IdeElicitationCompleteData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type IdeFileReference

type IdeFileReference = rpc.IdeFileReference

Session-event types are generated in the rpc package and aliased here for source compatibility.

type IdePosition

type IdePosition = rpc.IdePosition

Session-event types are generated in the rpc package and aliased here for source compatibility.

type IdeRange

type IdeRange = rpc.IdeRange

Session-event types are generated in the rpc package and aliased here for source compatibility.

type IdeSelection

type IdeSelection = rpc.IdeSelection

Session-event types are generated in the rpc package and aliased here for source compatibility.

type IdeSelectionChangedData

type IdeSelectionChangedData = rpc.IdeSelectionChangedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type IdeSelectionRange

type IdeSelectionRange = rpc.IdeSelectionRange

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ImageGenerationConfig

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

type InProcessConnection struct {
	BaseDirectory             string
	SessionIdleTimeoutSeconds int

	// 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.
	// 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.

Env and WorkingDirectory belong only to child-process transports. Use CreateSessionOptions.WorkingDirectory to select a session directory.

This is the default transport on supported hosts: macOS, Linux, and Windows on amd64 or arm64. No build tag is required.

type IndexedSearchState

type IndexedSearchState = rpc.IndexedSearchState

Session-event types are generated in the rpc package and aliased here for source compatibility.

type InfiniteSessionConfig

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.

type InstallationConfirmationContext

type InstallationConfirmationContext = context.Context

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

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

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

type InstallationConfirmationHandlerFunc func(request InstallationConfirmationRequest, context InstallationConfirmationContext) (InstallationConfirmationDecision, error)

InstallationConfirmationHandlerFunc adapts a function to InstallationConfirmationHandler.

Experimental: InstallationConfirmationHandlerFunc may change or be removed.

func (InstallationConfirmationHandlerFunc) ConfirmInstallation

ConfirmInstallation calls f(request, context).

type InstallationConfirmationRequest

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

type InstructionUpdateAuthority = rpc.InstructionUpdateAuthority

Session-event types are generated in the rpc package and aliased here for source compatibility.

type InstructionUpdateBoundary

type InstructionUpdateBoundary = rpc.InstructionUpdateBoundary

Session-event types are generated in the rpc package and aliased here for source compatibility.

type InstructionUpdateData

type InstructionUpdateData = rpc.InstructionUpdateData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type InstructionUpdateFallback

type InstructionUpdateFallback = rpc.InstructionUpdateFallback

Session-event types are generated in the rpc package and aliased here for source compatibility.

type InstructionUpdateLifetime

type InstructionUpdateLifetime = rpc.InstructionUpdateLifetime

Session-event types are generated in the rpc package and aliased here for source compatibility.

type InternalTestOptions

type InternalTestOptions struct {
	CopilotAPIURL     *string
	GitHubAPIURL      *string
	ProxyURL          *string
	NoProxy           *string
	CACertificatePath *string
}

InternalTestOptions is reserved for SDK test infrastructure, not production use. Non-nil values override owned-runtime startup configuration without changing the host process environment. A pointer to an empty string clears an override.

type LargeToolOutputConfig

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. Uses the runtime's configured threshold when unset
	// (20480 bytes by default).
	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

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

type MCPAppToolCallCompleteData = rpc.MCPAppToolCallCompleteData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPAppToolCallCompleteError

type MCPAppToolCallCompleteError = rpc.MCPAppToolCallCompleteError

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPAppToolCallCompleteToolMeta

type MCPAppToolCallCompleteToolMeta = rpc.MCPAppToolCallCompleteToolMeta

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPAppToolCallCompleteToolMetaUI

type MCPAppToolCallCompleteToolMetaUI = rpc.MCPAppToolCallCompleteToolMetaUI

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPAuthHandler

type MCPAuthHandler func(request MCPAuthRequest, invocation MCPAuthInvocation) (*MCPAuthResult, error)

MCPAuthHandler handles MCP OAuth requests from the runtime.

type MCPAuthInvocation

type MCPAuthInvocation struct {
	SessionID string
}

MCPAuthInvocation provides context about an MCP auth handler invocation.

type MCPAuthRequest

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

type MCPAuthResult struct {
	Kind  string
	Token *MCPAuthToken
}

MCPAuthResult is the result returned by an MCP auth request handler.

func MCPAuthResultCancelled

func MCPAuthResultCancelled() *MCPAuthResult

MCPAuthResultCancelled returns a cancelled result for an MCP OAuth request.

func MCPAuthResultRuntimeRefresh

func MCPAuthResultRuntimeRefresh() *MCPAuthResult

MCPAuthResultRuntimeRefresh requests noninteractive renewal for an advertised Refresh. Response acceptance is not token installation or reconnect completion.

func MCPAuthResultToken

func MCPAuthResultToken(token *MCPAuthToken) *MCPAuthResult

MCPAuthResultToken returns a token result for an MCP OAuth request.

type MCPAuthRuntimeRefreshHandler

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

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

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

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

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 (MCPHTTPServerConfig) MarshalJSON

func (c MCPHTTPServerConfig) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler, injecting the "type" discriminator.

type MCPHeadersRefreshCompletedData

type MCPHeadersRefreshCompletedData = rpc.MCPHeadersRefreshCompletedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPHeadersRefreshCompletedOutcome

type MCPHeadersRefreshCompletedOutcome = rpc.MCPHeadersRefreshCompletedOutcome

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPHeadersRefreshRequiredData

type MCPHeadersRefreshRequiredData = rpc.MCPHeadersRefreshRequiredData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPHeadersRefreshRequiredReason

type MCPHeadersRefreshRequiredReason = rpc.MCPHeadersRefreshRequiredReason

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPOauthCompletedData

type MCPOauthCompletedData = rpc.MCPOauthCompletedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPOauthCompletionOutcome

type MCPOauthCompletionOutcome = rpc.MCPOauthCompletionOutcome

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPOauthHTTPResponse

type MCPOauthHTTPResponse = rpc.MCPOauthHTTPResponse

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPOauthRecoveryCompletedData

type MCPOauthRecoveryCompletedData = rpc.MCPOauthRecoveryCompletedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPOauthRecoveryCompletedOutcome

type MCPOauthRecoveryCompletedOutcome = rpc.MCPOauthRecoveryCompletedOutcome

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPOauthRequestReason

type MCPOauthRequestReason = rpc.MCPOauthRequestReason

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPOauthRequiredData

type MCPOauthRequiredData = rpc.MCPOauthRequiredData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPOauthRequiredStaticClientConfig

type MCPOauthRequiredStaticClientConfig = rpc.MCPOauthRequiredStaticClientConfig

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPOauthRequiredStaticClientConfigGrantType

type MCPOauthRequiredStaticClientConfigGrantType = rpc.MCPOauthRequiredStaticClientConfigGrantType

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPOauthWwwAuthenticateParams

type MCPOauthWwwAuthenticateParams = rpc.MCPOauthWwwAuthenticateParams

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPPromptsListChangedData

type MCPPromptsListChangedData = rpc.MCPPromptsListChangedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPResourcesListChangedData

type MCPResourcesListChangedData = rpc.MCPResourcesListChangedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPServerConfig

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

type MCPServerMetadata = rpc.MCPServerMetadata

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPServerSource

type MCPServerSource = rpc.MCPServerSource

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPServerStatus

type MCPServerStatus = rpc.MCPServerStatus

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPServerTransport

type MCPServerTransport = rpc.MCPServerTransport

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPServersLoadedServer

type MCPServersLoadedServer = rpc.MCPServersLoadedServer

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPSkillOrigin

type MCPSkillOrigin = rpc.MCPSkillOrigin

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MCPStdioServerConfig

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:

  • nil (omitted from the wire): all tools (CLI default)
  • []string{"*"}: explicit "all tools"
  • []string{}: no tools
  • []string{"foo","bar"}: only those tools

func (MCPStdioServerConfig) MarshalJSON

func (c MCPStdioServerConfig) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler, injecting the "type" discriminator.

type MCPToolsListChangedData

type MCPToolsListChangedData = rpc.MCPToolsListChangedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ManagedPermissionsContext

type ManagedPermissionsContext = rpc.ManagedPermissionsContext

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ManagedPluginProgressPhase

type ManagedPluginProgressPhase = rpc.ManagedPluginProgressPhase

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ManagedSettings

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

type ManagedSettingsEnforcedAction = rpc.ManagedSettingsEnforcedAction

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ManagedSettingsEnforcedEscalation

type ManagedSettingsEnforcedEscalation = rpc.ManagedSettingsEnforcedEscalation

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ManagedSettingsPermissions

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

type ManagedSettingsResolvedData = rpc.ManagedSettingsResolvedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ManagedSettingsResolvedSource

type ManagedSettingsResolvedSource = rpc.ManagedSettingsResolvedSource

Session-event types are generated in the rpc package and aliased here for source compatibility.

type MemoryConfiguration

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

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

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
	// ClientTurnID is an opaque caller-chosen ID for the turn this message
	// starts. The runtime copies it unchanged into
	// _meta["com.github.copilot/turnId"] on every MCP tools/call made while
	// serving that turn, including calls from sub-agents and Autopilot
	// continuations. When a running turn consumes the message as visible user
	// steering, the value (or its absence) replaces the turn's ID from the next
	// model call onward. The user.message event for the message echoes it as
	// clientTurnId and is persisted like other events; the value stamped on MCP
	// calls is held in memory only and is not restored on resume. Nil omits it;
	// an empty string is sent unchanged like any other opaque ID. Use [String]
	// to set it.
	ClientTurnID *string
}

MessageOptions configures a message to send

type MessageSource

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

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.

func MessageSourceAutomation

func MessageSourceAutomation(id string) MessageSource

MessageSourceAutomation identifies the automation a turn is sent on behalf of, such as a recurring check-in the user configured. The turn defines the session's task like a user message but carries no human authority. The automation ID is opaque and is sent unchanged after the "automation-" prefix. It must not be empty: the runtime does not treat "automation-" alone as an automation turn.

type Model

type Model = rpc.Model

Model and its nested types are the generated runtime catalog contract.

type ModelBilling

type ModelBilling = rpc.ModelBilling

Model and its nested types are the generated runtime catalog contract.

type ModelCallFailureBadRequestKind

type ModelCallFailureBadRequestKind = rpc.ModelCallFailureBadRequestKind

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ModelCallFailureData

type ModelCallFailureData = rpc.ModelCallFailureData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ModelCallFailureKind

type ModelCallFailureKind = rpc.ModelCallFailureKind

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ModelCallFailureRequestFingerprint

type ModelCallFailureRequestFingerprint = rpc.ModelCallFailureRequestFingerprint

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ModelCallFailureSource

type ModelCallFailureSource = rpc.ModelCallFailureSource

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ModelCallFailureTransport

type ModelCallFailureTransport = rpc.ModelCallFailureTransport

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ModelCallFinalResult

type ModelCallFinalResult = rpc.ModelCallFinalResult

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ModelCallFinalResultData

type ModelCallFinalResultData = rpc.ModelCallFinalResultData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ModelCallFinishedData

type ModelCallFinishedData = rpc.ModelCallFinishedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ModelCallFinishedOutcome

type ModelCallFinishedOutcome = rpc.ModelCallFinishedOutcome

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ModelCallRequestBodyCompressionFallback

type ModelCallRequestBodyCompressionFallback = rpc.ModelCallRequestBodyCompressionFallback

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ModelCallRequestBodyEncoding

type ModelCallRequestBodyEncoding = rpc.ModelCallRequestBodyEncoding

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ModelCallStartData

type ModelCallStartData = rpc.ModelCallStartData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ModelCallWebSocketFallbackErrorKind

type ModelCallWebSocketFallbackErrorKind = rpc.ModelCallWebSocketFallbackErrorKind

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ModelCallWebSocketFallbackReason

type ModelCallWebSocketFallbackReason = rpc.ModelCallWebSocketFallbackReason

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ModelCapabilities

type ModelCapabilities = rpc.ModelCapabilities

Model and its nested types are the generated runtime catalog contract.

type ModelCapabilitiesLimits

type ModelCapabilitiesLimits = rpc.ModelCapabilitiesLimits

Model and its nested types are the generated runtime catalog contract.

type ModelCapabilitiesLimitsVision

type ModelCapabilitiesLimitsVision = rpc.ModelCapabilitiesLimitsVision

Model and its nested types are the generated runtime catalog contract.

type ModelCapabilitiesOverride

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

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

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

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 ModelCapabilitiesSupports

type ModelCapabilitiesSupports = rpc.ModelCapabilitiesSupports

Model and its nested types are the generated runtime catalog contract.

type ModelChangeSource

type ModelChangeSource = rpc.ModelChangeSource

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ModelDeselectedReason

type ModelDeselectedReason = rpc.ModelDeselectedReason

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ModelPolicy

type ModelPolicy = rpc.ModelPolicy

Model and its nested types are the generated runtime catalog contract.

type ModelProviderKind

type ModelProviderKind = rpc.ModelProviderKind

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ModelProviderRef

type ModelProviderRef = rpc.ModelProviderRef

Session-event types are generated in the rpc package and aliased here for source compatibility.

type NamedProviderConfig

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", "anthropic", or "google". Defaults to "openai".
	Type string `json:"type,omitempty"`
	// LocalModel contains forward-compatible runtime options for a local model.
	LocalModel json.RawMessage `json:"localModel,omitempty"`
	// WireAPI is the API format (openai/azure only): "completions" or "responses". Defaults to "completions".
	WireAPI string `json:"wireApi,omitempty"`
	// Transport is "http" (default) or "websockets" for the OpenAI Responses API.
	Transport string `json:"transport,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"`
	// APIKeyCommand runs before each request. Failure fails the request without
	// static-key fallback. Bearer authentication takes precedence.
	APIKeyCommand string `json:"apiKeyCommand,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.

Connections coexist with GitHub identity. CapiSessionOptions.Enabled controls Copilot model availability independently.

Experimental: NamedProviderConfig is part of an experimental multi-provider BYOK surface and may change or be removed in future SDK or CLI releases.

func (NamedProviderConfig) MarshalJSON

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 NetworkAuthenticateBasicRequest

type NetworkAuthenticateBasicRequest = rpc.NetworkAuthenticateBasicRequest

NetworkAuthenticateBasicRequest identifies the proxy whose Basic challenge needs credentials.

Experimental: NetworkAuthenticateBasicRequest is part of an experimental API and may change or be removed.

type NetworkAuthenticateBasicResult

type NetworkAuthenticateBasicResult = rpc.NetworkAuthenticateBasicResult

NetworkAuthenticateBasicResult holds the credentials for a proxy's Basic challenge.

Experimental: NetworkAuthenticateBasicResult is part of an experimental API and may change or be removed.

type NetworkAuthenticateNegotiateRequest

type NetworkAuthenticateNegotiateRequest = rpc.NetworkAuthenticateNegotiateRequest

NetworkAuthenticateNegotiateRequest identifies the service principal that needs a token.

Experimental: NetworkAuthenticateNegotiateRequest is part of an experimental API and may change or be removed.

type NetworkConfig

type NetworkConfig struct {
	// Scope selects which traffic the callbacks serve. When empty, the runtime
	// uses [NetworkScopeConnection]. With [NetworkScopeRuntime], Start fails if
	// another connection holds that scope. The registration ends when the
	// connection closes.
	Scope NetworkScope
	// ResolveProxy returns the proxies for request.URL as a PAC-style list such
	// as "PROXY proxy.example:8080; HTTPS proxy.example:443; DIRECT" (the format
	// of Electron's session.resolveProxy); return "DIRECT" for a direct
	// connection, or "" to let the runtime resolve the proxy itself, as if no
	// callback were registered. Entry types the runtime doesn't support, such as
	// SOCKS and QUIC, are skipped. request.URL is the
	// request target as a PAC script sees it: without credentials or fragment,
	// and for https and wss also without path and query.
	//
	// The callback decides every request that would otherwise follow ambient
	// proxy settings: proxy environment variables, NO_PROXY and operating-system
	// proxy settings are not consulted unless it returns "", and a failing
	// callback fails the request rather than connecting directly. Requests to
	// loopback targets, and requests with an explicitly configured proxy, never
	// consult it. The runtime caches answers, including "", for a few seconds.
	ResolveProxy func(ctx context.Context, request NetworkResolveProxyRequest) (string, error)
	// AuthenticateNegotiate returns a fresh, single-use base64 SPNEGO token
	// without the "Negotiate " prefix for a proxy's Negotiate challenge, or ""
	// when unavailable. The runtime then does not look up Kerberos credentials
	// itself, so a missing token or a failing callback fails the request, unless
	// the proxy also offers Basic and AuthenticateBasic supplies credentials.
	// request.Spn uses the platform-independent service/host[@REALM] form;
	// validate it before issuing credentials. Never log or persist tokens.
	AuthenticateNegotiate func(ctx context.Context, request NetworkAuthenticateNegotiateRequest) (string, error)
	// AuthenticateBasic returns credentials for a proxy's Basic challenge, or
	// nil when unavailable, which fails the request with the proxy's challenge,
	// as does an empty Username. It applies to requests the runtime tunnels
	// through the proxy (https and wss). The runtime remembers the answer for
	// that proxy and uses it for later connections, until the proxy rejects it;
	// then it calls again with request.PreviousRejected set, so answer with
	// different credentials, for example by asking the user, or with nil. A later
	// connection sends the answer without waiting for a challenge, unless the
	// runtime may try Negotiate with that proxy first. A connection submits at
	// most three sets of credentials. While a call is pending, other requests
	// through that proxy wait for its answer. When a proxy offers both Negotiate
	// and Basic, the runtime prefers Negotiate and answers with Basic when
	// Negotiate is unavailable or the proxy rejects it. request.Realm comes from
	// the proxy, so treat it as untrusted text. The user name must not contain a
	// colon, and neither the user name nor the password may contain control
	// characters; the runtime fails the request otherwise. A nil Password means
	// an empty password. The runtime does not time the callback out: a request
	// whose own deadline passes stops waiting, but the answer is still
	// remembered. Never log or persist credentials.
	AuthenticateBasic func(ctx context.Context, request NetworkAuthenticateBasicRequest) (*NetworkAuthenticateBasicResult, error)
}

NetworkConfig holds the callbacks through which the SDK host takes over parts of the runtime's networking, for example when the runtime runs in WSL or a container and should use VS Code's proxy settings and the host's Kerberos tickets. Each non-nil callback replaces the runtime's own handling for the traffic in Scope; for a nil callback, the runtime handles that part itself. Without any callback, nothing is registered.

Each callback's ctx is cancelled when the runtime stops waiting: it cancels the request (for example when its wait times out) or the connection closes. The SDK then stops waiting for the callback and ignores any later result, so abandon the lookup promptly once ctx is done. If that happens before the callback starts, the callback is not called at all. Returned errors and panics are reported to the runtime as callback failures.

Experimental: NetworkConfig is part of an experimental API and may change or be removed.

type NetworkResolveProxyRequest

type NetworkResolveProxyRequest = rpc.NetworkResolveProxyRequest

NetworkResolveProxyRequest identifies the request target whose proxies are requested.

Experimental: NetworkResolveProxyRequest is part of an experimental API and may change or be removed.

type NetworkScope

type NetworkScope = rpc.NetworkScope

NetworkScope selects which traffic the NetworkConfig callbacks serve.

Experimental: NetworkScope is part of an experimental API and may change or be removed.

type OmittedBinaryOmittedReason

type OmittedBinaryOmittedReason = rpc.OmittedBinaryOmittedReason

Session-event types are generated in the rpc package and aliased here for source compatibility.

type OmittedBinaryResult

type OmittedBinaryResult = rpc.OmittedBinaryResult

Session-event types are generated in the rpc package and aliased here for source compatibility.

type OmittedBinaryType

type OmittedBinaryType = rpc.OmittedBinaryType

Session-event types are generated in the rpc package and aliased here for source compatibility.

type OwnedRuntimeOptions

type OwnedRuntimeOptions struct {
	BaseDirectory             string
	SessionIdleTimeoutSeconds int
}

OwnedRuntimeOptions configures a runtime owned by the client.

type PendingMessagesModifiedData

type PendingMessagesModifiedData = rpc.PendingMessagesModifiedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionApprovalEvaluation

type PermissionApprovalEvaluation = rpc.PermissionApprovalEvaluation

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionApprovalEvaluationEvaluationStage

type PermissionApprovalEvaluationEvaluationStage = rpc.PermissionApprovalEvaluationEvaluationStage

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionApprovalEvaluationJudgeStatus

type PermissionApprovalEvaluationJudgeStatus = rpc.PermissionApprovalEvaluationJudgeStatus

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionApprovalEvaluationReasonCode

type PermissionApprovalEvaluationReasonCode = rpc.PermissionApprovalEvaluationReasonCode

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionApproved

type PermissionApproved = rpc.PermissionApproved

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionApprovedForLocation

type PermissionApprovedForLocation = rpc.PermissionApprovedForLocation

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionApprovedForSession

type PermissionApprovedForSession = rpc.PermissionApprovedForSession

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionApprovedReadOnlyForSession

type PermissionApprovedReadOnlyForSession = rpc.PermissionApprovedReadOnlyForSession

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionAssentDetectedData

type PermissionAssentDetectedData = rpc.PermissionAssentDetectedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionAssistedApproval

type PermissionAssistedApproval = rpc.PermissionAssistedApproval

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionCancelled

type PermissionCancelled = rpc.PermissionCancelled

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionCarriedForwardData

type PermissionCarriedForwardData = rpc.PermissionCarriedForwardData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionCompletedData

type PermissionCompletedData = rpc.PermissionCompletedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionContextualAuthorizationData

type PermissionContextualAuthorizationData = rpc.PermissionContextualAuthorizationData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionDecisionContext

type PermissionDecisionContext = rpc.PermissionDecisionContext

PermissionDecisionContext says who made a decision and how. Attach it to a permission decision with NewAttributedPermissionResult, or to a prompt answer with AttributedUserInputResponse, AttributedExitPlanModeResult or AttributedElicitationResult.

A Source of PermissionDecisionSourceHumanResponse from the session's owning connection makes the runtime record the decision as the person's: for a permission it sets permission.completed.decisionSource, and it gives the decision Assisted Permissions authority (for a prompt answer, with ResponseCapability PermissionResponseCapabilityInteractive). From any other connection the decision applies without that authority. The other fields attribute the decision in telemetry.

Experimental: PermissionDecisionContext is part of an experimental API and may change or be removed.

type PermissionDecisionOutcome

type PermissionDecisionOutcome = rpc.PermissionDecisionOutcome

PermissionDecisionOutcome describes the disposition of a permission request as observed by the responding client.

type PermissionDecisionSource

type PermissionDecisionSource = rpc.PermissionDecisionSource

PermissionDecisionSource identifies the controlled reason or actor responsible for a permission response.

type PermissionDecisionSurface

type PermissionDecisionSurface = rpc.PermissionDecisionSurface

PermissionDecisionSurface identifies the client surface that submitted a permission response.

type PermissionDeniedByContentExclusionPolicy

type PermissionDeniedByContentExclusionPolicy = rpc.PermissionDeniedByContentExclusionPolicy

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionDeniedByPermissionRequestHook

type PermissionDeniedByPermissionRequestHook = rpc.PermissionDeniedByPermissionRequestHook

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionDeniedByRules

type PermissionDeniedByRules = rpc.PermissionDeniedByRules

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionDeniedInteractivelyByUser

type PermissionDeniedInteractivelyByUser = rpc.PermissionDeniedInteractivelyByUser

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser

type PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser = rpc.PermissionDeniedNoApprovalRuleAndCouldNotRequestFromUser

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionHandlerFunc

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

type PermissionHandlerInvocation struct {
	PermissionInvocation
	// AssistedApprovalAssessment is the canonical runtime-owned Assisted
	// Permissions assessment. It explains the assisted review only; the final
	// permission result is reported by permission.completed. It is nil with
	// older runtimes and legacy direct permission callbacks.
	//
	// Experimental: AssistedApprovalAssessment is part of an experimental API
	// and may change or be removed.
	AssistedApprovalAssessment rpc.AssistedApprovalAssessment
	// 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 and Assisted Permissions assessment.

type PermissionHandlerWithEnvelopeFunc

type PermissionHandlerWithEnvelopeFunc func(request *PermissionRequestEnvelope, invocation PermissionHandlerInvocation) (rpc.PermissionDecision, error)

PermissionHandlerWithEnvelopeFunc receives an explicit lossless request. Its Request retains the usual concrete permission variant. Pass the envelope to ManagedReviewRequired to retain original unknown fields.

type PermissionHandlerWithPromptFunc

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.

type PermissionInvocation

type PermissionInvocation struct {
	SessionID              string
	ManagedSettingsEnabled bool
	// ProgramToolCallID identifies the owning program invocation, or is nil for
	// ordinary requests.
	//
	// Experimental: this API may change or be removed.
	ProgramToolCallID *string
}

PermissionInvocation provides context about a permission request.

type PermissionMessageAuthorizationData

type PermissionMessageAuthorizationData = rpc.PermissionMessageAuthorizationData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionMessageAuthorizationDegradedData

type PermissionMessageAuthorizationDegradedData = rpc.PermissionMessageAuthorizationDegradedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionMessageAuthorizationPolarity

type PermissionMessageAuthorizationPolarity = rpc.PermissionMessageAuthorizationPolarity

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionMessageAuthorizationReadData

type PermissionMessageAuthorizationReadData = rpc.PermissionMessageAuthorizationReadData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionMode

type PermissionMode = rpc.PermissionMode

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionPromptRequest

type PermissionPromptRequest = rpc.PermissionPromptRequest

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionPromptRequestCommands

type PermissionPromptRequestCommands = rpc.PermissionPromptRequestCommands

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionPromptRequestCustomTool

type PermissionPromptRequestCustomTool = rpc.PermissionPromptRequestCustomTool

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionPromptRequestExtensionEnvAccess

type PermissionPromptRequestExtensionEnvAccess = rpc.PermissionPromptRequestExtensionEnvAccess

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionPromptRequestExtensionManagement

type PermissionPromptRequestExtensionManagement = rpc.PermissionPromptRequestExtensionManagement

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionPromptRequestExtensionPermissionAccess

type PermissionPromptRequestExtensionPermissionAccess = rpc.PermissionPromptRequestExtensionPermissionAccess

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionPromptRequestHook

type PermissionPromptRequestHook = rpc.PermissionPromptRequestHook

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionPromptRequestKind

type PermissionPromptRequestKind = rpc.PermissionPromptRequestKind

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionPromptRequestMCP

type PermissionPromptRequestMCP = rpc.PermissionPromptRequestMCP

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionPromptRequestMemory

type PermissionPromptRequestMemory = rpc.PermissionPromptRequestMemory

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionPromptRequestPath

type PermissionPromptRequestPath = rpc.PermissionPromptRequestPath

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionPromptRequestPathAccessKind

type PermissionPromptRequestPathAccessKind = rpc.PermissionPromptRequestPathAccessKind

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionPromptRequestRead

type PermissionPromptRequestRead = rpc.PermissionPromptRequestRead

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionPromptRequestURL

type PermissionPromptRequestURL = rpc.PermissionPromptRequestURL

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionPromptRequestWorkflow

type PermissionPromptRequestWorkflow = rpc.PermissionPromptRequestWorkflow

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionPromptRequestWrite

type PermissionPromptRequestWrite = rpc.PermissionPromptRequestWrite

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRecommendation

type PermissionRecommendation = rpc.PermissionRecommendation

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRecoveryAttempt

type PermissionRecoveryAttempt = rpc.PermissionRecoveryAttempt

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRecoveryAttemptDisposition

type PermissionRecoveryAttemptDisposition = rpc.PermissionRecoveryAttemptDisposition

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRecoveryAttemptReason

type PermissionRecoveryAttemptReason = rpc.PermissionRecoveryAttemptReason

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRecoveryAttemptRelation

type PermissionRecoveryAttemptRelation = rpc.PermissionRecoveryAttemptRelation

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRecoveryData

type PermissionRecoveryData = rpc.PermissionRecoveryData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRecoveryOnBlocked

type PermissionRecoveryOnBlocked = rpc.PermissionRecoveryOnBlocked

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRecoveryReason

type PermissionRecoveryReason = rpc.PermissionRecoveryReason

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRecoveryRunState

type PermissionRecoveryRunState = rpc.PermissionRecoveryRunState

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRecoveryStatus

type PermissionRecoveryStatus = rpc.PermissionRecoveryStatus

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequest

type PermissionRequest = rpc.PermissionRequest

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequestCommand

type PermissionRequestCommand = rpc.PermissionRequestCommand

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequestCustomTool

type PermissionRequestCustomTool = rpc.PermissionRequestCustomTool

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequestEnvelope

type PermissionRequestEnvelope = rpc.PermissionRequestEnvelope

PermissionRequestEnvelope retains original JSON for lossless forwarding. Pass the envelope, not its Request, to ManagedReviewRequired.

type PermissionRequestExtensionEnvAccess

type PermissionRequestExtensionEnvAccess = rpc.PermissionRequestExtensionEnvAccess

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequestExtensionManagement

type PermissionRequestExtensionManagement = rpc.PermissionRequestExtensionManagement

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequestExtensionPermissionAccess

type PermissionRequestExtensionPermissionAccess = rpc.PermissionRequestExtensionPermissionAccess

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequestHook

type PermissionRequestHook = rpc.PermissionRequestHook

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequestKind

type PermissionRequestKind = rpc.PermissionRequestKind

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequestMCP

type PermissionRequestMCP = rpc.PermissionRequestMCP

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequestMemory

type PermissionRequestMemory = rpc.PermissionRequestMemory

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequestMemoryAction

type PermissionRequestMemoryAction = rpc.PermissionRequestMemoryAction

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequestMemoryDirection

type PermissionRequestMemoryDirection = rpc.PermissionRequestMemoryDirection

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequestMemoryScope

type PermissionRequestMemoryScope = rpc.PermissionRequestMemoryScope

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequestRead

type PermissionRequestRead = rpc.PermissionRequestRead

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequestShell

type PermissionRequestShell = rpc.PermissionRequestShell

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequestShellCommand

type PermissionRequestShellCommand = rpc.PermissionRequestShellCommand

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequestShellCommandSegment

type PermissionRequestShellCommandSegment = rpc.PermissionRequestShellCommandSegment

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequestShellPossibleURL

type PermissionRequestShellPossibleURL = rpc.PermissionRequestShellPossibleURL

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequestURL

type PermissionRequestURL = rpc.PermissionRequestURL

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequestWorkflow

type PermissionRequestWorkflow = rpc.PermissionRequestWorkflow

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequestWrite

type PermissionRequestWrite = rpc.PermissionRequestWrite

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequestedData

type PermissionRequestedData = rpc.PermissionRequestedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRequestedDataWithEnvelope

type PermissionRequestedDataWithEnvelope struct {
	*PermissionRequestedData
	Envelope *PermissionRequestEnvelope `json:"-"`
}

PermissionRequestedDataWithEnvelope exposes the original permission payload. Pass Envelope, not PermissionRequest, to ManagedReviewRequired. Its envelope is independent of the permission callback's envelope.

type PermissionResponseCapability

type PermissionResponseCapability = rpc.PermissionResponseCapability

PermissionResponseCapability describes whether the responding client could ask a user for a permission decision.

type PermissionResult

type PermissionResult = rpc.PermissionResult

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionResultKind

type PermissionResultKind = rpc.PermissionResultKind

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionRule

type PermissionRule = rpc.PermissionRule

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionSandboxPathGrant

type PermissionSandboxPathGrant = rpc.PermissionSandboxPathGrant

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionSandboxPathGrantAccess

type PermissionSandboxPathGrantAccess = rpc.PermissionSandboxPathGrantAccess

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionWriteFileContent

type PermissionWriteFileContent = rpc.PermissionWriteFileContent

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PermissionWriteFileEdit

type PermissionWriteFileEdit = rpc.PermissionWriteFileEdit

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PersistedBinaryImage

type PersistedBinaryImage = rpc.PersistedBinaryImage

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PersistedBinaryImageType

type PersistedBinaryImageType = rpc.PersistedBinaryImageType

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PersistedBinaryResult

type PersistedBinaryResult = rpc.PersistedBinaryResult

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PersistedBinaryResultType

type PersistedBinaryResultType = rpc.PersistedBinaryResultType

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PingResponse

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

type PlanChangedOperation = rpc.PlanChangedOperation

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PolicyHelperCapabilities

type PolicyHelperCapabilities = rpc.PolicyHelperCapabilities

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PolicyHelperFailure

type PolicyHelperFailure = rpc.PolicyHelperFailure

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PolicyHelperFailureDetail

type PolicyHelperFailureDetail = rpc.PolicyHelperFailureDetail

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PolicyHelperHelpLink = rpc.PolicyHelperHelpLink

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PossibleURL

type PossibleURL = rpc.PossibleURL

Session-event types are generated in the rpc package and aliased here for source compatibility.

type PostToolUseFailureHandler

type PostToolUseFailureHandler func(input PostToolUseFailureHookInput, invocation HookInvocation) (*PostToolUseFailureHookOutput, error)

PostToolUseFailureHandler handles post-tool-use-failure hook invocations.

type PostToolUseFailureHookInput

type PostToolUseFailureHookInput struct {
	// ToolCallID is the existing tool-call ID; correlate using (SessionID, ToolCallID).
	// Empty when omitted by older runtimes.
	ToolCallID       string    `json:"toolCallId,omitempty"`
	Traceparent      string    `json:"traceparent,omitempty"`
	Tracestate       string    `json:"tracestate,omitempty"`
	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 (PostToolUseFailureHookInput) MarshalJSON

func (h PostToolUseFailureHookInput) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.

func (*PostToolUseFailureHookInput) UnmarshalJSON

func (h *PostToolUseFailureHookInput) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.

type PostToolUseFailureHookOutput

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

type PostToolUseHandler func(input PostToolUseHookInput, invocation HookInvocation) (*PostToolUseHookOutput, error)

PostToolUseHandler handles post-tool-use hook invocations

type PostToolUseHookInput

type PostToolUseHookInput struct {
	// ToolCallID is the existing tool-call ID; correlate using (SessionID, ToolCallID).
	// Empty when omitted by older runtimes.
	ToolCallID       string    `json:"toolCallId,omitempty"`
	Traceparent      string    `json:"traceparent,omitempty"`
	Tracestate       string    `json:"tracestate,omitempty"`
	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 (PostToolUseHookInput) MarshalJSON

func (h PostToolUseHookInput) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.

func (*PostToolUseHookInput) UnmarshalJSON

func (h *PostToolUseHookInput) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.

type PostToolUseHookOutput

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

type PreMCPToolCallHandler func(input PreMCPToolCallHookInput, invocation HookInvocation) (*PreMCPToolCallHookOutput, error)

PreMCPToolCallHandler handles pre-mcp-tool-call hook invocations

type PreMCPToolCallHookInput

type PreMCPToolCallHookInput struct {
	Traceparent      string    `json:"traceparent,omitempty"`
	Tracestate       string    `json:"tracestate,omitempty"`
	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 (PreMCPToolCallHookInput) MarshalJSON

func (h PreMCPToolCallHookInput) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.

func (*PreMCPToolCallHookInput) UnmarshalJSON

func (h *PreMCPToolCallHookInput) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.

type PreMCPToolCallHookOutput

type PreMCPToolCallHookOutput struct {
	MetaToUse any `json:"metaToUse"`
}

PreMCPToolCallHookOutput is the output for a pre-mcp-tool-call hook

type PreToolUseHandler

type PreToolUseHandler func(input PreToolUseHookInput, invocation HookInvocation) (*PreToolUseHookOutput, error)

PreToolUseHandler handles pre-tool-use hook invocations

type PreToolUseHookInput

type PreToolUseHookInput struct {
	// ToolCallID is the existing tool-call ID; correlate using (SessionID, ToolCallID).
	// Empty when omitted by older runtimes.
	ToolCallID       string    `json:"toolCallId,omitempty"`
	Traceparent      string    `json:"traceparent,omitempty"`
	Tracestate       string    `json:"tracestate,omitempty"`
	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 (PreToolUseHookInput) MarshalJSON

func (h PreToolUseHookInput) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.

func (*PreToolUseHookInput) UnmarshalJSON

func (h *PreToolUseHookInput) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.

type PreToolUseHookOutput

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

type PromptCacheBreakData = rpc.PromptCacheBreakData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ProviderConfig

type ProviderConfig struct {
	// Type is the provider type: "openai", "azure", "anthropic", or "google". 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 CreateSessionOptions.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 CreateSessionOptions.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 (ProviderConfig) MarshalJSON

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

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"`
	// AutoLocal contains the persisted on-device Auto annotation.
	AutoLocal json.RawMessage `json:"autoLocal,omitempty"`
	// Metadata contains provider-published model metadata, including live Auto routing annotations.
	Metadata map[string]json.RawMessage `json:"metadata,omitempty"`
	// 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

type ProviderMonthlyUsage = rpc.ProviderMonthlyUsage

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ProviderMonthlyUsageScope

type ProviderMonthlyUsageScope = rpc.ProviderMonthlyUsageScope

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ProviderMonthlyUsageState

type ProviderMonthlyUsageState = rpc.ProviderMonthlyUsageState

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ProviderQuotaAccessState

type ProviderQuotaAccessState = rpc.ProviderQuotaAccessState

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ProviderQuotaAcquisitionStatus

type ProviderQuotaAcquisitionStatus = rpc.ProviderQuotaAcquisitionStatus

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ProviderQuotaBudgetMetadata

type ProviderQuotaBudgetMetadata = rpc.ProviderQuotaBudgetMetadata

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ProviderQuotaCapacityState

type ProviderQuotaCapacityState = rpc.ProviderQuotaCapacityState

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ProviderQuotaObservationKind

type ProviderQuotaObservationKind = rpc.ProviderQuotaObservationKind

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ProviderQuotaQuantityKind

type ProviderQuotaQuantityKind = rpc.ProviderQuotaQuantityKind

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ProviderQuotaState

type ProviderQuotaState = rpc.ProviderQuotaState

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ProviderQuotaUnit

type ProviderQuotaUnit = rpc.ProviderQuotaUnit

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ProviderTokenArgs

type ProviderTokenArgs struct {
	// ProviderName is the configured [NamedProviderConfig.Name] needing a token.
	//
	// 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.

type RPCError

type RPCError = jsonrpc2.Error

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 RawAssistedApprovalAssessment

type RawAssistedApprovalAssessment = rpc.RawAssistedApprovalAssessment

Session-event types are generated in the rpc package and aliased here for source compatibility.

type RawCitationLocation

type RawCitationLocation = rpc.RawCitationLocation

Session-event types are generated in the rpc package and aliased here for source compatibility.

type RawHumanResponseRecordedResponse

type RawHumanResponseRecordedResponse = rpc.RawHumanResponseRecordedResponse

Session-event types are generated in the rpc package and aliased here for source compatibility.

type RawPermissionPromptRequest

type RawPermissionPromptRequest = rpc.RawPermissionPromptRequest

Session-event types are generated in the rpc package and aliased here for source compatibility.

type RawPermissionRequest

type RawPermissionRequest = rpc.RawPermissionRequest

Session-event types are generated in the rpc package and aliased here for source compatibility.

type RawPermissionResult

type RawPermissionResult = rpc.RawPermissionResult

Session-event types are generated in the rpc package and aliased here for source compatibility.

type RawPersistedBinaryResult

type RawPersistedBinaryResult = rpc.RawPersistedBinaryResult

Session-event types are generated in the rpc package and aliased here for source compatibility.

type RawSessionEventData

type RawSessionEventData = rpc.RawSessionEventData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type RawSystemNotification

type RawSystemNotification = rpc.RawSystemNotification

Session-event types are generated in the rpc package and aliased here for source compatibility.

type RawSystemNotificationWorkflowPauseInfo

type RawSystemNotificationWorkflowPauseInfo = rpc.RawSystemNotificationWorkflowPauseInfo

Session-event types are generated in the rpc package and aliased here for source compatibility.

type RawToolExecutionCompleteContent

type RawToolExecutionCompleteContent = rpc.RawToolExecutionCompleteContent

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ReasoningSummary

type ReasoningSummary = rpc.ReasoningSummary

Session-event types are generated in the rpc package and aliased here for source compatibility.

type RecommendedAutoTier

type RecommendedAutoTier = rpc.RecommendedAutoTier

Session-event types are generated in the rpc package and aliased here for source compatibility.

type RemediationAction

type RemediationAction = rpc.RemediationAction

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ResponsesReasoning

type ResponsesReasoning = rpc.ResponsesReasoning

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ResumeSessionCanvasOptions

type ResumeSessionCanvasOptions struct {
	// Definitions 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).
	Definitions []CanvasDeclaration
	// RequestRenderer asks the host to enable canvas rendering for this session.
	RequestRenderer *bool
	// Handler 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.
	Handler CanvasHandler `json:"-"`
	// Provider is the stable identity for a host/SDK connection that
	// supplies built-in canvases, so they survive reconnect and CLI restart.
	Provider *CanvasProviderIdentity
	// Open 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`.
	Open []rpc.OpenCanvasInstance
}

ResumeSessionCanvasOptions adds operation-specific settings.

type ResumeSessionOptions

type ResumeSessionOptions struct {
	Inference SessionInferenceOptions
	// ClientName identifies the application using the SDK.
	// Included in the User-Agent header for API requests.
	ClientName string
	GitHub     SessionGitHubOptions
	// Model to use for this session. Can change the model when resuming.
	Model string
	Tools SessionToolOptions
	// SystemMessage configures system message customization
	SystemMessage *SystemMessageConfig
	Agents        SessionAgentOptions
	Skills        SessionSkillOptions
	Filesystem    SessionFilesystemOptions
	Execution     SessionExecutionOptions
	Experiments   SessionExperimentOptions
	Instructions  SessionInstructionOptions
	Git           SessionGitOptions
	Permissions   SessionPermissionOptions
	MCP           SessionMCPOptions
	Interaction   SessionInteractionOptions
	Hooks         SessionHookOptions
	// WorkingDirectory is the working directory for the session.
	// Tool operations will be relative to this directory.
	WorkingDirectory string
	// 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
	State                 SessionStateOptions
	Events                SessionEventOptions
	// Diagnostics updates explicitly configured sources. Leave it nil on a
	// resident resume to preserve the current settings.
	Diagnostics *rpc.DiagnosticsConfiguration
	Plugins     SessionPluginOptions
	// 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.
	//
	// When true, pending permission requests and external tool calls wait for
	// caller-supplied results via the corresponding low-level RPC methods. Resuming
	// does not re-emit restored permission requests or re-invoke permission handlers
	// or already-dispatched external tool callbacks.
	// If a pending call was recorded as SDK-handler-backed and resume registers a
	// handler for that tool, the abandoned callback is interrupted, never replayed.
	// Handlerless calls remain pending. To supply an abandoned callback's result
	// manually, resume without a handler for it. Older requests without recorded
	// callback ownership also remain pending.
	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
	Canvases                ResumeSessionCanvasOptions
	Extensions              SessionExtensionOptions
	Policy                  SessionPolicyOptions
}

ResumeSessionOptions groups options by the feature they configure.

type RuntimeConnection

type RuntimeConnection interface {
	// contains filtered or unexported methods
}

RuntimeConnection describes how a Client connects to the Copilot runtime.

Construct one with a SpawnedStdioConnection, SpawnedTCPConnection, TCPConnection, or InProcessConnection literal and pass it via ClientOptions.Runtime. When ClientOptions.Runtime is nil, COPILOT_SDK_DEFAULT_CONNECTION may select "inprocess" or "stdio"; when unset, the default is an empty InProcessConnection.

func ForDefault

func ForDefault(options *OwnedRuntimeOptions) RuntimeConnection

ForDefault resolves the current deployment default synchronously, without starting or connecting to a runtime. It reads COPILOT_SDK_DEFAULT_CONNECTION at invocation time; an unset or empty value uses in-process hosting.

type SamplingCompletedData

type SamplingCompletedData = rpc.SamplingCompletedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SamplingRequestedData

type SamplingRequestedData = rpc.SamplingRequestedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SandboxDecisionData

type SandboxDecisionData = rpc.SandboxDecisionData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ScheduleOrigin

type ScheduleOrigin = rpc.ScheduleOrigin

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SectionOverride

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

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"
)

type SectionTransformFn

type SectionTransformFn func(currentContent string) (string, error)

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

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.sessionOptions{
    Model: "gpt-5.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!",
})

func (*Session) Abort

func (s *Session) Abort(ctx context.Context) error

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 (*Session) Capabilities

func (s *Session) Capabilities() SessionCapabilities

Capabilities returns the session capabilities reported by the server.

func (*Session) Disconnect

func (s *Session) Disconnect() error

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 (*Session) GetEvents

func (s *Session) GetEvents(ctx context.Context) ([]SessionEvent, error)

GetEvents retrieves all events from this session's history. For lossless JSON, including task-analytics retries, use GetRawEvents instead.

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)
    }
}

func (*Session) GetRawEvents

func (s *Session) GetRawEvents(ctx context.Context) ([]json.RawMessage, error)

GetRawEvents retrieves session history without projecting it into typed events. It preserves timestamp strings, explicit nulls, and unknown fields. Use rpc.SessionEventsAsTrajectory to pass the result to task analytics unchanged.

func (*Session) Log

func (s *Session) Log(ctx context.Context, message string, opts *LogOptions) error

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 (*Session) On

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 (*Session) OnWithPermissionEnvelope

func (s *Session) OnWithPermissionEnvelope(handler SessionEventHandler) func()

OnWithPermissionEnvelope subscribes to lossless permission events. Permission requests use *PermissionRequestedDataWithEnvelope; other data types match On. Dispatch order and unsubscribe behavior are identical to On.

func (*Session) OpenCanvases

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.

func (*Session) PermissionModeResult

func (s *Session) PermissionModeResult() *rpc.PermissionsSetModeResult

PermissionModeResult reports the outcome of the PermissionMode requested when the session was created or resumed: whether it was applied, and the authoritative mode the session started in. It returns nil when no mode was requested. The returned value is independent of session state.

func (*Session) Send

func (s *Session) Send(ctx context.Context, options MessageOptions) (string, error)

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:

  • options: The message options including the prompt and optional attachments.

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 (*Session) SendAndWait

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:

  • options: The message options including the prompt and optional attachments.
  • timeout: How long to wait for completion. Defaults to 60 seconds if zero. Controls how long to wait; does not abort in-flight agent work.

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)
    }
}

func (*Session) SendPrompt

func (s *Session) SendPrompt(ctx context.Context, prompt string) (string, error)

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})

func (*Session) SendPromptAndWait

func (s *Session) SendPromptAndWait(ctx context.Context, prompt string) (*SessionEvent, error)

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 (*Session) SetAutoTier

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.

For Copilot Fusion, prefer Session.SetFusionTier. The balance, hydrafusion and hydrafusion-max identifiers it replaces remain accepted but are deprecated.

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)
}

func (*Session) SetFusionTier

func (s *Session) SetFusionTier(ctx context.Context, fusionTier FusionTier) (*rpc.ModelSwitchAutoTierResult, error)

SetFusionTier changes the Copilot Fusion tier without changing the selected model, naming the tier as the CLI's --fusion-tier does.

The runtime resolves the tier to the Auto routing preference it stands for and then handles the request exactly like Session.SetAutoTier: it takes effect on a later user turn that uses the "fusion" or "auto" model. To return to the provider's default routing, call SetAutoTier with nil.

Experimental: SetFusionTier is part of an experimental Auto routing surface and may change or be removed.

Example:

result, err := session.SetFusionTier(context.Background(), copilot.FusionTierMax)
if err != nil {
    log.Printf("Failed to set Fusion tier: %v", err)
}

func (*Session) SetModel

func (s *Session) SetModel(ctx context.Context, model string, opts *SetModelOptions) error

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)
}
// Like `copilot --model fusion --fusion-tier high`.
if err := session.SetModel(context.Background(), "fusion", &SetModelOptions{FusionTier: new(FusionTierHigh)}); err != nil {
    log.Printf("Failed to set model: %v", err)
}

func (*Session) SetTools

func (s *Session) SetTools(ctx context.Context, tools []Tool) error

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. If no connected client supplies a tool with that name any more, the call fails with an error that tells the agent the tool is no longer available, and the turn continues. If you don't want the agent to see that failure, replace tools while the session is idle.

Experimental: SetTools wraps the experimental session.tools.set RPC and may change or be removed.

func (*Session) TranscriptRecovery

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.

func (*Session) UI

func (s *Session) UI() *SessionUI

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).

func (*Session) WorkspacePath

func (s *Session) WorkspacePath() string

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 SessionAgentOptions

type SessionAgentOptions struct {
	// 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
	// IncludedBuiltinAgents allows only the named built-in subagents, subject to
	// availability and ExcludedBuiltInAgents. A non-nil []string{} disables all
	// built-in subagents; custom agents remain available, including same-name agents.
	// Nil uses defaults on create or cold resume and preserves the current allowlist
	// on warm resume. Not persisted; re-supply on resume after restart.
	IncludedBuiltinAgents []string
	// LocalDiscoveryOnly, when non-nil, restricts custom agents to those
	// defined locally. See also [ClientOptions.Mode] = [ModeEmpty].
	LocalDiscoveryOnly *bool
	// Definitions configures custom agents for the session
	Definitions []CustomAgentConfig
	// Default 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.
	Default *DefaultAgentConfig
	// Selected is the name of the custom agent to activate when the session starts.
	// Must match the Name of one of the agents in CustomAgents.
	Selected string
	// Directories 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.
	Directories []string
}

SessionAgentOptions configures session agents.

type SessionAutoModeResolvedData

type SessionAutoModeResolvedData = rpc.SessionAutoModeResolvedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionAutoTierRecommendationData

type SessionAutoTierRecommendationData = rpc.SessionAutoTierRecommendationData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionAutoTierSwitchFailedData

type SessionAutoTierSwitchFailedData = rpc.SessionAutoTierSwitchFailedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionAutopilotObjectiveChangedData

type SessionAutopilotObjectiveChangedData = rpc.SessionAutopilotObjectiveChangedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionAutopilotStoppedData

type SessionAutopilotStoppedData = rpc.SessionAutopilotStoppedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionBackgroundTasksChangedData

type SessionBackgroundTasksChangedData = rpc.SessionBackgroundTasksChangedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionBinaryAssetData

type SessionBinaryAssetData = rpc.SessionBinaryAssetData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionCanvasClosedData

type SessionCanvasClosedData = rpc.SessionCanvasClosedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionCanvasOpenedData

type SessionCanvasOpenedData = rpc.SessionCanvasOpenedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionCanvasOptions

type SessionCanvasOptions struct {
	// Definitions 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).
	Definitions []CanvasDeclaration
	// RequestRenderer asks the host to enable canvas rendering for this session.
	RequestRenderer *bool
	// Handler 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.
	Handler CanvasHandler `json:"-"`
	// Provider is the stable identity for a host/SDK connection that
	// supplies built-in canvases, so they survive reconnect and CLI restart.
	Provider *CanvasProviderIdentity
}

SessionCanvasOptions configures session canvases.

type SessionCanvasRecordedData

type SessionCanvasRecordedData = rpc.SessionCanvasRecordedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionCanvasRegistryChangedData

type SessionCanvasRegistryChangedData = rpc.SessionCanvasRegistryChangedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionCanvasRemovedData

type SessionCanvasRemovedData = rpc.SessionCanvasRemovedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionCanvasUnavailableData

type SessionCanvasUnavailableData = rpc.SessionCanvasUnavailableData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionCapabilities

type SessionCapabilities struct {
	UI *UICapabilities `json:"ui,omitempty"`
}

SessionCapabilities describes what features the host supports.

type SessionCompactionCompleteData

type SessionCompactionCompleteData = rpc.SessionCompactionCompleteData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionCompactionStartData

type SessionCompactionStartData = rpc.SessionCompactionStartData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionCompactionSummarizedData

type SessionCompactionSummarizedData = rpc.SessionCompactionSummarizedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionCompletionReceiptData

type SessionCompletionReceiptData = rpc.SessionCompletionReceiptData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionContext

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

type SessionContextChangedData = rpc.SessionContextChangedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionContextClearedData

type SessionContextClearedData = rpc.SessionContextClearedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionCustomAgentsUpdatedData

type SessionCustomAgentsUpdatedData = rpc.SessionCustomAgentsUpdatedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionCustomNotificationData

type SessionCustomNotificationData = rpc.SessionCustomNotificationData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionEndHandler

type SessionEndHandler func(input SessionEndHookInput, invocation HookInvocation) (*SessionEndHookOutput, error)

SessionEndHandler handles session-end hook invocations

type SessionEndHookInput

type SessionEndHookInput struct {
	Traceparent      string    `json:"traceparent,omitempty"`
	Tracestate       string    `json:"tracestate,omitempty"`
	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 (SessionEndHookInput) MarshalJSON

func (h SessionEndHookInput) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.

func (*SessionEndHookInput) UnmarshalJSON

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

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

type SessionErrorData = rpc.SessionErrorData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionEvent

type SessionEvent = rpc.SessionEvent

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionEventData

type SessionEventData = rpc.SessionEventData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionEventHandler

type SessionEventHandler func(event SessionEvent)

SessionEventHandler is a callback for session events

type SessionEventOptions

type SessionEventOptions struct {
	// OnEventWithPermissionEnvelope registers a lossless permission event handler
	// before session creation. Equivalent to session.OnWithPermissionEnvelope,
	// but also receives events emitted before CreateSession returns.
	OnEventWithPermissionEnvelope SessionEventHandler
	// 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
	// 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
}

SessionEventOptions configures session events.

type SessionEventType

type SessionEventType = rpc.SessionEventType

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionExecutionOptions

type SessionExecutionOptions struct {
	// Limits 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.
	Limits *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
}

SessionExecutionOptions configures session execution.

type SessionExperimentOptions

type SessionExperimentOptions struct {
	// EnableExperimentalMode controls whether the session enables experimental
	// features. When nil, it defaults to false in [ModeEmpty]; otherwise the
	// runtime decides.
	EnableExperimentalMode *bool
	// Assignments 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.
	Assignments *CopilotExpAssignmentResponse
	// Flags contains feature-flag values resolved by the host for this session.
	// Re-supply them when resuming after a runtime restart.
	Flags map[string]bool
}

SessionExperimentOptions configures session experiments.

type SessionExtensionOptions

type SessionExtensionOptions struct {
	// Enabled opts this connection into the extension surface: when true,
	// the host wires extension management tools and per-extension tool dispatch onto
	// the session.
	Enabled *bool
	// SDKPath 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.
	SDKPath *string
	// Identity identifies the stable extension providing this session's canvases.
	Identity *ExtensionInfo
}

SessionExtensionOptions configures session extensions.

type SessionExtensionsAttachmentsPushedData

type SessionExtensionsAttachmentsPushedData = rpc.SessionExtensionsAttachmentsPushedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionExtensionsLoadedData

type SessionExtensionsLoadedData = rpc.SessionExtensionsLoadedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionFSBinaryProvider

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 SessionFSByteRange

type SessionFSByteRange struct {
	Content    []byte
	ByteLength int64
}

SessionFSByteRange contains raw bytes and the authoritative total file byte length at the read.

type SessionFSCapabilities

type SessionFSCapabilities struct {
	// ReadFileRange declares bounded byte reads independently of binary support.
	ReadFileRange bool
	// 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

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

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

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 SessionFSReadFileRangeProvider

type SessionFSReadFileRangeProvider interface {
	// ReadFileRange reads raw bytes starting at offset. A nil length reads through EOF;
	// zero returns only byte length. At or beyond EOF, content is empty.
	// Offsets and lengths must be non-negative safe integers. Boundaries may split UTF-8.
	ReadFileRange(path string, offset int64, length *int64) (*SessionFSByteRange, error)
}

SessionFSReadFileRangeProvider is an optional bounded-read capability, independent of SessionFSBinaryProvider. Advertise ReadFileRange only when every provider implements it.

type SessionFSSqliteProvider

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

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

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 (*SessionFSSqliteTransactionFailure) Error

type SessionFSSqliteTransactionProvider

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

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 (*SessionFSWriteFailure) Error

func (e *SessionFSWriteFailure) Error() string

func (*SessionFSWriteFailure) Unwrap

func (e *SessionFSWriteFailure) Unwrap() error

type SessionFilesystemOptions

type SessionFilesystemOptions struct {
	// AdditionalDirectories are directories the agent may access beyond WorkingDirectory.
	// Relative paths are resolved against WorkingDirectory. Re-supply them when resuming.
	AdditionalDirectories []string
	// TrackFileChanges opts in to capturing file changes from the first
	// turn for session rewind and cumulative session diff.
	TrackFileChanges *bool
}

SessionFilesystemOptions configures session filesystem.

type SessionFusionCompletedData

type SessionFusionCompletedData = rpc.SessionFusionCompletedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionFusionResolvedData

type SessionFusionResolvedData = rpc.SessionFusionResolvedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionFusionRouteFailedData

type SessionFusionRouteFailedData = rpc.SessionFusionRouteFailedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionFusionRouteStartedData

type SessionFusionRouteStartedData = rpc.SessionFusionRouteStartedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionGitHubOptions

type SessionGitHubOptions struct {
	// TokenProvider acquires session-scoped GitHub tokens on demand. It
	// cannot be combined with GitHubToken.
	TokenProvider GitHubTokenProvider
	// Capi configures provider-scoped CAPI (Copilot API) session options.
	Capi *CapiSessionOptions
	// TelemetryEnabled enables or disables internal session telemetry for this session.
	// When false, disables session telemetry. When nil (the default) or true,
	// telemetry is enabled for eligible GitHub-authenticated sessions, including
	// custom Provider (BYOK) sessions. Host and account policies still control
	// uploads. This is independent of the OpenTelemetry
	// configuration in ClientOptions.Observability.Telemetry.
	TelemetryEnabled *bool
	// MCP 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.
	MCP *GitHubMCPToolConfig
	// Token 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.
	Token string `json:"-"`
	// FetchManagedSettings, 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.
	FetchManagedSettings *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
}

SessionGitHubOptions configures session github.

type SessionGitOptions

type SessionGitOptions struct {
	// 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
	// CoauthorEnabled, when non-nil, controls whether the agent is instructed to
	// include a Co-authored-by trailer in commit messages. Subagents inherit this
	// setting. See also [ClientOptions.Mode] = [ModeEmpty].
	CoauthorEnabled *bool
}

SessionGitOptions configures session git.

type SessionHandoffData

type SessionHandoffData = rpc.SessionHandoffData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionHookOptions

type SessionHookOptions struct {
	// EnableRepositoryHooks, 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.
	EnableRepositoryHooks *bool
	// Handlers configures hook handlers for session lifecycle events
	Handlers *SessionHooks
	// Directories 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.
	Directories []string
}

SessionHookOptions configures session hooks.

type SessionHooks

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

type SessionIdleData = rpc.SessionIdleData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionIndexedSearchData

type SessionIndexedSearchData = rpc.SessionIndexedSearchData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionInferenceOptions

type SessionInferenceOptions struct {
	// AllowMultipleToolCalls permits multiple model tool calls per response (default true).
	// False is a provider hint, not an execution guarantee: all returned calls are
	// handled and handlers may run concurrently. Re-supply on cold resume.
	AllowMultipleToolCalls *bool
	// 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
	// DefaultProvider resolves unqualified BYOK selections using a named connection.
	// Requires GitHub.Capi.Enabled=false. Nil omits the option (preserving it on
	// resume); a pointer to a nil *string clears it. Does not select the model.
	DefaultProvider **string
	// Providers configures named BYOK connections independently of GitHub identity.
	//
	// 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
	// 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
	// Capabilities overrides individual model capabilities resolved by the runtime.
	// Only non-nil fields are applied over the runtime-resolved capabilities.
	Capabilities *rpc.ModelCapabilitiesOverride
}

SessionInferenceOptions configures session inference.

func (*SessionInferenceOptions) UnmarshalJSON

func (options *SessionInferenceOptions) UnmarshalJSON(data []byte) error

UnmarshalJSON preserves an explicitly cleared default connection.

type SessionInfoData

type SessionInfoData = rpc.SessionInfoData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionInstructionOptions

type SessionInstructionOptions struct {
	// OrganizationText 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.
	OrganizationText *string
	// OnDemandDiscovery, when non-nil, controls on-demand discovery
	// of instruction files (AGENTS.md, .github/copilot-instructions.md, etc.) after
	// successful file views.
	OnDemandDiscovery *bool
	// SkipCustomInstructions, when non-nil, controls whether the runtime loads
	// custom instruction files. See also [ClientOptions.Mode] = [ModeEmpty].
	SkipCustomInstructions *bool
	// Directories 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.
	Directories []string
}

SessionInstructionOptions configures session instructions.

type SessionInteractionOptions

type SessionInteractionOptions struct {
	// AutoModeRecovery enrolls in runtime-owned active-request recovery.
	// Requires OnAutoModeSwitchRequest; re-supply on resume. The handler must
	// not resend or rewind the request.
	AutoModeRecovery bool
	// OnUserInputRequest handles legacy question-and-answer requests from the agent
	// and enables the legacy ask_user tool.
	OnUserInputRequest UserInputHandler
	// OnAttributedUserInputRequest reports who answered; see [AttributedUserInputResponse].
	// When both handlers are set, this handler takes precedence.
	// Experimental: this API may change or be removed.
	OnAttributedUserInputRequest AttributedUserInputHandler
	// OnShellAuthenticationRequest handles passwords and other answers that shell
	// commands run by the agent ask for. When provided, `sudo -A`, `ssh`, and
	// `git` prompts reach this handler instead of failing for lack of a
	// terminal. Cancel requests when nobody can answer.
	OnShellAuthenticationRequest ShellAuthenticationHandler
	// AskUserVariant selects the model-facing shape of the ask_user tool.
	// The zero value preserves legacy behavior. AskUserVariantElicitation also
	// requires OnElicitationRequest or OnAttributedElicitationRequest so the host
	// can answer structured forms.
	AskUserVariant AskUserVariant
	// 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
	// OnAttributedElicitationRequest reports who answered; see [AttributedElicitationResult].
	// When both handlers are set, this handler takes precedence.
	// Experimental: this API may change or be removed.
	OnAttributedElicitationRequest AttributedElicitationHandler
	// OnExitPlanModeRequest is a handler for exit-plan-mode requests from the server.
	// When provided, enables exitPlanMode.request callbacks for the session.
	OnExitPlanModeRequest ExitPlanModeRequestHandler
	// OnAttributedExitPlanModeRequest reports who reviewed the plan; see [AttributedExitPlanModeResult].
	// When both handlers are set, this handler takes precedence.
	// Experimental: this API may change or be removed.
	OnAttributedExitPlanModeRequest AttributedExitPlanModeRequestHandler
	// OnAutoModeSwitchRequest is a handler for auto-mode-switch requests from the server.
	// When provided, enables autoModeSwitch.request callbacks for the session.
	OnAutoModeSwitchRequest AutoModeSwitchRequestHandler
}

SessionInteractionOptions configures session interaction.

type SessionJournalLinkData

type SessionJournalLinkData = rpc.SessionJournalLinkData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionLifecycleEvent

type SessionLifecycleEvent struct {
	Type      SessionLifecycleEventType      `json:"type"`
	SessionID string                         `json:"sessionId"`
	Metadata  *SessionLifecycleEventMetadata `json:"metadata,omitempty"`
}

SessionLifecycleEvent represents a session lifecycle notification

type SessionLifecycleEventMetadata

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

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

type SessionLifecycleHandler func(event SessionLifecycleEvent)

SessionLifecycleHandler is a callback for session lifecycle events

type SessionLimitsConfig

type SessionLimitsConfig = rpc.SessionLimitsConfig

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionLimitsExhaustedCompletedData

type SessionLimitsExhaustedCompletedData = rpc.SessionLimitsExhaustedCompletedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionLimitsExhaustedRequestedData

type SessionLimitsExhaustedRequestedData = rpc.SessionLimitsExhaustedRequestedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionLimitsExhaustedResponse

type SessionLimitsExhaustedResponse = rpc.SessionLimitsExhaustedResponse

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionLimitsExhaustedResponseAction

type SessionLimitsExhaustedResponseAction = rpc.SessionLimitsExhaustedResponseAction

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionListFilter

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 SessionMCPOptions

type SessionMCPOptions struct {
	// OnAuthRuntimeRefresh overrides OnAuthRequest when non-nil.
	OnAuthRuntimeRefresh MCPAuthRuntimeRefreshHandler
	// OnAuthRequest 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.
	OnAuthRequest MCPAuthHandler
	// Servers configures MCP servers for the session
	Servers map[string]MCPServerConfig
	// OAuthTokenStorage controls how MCP OAuth tokens are stored for this session.
	// When empty, the runtime default ("in-memory") is used.
	OAuthTokenStorage string
	// AuthClientIDMetadataURL identifies the host for MCP OAuth authorization.
	// When empty, no host identity is supplied.
	AuthClientIDMetadataURL string
	// DisabledServers 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.
	DisabledServers []string
	// EnableApps 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.
	EnableApps bool
}

SessionMCPOptions configures session mcp.

type SessionMCPServerNeedsReconnectData

type SessionMCPServerNeedsReconnectData = rpc.SessionMCPServerNeedsReconnectData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionMCPServerRemovedData

type SessionMCPServerRemovedData = rpc.SessionMCPServerRemovedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionMCPServerStatusChangedData

type SessionMCPServerStatusChangedData = rpc.SessionMCPServerStatusChangedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionMCPServerToolsLoadedData

type SessionMCPServerToolsLoadedData = rpc.SessionMCPServerToolsLoadedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionMCPServersLoadedData

type SessionMCPServersLoadedData = rpc.SessionMCPServersLoadedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionManagedPluginProgressData

type SessionManagedPluginProgressData = rpc.SessionManagedPluginProgressData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionManagedSettingsEnforcedData

type SessionManagedSettingsEnforcedData = rpc.SessionManagedSettingsEnforcedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionManagedSettingsResolvedData

type SessionManagedSettingsResolvedData = rpc.SessionManagedSettingsResolvedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionMetadata

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"`
	// ClientName is the name of the client that created the session (for example
	// "github/cli"). Nil when unknown.
	ClientName *string `json:"clientName,omitempty"`
	// LastClientName is the name of the client that most recently ran the
	// session: the client that created it, or a client that resumed it and then
	// ran it. Resuming a session only to observe it does not change it. Nil when
	// unknown, such as for sessions persisted before this field existed.
	LastClientName *string `json:"lastClientName,omitempty"`
}

SessionMetadata contains metadata about a session

type SessionMode

type SessionMode = rpc.SessionMode

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionModeChangedData

type SessionModeChangedData = rpc.SessionModeChangedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionModeNoticeDeliveredData

type SessionModeNoticeDeliveredData = rpc.SessionModeNoticeDeliveredData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionModelChangeData

type SessionModelChangeData = rpc.SessionModelChangeData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionModelDeselectedData

type SessionModelDeselectedData = rpc.SessionModelDeselectedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionPermissionOptions

type SessionPermissionOptions struct {
	// OnRequestWithEnvelope overrides the other permission decision
	// handlers when non-nil, preserving the complete permission envelope.
	OnRequestWithEnvelope PermissionHandlerWithEnvelopeFunc
	// OnRequestWithPrompt receives the optional derived user-facing
	// prompt supplied by newer runtimes. When both permission handlers are set,
	// this handler takes precedence.
	OnRequestWithPrompt PermissionHandlerWithPromptFunc
	// OnRequest 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.
	OnRequest PermissionHandlerFunc
	// Sandbox 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.
	Sandbox *rpc.SandboxConfig
	// Mode is applied before the session's first turn: before
	// CreateSession returns. It uses the same checks as
	// session.RPC.Permissions.SetMode; a mode that managed policy or session
	// capabilities refuse leaves the current mode in place.
	// Session.PermissionModeResult reports whether it was applied and the
	// authoritative mode. Empty keeps the default mode. Not supported for cloud
	// sessions.
	Mode rpc.PermissionMode
}

SessionPermissionOptions configures session permissions.

type SessionPermissionRecoveryData

type SessionPermissionRecoveryData = rpc.SessionPermissionRecoveryData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionPermissionsChangedData

type SessionPermissionsChangedData = rpc.SessionPermissionsChangedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionPlanChangedData

type SessionPlanChangedData = rpc.SessionPlanChangedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionPluginOptions

type SessionPluginOptions struct {
	// Directories 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.
	Directories []string
}

SessionPluginOptions configures session plugins.

type SessionPolicyOptions

type SessionPolicyOptions struct {
	// 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
	// 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
}

SessionPolicyOptions configures session policy.

type SessionQuotaObservationData

type SessionQuotaObservationData = rpc.SessionQuotaObservationData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionRemoteSteerableChangedData

type SessionRemoteSteerableChangedData = rpc.SessionRemoteSteerableChangedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionResumeData

type SessionResumeData = rpc.SessionResumeData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionScheduleCancelledData

type SessionScheduleCancelledData = rpc.SessionScheduleCancelledData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionScheduleCreatedData

type SessionScheduleCreatedData = rpc.SessionScheduleCreatedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionScheduleRearmedData

type SessionScheduleRearmedData = rpc.SessionScheduleRearmedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionSessionLimitsChangedData

type SessionSessionLimitsChangedData = rpc.SessionSessionLimitsChangedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionShutdownData

type SessionShutdownData = rpc.SessionShutdownData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionSkillOptions

type SessionSkillOptions struct {
	// Enabled, 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.
	Enabled *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
	// Directories 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.
	Directories []string
	// Provider 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.
	Provider SkillProvider `json:"-"`
	// DisabledSkills is a list of skill names to disable
	DisabledSkills []string
}

SessionSkillOptions configures session skills.

type SessionSkillsLoadedData

type SessionSkillsLoadedData = rpc.SessionSkillsLoadedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionSnapshotRewindData

type SessionSnapshotRewindData = rpc.SessionSnapshotRewindData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionStartData

type SessionStartData = rpc.SessionStartData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionStartHandler

type SessionStartHandler func(input SessionStartHookInput, invocation HookInvocation) (*SessionStartHookOutput, error)

SessionStartHandler handles session-start hook invocations

type SessionStartHookInput

type SessionStartHookInput struct {
	Traceparent      string    `json:"traceparent,omitempty"`
	Tracestate       string    `json:"tracestate,omitempty"`
	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 (SessionStartHookInput) MarshalJSON

func (h SessionStartHookInput) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.

func (*SessionStartHookInput) UnmarshalJSON

func (h *SessionStartHookInput) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.

type SessionStartHookOutput

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 SessionStateOptions

type SessionStateOptions struct {
	// 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
	// EnableCrossSessionStore, 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.
	EnableCrossSessionStore *bool
	// InfiniteSessions configures infinite sessions for persistent workspaces and automatic compaction.
	// When enabled (default), sessions automatically manage context limits and persist state.
	InfiniteSessions *InfiniteSessionConfig
	// Memory configures the memory feature for the session. When omitted, the
	// runtime default applies.
	Memory *MemoryConfiguration
	// StoreMemory stores memories in the app instead of the built-in memory backends.
	//
	// The runtime validates the memory, filters secrets and requests approval,
	// then calls this callback. store_memory succeeds only after the callback
	// returns nil; an error fails the tool call with a generic message and
	// nothing is stored elsewhere. While set, the runtime retrieves no memories
	// and vote_memory is unavailable, so supply recall yourself, for example
	// through SystemMessage. Requires Memory.Enabled to be true; creating or resuming
	// a session fails otherwise.
	// Experimental: this option may change or be removed in a future release.
	StoreMemory func(ctx context.Context, memory StoredMemory) error `json:"-"`
	// CreateSessionFSProvider supplies a handler for session filesystem operations.
	// This takes effect only when ClientOptions.SessionFS is configured.
	CreateSessionFSProvider func(session *Session) SessionFSProvider
}

SessionStateOptions configures session state.

type SessionTaskCompleteData

type SessionTaskCompleteData = rpc.SessionTaskCompleteData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionTitleChangedData

type SessionTitleChangedData = rpc.SessionTitleChangedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionTodosChangedData

type SessionTodosChangedData = rpc.SessionTodosChangedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionToolOptions

type SessionToolOptions struct {
	// Definitions 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.
	Definitions []Tool
	// AvailableTools is a list of tool names to allow. When specified, only these tools will be available.
	// When ExcludedTools is also set, a tool must match AvailableTools and not match ExcludedTools.
	AvailableTools []string
	// ExcludedTools is a list of tool names to disable. All other tools remain available.
	// Takes precedence over AvailableTools: a tool listed here is disabled even if it
	// also matches AvailableTools.
	ExcludedTools []string
	// ManageScheduleEnabled, when non-nil, controls whether the
	// `manage_schedule` tool is exposed. See also [ClientOptions.Mode] =
	// [ModeEmpty].
	ManageScheduleEnabled *bool
	// 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
	// Search overrides the runtime's built-in tool-search behavior, which
	// defers rarely used tools behind a searchable index. When nil, the runtime
	// default applies.
	Search *ToolSearchConfig
	// ImageGeneration is the non-persisted image generation opt-in.
	// Experimental: this API may change or be removed in a future release.
	ImageGeneration *ImageGenerationConfig
}

SessionToolOptions configures session tools.

type SessionToolsUpdatedData

type SessionToolsUpdatedData = rpc.SessionToolsUpdatedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionTruncationData

type SessionTruncationData = rpc.SessionTruncationData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionUI

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.

func (*SessionUI) Confirm

func (ui *SessionUI) Confirm(ctx context.Context, message string) (bool, error)

Confirm shows a confirmation dialog and returns the user's boolean answer. Returns false if the user declines or cancels.

func (*SessionUI) Elicitation

func (ui *SessionUI) Elicitation(ctx context.Context, message string, requestedSchema ElicitationSchema) (*ElicitationResult, error)

Elicitation shows a generic elicitation dialog with a custom schema.

func (*SessionUI) Input

func (ui *SessionUI) Input(ctx context.Context, message string, opts *UIInputOptions) (string, bool, error)

Input shows a text input dialog. Returns the entered text, or empty string and false if the user declines/cancels.

func (*SessionUI) Select

func (ui *SessionUI) Select(ctx context.Context, message string, options []string) (string, bool, error)

Select shows a selection dialog with the given options. Returns the selected string, or empty string and false if the user declines/cancels.

type SessionUsageCheckpointData

type SessionUsageCheckpointData = rpc.SessionUsageCheckpointData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionUsageInfoData

type SessionUsageInfoData = rpc.SessionUsageInfoData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionWarningData

type SessionWarningData = rpc.SessionWarningData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SessionWorkspaceFileChangedData

type SessionWorkspaceFileChangedData = rpc.SessionWorkspaceFileChangedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SetModelOptions

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.
	//
	// For Copilot Fusion, prefer FusionTier. The balance, hydrafusion and
	// hydrafusion-max identifiers it replaces remain accepted but are deprecated.
	//
	// 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
	// FusionTier stages a Copilot Fusion tier atomically with selecting the
	// "fusion" or "auto" model, matching the CLI's --fusion-tier. The runtime
	// resolves the tier to the Auto routing preference it stands for and stages
	// it exactly like AutoTier. It is mutually exclusive with AutoTier and
	// ResetAutoTier. Use [Session.SetFusionTier] to change the tier without
	// changing the selected model.
	//
	// Experimental: FusionTier is part of an experimental Auto routing surface
	// and may change or be removed.
	FusionTier *FusionTier
}

SetModelOptions configures optional parameters for SetModel.

type ShellAuthenticationAction

type ShellAuthenticationAction string

ShellAuthenticationAction is the outcome of a ShellAuthenticationRequest.

const (
	// ShellAuthenticationActionAccept answers the request with ShellAuthenticationResponse.Value.
	ShellAuthenticationActionAccept ShellAuthenticationAction = "accept"
	// ShellAuthenticationActionCancel declines the request. The program that asked fails.
	ShellAuthenticationActionCancel ShellAuthenticationAction = "cancel"
)

type ShellAuthenticationHandler

type ShellAuthenticationHandler func(request ShellAuthenticationRequest, invocation ShellAuthenticationInvocation) (ShellAuthenticationResponse, error)

ShellAuthenticationHandler handles passwords and other answers that shell commands run by the agent ask for. Returning an error, an action other than ShellAuthenticationActionAccept, or returning after the invocation's Context is done cancels the prompt, so the program that asked fails instead of receiving a wrong value.

type ShellAuthenticationInputKind

type ShellAuthenticationInputKind string

ShellAuthenticationInputKind says how to present a ShellAuthenticationRequest.

const (
	// ShellAuthenticationInputKindSecret is a password or passphrase. Mask the input.
	ShellAuthenticationInputKindSecret ShellAuthenticationInputKind = "secret"
	// ShellAuthenticationInputKindText is a visible answer, such as a user name.
	ShellAuthenticationInputKindText ShellAuthenticationInputKind = "text"
	// ShellAuthenticationInputKindConfirm is a yes or no question, such as an ssh host-key
	// check. Answer "yes", or cancel to decline.
	ShellAuthenticationInputKindConfirm ShellAuthenticationInputKind = "confirm"
)

type ShellAuthenticationInvocation

type ShellAuthenticationInvocation struct {
	SessionID string
	// Context is cancelled when the answer is no longer needed, for example
	// because the command ended, the prompt timed out, or the session ended or
	// switched to autopilot. Close the input when it is.
	Context context.Context
}

ShellAuthenticationInvocation provides context about a shell authentication request.

type ShellAuthenticationRequest

type ShellAuthenticationRequest struct {
	// RequestID identifies the request. A cancellation for it carries the same id.
	RequestID string
	// Program is the program that asked: "sudo", "ssh", or "git".
	Program string
	// Prompt is the prompt text the program supplied.
	Prompt string
	// InputKind says how to present the request.
	InputKind ShellAuthenticationInputKind
	// Command is the shell command that triggered the prompt.
	Command string
	// Cwd is the command's working directory.
	Cwd string
}

ShellAuthenticationRequest is a password or other answer that a shell command run by the agent asks for, for example `sudo -A`, `ssh`, or `git` over HTTPS. The answer goes only to the program that asked: it is not shown to the model and is not recorded in session events.

type ShellAuthenticationResponse

type ShellAuthenticationResponse struct {
	Action ShellAuthenticationAction `json:"action"`
	// Value is the answer when Action is ShellAuthenticationActionAccept.
	Value string `json:"value,omitempty"`
}

ShellAuthenticationResponse answers a ShellAuthenticationRequest. Answer a ShellAuthenticationInputKindConfirm request with "yes", or cancel it to decline.

func (ShellAuthenticationResponse) MarshalJSON

func (r ShellAuthenticationResponse) MarshalJSON() ([]byte, error)

MarshalJSON sends Value with every accept, even an empty one, such as an empty user name. A cancel carries no value.

type ShutdownAgentMetric

type ShutdownAgentMetric = rpc.ShutdownAgentMetric

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ShutdownCodeChanges

type ShutdownCodeChanges = rpc.ShutdownCodeChanges

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ShutdownModelMetric

type ShutdownModelMetric = rpc.ShutdownModelMetric

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ShutdownModelMetricRequests

type ShutdownModelMetricRequests = rpc.ShutdownModelMetricRequests

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ShutdownModelMetricTokenDetail

type ShutdownModelMetricTokenDetail = rpc.ShutdownModelMetricTokenDetail

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ShutdownModelMetricUsage

type ShutdownModelMetricUsage = rpc.ShutdownModelMetricUsage

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ShutdownTokenDetail

type ShutdownTokenDetail = rpc.ShutdownTokenDetail

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ShutdownType

type ShutdownType = rpc.ShutdownType

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SkillContextDeliveredData

type SkillContextDeliveredData = rpc.SkillContextDeliveredData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SkillContextDeliveredRefData

type SkillContextDeliveredRefData = rpc.SkillContextDeliveredRefData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SkillInvokedData

type SkillInvokedData = rpc.SkillInvokedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SkillInvokedRefData

type SkillInvokedRefData = rpc.SkillInvokedRefData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SkillInvokedTrigger

type SkillInvokedTrigger = rpc.SkillInvokedTrigger

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SkillProvider

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

type SkillSource = rpc.SkillSource

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SkillsLoadedSkill

type SkillsLoadedSkill = rpc.SkillsLoadedSkill

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SpawnedStdioConnection

type SpawnedStdioConnection struct {
	BaseDirectory             string
	SessionIdleTimeoutSeconds int
	// Path is the runtime executable. When empty, the bundled runtime is used.
	Path string
	// Args are extra command-line arguments inserted before SDK-managed arguments.
	Args []string
	// Env are the environment variables for the runtime process, each of the
	// form "KEY=VALUE", replacing inherited variables. Nil inherits the current
	// environment; an empty slice has no inherited variables. The SDK still adds
	// its managed runtime settings. Duplicate keys use the last value.
	Env []string
	// WorkingDirectory is the child process directory. Empty inherits the current directory.
	WorkingDirectory string
}

SpawnedStdioConnection spawns a runtime child process and communicates over its stdin/stdout pipes.

type SpawnedTCPConnection

type SpawnedTCPConnection struct {
	BaseDirectory             string
	SessionIdleTimeoutSeconds int
	// 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 arguments.
	Args []string
	// Env are the environment variables for the runtime process, each of the
	// form "KEY=VALUE", replacing inherited variables. Nil inherits the current
	// environment; an empty slice has no inherited variables. The SDK still adds
	// its managed runtime settings. Duplicate keys use the last value.
	Env []string
	// WorkingDirectory is the child process directory. Empty inherits the current directory.
	WorkingDirectory string
}

SpawnedTCPConnection spawns a runtime child process that listens on a TCP socket and connects to it.

type StoredMemory

type StoredMemory struct {
	// SessionID is the ID of the session that stored the memory.
	SessionID string `json:"sessionId"`
	// Subject is the short topic the memory is about.
	Subject string `json:"subject"`
	// Fact is the fact to remember.
	Fact string `json:"fact"`
	// Citations are sources supporting the fact, such as file paths with line numbers.
	Citations string `json:"citations"`
	// Reason explains why the agent considers the fact worth remembering.
	Reason string `json:"reason"`
}

StoredMemory is a memory the agent asked to store, after validation, secret filtering and approval. Experimental: this type may change or be removed in a future release.

type SubagentCompletedData

type SubagentCompletedData = rpc.SubagentCompletedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SubagentConfiguredData

type SubagentConfiguredData = rpc.SubagentConfiguredData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SubagentDeselectedData

type SubagentDeselectedData = rpc.SubagentDeselectedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SubagentFailedData

type SubagentFailedData = rpc.SubagentFailedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SubagentModelSelectionSource

type SubagentModelSelectionSource = rpc.SubagentModelSelectionSource

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SubagentSelectedData

type SubagentSelectedData = rpc.SubagentSelectedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SubagentStartHandler

type SubagentStartHandler func(input SubagentStartHookInput, invocation HookInvocation) (*SubagentStartHookOutput, error)

SubagentStartHandler handles subagent-start hook invocations.

type SubagentStartHookInput

type SubagentStartHookInput struct {
	Traceparent      string    `json:"traceparent,omitempty"`
	Tracestate       string    `json:"tracestate,omitempty"`
	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 (SubagentStartHookInput) MarshalJSON

func (h SubagentStartHookInput) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.

func (*SubagentStartHookInput) UnmarshalJSON

func (h *SubagentStartHookInput) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.

type SubagentStartHookOutput

type SubagentStartHookOutput struct {
	AdditionalContext string `json:"additionalContext,omitempty"`
}

SubagentStartHookOutput provides context prepended to the subagent's initial prompt.

type SubagentStartedData

type SubagentStartedData = rpc.SubagentStartedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SubagentStopHandler

type SubagentStopHandler func(input SubagentStopHookInput, invocation HookInvocation) (*SubagentStopHookOutput, error)

SubagentStopHandler handles subagent-stop hook invocations.

type SubagentStopHookInput

type SubagentStopHookInput struct {
	Traceparent      string    `json:"traceparent,omitempty"`
	Tracestate       string    `json:"tracestate,omitempty"`
	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 (SubagentStopHookInput) MarshalJSON

func (h SubagentStopHookInput) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.

func (*SubagentStopHookInput) UnmarshalJSON

func (h *SubagentStopHookInput) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.

type SubagentStopHookOutput

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

type SubagentTaskModelSource = rpc.SubagentTaskModelSource

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SystemMessageAppendConfig

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

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.

  • Append mode (default): SDK foundation + optional custom content
  • Replace mode: Full control, caller provides entire system message
  • Customize mode: Section-level overrides with graceful fallback

In Go, use one struct and set fields appropriate for the desired mode.

type SystemMessageContentBlock

type SystemMessageContentBlock = rpc.SystemMessageContentBlock

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SystemMessageData

type SystemMessageData = rpc.SystemMessageData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SystemMessageMetadata

type SystemMessageMetadata = rpc.SystemMessageMetadata

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SystemMessageReplaceConfig

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

type SystemMessageRole = rpc.SystemMessageRole

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SystemNotification

type SystemNotification = rpc.SystemNotification

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SystemNotificationAgentCompleted

type SystemNotificationAgentCompleted = rpc.SystemNotificationAgentCompleted

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SystemNotificationAgentCompletedStatus

type SystemNotificationAgentCompletedStatus = rpc.SystemNotificationAgentCompletedStatus

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SystemNotificationAgentIdle

type SystemNotificationAgentIdle = rpc.SystemNotificationAgentIdle

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SystemNotificationData

type SystemNotificationData = rpc.SystemNotificationData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SystemNotificationInstructionDiscovered

type SystemNotificationInstructionDiscovered = rpc.SystemNotificationInstructionDiscovered

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SystemNotificationNewInboxMessage

type SystemNotificationNewInboxMessage = rpc.SystemNotificationNewInboxMessage

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SystemNotificationShellCompleted

type SystemNotificationShellCompleted = rpc.SystemNotificationShellCompleted

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SystemNotificationShellDetachedCompleted

type SystemNotificationShellDetachedCompleted = rpc.SystemNotificationShellDetachedCompleted

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SystemNotificationType

type SystemNotificationType = rpc.SystemNotificationType

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SystemNotificationUnclassified

type SystemNotificationUnclassified = rpc.SystemNotificationUnclassified

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SystemNotificationWorkflowCompleted

type SystemNotificationWorkflowCompleted = rpc.SystemNotificationWorkflowCompleted

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SystemNotificationWorkflowCompletedStatus

type SystemNotificationWorkflowCompletedStatus = rpc.SystemNotificationWorkflowCompletedStatus

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SystemNotificationWorkflowPauseInfo

type SystemNotificationWorkflowPauseInfo = rpc.SystemNotificationWorkflowPauseInfo

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SystemNotificationWorkflowPauseInfoCheckpoint

type SystemNotificationWorkflowPauseInfoCheckpoint = rpc.SystemNotificationWorkflowPauseInfoCheckpoint

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SystemNotificationWorkflowPauseInfoType

type SystemNotificationWorkflowPauseInfoType = rpc.SystemNotificationWorkflowPauseInfoType

Session-event types are generated in the rpc package and aliased here for source compatibility.

type SystemNotificationWorkflowPauseInfoUser

type SystemNotificationWorkflowPauseInfoUser = rpc.SystemNotificationWorkflowPauseInfoUser

Session-event types are generated in the rpc package and aliased here for source compatibility.

type TCPConnection

type TCPConnection struct {
	// Host is a hostname or IP address without a scheme, port, path, or IPv6 brackets.
	Host string
	// Port is the TCP port, from 1 through 65535.
	Port int
	// ConnectionToken authenticates the connection; must match what the
	// remote runtime expects.
	ConnectionToken string
}

TCPConnection connects to an already-running runtime over plaintext TCP. The SDK does not spawn a process or own the runtime's lifetime.

type TaskBlocker

type TaskBlocker = rpc.TaskBlocker

Session-event types are generated in the rpc package and aliased here for source compatibility.

type TaskBlockerKind

type TaskBlockerKind = rpc.TaskBlockerKind

Session-event types are generated in the rpc package and aliased here for source compatibility.

type TaskBlockerReason

type TaskBlockerReason = rpc.TaskBlockerReason

Session-event types are generated in the rpc package and aliased here for source compatibility.

type TaskCompleteData

type TaskCompleteData = rpc.TaskCompleteData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type TaskCompletionOutcome

type TaskCompletionOutcome = rpc.TaskCompletionOutcome

Session-event types are generated in the rpc package and aliased here for source compatibility.

type TelemetryConfig

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.
	// In-process connections require a valid UTF-8 path.
	// 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_CONTENT and its legacy boolean alias.
	CaptureContent *bool
}

TelemetryConfig configures OpenTelemetry integration for the Copilot CLI process.

type Tool

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"`
	// Idempotent declares that repeating a call with the same arguments has no
	// additional effect beyond the first call, as is true of any tool without
	// side effects. The runtime may use this to decide that a call whose
	// outcome was lost can be safely repeated. It does not affect permission
	// checks.
	Idempotent bool `json:"idempotent,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

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

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

type ToolDefer string

ToolDefer controls whether a tool may be deferred (loaded lazily via tool search) rather than always pre-loaded.

const (
	// ToolDeferAuto allows the tool to be deferred and surfaced through tool search.
	ToolDeferAuto ToolDefer = "auto"
	// ToolDeferNever forces the tool to always be pre-loaded.
	ToolDeferNever ToolDefer = "never"
)

type ToolExecutionCompleteContent

type ToolExecutionCompleteContent = rpc.ToolExecutionCompleteContent

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteContentAudio

type ToolExecutionCompleteContentAudio = rpc.ToolExecutionCompleteContentAudio

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteContentImage

type ToolExecutionCompleteContentImage = rpc.ToolExecutionCompleteContentImage

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteContentResource

type ToolExecutionCompleteContentResource = rpc.ToolExecutionCompleteContentResource

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteContentResourceDetails

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

type ToolExecutionCompleteContentResourceLinkIcon = rpc.ToolExecutionCompleteContentResourceLinkIcon

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteContentResourceLinkIconTheme

type ToolExecutionCompleteContentResourceLinkIconTheme = rpc.ToolExecutionCompleteContentResourceLinkIconTheme

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteContentShellExit

type ToolExecutionCompleteContentShellExit = rpc.ToolExecutionCompleteContentShellExit

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteContentText

type ToolExecutionCompleteContentText = rpc.ToolExecutionCompleteContentText

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteContentType

type ToolExecutionCompleteContentType = rpc.ToolExecutionCompleteContentType

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteData

type ToolExecutionCompleteData = rpc.ToolExecutionCompleteData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteError

type ToolExecutionCompleteError = rpc.ToolExecutionCompleteError

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteFileEdit

type ToolExecutionCompleteFileEdit = rpc.ToolExecutionCompleteFileEdit

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteFileEditKind

type ToolExecutionCompleteFileEditKind = rpc.ToolExecutionCompleteFileEditKind

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteResult

type ToolExecutionCompleteResult = rpc.ToolExecutionCompleteResult

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteShellExecution

type ToolExecutionCompleteShellExecution = rpc.ToolExecutionCompleteShellExecution

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteToolDescription

type ToolExecutionCompleteToolDescription = rpc.ToolExecutionCompleteToolDescription

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteToolDescriptionMeta

type ToolExecutionCompleteToolDescriptionMeta = rpc.ToolExecutionCompleteToolDescriptionMeta

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteToolDescriptionMetaUI

type ToolExecutionCompleteToolDescriptionMetaUI = rpc.ToolExecutionCompleteToolDescriptionMetaUI

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteToolDescriptionMetaUIVisibility

type ToolExecutionCompleteToolDescriptionMetaUIVisibility = rpc.ToolExecutionCompleteToolDescriptionMetaUIVisibility

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteUIResource

type ToolExecutionCompleteUIResource = rpc.ToolExecutionCompleteUIResource

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteUIResourceMeta

type ToolExecutionCompleteUIResourceMeta = rpc.ToolExecutionCompleteUIResourceMeta

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteUIResourceMetaUI

type ToolExecutionCompleteUIResourceMetaUI = rpc.ToolExecutionCompleteUIResourceMetaUI

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteUIResourceMetaUICsp

type ToolExecutionCompleteUIResourceMetaUICsp = rpc.ToolExecutionCompleteUIResourceMetaUICsp

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteUIResourceMetaUIPermissions

type ToolExecutionCompleteUIResourceMetaUIPermissions = rpc.ToolExecutionCompleteUIResourceMetaUIPermissions

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteUIResourceMetaUIPermissionsCamera

type ToolExecutionCompleteUIResourceMetaUIPermissionsCamera = rpc.ToolExecutionCompleteUIResourceMetaUIPermissionsCamera

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite

type ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite = rpc.ToolExecutionCompleteUIResourceMetaUIPermissionsClipboardWrite

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation

type ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation = rpc.ToolExecutionCompleteUIResourceMetaUIPermissionsGeolocation

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone

type ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone = rpc.ToolExecutionCompleteUIResourceMetaUIPermissionsMicrophone

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionProgressData

type ToolExecutionProgressData = rpc.ToolExecutionProgressData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionStartData

type ToolExecutionStartData = rpc.ToolExecutionStartData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionStartShellToolInfo

type ToolExecutionStartShellToolInfo = rpc.ToolExecutionStartShellToolInfo

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionStartToolDescription

type ToolExecutionStartToolDescription = rpc.ToolExecutionStartToolDescription

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionStartToolDescriptionMeta

type ToolExecutionStartToolDescriptionMeta = rpc.ToolExecutionStartToolDescriptionMeta

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionStartToolDescriptionMetaUI

type ToolExecutionStartToolDescriptionMetaUI = rpc.ToolExecutionStartToolDescriptionMetaUI

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionStartToolDescriptionMetaUIVisibility

type ToolExecutionStartToolDescriptionMetaUIVisibility = rpc.ToolExecutionStartToolDescriptionMetaUIVisibility

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionUsage

type ToolExecutionUsage = rpc.ToolExecutionUsage

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolExecutionUsageTokenDetails

type ToolExecutionUsageTokenDetails = rpc.ToolExecutionUsageTokenDetails

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolHandler

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

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

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

type ToolResult struct {
	// TextResultForLLM is the tool output for the model. The SDK sends it
	// unchanged, including when it is empty.
	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

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

type ToolSearchActivatedData = rpc.ToolSearchActivatedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolSearchConfig

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

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 [sessionOptions.AvailableTools] or [sessionOptions.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 [sessionOptions] fields, e.g. `(&ToolSet{}).AddBuiltIn(...).ToSlice()`.

func NewToolSet

func NewToolSet() *ToolSet

NewToolSet returns an empty ToolSet.

func (*ToolSet) AddBuiltIn

func (s *ToolSet) AddBuiltIn(names ...string) *ToolSet

AddBuiltIn adds one or more built-in tool patterns. Pass a specific tool name (e.g. "bash") or "*" to match all built-in tools.

func (*ToolSet) AddCustom

func (s *ToolSet) AddCustom(name string) *ToolSet

AddCustom adds a custom-tool pattern. Matches tools registered via [sessionOptions.Tools] or via custom agents.

func (*ToolSet) AddMCP

func (s *ToolSet) AddMCP(toolName string) *ToolSet

AddMCP adds an MCP tool pattern. Matches tools advertised by any configured MCP server.

func (*ToolSet) ToSlice

func (s *ToolSet) ToSlice() []string

ToSlice returns a defensive copy of the accumulated filter strings.

type ToolShellOutputData

type ToolShellOutputData = rpc.ToolShellOutputData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolShellOutputStream

type ToolShellOutputStream = rpc.ToolShellOutputStream

Session-event types are generated in the rpc package and aliased here for source compatibility.

type ToolUserRequestedData

type ToolUserRequestedData = rpc.ToolUserRequestedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type TranscriptRecoveryReport

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

type UICapabilities struct {
	// AutoModeRecovery acknowledges retained-request Auto recovery. Absent means unsupported.
	AutoModeRecovery bool `json:"autoModeRecovery,omitempty"`
	// 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

type UIEphemeralQueryData = rpc.UIEphemeralQueryData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UIEphemeralQueryPhase

type UIEphemeralQueryPhase = rpc.UIEphemeralQueryPhase

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UIInputOptions

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 UsageAccountingIdentity

type UsageAccountingIdentity = rpc.UsageAccountingIdentity

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UsageGetMetricsResult

type UsageGetMetricsResult = rpc.UsageGetMetricsResult

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UsageMetricsAgentMetric

type UsageMetricsAgentMetric = rpc.UsageMetricsAgentMetric

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UsageMetricsCodeChanges

type UsageMetricsCodeChanges = rpc.UsageMetricsCodeChanges

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UsageMetricsModelMetric

type UsageMetricsModelMetric = rpc.UsageMetricsModelMetric

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UsageMetricsModelMetricRequests

type UsageMetricsModelMetricRequests = rpc.UsageMetricsModelMetricRequests

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UsageMetricsModelMetricTokenDetail

type UsageMetricsModelMetricTokenDetail = rpc.UsageMetricsModelMetricTokenDetail

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UsageMetricsModelMetricUsage

type UsageMetricsModelMetricUsage = rpc.UsageMetricsModelMetricUsage

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UsageMetricsProviderModelMetric

type UsageMetricsProviderModelMetric = rpc.UsageMetricsProviderModelMetric

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UsageMetricsTokenDetail

type UsageMetricsTokenDetail = rpc.UsageMetricsTokenDetail

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UserInputCompletedData

type UserInputCompletedData = rpc.UserInputCompletedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UserInputHandler

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

type UserInputInvocation struct {
	SessionID string
}

UserInputInvocation provides context about a user input request

type UserInputRequest

type UserInputRequest struct {
	Question      string
	Choices       []string
	AllowFreeform *bool

	// RequestID is the runtime request ID of the pending `user_input.requested`
	// event. Pass it as RequestID to the session's RPC.UI.HandlePendingUserInput
	// (or the trusted handleHumanUserInput path) to correlate an out-of-band
	// answer. It is empty when the runtime predates this field.
	RequestID string
}

UserInputRequest represents a request for user input from the agent

type UserInputRequestedData

type UserInputRequestedData = rpc.UserInputRequestedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UserInputResponse

type UserInputResponse struct {
	Answer      string
	WasFreeform bool
}

UserInputResponse represents the user's response to an input request

type UserMessageAgentMode

type UserMessageAgentMode = rpc.UserMessageAgentMode

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UserMessageData

type UserMessageData = rpc.UserMessageData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UserMessageDelivery

type UserMessageDelivery = rpc.UserMessageDelivery

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UserPromptSubmittedHandler

type UserPromptSubmittedHandler func(input UserPromptSubmittedHookInput, invocation HookInvocation) (*UserPromptSubmittedHookOutput, error)

UserPromptSubmittedHandler handles user-prompt-submitted hook invocations

type UserPromptSubmittedHookInput

type UserPromptSubmittedHookInput struct {
	Traceparent      string    `json:"traceparent,omitempty"`
	Tracestate       string    `json:"tracestate,omitempty"`
	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 (UserPromptSubmittedHookInput) MarshalJSON

func (h UserPromptSubmittedHookInput) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.

func (*UserPromptSubmittedHookInput) UnmarshalJSON

func (h *UserPromptSubmittedHookInput) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.

type UserPromptSubmittedHookOutput

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

type UserPromptTransformedHandler func(input UserPromptTransformedHookInput, invocation HookInvocation) (*UserPromptTransformedHookOutput, error)

UserPromptTransformedHandler handles user-prompt-transformed hook invocations.

type UserPromptTransformedHookInput

type UserPromptTransformedHookInput struct {
	Traceparent       string    `json:"traceparent,omitempty"`
	Tracestate        string    `json:"tracestate,omitempty"`
	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 (UserPromptTransformedHookInput) MarshalJSON

func (h UserPromptTransformedHookInput) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler, emitting Timestamp as Unix milliseconds.

func (*UserPromptTransformedHookInput) UnmarshalJSON

func (h *UserPromptTransformedHookInput) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler, parsing Timestamp from Unix milliseconds.

type UserPromptTransformedHookOutput

type UserPromptTransformedHookOutput struct {
	ModifiedTransformedPrompt *string `json:"modifiedTransformedPrompt,omitempty"`
}

UserPromptTransformedHookOutput is the output for a user-prompt-transformed hook.

type UserToolSessionApproval

type UserToolSessionApproval = rpc.UserToolSessionApproval

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UserToolSessionApprovalCommands

type UserToolSessionApprovalCommands = rpc.UserToolSessionApprovalCommands

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UserToolSessionApprovalCustomTool

type UserToolSessionApprovalCustomTool = rpc.UserToolSessionApprovalCustomTool

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UserToolSessionApprovalExtensionEnvAccess

type UserToolSessionApprovalExtensionEnvAccess = rpc.UserToolSessionApprovalExtensionEnvAccess

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UserToolSessionApprovalExtensionManagement

type UserToolSessionApprovalExtensionManagement = rpc.UserToolSessionApprovalExtensionManagement

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UserToolSessionApprovalExtensionPermissionAccess

type UserToolSessionApprovalExtensionPermissionAccess = rpc.UserToolSessionApprovalExtensionPermissionAccess

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UserToolSessionApprovalKind

type UserToolSessionApprovalKind = rpc.UserToolSessionApprovalKind

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UserToolSessionApprovalMCP

type UserToolSessionApprovalMCP = rpc.UserToolSessionApprovalMCP

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UserToolSessionApprovalMemory

type UserToolSessionApprovalMemory = rpc.UserToolSessionApprovalMemory

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UserToolSessionApprovalRead

type UserToolSessionApprovalRead = rpc.UserToolSessionApprovalRead

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UserToolSessionApprovalWorkflow

type UserToolSessionApprovalWorkflow = rpc.UserToolSessionApprovalWorkflow

Session-event types are generated in the rpc package and aliased here for source compatibility.

type UserToolSessionApprovalWrite

type UserToolSessionApprovalWrite = rpc.UserToolSessionApprovalWrite

Session-event types are generated in the rpc package and aliased here for source compatibility.

type Verbosity

type Verbosity = rpc.Verbosity

Session-event types are generated in the rpc package and aliased here for source compatibility.

type WebSocketResponseWriter

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

type WorkflowPermissionOperation = rpc.WorkflowPermissionOperation

Session-event types are generated in the rpc package and aliased here for source compatibility.

type WorkflowPermissionPhase

type WorkflowPermissionPhase = rpc.WorkflowPermissionPhase

Session-event types are generated in the rpc package and aliased here for source compatibility.

type WorkflowRunSettledData

type WorkflowRunSettledData = rpc.WorkflowRunSettledData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type WorkflowRunSettledStatus

type WorkflowRunSettledStatus = rpc.WorkflowRunSettledStatus

Session-event types are generated in the rpc package and aliased here for source compatibility.

type WorkflowRunStartedData

type WorkflowRunStartedData = rpc.WorkflowRunStartedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type WorkflowRunUpdatedData

type WorkflowRunUpdatedData = rpc.WorkflowRunUpdatedData

Session-event types are generated in the rpc package and aliased here for source compatibility.

type WorkingDirectoryContext

type WorkingDirectoryContext = rpc.WorkingDirectoryContext

Session-event types are generated in the rpc package and aliased here for source compatibility.

type WorkingDirectoryContextHostType

type WorkingDirectoryContextHostType = rpc.WorkingDirectoryContextHostType

Session-event types are generated in the rpc package and aliased here for source compatibility.

type WorkingDirectoryTrust

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

type WorkspaceFileChangedOperation = rpc.WorkspaceFileChangedOperation

Session-event types are generated in the rpc package and aliased here for source compatibility.

Directories

Path Synopsis
cmd
bundler command
Bundler downloads Copilot CLI binaries and packages them as a binary file, along with a Go source file that embeds the binary and metadata.
Bundler downloads Copilot CLI binaries and packages them as a binary file, along with a Go source file that embeds the binary and metadata.
internal
ffihost
Package ffihost hosts the Copilot runtime in-process by loading its native library and driving JSON-RPC over the runtime's C ABI.
Package ffihost hosts the Copilot runtime in-process by loading its native library and driving JSON-RPC over the runtime's C ABI.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL