Skip to content

Latest commit

 

History

History
1125 lines (852 loc) · 57.7 KB

streaming-events.md

File metadata and controls

1125 lines (852 loc) · 57.7 KB

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
Loading
Concept Description
Ephemeral event Transient; streamed in real time but not persisted to the session log. Not replayed on session resume.
Persisted event Saved to the session event log on disk. Replayed when resuming a session.
Delta event An ephemeral streaming chunk (text or reasoning). Accumulate deltas to build the complete content.
parentId chain Each 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:

Field Type Description
id string (UUID v4) Unique event identifier
timestamp string (ISO 8601) When the event was created
parentId string | null ID of the most recent persisted event when this event was emitted; null if there was none yet
agentId string? Sub-agent instance ID for sub-agent-originated events; absent for root/main agent and session-level events
occurredAt string? (ISO 8601) When the event happened, on a copy recorded later, such as a sub-agent's event forwarded to its parent; timestamp is then when the copy was recorded
ephemeral boolean? true for transient events; absent or false for persisted events
type string Event type discriminator (see tables below)
data object Event-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 "@microsoft/copilot-sdk";

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 Field Type Required Description
turnId string ✅ Turn identifier (typically a stringified turn number)
interactionId string 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
model string Model identifier used for this turn, when known
parentToolCallId string Parent task tool call ID when this turn belongs to a sub-agent
toolTurnBudget ToolTurnBudget Internal replay metadata for the active request's logical model-turn limit and usage

assistant.intent

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

Data Field Type Required Description
intent string ✅ Human-readable intent (e.g., "Exploring codebase")

assistant.reasoning

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

Data Field Type Required Description
reasoningId string ✅ Unique identifier for this reasoning block
content string ✅ The complete extended thinking text

assistant.reasoning_delta

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

Data Field Type Required Description
reasoningId string ✅ Matches the corresponding assistant.reasoning event
deltaContent string ✅ Text chunk to append to reasoning content
fusion FusionAttribution Experimental. HydraFusion phase attribution; present without a commitId while a staged phase streams provisional reasoning that may still be discarded. Its turnId names the phase's turn, matching the turnId of the completed assistant.reasoning

assistant.message

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

Data Field Type Required Description
messageId string ✅ Unique identifier for this message
content string ✅ The assistant's text response
toolRequests ToolRequest[] Tool calls the assistant wants to make (see below)
reasoningOpaque string Encrypted extended thinking (Anthropic models); session-bound
reasoningText string Readable reasoning text from extended thinking
encryptedContent string Deprecated. Older events can contain this field; new events omit it
reasoningBlocks AssistantMessageReasoningBlocks Experimental. For provider: "openai-responses", reasoning items in blocks can contain encrypted_content
phase string Generation phase (e.g., "thinking" vs "response")
outputTokens number Output tokens this message adds to replayed context, for token accounting. Use assistant.usage for billed usage
interactionId string 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:

Field Type Required Description
toolCallId string ✅ Unique ID for this tool call
name string ✅ Tool name (e.g., "bash", "edit", "grep")
arguments object 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 Field Type Required Description
messageId string ✅ Matches the corresponding assistant.message event
deltaContent string ✅ Text chunk to append to the message
fusion FusionAttribution Experimental. HydraFusion phase attribution; present without a commitId while a staged phase streams provisional text that may still be discarded. Its turnId names the phase's turn, matching the turnId of the completed assistant.message

assistant.turn_end

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

