How to Access Previous Copilot Suggestions or Context Using the Copilot SDK

Use the GetEvents method on a session object to retrieve the full chronological event log containing every previous Copilot suggestion, user message, and tool interaction.

The Copilot SDK provides persistent session management that allows developers to access previous Copilot suggestions or context across multiple interactions. According to the github/copilot-sdk source code, every conversation turn is stored as a structured event log within a session, enabling full historical retrieval and context reconstruction through language-specific RPC interfaces.

Understanding Session-Based Persistence

A session represents the fundamental unit of persistence in the Copilot SDK, maintaining a complete record of all interactions between the user and the assistant.

Session as the Persistence Container

In go/session.go, the Session struct owns a persistent event log stored on disk. This log captures every message, suggestion, and tool-related event in chronological order. When you create a session using client.NewSession or attach to an existing one via client.AttachSession, you gain access to this append-only history store. The session ID serves as the unique identifier that allows the SDK to reload stored context even after application restarts.

SessionEvent Types

The atomic unit stored in the history log is the SessionEvent struct, defined in go/types.go. Each event contains a Type field distinguishing between:

  • user.message – Input provided by the user
  • assistant.message – Generated Copilot suggestions
  • tool.execution_start and tool.execution_complete – Tool invocation metadata

The AssistantMessage type contains the actual suggestion content, while the SessionEventType enum provides type-safe filtering constants for Go developers (e.g., copilot.EventAssistantMessage).

Retrieving Previous Suggestions with GetEvents

Access to historical context flows through the GetEvents RPC method, which exposes the complete session transcript.

The GetEvents RPC Method

Located in go/session.go, the GetEvents method accepts a context parameter and returns a slice of SessionEvent ([]SessionEvent) ordered chronologically from the session start to the most recent interaction. This method streams the full event log from disk, making it available for inspection, debugging, or context reconstruction. The implementation handles pagination internally for large histories while maintaining memory efficiency.

Filtering for Assistant Messages

When processing the returned events, filter by type to isolate previous Copilot suggestions:

events, err := sess.GetEvents(context.Background())
if err != nil { log.Fatal(err) }

for _, ev := range events {
    if ev.Type == copilot.EventAssistantMessage {
        content := ev.Data.(copilot.AssistantMessage).Content
        // Process previous suggestion
    }
}

Python and Node.js implementations expose equivalent filtering through string type checks ("assistant.message") or enum comparisons.

Managing Conversation History

Long-running sessions accumulate substantial context, requiring active management to maintain performance and token budgets.

History Operations

The SDK exposes specialized RPCs defined in go/rpc/zsession_events.go for history manipulation:

  • session.history.truncate – Removes events from the beginning of the log up to a specified point
  • session.history.compact – Summarizes older events into a token-efficient representation while preserving recent context
  • session.history.summarizeForHandoff – Generates a condensed summary for transferring context between sessions

These operations maintain data integrity while preventing unbounded growth of the persisted log.

Compaction for Token Efficiency

When approaching context window limits, call the compaction method with a target token budget:

_, err := sess.Compaction(context.Background(), copilot.CompactionRequest{
    MaxTokens: 20000,
})

The compaction routine replaces older event sequences with a <history> placeholder containing a semantic summary, while preserving recent assistant.message events in full resolution. Python developers use session.compact_history(max_tokens=20000) to achieve identical behavior.

Implementation Examples by Language

The following patterns demonstrate how to access previous Copilot suggestions or context across supported languages.

Go

// Initialize or attach to session
sess, err := client.NewSession(context.Background(), "")
if err != nil { log.Fatalf("new session: %v", err) }

// Generate a suggestion
_, err = sess.SendMessage(context.Background(), copilot.UserMessage{
    Content: "Write a Python function that adds two numbers.",
})
if err != nil { log.Fatalf("send message: %v", err) }

