Liking cljdoc? Tell your friends :D

Streaming session events

Every action the Copilot agent takes—thinking, writing code, running tools—is emitted as a session event you can subscribe to. This guide is a field-level reference for the event types applications most often handle, so you know exactly what data to expect without reading the SDK source. It does not cover every event type: the session event types each SDK generates (for example, the SessionEvent union in Node.js) list every event the runtime can emit.

Overview

When events.streaming is set to true on a session, the SDK emits ephemeral events in real time (deltas, progress updates) alongside persisted events (complete messages, tool results). All events share a common envelope and carry a data payload whose shape depends on the event type.

sequenceDiagram
    participant App as Your App
    participant SDK as SDK Session
    participant Agent as Copilot Agent

    App->>SDK: send({ prompt })
    SDK->>Agent: JSON-RPC

    Agent-->>SDK: assistant.turn_start
    SDK-->>App: event

    loop Streaming response
        Agent-->>SDK: assistant.message_delta (ephemeral)
        SDK-->>App: event
    end

    Agent-->>SDK: assistant.message
    SDK-->>App: event

    loop Tool execution
        Agent-->>SDK: tool.execution_start
        SDK-->>App: event
        Agent-->>SDK: tool.execution_complete
        SDK-->>App: event
    end

    Agent-->>SDK: assistant.turn_end
    SDK-->>App: event

    Agent-->>SDK: session.idle (ephemeral)
    SDK-->>App: event
ConceptDescription
Ephemeral eventTransient; streamed in real time but not persisted to the session log. Not replayed on session resume.
Persisted eventSaved to the session event log on disk. Replayed when resuming a session.
Delta eventAn ephemeral streaming chunk (text or reasoning). Accumulate deltas to build the complete content.
parentId chainEach persisted event's parentId points to the persisted event before it, forming a chain you can walk. An ephemeral event's parentId points to the most recent persisted event, and no event's parentId points to an ephemeral event, so walking the chain visits only persisted events.

Event envelope

Every session event, regardless of type, includes these fields:

FieldTypeDescription
idstring (UUID v4)Unique event identifier
timestampstring (ISO 8601)When the event was created
parentIdstring \| nullID of the most recent persisted event when this event was emitted; null if there was none yet
agentIdstring?Sub-agent instance ID for sub-agent-originated events; absent for root/main agent and session-level events
ephemeralboolean?true for transient events; absent or false for persisted events
typestringEvent type discriminator (see tables below)
dataobjectEvent-specific payload

Subscribing to events

Node.js / TypeScript
// All events
session.on((event) => {
    console.log(event.type, event.data);
});

// Specific event type — data is narrowed automatically
session.on("assistant.message_delta", (event) => {
    process.stdout.write(event.data.deltaContent);
});
Python
from copilot.session import CopilotSession
from copilot.session_events import SessionEventType

def handle(event):
    if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:
        print(event.data.delta_content, end="", flush=True)

def register(session: CopilotSession):
    session.on(handle)
from copilot.session_events import SessionEventType

def handle(event):
    if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA:
        print(event.data.delta_content, end="", flush=True)

session.on(handle)
Go
package main

import (
	"context"
	"fmt"
	copilot "github.com/microsoft/copilot-sdk/go/v2"
	"github.com/microsoft/copilot-sdk/go/v2/rpc"
)

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

	session, _ := client.CreateSession(ctx, &copilot.CreateSessionOptions{
		Model: "auto",
		Events: copilot.SessionEventOptions{
			Streaming: copilot.Bool(true),
		},
		Permissions: copilot.SessionPermissionOptions{
			OnRequest: func(req copilot.PermissionRequest, inv copilot.PermissionInvocation) (rpc.PermissionDecision, error) {
				return &rpc.PermissionDecisionApproveOnce{}, nil
			},
		},
	})

	session.On(func(event copilot.SessionEvent) {
		if d, ok := event.Data.(*copilot.AssistantMessageDeltaData); ok {
			fmt.Print(d.DeltaContent)
		}
	})
	_ = session
}
session.On(func(event copilot.SessionEvent) {
    if d, ok := event.Data.(*copilot.AssistantMessageDeltaData); ok {
        fmt.Print(d.DeltaContent)
    }
})
.NET
session.On<SessionEvent>(evt =>
{
    if (evt is AssistantMessageDeltaEvent delta)
    {
        Console.Write(delta.Data.DeltaContent);
    }
});
Java
import com.microsoft.copilot.*;
import com.microsoft.copilot.generated.*;

public class SubscribingToEventsExample {
    static void subscribe(CopilotSession session) {
        // All events
        session.on(event -> System.out.println(event.getType()));

        // Specific event type — data is narrowed to the matching class
        session.on(AssistantMessageDeltaEvent.class, event ->
            System.out.print(event.getData().deltaContent())
        );
    }
}
// All events
session.on(event -> System.out.println(event.getType()));

// Specific event type — data is narrowed to the matching class
session.on(AssistantMessageDeltaEvent.class, event ->
    System.out.print(event.getData().deltaContent())
);

tip

(Python / Go) These SDKs use separate, per-event data types (for example, AssistantMessageDeltaData), so only the relevant fields exist on each type.

[!TIP] (.NET) The .NET SDK uses separate, strongly-typed data classes per event (e.g., AssistantMessageDeltaData), so only the relevant fields exist on each type.

[!TIP] (TypeScript) The TypeScript SDK uses a discriminated union—when you match on event.type, the data payload is automatically narrowed to the correct shape.

Subscribing before a session starts

A session can emit events before its create or resume call returns. The agent may already be working—especially on resume with continuePendingWork—and ephemeral events such as session.idle are never written to the session log, so getMessages cannot recover them afterwards. A subscription installed after the session handle exists misses that startup window.

tip

(Rust) Client::prepare_session and Client::prepare_resume_session return a PreparedSession that owns the session's event channel before any protocol activity happens. Subscribe first, then call start().

use copilot_sdk::{Client, CreateSessionOptions};

async fn create_without_missing_startup_events(
    client: &Client,
) -> Result<(), copilot_sdk::Error> {
    let prepared = client.prepare_session(
        CreateSessionOptions::default()
            .with_events(|__sdk_group| __sdk_group.with_buffer_capacity(2048)),
    )?;

    // Installed before any wire activity: nothing is dropped for lack of a receiver.
    let mut events = prepared.subscribe();
    tokio::spawn(async move {
        while let Ok(event) = events.recv().await {
            println!("{}", event.event_type);
        }
    });

    let session = prepared.start().await?;
    let _ = session;
    Ok(())
}

prepare_* is synchronous and inert: it validates the buffer capacity, allocates a local channel, and does nothing else. No session is registered and nothing reaches the runtime until start() is first polled. Dropping a prepared session that was never started leaves no state behind and closes its subscriptions; dropping the start() future cancels the in-flight startup and unregisters the session, so a retry with the same session ID succeeds. Cleanup is scoped to the exact registration the abandoned startup owned, so it cannot evict a retry that has already taken over the same session ID.

Startup buffering is worth planning for:

  • The event buffer is finite—512 events unless event_buffer_capacity overrides it. A capacity of 0 is rejected with an invalid-config error rather than clamped.
  • Slow subscribers observe a Lagged error reporting how many events were skipped. They never apply backpressure to the session's event loop.
  • Consumers that need a lossless view of a large startup burst must either configure a capacity that covers it or drain the subscription concurrently with start().

note

For cloud sessions where the server assigns the session ID, the SDK cannot route notifications until the create response arrives and the ID is known. Events emitted before that point are not routable to any session. The guarantee is narrower: routed events are never dropped for lack of an installed receiver. Pin session_id on the config to get routing—and full pre-response coverage—from the first byte.

Render only the parent agent response

Sub-agent events share the parent session stream and include envelope-level agentId. Root/main agent events and session-level events omit agentId, so main-chat renderers can ignore assistant events where agentId is set and route those events to traces or progress UI instead.

TypeScript
import type { CopilotSession } from "copilot-sdk-supercharged";

export function subscribeParentResponse(session: CopilotSession): void {
    session.on("assistant.message_delta", (event) => {
        if (!event.agentId) {
            process.stdout.write(event.data.deltaContent);
        }
    });
}
Python
from copilot import CopilotSession, SessionEvent, SessionEventType
from copilot.session_events import AssistantMessageDeltaData


def subscribe_parent_response(session: CopilotSession) -> None:
    def handle(event: SessionEvent) -> None:
        if event.type == SessionEventType.ASSISTANT_MESSAGE_DELTA and event.agent_id is None:
            data = event.data
            if isinstance(data, AssistantMessageDeltaData):
                print(data.delta_content, end="", flush=True)

    session.on(handle)
Go
package example

import (
	"fmt"

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

func subscribeParentResponse(session *copilot.Session) {
	session.On(func(event copilot.SessionEvent) {
		if event.AgentID != nil {
			return
		}

		if d, ok := event.Data.(*copilot.AssistantMessageDeltaData); ok {
			fmt.Print(d.DeltaContent)
		}
	})
}
.NET
using System;
using Microsoft.Copilot;

static class ParentAgentResponseExample
{
    public static void SubscribeParentResponse(CopilotSession session)
    {
        session.On<AssistantMessageDeltaEvent>(evt =>
        {
            if (evt.AgentId is null)
            {
                Console.Write(evt.Data.DeltaContent);
            }
        });
    }
}
Java
import com.microsoft.copilot.CopilotSession;
import com.microsoft.copilot.generated.AssistantMessageDeltaEvent;

final class ParentAgentResponseExample {
    static void subscribeParentResponse(CopilotSession session) {
        session.on(AssistantMessageDeltaEvent.class, event -> {
            if (event.getAgentId() == null) {
                System.out.print(event.getData().deltaContent());
            }
        });
    }
}
Rust
use copilot_sdk::session::Session;

async fn subscribe_parent_response(session: &Session) {
    let mut events = session.subscribe();

    while let Ok(event) = events.recv().await {
        if event.event_type == "assistant.message_delta" && event.agent_id.is_none() {
            if let Some(delta) = event.data.get("deltaContent").and_then(|v| v.as_str()) {
                print!("{delta}");
            }
        }
    }
}

Assistant events

These events track the agent's response lifecycle—from turn start through streaming chunks to the final message.

assistant.turn_start

Emitted when the agent begins processing a turn.

Data FieldTypeRequiredDescription
turnIdstring✅Turn identifier (typically a stringified turn number)
interactionIdstring CAPI interaction ID for telemetry correlation
agentMode"interactive" \| "plan" \| "autopilot" Agent mode whose tools this turn was offered; absent on historical events and sub-agent turns
modelstring Model identifier used for this turn, when known
parentToolCallIdstring Parent task tool call ID when this turn belongs to a sub-agent

assistant.intent

Ephemeral. Short description of what the agent is currently doing, updated as it works.

Data FieldTypeRequiredDescription
intentstring✅Human-readable intent (e.g., "Exploring codebase")

assistant.reasoning

Complete extended thinking block from the model. Emitted after reasoning is finished.

Data FieldTypeRequiredDescription
reasoningIdstring✅Unique identifier for this reasoning block
contentstring✅The complete extended thinking text

assistant.reasoning_delta

Ephemeral. Incremental chunk of the model's extended thinking, streamed in real time.

Data FieldTypeRequiredDescription
reasoningIdstring✅Matches the corresponding assistant.reasoning event
deltaContentstring✅Text chunk to append to reasoning content
fusionFusionAttribution Experimental. HydraFusion phase attribution; present without a commitId while a staged phase streams provisional reasoning that may still be discarded

assistant.message

The assistant's complete response for this LLM call. May include tool invocation requests.

Data FieldTypeRequiredDescription
messageIdstring✅Unique identifier for this message
contentstring✅The assistant's text response
toolRequestsToolRequest[] Tool calls the assistant wants to make (see below)
reasoningOpaquestring Encrypted extended thinking (Anthropic models); session-bound
reasoningTextstring Readable reasoning text from extended thinking
encryptedContentstring Deprecated. Older events can contain this field; new events omit it
reasoningBlocksAssistantMessageReasoningBlocks Experimental. For provider: "openai-responses", reasoning items in blocks can contain encrypted_content
phasestring Generation phase (e.g., "thinking" vs "response")
outputTokensnumber Output tokens this message adds to replayed context, for token accounting. Use assistant.usage for billed usage
interactionIdstring CAPI interaction ID for telemetry

If your SDK's event decoder does not expose reasoningBlocks, its typed callback cannot read the ciphertext from new events. In .NET, explicitly referencing AssistantMessageReasoningBlocks raises the MCPSDK001 experimental diagnostic. For readable reasoning, use reasoningText instead.

ToolRequest fields:

FieldTypeRequiredDescription
toolCallIdstring✅Unique ID for this tool call
namestring✅Tool name (e.g., "bash", "edit", "grep")
argumentsobject Parsed arguments for the tool
type"function" \| "custom" Call type; defaults to "function" when absent

assistant.message_delta

Ephemeral. Incremental chunk of the assistant's text response, streamed in real time.

Data FieldTypeRequiredDescription
messageIdstring✅Matches the corresponding assistant.message event
deltaContentstring✅Text chunk to append to the message
fusionFusionAttribution Experimental. HydraFusion phase attribution; present without a commitId while a staged phase streams provisional text that may still be discarded

assistant.turn_end

Emitted when the agent finishes a turn (all tool executions complete, final response delivered).

Data FieldTypeRequiredDescription
turnIdstring✅Matches the corresponding assistant.turn_start event
modelstring Model identifier used for this turn, when known
parentToolCallIdstring Parent task tool call ID when this turn belongs to a sub-agent

assistant.usage

Ephemeral. Token usage and cost information for an individual API call.

Data FieldTypeRequiredDescription
modelstring✅Model identifier (e.g., "claude-sonnet-5")
inputTokensnumber Total input tokens for this call, including cacheReadTokens and cacheWriteTokens
outputTokensnumber Output tokens produced
reasoningTokensnumber Output tokens used for reasoning/chain-of-thought (subset of outputTokens)
cacheReadTokensnumber Tokens read from prompt cache (subset of inputTokens)
cacheWriteTokensnumber Tokens written to prompt cache (subset of inputTokens)
cacheExpiresAtstring ISO 8601 timestamp when the prompt cache for this model call expires
contentFilterTriggeredboolean Whether the response was blocked or truncated by content filtering (finish_reason === 'content_filter')
finishReasonstring Model finish reason (e.g., "stop", "length", "tool_calls", "content_filter")
costnumber Model multiplier cost for billing
durationnumber API call duration in milliseconds
timeToFirstTokenMsnumber Time from request dispatch to first token received (streaming latency)
interTokenLatencyMsnumber Average latency between consecutive tokens (streaming throughput)
reasoningEffortstring Reasoning effort level used for this call (e.g., "low", "medium", "high")
initiatorstring What triggered this call: "user" for a request that carries a user prompt, "agent" for an agent-driven request such as the follow-up after a tool result, or the delegating caller (e.g., "sub-agent", "mcp-sampling")
apiCallIdstring Completion ID from the provider (e.g., chatcmpl-abc123)
serviceRequestIdstring Copilot service request ID (x-copilot-service-request-id) for CAPI log correlation
apiEndpoint"/chat/completions" \| "/v1/messages" \| "/responses" \| "ws:/responses" \| "/interactions" API endpoint used for the model call; useful for observability and cost attribution. ws:/responses is the websocket variant of the responses API; /interactions is the native Gemini Interactions API, served by CAPI or by a BYOK google provider
providerCallIdstring GitHub request tracing ID (x-github-request-id)
quotaSnapshotsRecord<string, QuotaSnapshot> Per-quota resource usage, keyed by quota identifier
copilotUsageCopilotUsage Itemized token cost breakdown from the API

assistant.streaming_delta

Ephemeral. Low-level network progress indicator—total bytes received from the streaming API response.

Data FieldTypeRequiredDescription
totalResponseSizeBytesnumber✅Cumulative bytes received so far

Tool execution events

These events track the full lifecycle of each tool invocation—from the model requesting a tool call through execution to completion.

tool.execution_start

Emitted for each tool call the model requests, when its response arrives and before the tool runs. Permission is checked after this event, so it doesn't mean the call is approved: a call that needs approval emits permission.requested next, and a denied call ends with a tool.execution_complete whose success is false. This order is the same for built-in, custom and MCP tools. The exception is a tool from an extension that hasn't started yet (request-driven activation). Its tool.execution_start is held while permission is requested. It's emitted after approval, once the extension starts, or just before its tool.execution_complete if the call fails, for example when permission is denied. Don't wait for tool.execution_start before answering a permission.requested. MCP identity: mcpConfigServerName ?? mcpServerName (legacy-compatible).

Data FieldTypeRequiredDescription
toolCallIdstring✅Unique identifier for this tool call
toolNamestring✅Name of the tool (e.g., "bash", "edit", "grep")
argumentsobject Parsed arguments passed to the tool
mcpServerNamestring Configured MCP server key
mcpServerDisplayNamestring Explicit display label; otherwise display mcpServerName
mcpToolNamestring Original tool name on the MCP server

tool.shell_output

Ephemeral. Append-only output from an attached terminal command or a user-requested terminal command. Each event contains newly observed, secret-filtered text, without the separators or markers used to format final tool results for the model.

Data FieldTypeRequiredDescription
toolCallIdstring✅Identifies the originating tool call
textstring✅New text to append, not a replacement snapshot
stream"stdout" \| "stderr" \| "terminal" Output source; omitted means "stdout". "terminal" identifies inherently merged PTY output, whose stdout/stderr origin cannot be recovered
sequencenumber✅Starts at zero and increases across all streams for this tool call, in observed publication order

Accumulate text separately by toolCallId and stream, or join the chunks in sequence order for a combined display. A sequence number identifies duplicates and missing chunks; it does not establish exact ordering between independent operating-system writes. A late subscriber can receive a first sequence greater than zero.

These events are live-only: they are not persisted or replayed after resume. Final tool.execution_complete results, model-facing formatting, and detached command capture are unchanged. Text can contain terminal control sequences; renderers must apply their normal terminal-text handling.

An attached terminal command can keep running after tool.execution_complete when it runs asynchronously or continues beyond initial_wait. Output received while it continues uses the original toolCallId and continues the same sequence, rather than restarting at zero. Consumers that display only active calls must ignore chunks received after completion instead of recreating completed-call state.

Secret filtering operates on each decoded chunk. The runtime does not artificially split lines, but operating-system reads can divide a line or secret across chunks; cross-chunk secret reconstruction is not provided.

tool.execution_progress

Ephemeral. Human-readable progress status from a running tool (e.g., MCP server progress notifications).

Data FieldTypeRequiredDescription
toolCallIdstring✅Matches the corresponding tool.execution_start
progressMessagestring✅Progress status message

tool.execution_complete

Emitted when a tool finishes executing—successfully or with an error.

Data FieldTypeRequiredDescription
toolCallIdstring✅Matches the corresponding tool.execution_start
successboolean✅Whether execution succeeded
modelstring Model that generated this tool call
interactionIdstring CAPI interaction ID
isUserRequestedboolean true when the user explicitly requested this tool call
resultResult Present on success. On failure, present when the tool returned content with its error, or when the text sent to the LLM differs from error.message; content is then that text
error{ message, code? } Present on failure
toolTelemetryobject Tool-specific telemetry (e.g., CodeQL check counts)

Result fields:

FieldTypeRequiredDescription
contentstring✅Concise result sent to the LLM (may be truncated for token efficiency)
detailedContentstring Full result for display, preserving complete content like diffs
contentsContentBlock[] Structured content blocks (text, terminal, image, audio, resource)

tool.user_requested

Emitted when the user explicitly requests a tool invocation (rather than the model choosing to call one).

Data FieldTypeRequiredDescription
toolCallIdstring✅Unique identifier for this tool call
toolNamestring✅Name of the tool the user wants to invoke
argumentsobject Arguments for the invocation

Session lifecycle events

session.idle

Ephemeral. The agent has finished all processing and is ready for the next message. This is the signal that a turn is fully complete.

Data FieldTypeRequiredDescription
abortedboolean True when the preceding turn was cancelled via abort signal
mode"interactive" \| "plan" \| "autopilot" Session mode the agent was in when it went idle; absent when the mode is unknown

session.error

An error occurred during session processing.

Data FieldTypeRequiredDescription
errorTypestring✅Error category (e.g., "authentication", "quota", "rate_limit")
errorCodestring Fine-grained classification, an extensible string (e.g., "no_account" when the session has no account to send with, "rate_limited")
messagestring✅Human-readable error message
remediationstring Action the user must take to recover, when the runtime knows one (e.g., "sign_in")
stackstring Error stack trace
statusCodenumber HTTP status code from the upstream request
providerCallIdstring GitHub request tracing ID for server-side log correlation

session.compaction_start

Context window compaction has begun. Data payload is empty ({}).

session.compaction_complete

Context window compaction finished.

Data FieldTypeRequiredDescription
successboolean✅Whether compaction succeeded
errorstring Error message if compaction failed
preCompactionTokensnumber Tokens before compaction
postCompactionTokensnumber Tokens after compaction
preCompactionMessagesLengthnumber Message count before compaction
messagesRemovednumber Messages removed
tokensRemovednumber Tokens removed
summaryContentstring LLM-generated summary of compacted history
checkpointNumbernumber Checkpoint snapshot number created for recovery
checkpointPathstring File path where the checkpoint was stored
compactionTokensUsed{ input, output, cachedInput } Token usage for the compaction LLM call
requestIdstring GitHub request tracing ID for the compaction call

session.title_changed

Ephemeral. The session's auto-generated title was updated.

Data FieldTypeRequiredDescription
titlestring✅New session title

session.context_changed

The session's working directory or repository context changed.

Data FieldTypeRequiredDescription
cwdstring✅Current working directory
gitRootstring Git repository root
repositorystring Repository in "owner/name" format
branchstring Current git branch

session.usage_info

Ephemeral. Context window utilization snapshot.

Data FieldTypeRequiredDescription
tokenLimitnumber✅Maximum tokens for the model's context window
currentTokensnumber✅Current tokens in the context window
messagesLengthnumber✅Current message count in the conversation
systemTokensnumber Tokens used by system messages
conversationTokensnumber Tokens used by non-system messages (user, assistant, tool)
toolDefinitionsTokensnumber Tokens used by tool definitions
isInitialboolean Whether this is the session's first session.usage_info event

session.session_limits_changed

Session limits changed for the current accounting window. A null sessionLimits value means no limits are active.

Data FieldTypeRequiredDescription
sessionLimitsSessionLimitsConfig \| null✅Current session limits, or null when no limits are active
sessionLimits.maxAiCreditsnumber Maximum AI Credits allowed across the session's current accounting window. When setting a limit, the value must be at least 30 and greater than the AI Credits the session has already used

session.usage_checkpoint

Durable aggregate usage checkpoint used to reconstruct accounting when a session is resumed.

Data FieldTypeRequiredDescription
totalNanoAiunumber✅Session-wide accumulated nano-AI units cost at checkpoint time
totalPremiumRequestsnumber Total number of premium API requests used at checkpoint time

session.task_complete

The agent has completed its assigned task.

Data FieldTypeRequiredDescription
summarystring Summary of the completed task

session.shutdown

The session has ended.

Data FieldTypeRequiredDescription
shutdownType"routine" \| "error"✅Normal shutdown or crash
errorReasonstring Error description when shutdownType is "error"
totalPremiumRequestsnumber Total premium API requests used
totalApiDurationMsnumber✅Cumulative API call time in milliseconds
sessionStartTimenumber✅Unix timestamp (ms) when the session started
codeChanges{ linesAdded, linesRemoved, filesModified }✅Aggregate code change metrics
modelMetricsRecord<string, ModelMetric>✅Per-model usage breakdown
currentModelstring Model selected at shutdown time

Permission and user input events

These events are emitted when the agent needs approval or input from the user before continuing.

permission.requested

The agent needs permission to perform an action (run a command, write a file, etc.).

For a tool call, the request is made while the tool executes, so it usually arrives after that call's tool.execution_start. A tool from an extension that hasn't started yet asks for permission before its tool.execution_start (see tool.execution_start). Use permissionRequest.toolCallId to match a request to its call, and don't require a prior start. A call can raise more than one request. A call that an approval rule or the session's mode already allows normally gets no permission.requested. A request the runtime already decided, through a permissionRequest hook or an automatic assisted-mode decision, is still reported as a permission.requested with resolvedByHook: true, followed immediately by its permission.completed. Don't prompt for or respond to it: it isn't pending, and SDK permission handlers aren't called for it.

Data FieldTypeRequiredDescription
requestIdstring✅Pass this as the requestId of the session.permissions.handlePendingPermissionRequest RPC to respond, unless resolvedByHook is true
permissionRequestPermissionRequest✅Details of the permission being requested
resolvedByHookboolean When true, the request is already decided and needs no prompt or response

The permissionRequest is a discriminated union on kind:

kindKey FieldsDescription
"shell"fullCommandText, intention, commands[], possiblePaths[]Execute a shell command
"write"fileName, diff, intention, newFileContents?, fileEdits?Write/modify a file
"read"path, intentionRead a file or directory
"mcp"serverName, toolName, toolTitle, args?, readOnlyCall an MCP tool
"url"url, intentionFetch a URL
"memory"subject, fact, citationsStore a memory
"custom-tool"toolName, toolDescription, args?Call a custom tool

All kind variants also include an optional toolCallId linking back to the tool call that triggered the request.

Write requests can also include fileEdits in both permissionRequest and promptRequest. Each entry contains an optional before and after snapshot, each with an absolute path in the session filesystem namespace and complete UTF-8 content. A missing before means creation; a missing after means deletion. An empty content string represents an empty file, not an unavailable preview. A move can have different paths on its two sides. When a move overwrites an existing destination, separate entries describe the source deletion and destination replacement.

These snapshots describe the planned operation, not a later read of the live filesystem. The runtime omits fileEdits when it cannot provide a complete text preview, including requests made before reading a sandbox-protected file, non-UTF-8 contents, or an unreadable or non-regular move destination, such as a named pipe. Do not infer a deletion from an empty legacy newFileContents value. The existing fields and approval choices remain available to consumers that do not use previews.

permission.completed

A permission request was resolved.

Data FieldTypeRequiredDescription
requestIdstring✅Matches the corresponding permission.requested
result.kindstring✅One of: "approved", "denied-by-rules", "denied-interactively-by-user", "denied-no-approval-rule-and-could-not-request-from-user", "denied-by-content-exclusion-policy"
decisionSourcestring Who decided: "human_response", "assisted_approval", "host_policy" or "unattended_fallback". Sessions recorded by older runtimes may also contain the historical value "authorization_carry_forward", which current runtimes no longer produce. Read this, not result.kind, to tell a person's decision from an automatic one: the Assisted Permissions judge's denials are also saved as "denied-interactively-by-user". Treat an absent value as not a person's decision.

user_input.requested

Ephemeral. The agent is asking the user a question.

Data FieldTypeRequiredDescription
requestIdstring✅Pass this as the requestId of the session.ui.handlePendingUserInput RPC to respond
questionstring✅The question to present to the user
choicesstring[] Predefined choices for the user
allowFreeformboolean Whether free-form text input is allowed
toolCallIdstring The tool call that asked the question, for correlating the request with it

user_input.completed

Ephemeral. A user input request was resolved.

Data FieldTypeRequiredDescription
requestIdstring✅Matches the corresponding user_input.requested
answerstring The user's answer
wasFreeformboolean Whether the answer was typed as free-form text rather than selected from choices

elicitation.requested

Ephemeral. The agent needs input from the user, either as structured form fields (MCP elicitation protocol) or by opening a URL in the user's browser.

Data FieldTypeRequiredDescription
requestIdstring✅Pass this as the requestId of the session.ui.handlePendingElicitation RPC to respond
messagestring✅Description of what information is needed
mode"form" \| "url" Elicitation mode: structured form or browser URL
requestedSchema{ type: "object", properties, required? } JSON Schema describing the form fields (form mode only)
urlstring URL to open in the user's browser (url mode only)
elicitationSourcestring The MCP server that initiated the request; absent when the agent initiated it
elicitationSourceDisplayNamestring Display label for a connector-owned MCP server; elicitationSource remains its identity
toolCallIdstring The tool call that triggered the request, for correlating the request with it

elicitation.completed

Ephemeral. An elicitation request was resolved.

Data FieldTypeRequiredDescription
requestIdstring✅Matches the corresponding elicitation.requested
action"accept" \| "decline" \| "cancel" The user's choice: submitted the form, explicitly refused, or dismissed
contentRecord<string, JsonValue> The submitted form values when action is "accept"; keys match the requestedSchema fields

Sub-agent and skill events

subagent.started

A custom agent was invoked as a sub-agent.

Data FieldTypeRequiredDescription
toolCallIdstring✅Parent tool call that spawned this sub-agent
agentNamestring✅Internal name of the sub-agent
agentDisplayNamestring✅Human-readable display name
agentDescriptionstring✅Description of what the sub-agent does
modelstring Model the sub-agent will run with, when known at start

subagent.completed

A sub-agent finished successfully.

Data FieldTypeRequiredDescription
toolCallIdstring✅Matches the corresponding subagent.started
agentNamestring✅Internal name
agentDisplayNamestring✅Display name
modelstring Model used by the sub-agent
durationMsnumber Wall-clock execution duration in milliseconds
totalTokensnumber Total input and output tokens consumed
totalToolCallsnumber Total tool calls made

subagent.failed

A sub-agent encountered an error.

Data FieldTypeRequiredDescription
toolCallIdstring✅Matches the corresponding subagent.started
agentNamestring✅Internal name
agentDisplayNamestring✅Display name
errorstring✅Error message
modelstring Model selected for the sub-agent, when known
durationMsnumber Wall-clock execution duration in milliseconds
totalTokensnumber Total input and output tokens consumed before failure
totalToolCallsnumber Total tool calls made before failure

subagent.selected

A custom agent was selected (inferred) to handle the current request.

Data FieldTypeRequiredDescription
agentNamestring✅Internal name of the selected agent
agentDisplayNamestring✅Display name
toolsstring[] \| null✅Tool names available to this agent; null for all tools

subagent.deselected

A custom agent was deselected, returning to the default agent. Data payload is empty ({}).

skill.invoked

A skill was activated for the current conversation.

Data FieldTypeRequiredDescription
namestring✅Skill name
pathstring✅File path to the SKILL.md definition
contentstring✅Full skill content injected into the conversation
allowedToolsstring[] Tools listed in the skill's allowed-tools frontmatter. The SDK doesn't approve them automatically; your permission handler still decides. The Copilot CLI auto-approves them while the skill is active.
pluginNamestring Plugin the skill originated from
pluginVersionstring Plugin version

Other events

abort

The current turn was aborted.

Data FieldTypeRequiredDescription
reason"user_initiated" \| "remote_command" \| "user_abort" \| "autopilot_credit_limit"✅Why the turn was aborted

user.message

The user sent a message. Recorded for the session timeline.

Data FieldTypeRequiredDescription
contentstring✅The user's message text
transformedContentstring Transformed version after preprocessing
attachmentsAttachment[] File, directory, selection, blob, or GitHub reference attachments
sourcestring Message source identifier
agentModestring Agent mode: "interactive", "plan", "autopilot", or "shell"
interactionIdstring CAPI interaction ID

system.message

A system or developer prompt was injected into the conversation.

Data FieldTypeRequiredDescription
contentstring✅The prompt text
role"system" \| "developer"✅Message role
namestring Source identifier
metadata{ promptVersion?, variables? } Prompt template metadata
contentBlocks{ content, cacheBreakpoint?, isStatic? }[] Ordered structured blocks corresponding to content, retained to restore the prompt-cache layout
interactionIdstring Interaction identifier of the model run receiving this prompt

external_tool.requested

The agent wants to invoke an external tool (one provided by the SDK consumer).

Data FieldTypeRequiredDescription
requestIdstring✅Pass this as the requestId of the session.tools.handlePendingToolCall RPC to respond
sessionIdstring✅Session this request belongs to
toolCallIdstring✅Tool call ID for this invocation
toolNamestring✅Name of the external tool
argumentsobject Arguments for the tool

external_tool.completed

An external tool request was resolved.

Data FieldTypeRequiredDescription
requestIdstring✅Matches the corresponding external_tool.requested

exit_plan_mode.requested

Ephemeral. The agent has created a plan and wants to exit plan mode.

Data FieldTypeRequiredDescription
requestIdstring✅Pass this as the requestId of the session.ui.handlePendingExitPlanMode RPC to respond
summarystring✅Summary of the plan
planContentstring✅Full plan file content
actions("exit_only" \| "interactive" \| "autopilot" \| "autopilot_fleet")[]✅Available user actions
recommendedAction"exit_only" \| "interactive" \| "autopilot" \| "autopilot_fleet"✅Suggested action to preselect
modelstring Model the session had selected when the plan was authored, when one is known

exit_plan_mode.completed

Ephemeral. An exit plan mode request was resolved.

Data FieldTypeRequiredDescription
requestIdstring✅Matches the corresponding exit_plan_mode.requested
approvedboolean Whether the user approved the plan
selectedAction"exit_only" \| "interactive" \| "autopilot" \| "autopilot_fleet" Action the user selected
autoApproveEditsboolean Whether edits should be auto-approved without confirmation
feedbackstring Free-form feedback from the user if they requested changes to the plan

command.queued

Ephemeral. scheduled: true requires checking scheduling eligibility before execution.

Data FieldTypeRequiredDescription
requestIdstring✅Pass this as the requestId of the session.commands.respondToQueuedCommand RPC to respond
commandstring✅The slash command text (e.g., /help, /clear)
scheduledboolean Whether a schedule dispatched this command; absent for ordinary queued commands

command.completed

Ephemeral. A queued command was resolved.

Data FieldTypeRequiredDescription
requestIdstring✅Matches the corresponding command.queued

session_limits_exhausted.requested

Ephemeral. The session budget is used up, or 10% or less of it remains and the next model call would be the session's final call without tools; the runtime needs a user decision before continuing.

Data FieldTypeRequiredDescription
requestIdstring✅Use this ID when responding to the pending exhausted-limit request
maxAiCreditsnumber✅Configured max AI Credits for the current accounting window
usedAiCreditsnumber✅AI Credits already consumed in the current accounting window

session_limits_exhausted.completed

Ephemeral. A pending exhausted-limit request was resolved.

Data FieldTypeRequiredDescription
requestIdstring✅Matches the corresponding session_limits_exhausted.requested event
response.action"add" \| "set" \| "unset" \| "cancel"✅Action selected for the exhausted-limit request
response.additionalAiCreditsnumber AI Credits to add to the current max when response.action is "add"
response.maxAiCreditsnumber New absolute max AI Credits when response.action is "set"

Quick reference: agentic turn flow

A typical agentic turn emits events in this order:

assistant.turn_start          → Turn begins
├── assistant.intent          → What the agent plans to do (ephemeral)
├── assistant.reasoning_delta → Streaming thinking chunks (ephemeral, repeated)
├── assistant.reasoning       → Complete thinking block
├── assistant.message_delta   → Streaming response chunks (ephemeral, repeated)
├── assistant.message         → Complete response (may include toolRequests)
├── assistant.usage           → Token usage for this API call (ephemeral)
│
├── [If tools were requested:]
│   ├── tool.execution_start  → Tool call announced (not yet approved; held until approval for an unstarted extension's tool)
│   ├── permission.requested  → Needs user approval (when no rule or mode allows it)
│   ├── permission.completed  → Approval result
│   ├── tool.shell_output              → Stream-tagged terminal output (ephemeral, repeated)
│   ├── tool.execution_progress        → Progress updates (ephemeral, repeated)
│   ├── tool.execution_complete        → Tool finished
│   │
│   └── [Agent loops: more reasoning → message → tool calls...]
│
assistant.turn_end            → Turn complete
session.idle                  → Ready for next message (ephemeral)

Documented event types at a glance

This table lists every event type documented on this page with its key data payload fields. Common envelope fields are documented above.

Event TypeEphemeralCategoryKey Data Fields
assistant.turn_start AssistantturnId, interactionId?
assistant.intent✅Assistantintent
assistant.reasoning AssistantreasoningId, content
assistant.reasoning_delta✅AssistantreasoningId, deltaContent
assistant.streaming_delta✅AssistanttotalResponseSizeBytes
assistant.message AssistantmessageId, content, toolRequests?, outputTokens?, phase?
assistant.message_delta✅AssistantmessageId, deltaContent
assistant.turn_end AssistantturnId
assistant.usage✅Assistantmodel, apiEndpoint?, inputTokens?, outputTokens?, cost?, duration?
tool.user_requested TooltoolCallId, toolName, arguments?
tool.execution_start TooltoolCallId, toolName, arguments?, mcpServerName?, mcpServerDisplayName?
tool.shell_output✅TooltoolCallId, text, stream?, sequence
tool.execution_progress✅TooltoolCallId, progressMessage
tool.execution_complete TooltoolCallId, success, result?, error?
session.idle✅Sessionaborted?, mode?
session.error SessionerrorType, message, statusCode?
session.compaction_start Session(empty)
session.compaction_complete Sessionsuccess, preCompactionTokens?, summaryContent?
session.title_changed✅Sessiontitle
session.context_changed Sessioncwd, gitRoot?, repository?, branch?
session.usage_info✅SessiontokenLimit, currentTokens, messagesLength
session.session_limits_changed SessionsessionLimits
session.usage_checkpoint SessiontotalNanoAiu, totalPremiumRequests?
session.task_complete Sessionsummary?
session.shutdown SessionshutdownType, codeChanges, modelMetrics
permission.requested PermissionrequestId, permissionRequest
permission.completed PermissionrequestId, result.kind
user_input.requested✅User InputrequestId, question, choices?
user_input.completed✅User InputrequestId, answer?
elicitation.requested✅User InputrequestId, message, mode?, requestedSchema?, url?
elicitation.completed✅User InputrequestId, action?, content?
subagent.started Sub-AgenttoolCallId, agentName, agentDisplayName, model?
subagent.completed Sub-AgenttoolCallId, agentName, agentDisplayName, model?, durationMs?, totalTokens?, totalToolCalls?
subagent.failed Sub-AgenttoolCallId, agentName, error, model?, durationMs?, totalTokens?, totalToolCalls?
subagent.selected Sub-AgentagentName, agentDisplayName, tools
subagent.deselected Sub-Agent(empty)
skill.invoked Skillname, path, content, allowedTools?
abort Controlreason
user.message Usercontent, attachments?, agentMode?
system.message Systemcontent, role
external_tool.requested External ToolrequestId, toolName, arguments?
external_tool.completed External ToolrequestId
command.queued✅CommandrequestId, command, scheduled?
command.completed✅CommandrequestId
session_limits_exhausted.requested✅SessionrequestId, maxAiCredits, usedAiCredits
session_limits_exhausted.completed✅SessionrequestId, response.action
exit_plan_mode.requested✅Plan ModerequestId, summary, planContent, actions
exit_plan_mode.completed✅Plan ModerequestId, approved?, selectedAction?

Can you improve this documentation? These fine people already did:
copilot-cli-release-app[bot], copilot-sdk-mirror-writer[bot], Steve Sanderson, examon, Rince Yuan, Patrick Nikoletich, Antonio Goncalves, Jeremiah Isaacson, Stephen Toub, Sunbrye Ly, Ed Burns, Jeremy Moseley, Bruno Borges, Tamás Szabó, Logan Rosen & Mackinnon Buck
Edit on GitHub

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
←Move to previous article
→Move to next article
Ctrl+/Jump to the search field
× close