Data Field Type Required Description
turnId string ✅ Matches the corresponding assistant.turn_start event
model string Model identifier used for this turn, when known
parentToolCallId string 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 Field Type Required Description
model string ✅ Model identifier (e.g., "claude-sonnet-5")
inputTokens number Total input tokens for this call, including cacheReadTokens and cacheWriteTokens
outputTokens number Output tokens produced
reasoningTokens number Output tokens used for reasoning/chain-of-thought (subset of outputTokens)
cacheReadTokens number Tokens read from prompt cache (subset of inputTokens)
cacheWriteTokens number Tokens written to prompt cache (subset of inputTokens)
cacheExpiresAt string ISO 8601 timestamp when the prompt cache for this model call expires
contentFilterTriggered boolean Whether the response was blocked or truncated by content filtering (finish_reason === 'content_filter')
finishReason string Model finish reason (e.g., "stop", "length", "tool_calls", "content_filter")
cost number Model multiplier cost for billing
duration number API call duration in milliseconds
timeToFirstTokenMs number Time from request dispatch to first token received (streaming latency)
interTokenLatencyMs number Average latency between consecutive tokens (streaming throughput)
reasoningEffort string Reasoning effort level used for this call (e.g., "low", "medium", "high")
initiator string 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")
apiCallId string Completion ID from the provider (e.g., chatcmpl-abc123)
serviceRequestId string 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
providerCallId string GitHub request tracing ID (x-github-request-id)
quotaSnapshots Record<string, QuotaSnapshot> Per-quota resource usage, keyed by quota identifier
copilotUsage CopilotUsage 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 Field Type Required Description
totalResponseSizeBytes number ✅ 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 Field Type Required Description
toolCallId string ✅ Unique identifier for this tool call
toolName string ✅ Name of the tool (e.g., "bash", "edit", "grep")
arguments object Parsed arguments passed to the tool
mcpServerName string Configured MCP server key
mcpServerDisplayName string Explicit display label; otherwise display mcpServerName
mcpToolName string 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 Field Type Required Description
toolCallId string ✅ Identifies the originating tool call
text string ✅ 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
sequence number ✅ 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 Field Type Required Description
toolCallId string ✅ Matches the corresponding tool.execution_start
progressMessage string ✅ Progress status message

tool.execution_complete

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

Data Field Type Required Description
toolCallId string ✅ Matches the corresponding tool.execution_start
success boolean ✅ Whether execution succeeded
model string Model that generated this tool call
interactionId string CAPI interaction ID
isUserRequested boolean true when the user explicitly requested this tool call
result Result 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
toolTelemetry object Tool-specific telemetry (e.g., CodeQL check counts)

Result fields:

Field Type Required Description
content string ✅ Concise result sent to the LLM (may be truncated for token efficiency)
detailedContent string Full result for display, preserving complete content like diffs
contents ContentBlock[] 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 Field Type Required Description
toolCallId string ✅ Unique identifier for this tool call
toolName string ✅ Name of the tool the user wants to invoke
arguments object 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 Field Type Required Description
aborted boolean 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 Field Type Required Description
errorType string ✅ Error category (e.g., "authentication", "quota", "rate_limit")
errorCode string Fine-grained classification, an extensible string (e.g., "no_account" when the session has no account to send with, "rate_limited")
message string ✅ Human-readable error message
remediation string Action the user must take to recover, when the runtime knows one (e.g., "sign_in")
stack string Error stack trace
statusCode number HTTP status code from the upstream request
providerCallId string 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 Field Type Required Description
success boolean ✅ Whether compaction succeeded
error string Error message if compaction failed
preCompactionTokens number Tokens before compaction
postCompactionTokens number Tokens after compaction
preCompactionMessagesLength number Message count before compaction
messagesRemoved number Messages removed
tokensRemoved number Tokens removed
summaryContent string LLM-generated summary of compacted history
checkpointNumber number Checkpoint snapshot number created for recovery
checkpointPath string File path where the checkpoint was stored
compactionTokensUsed { input, output, cachedInput } Token usage for the compaction LLM call
requestId string GitHub request tracing ID for the compaction call

session.title_changed

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

Data Field Type Required Description
title string ✅ New session title

session.context_changed

The session's working directory or repository context changed.

Data Field Type Required Description
cwd string ✅ Current working directory
gitRoot string Git repository root
repository string Repository in "owner/name" format
branch string Current git branch

session.usage_info

Ephemeral. Context window utilization snapshot.

Data Field Type Required Description
tokenLimit number ✅ Maximum tokens for the model's context window
currentTokens number ✅ Current tokens in the context window
messagesLength number ✅ Current message count in the conversation
systemTokens number Tokens used by system messages
conversationTokens number Tokens used by non-system messages (user, assistant, tool)
toolDefinitionsTokens number Tokens used by tool definitions
isInitial boolean 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 Field Type Required Description
sessionLimits SessionLimitsConfig | null ✅ Current session limits, or null when no limits are active
sessionLimits.maxAiCredits number 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 Field Type Required Description
totalNanoAiu number ✅ Session-wide accumulated nano-AI units cost at checkpoint time
totalPremiumRequests number Total number of premium API requests used at checkpoint time

session.task_complete

The agent has completed its assigned task.

Data Field Type Required Description
summary string Summary of the completed task

session.shutdown

The session has ended.

Data Field Type Required Description
shutdownType "routine" | "error" ✅ Normal shutdown or crash
errorReason string Error description when shutdownType is "error"
totalPremiumRequests number Total premium API requests used
totalApiDurationMs number ✅ Cumulative API call time in milliseconds
sessionStartTime number ✅ Unix timestamp (ms) when the session started
codeChanges { linesAdded, linesRemoved, filesModified } ✅ Aggregate code change metrics
modelMetrics Record<string, ModelMetric> ✅ Per-model usage breakdown
currentModel string Model selected at shutdown time

session.mcp_servers_loaded

Ephemeral. A snapshot of the MCP servers visible to the session, emitted when they finish loading or reloading: during local turn preparation, after a plugin change, or after an MCP configuration refresh. It carries no message or turn ID. Servers that policy filters out are left out, except managed servers, which stay listed with status: "stopped". See Events around a sent message.

Data Field Type Required Description
servers McpServersLoadedServer[] ✅ One entry per visible server: name, status, source?, displayName?, error?, serverMetadata?

session.mcp_server_status_changed

Ephemeral. One MCP server's connection status changed. It can arrive at any time, independent of a send.

Data Field Type Required Description
serverName string ✅ Name of the server whose status changed
status McpServerStatus ✅ "connected", "failed", "needs-auth", "pending", "disabled", "stopped" or "not_configured"
error string Error message when the server entered a failed state

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 Field Type Required Description
requestId string ✅ Pass this as the requestId of the session.permissions.handlePendingPermissionRequest RPC to respond, unless resolvedByHook is true
permissionRequest PermissionRequest ✅ Details of the permission being requested
resolvedByHook boolean When true, the request is already decided and needs no prompt or response

The permissionRequest is a discriminated union on kind:

kind Key Fields Description
"shell" fullCommandText, intention, commands[], possiblePaths[] Execute a shell command
"write" fileName, diff, intention, newFileContents?, fileEdits? Write/modify a file
"read" path, intention Read a file or directory
"mcp" serverName, toolName, toolTitle, args?, readOnly Call an MCP tool
"url" url, intention Fetch a URL
"memory" subject, fact, citations Store 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 Field Type Required Description
requestId string ✅ Matches the corresponding permission.requested
result.kind string ✅ 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"
decisionSource string 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 Field Type Required Description
requestId string ✅ Pass this as the requestId of the session.ui.handlePendingUserInput RPC to respond
question string ✅ The question to present to the user
choices string[] Predefined choices for the user
allowFreeform boolean Whether free-form text input is allowed
toolCallId string The tool call that asked the question, for correlating the request with it
imageAttachmentConstraints object Advertises image answers with allowedMimeTypes, maxCount, and maxBytesPerImage; absent means images are unsupported

user_input.completed

Ephemeral. A user input request was resolved.

Data Field Type Required Description
requestId string ✅ Matches the corresponding user_input.requested
answer string The user's answer
wasFreeform boolean Whether the answer was typed as free-form text rather than selected from choices
attachments object[] Optional images with type: "image", padded base64 data, mimeType, and optional displayName and description; image-only answers use answer: "" and wasFreeform: true

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 Field Type Required Description
requestId string ✅ Pass this as the requestId of the session.ui.handlePendingElicitation RPC to respond
message string ✅ 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)
url string URL to open in the user's browser (url mode only)
elicitationSource string The MCP server that initiated the request; absent when the agent initiated it
elicitationSourceDisplayName string Display label for a connector-owned MCP server; elicitationSource remains its identity
toolCallId string The tool call that triggered the request, for correlating the request with it
_meta Record<string, JsonValue> Optional extension metadata; only built-in ask_user advertises image constraints and eligible field names under github.com/copilot/ask-user-images version 1. Images also require a supported local SDK transport; this is not an MCP image-response standard

elicitation.completed

Ephemeral. An elicitation request was resolved.

Data Field Type Required Description
requestId string ✅ Matches the corresponding elicitation.requested
action "accept" | "decline" | "cancel" The user's choice: submitted the form, explicitly refused, or dismissed
content Record<string, JsonValue> The submitted form values when action is "accept"; keys match the requestedSchema fields
_meta Record<string, JsonValue> Optional extension metadata; negotiated built-in image answers retain per-field attachment descriptors without inline bytes. Original images remain in canonical tool results

Sub-agent and skill events

subagent.started

A custom agent was invoked as a sub-agent.

Data Field Type Required Description
toolCallId string ✅ Parent tool call that spawned this sub-agent
agentName string ✅ Internal name of the sub-agent
agentDisplayName string ✅ Human-readable display name
agentDescription string ✅ Description of what the sub-agent does
model string Model the sub-agent will run with, when known at start

subagent.completed

A sub-agent finished successfully.

Data Field Type Required Description
toolCallId string ✅ Matches the corresponding subagent.started
agentName string ✅ Internal name
agentDisplayName string ✅ Display name
model string Model used by the sub-agent
durationMs number Wall-clock execution duration in milliseconds
totalTokens number Total input and output tokens consumed
totalToolCalls number Total tool calls made

subagent.failed

A sub-agent encountered an error.

Data Field Type Required Description
toolCallId string ✅ Matches the corresponding subagent.started
agentName string ✅ Internal name
agentDisplayName string ✅ Display name
error string ✅ Error message
model string Model selected for the sub-agent, when known
durationMs number Wall-clock execution duration in milliseconds
totalTokens number Total input and output tokens consumed before failure
totalToolCalls number Total tool calls made before failure

subagent.selected

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

Data Field Type Required Description
agentName string ✅ Internal name of the selected agent
agentDisplayName string ✅ Display name
tools string[] | 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 Field Type Required Description
name string ✅ Skill name
path string ✅ File path to the SKILL.md definition
content string ✅ Full skill content injected into the conversation
allowedTools string[] 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.
pluginName string Plugin the skill originated from
pluginVersion string Plugin version

Other events

abort

The current turn was aborted.

Data Field Type Required Description
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 Field Type Required Description
content string ✅ The user's message text
transformedContent string Transformed version after preprocessing
attachments Attachment[] File, directory, selection, blob, or GitHub reference attachments
source string Message source identifier
agentMode string Agent mode: "interactive", "plan", "autopilot", or "shell"
interactionId string CAPI interaction ID

pending_messages.modified

Ephemeral. The session's pending message queue changed: a message was queued, taken off the queue to run, or removed. Data payload is empty ({}); call session.rpc.queue.pendingItems() (experimental) to read the queue.

system.message

A system or developer prompt was injected into the conversation.

Data Field Type Required Description
content string ✅ The prompt text
role "system" | "developer" ✅ Message role
name string 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
interactionId string 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 Field Type Required Description
requestId string ✅ Pass this as the requestId of the session.tools.handlePendingToolCall RPC to respond
sessionId string ✅ Session this request belongs to
toolCallId string ✅ Tool call ID for this invocation
toolName string ✅ Name of the external tool
arguments object Arguments for the tool

external_tool.completed

An external tool request was resolved.

Data Field Type Required Description
requestId string ✅ Matches the corresponding external_tool.requested

exit_plan_mode.requested

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

Data Field Type Required Description
requestId string ✅ Pass this as the requestId of the session.ui.handlePendingExitPlanMode RPC to respond
summary string ✅ Summary of the plan
planContent string ✅ 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
model string 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 Field Type Required Description
requestId string ✅ Matches the corresponding exit_plan_mode.requested
approved boolean Whether the user approved the plan
selectedAction "exit_only" | "interactive" | "autopilot" | "autopilot_fleet" Action the user selected
autoApproveEdits boolean Whether edits should be auto-approved without confirmation
feedback string 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 Field Type Required Description
requestId string ✅ Pass this as the requestId of the session.commands.respondToQueuedCommand RPC to respond
command string ✅ The slash command text (e.g., /help, /clear)
scheduled boolean Whether a schedule dispatched this command; absent for ordinary queued commands

command.completed

Ephemeral. A queued command was resolved.

Data Field Type Required Description
requestId string ✅ 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 Field Type Required Description
requestId string ✅ Use this ID when responding to the pending exhausted-limit request
maxAiCredits number ✅ Configured max AI Credits for the current accounting window
usedAiCredits number ✅ AI Credits already consumed in the current accounting window

session_limits_exhausted.completed

Ephemeral. A pending exhausted-limit request was resolved.

Data Field Type Required Description
requestId string ✅ Matches the corresponding session_limits_exhausted.requested event
response.action "add" | "set" | "unset" | "cancel" ✅ Action selected for the exhausted-limit request
response.additionalAiCredits number AI Credits to add to the current max when response.action is "add"
response.maxAiCredits number 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)

Events around a sent message