// Retrieve full history
events, err := sess.GetEvents(context.Background())
if err != nil { log.Fatalf("get events: %v", err) }

// Extract previous suggestions
for _, ev := range events {
    if ev.Type == copilot.EventAssistantMessage {
        fmt.Printf("💡 Previous suggestion:\n%s\n---\n", 
            ev.Data.(copilot.AssistantMessage).Content)
    }
}

Python

import copilot_sdk

client = copilot_sdk.Client()
session = client.new_session()  # or client.attach_session(session_id)

session.send_message({"role": "user", "content": "Explain quicksort in plain English."})

events = session.get_events()

for ev in events:
    if ev["type"] == "assistant.message":
        print("💡 Previous suggestion:\n", ev["data"]["content"], "\n---")

Node.js TypeScript

import { CopilotClient } from "@modelcontextprotocol/sdk";

async function accessHistory() {
  const client = new CopilotClient();
  const session = await client.newSession();

  await session.sendMessage({ 
    role: "user", 
    content: "Create a README for a Node project." 
  });

  const events = await session.getEvents();
  for (const ev of events) {
    if (ev.type === "assistant.message") {
      console.log("💡 Previous suggestion:\n", ev.data.content);
    }
  }
}

Advanced Context Workflows

Beyond simple retrieval, the SDK supports sophisticated patterns for maintaining context across application lifecycles.

Resuming Existing Sessions

As implemented in go/client.go, the AttachSession(sessionID) method reloads the complete event history from disk storage. When creating a new client instance with an existing session ID, the LLM automatically receives all previous context, enabling coherent multi-turn conversations that persist across process restarts. This resume capability requires no additional configuration; the SDK handles deserialization of the stored event log transparently.

Compacting Large Histories

For production deployments handling extended conversations, implement token-aware compaction:

// Check current history size
events, _ := sess.GetEvents(ctx)
estimatedTokens := estimateTokens(events) // Implementation dependent

if estimatedTokens > 25000 {
    _, err := sess.Compaction(ctx, copilot.CompactionRequest{
        MaxTokens: 15000,
        PreserveRecent: 5, // Keep last 5 events uncompressed
    })
}

This pattern ensures the model receives relevant context without exceeding token limits or incurring unnecessary latency when transmitting history.

Summary

  • Session persistence in go/session.go stores every interaction as a SessionEvent, enabling complete history reconstruction.
  • Retrieve previous suggestions by calling GetEvents and filtering for assistant.message or EventAssistantMessage types.
  • Manage history growth using session.history.compact or session.history.truncate RPCs defined in go/rpc/zsession_events.go.
  • Resume context across application restarts by attaching to existing session IDs via client.AttachSession.
  • Token optimization through compaction preserves semantic context while reducing payload size for subsequent LLM calls.

Frequently Asked Questions

How does the Copilot SDK persist conversation history?

The SDK writes every SessionEvent to a disk-based log associated with a unique session ID. As defined in go/session.go, this append-only storage survives application restarts and is automatically loaded when attaching to an existing session through client.AttachSession.

What is the difference between truncating and compacting session history?

Truncation (session.history.truncate) permanently removes events from the beginning of the log up to a specified index, while compaction (session.history.compact) generates a semantic summary of older events and replaces them with a compressed representation. Compaction preserves information density, whereas truncation reduces storage size by deleting data irreversibly.

Can I access previous suggestions after restarting my application?

Yes. Store the session ID returned by client.NewSession and subsequently call client.AttachSession(sessionID) after restart. The SDK automatically reloads the complete event history from go/client.go, making all previous Copilot suggestions available through GetEvents without re-transmitting prior user messages.

Which event type represents Copilot suggestions in the event log?

According to go/types.go, Copilot suggestions appear as events with Type equal to assistant.message (JSON string) or copilot.EventAssistantMessage (Go constant). The event Data field contains an AssistantMessage struct with the Content field holding the actual suggestion text.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →