Update .NET Copilot SDK cookbook for current SDK releases (#3548)

* Update .NET Copilot SDK cookbook: fix On<T> breaking change, add in-process runtime, tool search, and message provenance recipes

- Fix breaking change: Session.On is now generic (On<T> where T : SessionEvent).
  Updated all recipes that used the old non-generic session.On(evt => ...) pattern:
  error-handling, pr-visualization, managing-local-files, accessibility-report,
  ralph-loop (both .md and .cs where applicable).
- Add new 'In-Process Runtime' recipe (in-process-runtime.md + recipe/in-process-runtime.cs)
  demonstrating RuntimeConnection.ForInProcess(), live-tested.
- Document tool search / deferred loading (SessionConfig.ToolSearch / ToolSearchConfig)
  in pr-visualization.md, live-tested.
- Document typed message provenance (MessageOptions.Source / MessageSource) in
  error-handling.md, live-tested.
- Fix dotnet/README.md recipe index: it was missing Ralph Loop and Accessibility
  Report entries; also added the new In-Process Runtime entry.
- Add In-Process Runtime entry to the top-level cookbook/copilot-sdk/README.md
  .NET section.
- Update dotnet/recipe/README.md runnable-examples table with the new recipe.

All existing .NET cookbook recipes were rebuilt and rechecked against the current
GitHub Copilot SDK (Copilot CLI 1.0.85); no other breaking changes were found.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Update cookbook model names to current supported models

- Replace stale/nonexistent model IDs (gpt-5, claude-sonnet-4.5,
  claude-opus-4.6, gpt-5.1-codex-mini) with current values from the
  supported AI models list
- Prefer Model = "auto" wherever a specific model isn't load-bearing
  to the recipe's teaching point
- ralph-loop: pin gpt-5.3-codex (current codex-family GA model), since
  a dedicated coding model is a deliberate, documented choice for the
  autonomous loop
- multiple-sessions: reshape the model narrative so it demonstrates a
  real explicit-override use case (A/B testing via claude-sonnet-5)
  instead of two sessions sharing the same hardcoded model

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Use SendAndWaitAsync in in-process runtime recipe

Replace the event-based TaskCompletionSource pattern with SendAndWaitAsync so the example waits for the final assistant response, propagates session errors, and uses the SDK timeout behavior.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Jon Galloway
2026-09-22 00:15:06 +00:00
committed by GitHub
co-authored by Copilot
parent d67204825b
commit a19b3101cc
19 changed files with 255 additions and 38 deletions
+1
View File
@@ -13,6 +13,7 @@ This cookbook collects small, focused recipes showing how to accomplish common t
- [PR Visualization](dotnet/pr-visualization.md): Generate interactive PR age charts using GitHub MCP Server.
- [Persisting Sessions](dotnet/persisting-sessions.md): Save and resume sessions across restarts.
- [Accessibility Report](dotnet/accessibility-report.md): Generate WCAG accessibility reports using the Playwright MCP server.
- [In-Process Runtime](dotnet/in-process-runtime.md): Run the Copilot runtime in-process instead of launching a separate CLI process.
### Node.js / TypeScript
+3
View File
@@ -9,6 +9,9 @@ This folder hosts short, practical recipes for using the GitHub Copilot SDK with
- [Managing Local Files](managing-local-files.md): Organize files by metadata using AI-powered grouping strategies.
- [PR Visualization](pr-visualization.md): Generate interactive PR age charts using GitHub MCP Server.
- [Persisting Sessions](persisting-sessions.md): Save and resume sessions across restarts.
- [Ralph Loop](ralph-loop.md): Run an unattended agentic loop that iterates on a task until it's done.
- [Accessibility Report](accessibility-report.md): Audit a web page for accessibility issues and stream the findings live.
- [In-Process Runtime](in-process-runtime.md): Run the Copilot runtime in-process instead of launching a separate CLI process.
## Contributing
@@ -62,7 +62,7 @@ Console.WriteLine("Please wait...\n");
// Create a session with Playwright MCP server
await using var session = await client.CreateSessionAsync(new SessionConfig
{
Model = "claude-opus-4.6",
Model = "auto",
Streaming = true,
OnPermissionRequest = PermissionHandler.ApproveAll,
McpServers = new Dictionary<string, McpServerConfig>()
@@ -80,7 +80,7 @@ await using var session = await client.CreateSessionAsync(new SessionConfig
// Wait for response using session.idle event
var done = new TaskCompletionSource();
session.On(evt =>
session.On<SessionEvent>(evt =>
{
switch (evt)
{
@@ -226,7 +226,7 @@ This gives the model access to Playwright browser tools like `browser_navigate`,
Unlike `SendAndWaitAsync`, this recipe uses streaming for real-time output:
```csharp
session.On(evt =>
session.On<SessionEvent>(evt =>
{
switch (evt)
{
+53 -6
View File
@@ -24,12 +24,12 @@ try
await client.StartAsync();
var session = await client.CreateSessionAsync(new SessionConfig
{
Model = "gpt-5",
Model = "auto",
OnPermissionRequest = PermissionHandler.ApproveAll
});
var done = new TaskCompletionSource<string>();
session.On(evt =>
session.On<SessionEvent>(evt =>
{
if (evt is AssistantMessageEvent msg)
{
@@ -53,6 +53,13 @@ finally
}
```
> `Session.On` is now generic: `On<T>(Action<T> handler) where T : SessionEvent`. The type
> argument can no longer be inferred from a lambda that only pattern-matches inside the body, so
> calls like `session.On(evt => { if (evt is AssistantMessageEvent msg) ... })` fail to compile
> with `CS0411`. Either specify `On<SessionEvent>` and pattern-match inside (as above), or
> subscribe directly to the concrete event type you care about, e.g.
> `session.On<AssistantMessageEvent>(evt => Console.WriteLine(evt.Data?.Content))`.
## Handling specific error types
```csharp
@@ -79,14 +86,14 @@ catch (Exception ex)
```csharp
var session = await client.CreateSessionAsync(new SessionConfig
{
Model = "gpt-5",
Model = "auto",
OnPermissionRequest = PermissionHandler.ApproveAll
});
try
{
var done = new TaskCompletionSource<string>();
session.On(evt =>
session.On<SessionEvent>(evt =>
{
if (evt is AssistantMessageEvent msg)
{
@@ -113,7 +120,7 @@ catch (OperationCanceledException)
```csharp
var session = await client.CreateSessionAsync(new SessionConfig
{
Model = "gpt-5",
Model = "auto",
OnPermissionRequest = PermissionHandler.ApproveAll
});
@@ -159,7 +166,7 @@ await client.StartAsync();
var session = await client.CreateSessionAsync(new SessionConfig
{
Model = "gpt-5",
Model = "auto",
OnPermissionRequest = PermissionHandler.ApproveAll
});
@@ -168,6 +175,46 @@ var session = await client.CreateSessionAsync(new SessionConfig
// client.StopAsync() is automatically called when exiting scope
```
## Tagging message provenance
Since v1.0.14, `MessageOptions` has a `Source` property so you can tag *why* a message was sent —
useful when errors or unexpected turns show up in transcripts and you need to tell human input
apart from messages an automated system (a webhook handler, a scheduled job, another agent) sent
on the user's behalf.
```csharp
using GitHub.Copilot;
// Ordinary human input (also the default when Source is omitted).
await session.SendAsync(new MessageOptions
{
Prompt = "What changed in the last release?",
Source = MessageSource.User
});
// A message injected by your own system rather than typed by a person,
// e.g. a scheduled health check or automated retry.
await session.SendAsync(new MessageOptions
{
Prompt = "Re-run the failed step and report the result.",
Source = MessageSource.System
});
// A message sent by another agent or automation acting on the user's behalf,
// tagged with a caller-supplied identifier.
await session.SendAsync(new MessageOptions
{
Prompt = "Summarize the open incidents.",
Source = MessageSource.Agent("incident-bot")
});
```
`MessageSource` is a closed record with `User`, `System`, and a `MessageSource.Agent(string id)`
factory (serialized as `"agent-<id>"`). Tagging a source only records provenance on the message —
it does not change how the message is delivered, replace the session's system prompt, or grant
extra permissions. When `Source` is omitted, the field is left unset and the runtime treats the
message as ordinary user input.
## Best practices
Permission handling is opt-in. If a session may need tool, file, or system access, set `OnPermissionRequest` explicitly when creating it.
@@ -0,0 +1,88 @@
# In-Process Runtime
Run the Copilot runtime inside your own process instead of launching a separate Copilot CLI process.
> **Runnable example:** [recipe/in-process-runtime.cs](recipe/in-process-runtime.cs)
>
> ```bash
> dotnet run recipe/in-process-runtime.cs
> ```
## Example scenario
By default, `CopilotClient` launches and manages a separate Copilot CLI child process and talks to
it over stdio or TCP. Some deployments — for example, tightly sandboxed hosts, single-binary
services, or environments where spawning child processes is restricted — need the runtime loaded
directly into the application process instead.
## Using the in-process connection
```csharp
using GitHub.Copilot;
// RuntimeConnection.ForInProcess() is an experimental API (diagnostic GHCP001).
#pragma warning disable GHCP001
var client = new CopilotClient(new CopilotClientOptions
{
Connection = RuntimeConnection.ForInProcess()
});
await client.StartAsync();
var session = await client.CreateSessionAsync(new SessionConfig
{
Model = "auto",
OnPermissionRequest = PermissionHandler.ApproveAll
});
var response = await session.SendAndWaitAsync(
new MessageOptions { Prompt = "Hello from the in-process runtime!" });
Console.WriteLine(response?.Data.Content);
await client.StopAsync();
```
`RuntimeConnection.ForInProcess()` is marked `[Experimental("GHCP001")]`, so any code that calls it
must either suppress the diagnostic with `#pragma warning disable GHCP001` (as above) or opt in at
the project level. Everything past client construction — sessions, streaming events, tools, hooks,
and permissions — behaves the same as with the default CLI-launching connection.
## How it works
Instead of spawning a child process, the SDK loads the native Copilot runtime library directly into
your application and communicates with it over an in-memory connection using the same
`Content-Length`-framed JSON-RPC protocol the CLI transport uses. The runtime can invoke SDK
callbacks from native worker threads; the SDK handles marshalling those calls back onto managed
threads for you.
You can also select the in-process transport without changing application code by setting
`COPILOT_SDK_DEFAULT_CONNECTION=inprocess` before startup — the SDK only falls back to this
environment variable when the client doesn't specify a connection explicitly.
## Limitations
The in-process transport is experimental and comes with a few constraints to be aware of:
- **Shared process state**: every in-process client shares the host process's environment,
current working directory, and native runtime library — there's no per-client working directory
or environment override.
- **Rejected process options**: `CopilotClientOptions.Environment`, telemetry configuration, and
similar options that assume a separate child process are not supported and throw if set.
- **One runtime version per process**: once a native runtime library is loaded, starting another
client with a different runtime library path or version fails. Starting additional clients that
reuse the same already-loaded library is fine.
- **Persistent load**: the native library stays loaded for the lifetime of the process even after
`StopAsync()` gracefully shuts down the client's sessions and connection — don't rely on being
able to unload and swap in a different runtime build later.
## Best practices
1. **Test per platform**: validate startup, model turns, and shutdown on every OS/architecture
combination you deploy, since runtime library support varies.
2. **Prefer the default CLI transport** unless you specifically need to avoid a child process —
it's the most established and isolated deployment path.
3. **Still call `StopAsync()`**: graceful shutdown still closes sessions and the JSON-RPC
connection cleanly, even though the native library itself remains loaded.
4. **Set process-wide values early**: configure environment variables and working directory before
creating the first in-process client, since later clients can't override them per-instance.
@@ -25,14 +25,14 @@ await client.StartAsync();
// Define tools for file operations
var session = await client.CreateSessionAsync(new SessionConfig
{
Model = "gpt-5",
Model = "auto",
OnPermissionRequest = PermissionHandler.ApproveAll
});
// Wait for completion
var done = new TaskCompletionSource();
session.On(evt =>
session.On<SessionEvent>(evt =>
{
switch (evt)
{
@@ -20,20 +20,22 @@ using GitHub.Copilot;
await using var client = new CopilotClient();
await client.StartAsync();
// Create multiple independent sessions
// Create multiple independent sessions. Most sessions should let Copilot pick the
// best model automatically; pin an explicit model only when you have a deliberate
// reason to (e.g. an A/B comparison, as with session3 here).
var session1 = await client.CreateSessionAsync(new SessionConfig
{
Model = "gpt-5",
Model = "auto",
OnPermissionRequest = PermissionHandler.ApproveAll
});
var session2 = await client.CreateSessionAsync(new SessionConfig
{
Model = "gpt-5",
Model = "auto",
OnPermissionRequest = PermissionHandler.ApproveAll
});
var session3 = await client.CreateSessionAsync(new SessionConfig
{
Model = "claude-sonnet-4.5",
Model = "claude-sonnet-5",
OnPermissionRequest = PermissionHandler.ApproveAll
});
@@ -61,7 +63,7 @@ Use custom IDs for easier tracking:
var session = await client.CreateSessionAsync(new SessionConfig
{
SessionId = "user-123-chat",
Model = "gpt-5",
Model = "auto",
OnPermissionRequest = PermissionHandler.ApproveAll
});
@@ -89,4 +91,5 @@ await client.DeleteSessionAsync("user-123-chat");
- **Multi-user applications**: One session per user
- **Multi-task workflows**: Separate sessions for different tasks
- **A/B testing**: Compare responses from different models
- **A/B testing**: Compare responses from different models by pinning an explicit
`Model` per session (as `session3` does above) instead of the default `"auto"`
@@ -25,7 +25,7 @@ await client.StartAsync();
var session = await client.CreateSessionAsync(new SessionConfig
{
SessionId = "user-123-conversation",
Model = "gpt-5",
Model = "auto",
OnPermissionRequest = PermissionHandler.ApproveAll
});
@@ -164,7 +164,7 @@ await client.StartAsync();
var session = await client.CreateSessionAsync(new SessionConfig
{
Model = "gpt-5",
Model = "auto",
OnPermissionRequest = PermissionHandler.ApproveAll,
SystemMessage = new SystemMessageConfig
{
@@ -185,7 +185,7 @@ The current working directory is: {Environment.CurrentDirectory}
});
// Set up event handling
session.On(evt =>
session.On<SessionEvent>(evt =>
{
switch (evt)
{
@@ -256,3 +256,37 @@ while (true)
| Flexibility | Fixed logic | **AI decides best approach** |
| Chart types | What you coded | **Any type Copilot can generate** |
| Data grouping | Hardcoded buckets | **Intelligent grouping** |
## Deferring tools with tool search
The GitHub MCP Server alone exposes dozens of tools, and this recipe also has the file and code
execution tools available — well past the point where stuffing every tool description into the
model's context on every turn helps more than it costs. `SessionConfig.ToolSearch` controls when
the SDK defers less-frequently-needed tools behind a search step instead of listing them all
up front:
```csharp
var session = await client.CreateSessionAsync(new SessionConfig
{
Model = "auto",
OnPermissionRequest = PermissionHandler.ApproveAll,
ToolSearch = new ToolSearchConfig
{
Enabled = true,
DeferThreshold = 20
},
SystemMessage = new SystemMessageConfig { Content = "..." }
});
```
- `Enabled` turns tool search on or off explicitly; leave it `null` to use the runtime default.
- `DeferThreshold` is the tool count above which MCP/external tools are deferred behind a
`tool_search_tool` call instead of being listed directly (the runtime default is 30 when
unset). Lowering it — as above — is useful once a recipe pulls in a large MCP server like the
GitHub MCP Server alongside file and code-execution tools, since it keeps the per-turn tool
list small while still letting Copilot search for the exact tool it needs.
- To customize how the search itself behaves, register your own tool named `"tool_search_tool"`
with `OverridesBuiltInTool = true` to replace the built-in implementation.
This is a per-session setting, not a global one, so you can tune it independently for
tool-heavy recipes like this one versus lighter sessions elsewhere in your app.
+4 -4
View File
@@ -60,13 +60,13 @@ try
var session = await client.CreateSessionAsync(
new SessionConfig
{
Model = "gpt-5.1-codex-mini",
Model = "gpt-5.3-codex",
OnPermissionRequest = PermissionHandler.ApproveAll
});
try
{
var done = new TaskCompletionSource<string>();
session.On(evt =>
session.On<SessionEvent>(evt =>
{
if (evt is AssistantMessageEvent msg)
done.TrySetResult(msg.Data.Content);
@@ -125,7 +125,7 @@ try
var session = await client.CreateSessionAsync(
new SessionConfig
{
Model = "gpt-5.1-codex-mini",
Model = "gpt-5.3-codex",
// Pin the agent to the project directory
WorkingDirectory = Environment.CurrentDirectory,
// Auto-approve tool calls for unattended operation
@@ -134,7 +134,7 @@ try
try
{
var done = new TaskCompletionSource<string>();
session.On(evt =>
session.On<SessionEvent>(evt =>
{
// Log tool usage for visibility
if (evt is ToolExecutionStartEvent toolStart)
@@ -26,6 +26,7 @@ dotnet run <filename>.cs
| Persisting Sessions | `dotnet run persisting-sessions.cs` | Save and resume sessions across restarts |
| Accessibility Report ️ | `dotnet run accessibility-report.cs` | Analyzes web page accessibility |
| Ralph Loop ⚠️ | `dotnet run ralph-loop.cs` | Autonomous development loop |
| In-Process Runtime | `dotnet run in-process-runtime.cs` | Runs the Copilot runtime in-process |
### Examples with Arguments
@@ -31,7 +31,7 @@ Console.WriteLine("Please wait...\n");
// Create a session with Playwright MCP server
await using var session = await client.CreateSessionAsync(new SessionConfig
{
Model = "claude-opus-4.6",
Model = "auto",
Streaming = true,
OnPermissionRequest = PermissionHandler.ApproveAll,
McpServers = new Dictionary<string, McpServerConfig>()
@@ -49,7 +49,7 @@ await using var session = await client.CreateSessionAsync(new SessionConfig
// Wait for response using session.idle event
var done = new TaskCompletionSource();
session.On(evt =>
session.On<SessionEvent>(evt =>
{
switch (evt)
{
@@ -11,12 +11,12 @@ try
await client.StartAsync();
var session = await client.CreateSessionAsync(new SessionConfig
{
Model = "gpt-5",
Model = "auto",
OnPermissionRequest = PermissionHandler.ApproveAll
});
var done = new TaskCompletionSource<string>();
session.On(evt =>
session.On<SessionEvent>(evt =>
{
if (evt is AssistantMessageEvent msg)
{
@@ -0,0 +1,38 @@
#:package GitHub.Copilot.SDK@*
#:property PublishAot=false
// The GitHub.Copilot.SDK package exposes the GitHub.Copilot namespace.
using GitHub.Copilot;
// RuntimeConnection.ForInProcess() is an experimental API (diagnostic GHCP001):
// it loads the native Copilot runtime directly into this process instead of
// launching a separate Copilot CLI process.
#pragma warning disable GHCP001
var client = new CopilotClient(new CopilotClientOptions
{
Connection = RuntimeConnection.ForInProcess()
});
try
{
await client.StartAsync();
var session = await client.CreateSessionAsync(new SessionConfig
{
Model = "auto",
OnPermissionRequest = PermissionHandler.ApproveAll
});
var response = await session.SendAndWaitAsync(
new MessageOptions { Prompt = "Hello from the in-process runtime!" });
Console.WriteLine(response?.Data.Content);
await session.DisposeAsync();
}
finally
{
// Gracefully stop; the native runtime library itself stays loaded for the
// lifetime of the process (see the "Lifecycle behavior" notes in the docs).
await client.StopAsync();
}
@@ -11,14 +11,14 @@ await client.StartAsync();
// Define tools for file operations
var session = await client.CreateSessionAsync(new SessionConfig
{
Model = "gpt-5",
Model = "auto",
OnPermissionRequest = PermissionHandler.ApproveAll
});
// Wait for completion
var done = new TaskCompletionSource();
session.On(evt =>
session.On<SessionEvent>(evt =>
{
switch (evt)
{
@@ -7,20 +7,22 @@ using GitHub.Copilot;
await using var client = new CopilotClient();
await client.StartAsync();
// Create multiple independent sessions
// Create multiple independent sessions. Most sessions should let Copilot pick the
// best model automatically; pin an explicit model only when you have a deliberate
// reason to (e.g. an A/B comparison, as with session3 here).
var session1 = await client.CreateSessionAsync(new SessionConfig
{
Model = "gpt-5",
Model = "auto",
OnPermissionRequest = PermissionHandler.ApproveAll
});
var session2 = await client.CreateSessionAsync(new SessionConfig
{
Model = "gpt-5",
Model = "auto",
OnPermissionRequest = PermissionHandler.ApproveAll
});
var session3 = await client.CreateSessionAsync(new SessionConfig
{
Model = "claude-sonnet-4.5",
Model = "claude-sonnet-5",
OnPermissionRequest = PermissionHandler.ApproveAll
});
@@ -11,7 +11,7 @@ await client.StartAsync();
var session = await client.CreateSessionAsync(new SessionConfig
{
SessionId = "user-123-conversation",
Model = "gpt-5",
Model = "auto",
OnPermissionRequest = PermissionHandler.ApproveAll
});
@@ -132,7 +132,7 @@ await client.StartAsync();
var session = await client.CreateSessionAsync(new SessionConfig
{
Model = "gpt-5",
Model = "auto",
OnPermissionRequest = PermissionHandler.ApproveAll,
SystemMessage = new SystemMessageConfig
{
@@ -45,7 +45,7 @@ try
var session = await client.CreateSessionAsync(
new SessionConfig
{
Model = "gpt-5.1-codex-mini",
Model = "gpt-5.3-codex",
// Pin the agent to the project directory
WorkingDirectory = Environment.CurrentDirectory,
// Auto-approve tool calls for unattended operation
@@ -55,7 +55,7 @@ try
try
{
var done = new TaskCompletionSource<string>();
session.On(evt =>
session.On<SessionEvent>(evt =>
{
// Log tool usage for visibility
if (evt is ToolExecutionStartEvent toolStart)