For a normal local send that starts a turn, user.message arrives before that turn's assistant.turn_start. A steering send (mode: "immediate" while a turn is running) joins the turn already in progress, so its user.message can arrive after that turn's assistant.turn_start.

  • MCP snapshots are optional. When local turn preparation emits session.mcp_servers_loaded, it comes before that turn's user.message. A send may have no snapshot, and a plugin change or MCP configuration refresh can emit one with no send. The event carries no message or turn ID, so don't wait for it or treat it as a sign that tools are ready.
  • MCP status changes are independent of sends. session.mcp_server_status_changed can arrive at any time, including during a turn.
  • pending_messages.modified is a hint to refresh the queue, not a log of transitions. Its payload is empty, and one send can produce more than one.
  • A turn can fail after send() returns. send() can return a message ID before the turn's preparation runs. A later failure surfaces as session.error, possibly with no user.message.

These three events are ephemeral and are not replayed on resume. Where supported, read the current state with session.rpc.mcp.list() and session.rpc.queue.pendingItems() (both experimental) instead of rebuilding it from events. For queueing and steering, see Steering and queueing.

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 Type Ephemeral Category Key Data Fields
assistant.turn_start Assistant turnId, interactionId?
assistant.intent ✅ Assistant intent
assistant.reasoning Assistant reasoningId, content
assistant.reasoning_delta ✅ Assistant reasoningId, deltaContent
assistant.streaming_delta ✅ Assistant totalResponseSizeBytes
assistant.message Assistant messageId, content, toolRequests?, outputTokens?, phase?
assistant.message_delta ✅ Assistant messageId, deltaContent
assistant.turn_end Assistant turnId
assistant.usage ✅ Assistant model, apiEndpoint?, inputTokens?, outputTokens?, cacheReadTokens?, cacheWriteTokens?, cost?, duration?
tool.user_requested Tool toolCallId, toolName, arguments?
tool.execution_start Tool toolCallId, toolName, arguments?, mcpServerName?, mcpServerDisplayName?
tool.shell_output ✅ Tool toolCallId, text, stream?, sequence
tool.execution_progress ✅ Tool toolCallId, progressMessage
tool.execution_complete Tool toolCallId, success, result?, error?
session.idle ✅ Session aborted?, mode?
session.error Session errorType, message, statusCode?
session.compaction_start Session (empty)
session.compaction_complete Session success, preCompactionTokens?, summaryContent?
session.title_changed ✅ Session title
session.context_changed Session cwd, gitRoot?, repository?, branch?
session.usage_info ✅ Session tokenLimit, currentTokens, messagesLength
session.session_limits_changed Session sessionLimits
session.usage_checkpoint Session totalNanoAiu, totalPremiumRequests?
session.task_complete Session summary?
session.shutdown Session shutdownType, codeChanges, modelMetrics
session.mcp_servers_loaded ✅ Session servers
session.mcp_server_status_changed ✅ Session serverName, status, error?
pending_messages.modified ✅ Queue (empty)
permission.requested Permission requestId, permissionRequest
permission.completed Permission requestId, result.kind
user_input.requested ✅ User Input requestId, question, choices?
user_input.completed ✅ User Input requestId, answer?
elicitation.requested ✅ User Input requestId, message, mode?, requestedSchema?, url?
elicitation.completed ✅ User Input requestId, action?, content?
subagent.started Sub-Agent toolCallId, agentName, agentDisplayName, model?
subagent.completed Sub-Agent toolCallId, agentName, agentDisplayName, model?, durationMs?, totalTokens?, totalToolCalls?
subagent.failed Sub-Agent toolCallId, agentName, error, model?, durationMs?, totalTokens?, totalToolCalls?
subagent.selected Sub-Agent agentName, agentDisplayName, tools
subagent.deselected Sub-Agent (empty)
skill.invoked Skill name, path, content, allowedTools?
abort Control reason
user.message User content, attachments?, agentMode?
system.message System content, role
external_tool.requested External Tool requestId, toolName, arguments?
external_tool.completed External Tool requestId
command.queued ✅ Command requestId, command, scheduled?
command.completed ✅ Command requestId
session_limits_exhausted.requested ✅ Session requestId, maxAiCredits, usedAiCredits
session_limits_exhausted.completed ✅ Session requestId, response.action
exit_plan_mode.requested ✅ Plan Mode requestId, summary, planContent, actions
exit_plan_mode.completed ✅ Plan Mode requestId, approved?, selectedAction?