Align Copilot SDK documentation with permission handling requirements (#1107)

* Apply permission handler requirements across Copilot SDK docs

Co-authored-by: jamesmontemagno <1676321+jamesmontemagno@users.noreply.github.com>
Agent-Logs-Url: https://github.com/jamesmontemagno/awesome-copilot/sessions/adf27a88-92f8-4ca6-b3fe-1204e3bb9963

* Polish permission update formatting in SDK examples

Co-authored-by: jamesmontemagno <1676321+jamesmontemagno@users.noreply.github.com>
Agent-Logs-Url: https://github.com/jamesmontemagno/awesome-copilot/sessions/adf27a88-92f8-4ca6-b3fe-1204e3bb9963

* Fix review comments on SDK permission handling PR

Address 5 review comments from PR #1103:

1. Fix invalid object literal syntax (stray comma) in resumeSession
   example in copilot-sdk-nodejs.instructions.md

2. Replace unused PermissionHandler import with actual usage in
   cookbook/copilot-sdk/python/recipe/ralph_loop.py (was using
   inline lambda instead)

3. Replace unused approveAll import with actual usage in
   cookbook/copilot-sdk/nodejs/recipe/ralph-loop.ts (was using
   inline handler instead)

4. Add missing PermissionHandler import to 4 Python code snippets
   in skills/copilot-sdk/SKILL.md that reference it without importing

5. Add missing approveAll import to 3 TypeScript code snippets
   in skills/copilot-sdk/SKILL.md that reference it without importing

* Refactor session creation to improve code formatting and consistency across SDK examples

* Fix formatting: split multi-property lines and put closing braces on own lines

Address review comments on PR #1107:
- Split OnPermissionRequest + Model onto separate lines in Go, C#, TypeScript
- Put closing }); on its own line consistently across all examples
- Fix indentation in SKILL.md Quick Start, CLI URL, Error Handling sections
- Fix cookbook Go multiple-sessions and error-handling formatting
- Fix ralph-loop.md TypeScript indentation

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: jamesmontemagno <1676321+jamesmontemagno@users.noreply.github.com>
This commit is contained in:
James Montemagno
2026-03-22 17:11:19 -07:00
committed by GitHub
parent 6d48c08215
commit 33f544c71d
48 changed files with 376 additions and 143 deletions

View File

@@ -46,7 +46,7 @@ await using var client = new CopilotClient();
await client.StartAsync(); await client.StartAsync();
// Resume the previous session // Resume the previous session
var session = await client.ResumeSessionAsync("user-123-conversation"); var session = await client.ResumeSessionAsync("user-123-conversation", new ResumeSessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll });
// Previous context is restored // Previous context is restored
await session.SendAsync(new MessageOptions { Prompt = "What were we discussing?" }); await session.SendAsync(new MessageOptions { Prompt = "What were we discussing?" });

View File

@@ -22,7 +22,7 @@ await session.DisposeAsync();
Console.WriteLine("Session destroyed (state persisted)"); Console.WriteLine("Session destroyed (state persisted)");
// Resume the previous session // Resume the previous session
var resumed = await client.ResumeSessionAsync("user-123-conversation"); var resumed = await client.ResumeSessionAsync("user-123-conversation", new ResumeSessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll });
Console.WriteLine($"Resumed: {resumed.SessionId}"); Console.WriteLine($"Resumed: {resumed.SessionId}");
await resumed.SendAsync(new MessageOptions { Prompt = "What were we discussing?" }); await resumed.SendAsync(new MessageOptions { Prompt = "What were we discussing?" });

View File

@@ -77,6 +77,7 @@ func main() {
streaming := true streaming := true
session, err := client.CreateSession(ctx, &copilot.SessionConfig{ session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "claude-opus-4.6", Model: "claude-opus-4.6",
Streaming: &streaming, Streaming: &streaming,
McpServers: map[string]interface{}{ McpServers: map[string]interface{}{
@@ -214,6 +215,7 @@ The recipe configures a local MCP server that runs alongside the session:
```go ```go
session, err := client.CreateSession(ctx, &copilot.SessionConfig{ session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
McpServers: map[string]interface{}{ McpServers: map[string]interface{}{
"playwright": map[string]interface{}{ "playwright": map[string]interface{}{
"type": "local", "type": "local",

View File

@@ -34,6 +34,7 @@ func main() {
defer client.Stop() defer client.Stop()
session, err := client.CreateSession(ctx, &copilot.SessionConfig{ session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5", Model: "gpt-5",
}) })
if err != nil { if err != nil {
@@ -177,7 +178,10 @@ func doWork() error {
} }
defer client.Stop() defer client.Stop()
session, err := client.CreateSession(ctx, &copilot.SessionConfig{Model: "gpt-5"}) session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
})
if err != nil { if err != nil {
return fmt.Errorf("failed to create session: %w", err) return fmt.Errorf("failed to create session: %w", err)
} }

View File

@@ -38,6 +38,7 @@ func main() {
// Create session // Create session
session, err := client.CreateSession(ctx, &copilot.SessionConfig{ session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5", Model: "gpt-5",
}) })
if err != nil { if err != nil {

View File

@@ -34,19 +34,28 @@ func main() {
defer client.Stop() defer client.Stop()
// Create multiple independent sessions // Create multiple independent sessions
session1, err := client.CreateSession(ctx, &copilot.SessionConfig{Model: "gpt-5"}) session1, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
})
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
defer session1.Destroy() defer session1.Destroy()
session2, err := client.CreateSession(ctx, &copilot.SessionConfig{Model: "gpt-5"}) session2, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
})
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
defer session2.Destroy() defer session2.Destroy()
session3, err := client.CreateSession(ctx, &copilot.SessionConfig{Model: "claude-sonnet-4.5"}) session3, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "claude-sonnet-4.5",
})
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@@ -70,6 +79,7 @@ Use custom IDs for easier tracking:
```go ```go
session, err := client.CreateSession(ctx, &copilot.SessionConfig{ session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
SessionID: "user-123-chat", SessionID: "user-123-chat",
Model: "gpt-5", Model: "gpt-5",
}) })

View File

@@ -32,6 +32,7 @@ func main() {
// Create session with a memorable ID // Create session with a memorable ID
session, _ := client.CreateSession(ctx, &copilot.SessionConfig{ session, _ := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
SessionID: "user-123-conversation", SessionID: "user-123-conversation",
Model: "gpt-5", Model: "gpt-5",
}) })
@@ -55,7 +56,7 @@ client.Start(ctx)
defer client.Stop() defer client.Stop()
// Resume the previous session // Resume the previous session
session, _ := client.ResumeSession(ctx, "user-123-conversation") session, _ := client.ResumeSession(ctx, "user-123-conversation", &copilot.ResumeSessionConfig{OnPermissionRequest: copilot.PermissionHandler.ApproveAll})
// Previous context is restored // Previous context is restored
session.SendAndWait(ctx, copilot.MessageOptions{Prompt: "What were we discussing?"}) session.SendAndWait(ctx, copilot.MessageOptions{Prompt: "What were we discussing?"})

View File

@@ -138,6 +138,7 @@ func main() {
cwd, _ := os.Getwd() cwd, _ := os.Getwd()
session, err := client.CreateSession(ctx, &copilot.SessionConfig{ session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5", Model: "gpt-5",
SystemMessage: &copilot.SystemMessageConfig{ SystemMessage: &copilot.SystemMessageConfig{
Content: fmt.Sprintf(` Content: fmt.Sprintf(`

View File

@@ -70,6 +70,7 @@ func ralphLoop(ctx context.Context, promptFile string, maxIterations int) error
// Fresh session each iteration — context isolation is the point // Fresh session each iteration — context isolation is the point
session, err := client.CreateSession(ctx, &copilot.SessionConfig{ session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5.1-codex-mini", Model: "gpt-5.1-codex-mini",
}) })
if err != nil { if err != nil {

View File

@@ -45,6 +45,7 @@ func main() {
streaming := true streaming := true
session, err := client.CreateSession(ctx, &copilot.SessionConfig{ session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "claude-opus-4.6", Model: "claude-opus-4.6",
Streaming: &streaming, Streaming: &streaming,
McpServers: map[string]interface{}{ McpServers: map[string]interface{}{

View File

@@ -18,6 +18,7 @@ func main() {
defer client.Stop() defer client.Stop()
session, err := client.CreateSession(ctx, &copilot.SessionConfig{ session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5", Model: "gpt-5",
}) })
if err != nil { if err != nil {

View File

@@ -22,6 +22,7 @@ func main() {
// Create session // Create session
session, err := client.CreateSession(ctx, &copilot.SessionConfig{ session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5", Model: "gpt-5",
}) })
if err != nil { if err != nil {

View File

@@ -18,19 +18,28 @@ func main() {
defer client.Stop() defer client.Stop()
// Create multiple independent sessions // Create multiple independent sessions
session1, err := client.CreateSession(ctx, &copilot.SessionConfig{Model: "gpt-5"}) session1, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
})
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
defer session1.Destroy() defer session1.Destroy()
session2, err := client.CreateSession(ctx, &copilot.SessionConfig{Model: "gpt-5"}) session2, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
})
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
defer session2.Destroy() defer session2.Destroy()
session3, err := client.CreateSession(ctx, &copilot.SessionConfig{Model: "claude-sonnet-4.5"}) session3, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "claude-sonnet-4.5",
})
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }

View File

@@ -18,6 +18,7 @@ func main() {
// Create session with a memorable ID // Create session with a memorable ID
session, err := client.CreateSession(ctx, &copilot.SessionConfig{ session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
SessionID: "user-123-conversation", SessionID: "user-123-conversation",
Model: "gpt-5", Model: "gpt-5",
}) })
@@ -36,7 +37,7 @@ func main() {
fmt.Println("Session destroyed (state persisted)") fmt.Println("Session destroyed (state persisted)")
// Resume the previous session // Resume the previous session
resumed, err := client.ResumeSession(ctx, "user-123-conversation") resumed, err := client.ResumeSession(ctx, "user-123-conversation", &copilot.ResumeSessionConfig{OnPermissionRequest: copilot.PermissionHandler.ApproveAll})
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }

View File

@@ -102,6 +102,7 @@ func main() {
cwd, _ := os.Getwd() cwd, _ := os.Getwd()
session, err := client.CreateSession(ctx, &copilot.SessionConfig{ session, err := client.CreateSession(ctx, &copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5", Model: "gpt-5",
SystemMessage: &copilot.SystemMessageConfig{ SystemMessage: &copilot.SystemMessageConfig{
Content: fmt.Sprintf(` Content: fmt.Sprintf(`

View File

@@ -35,7 +35,7 @@ npx tsx accessibility-report.ts
```typescript ```typescript
#!/usr/bin/env npx tsx #!/usr/bin/env npx tsx
import { CopilotClient } from "@github/copilot-sdk"; import { CopilotClient, approveAll } from "@github/copilot-sdk";
import * as readline from "node:readline"; import * as readline from "node:readline";
// ============================================================================ // ============================================================================
@@ -73,6 +73,7 @@ async function main() {
const client = new CopilotClient(); const client = new CopilotClient();
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
model: "claude-opus-4.6", model: "claude-opus-4.6",
streaming: true, streaming: true,
mcpServers: { mcpServers: {
@@ -191,6 +192,7 @@ The recipe configures a local MCP server that runs alongside the session:
```typescript ```typescript
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
mcpServers: { mcpServers: {
playwright: { playwright: {
type: "local", type: "local",

View File

@@ -17,13 +17,16 @@ You need to handle various error conditions like connection failures, timeouts,
## Basic try-catch ## Basic try-catch
```typescript ```typescript
import { CopilotClient } from "@github/copilot-sdk"; import { CopilotClient, approveAll } from "@github/copilot-sdk";
const client = new CopilotClient(); const client = new CopilotClient();
try { try {
await client.start(); await client.start();
const session = await client.createSession({ model: "gpt-5" }); const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5",
});
const response = await session.sendAndWait({ prompt: "Hello!" }); const response = await session.sendAndWait({ prompt: "Hello!" });
console.log(response?.data.content); console.log(response?.data.content);
@@ -55,7 +58,10 @@ try {
## Timeout handling ## Timeout handling
```typescript ```typescript
const session = await client.createSession({ model: "gpt-5" }); const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5",
});
try { try {
// sendAndWait with timeout (in milliseconds) // sendAndWait with timeout (in milliseconds)
@@ -79,7 +85,10 @@ try {
## Aborting a request ## Aborting a request
```typescript ```typescript
const session = await client.createSession({ model: "gpt-5" }); const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5",
});
// Start a request // Start a request
session.send({ prompt: "Write a very long story..." }); session.send({ prompt: "Write a very long story..." });

View File

@@ -17,7 +17,7 @@ You have a folder with many files and want to organize them into subfolders base
## Example code ## Example code
```typescript ```typescript
import { CopilotClient } from "@github/copilot-sdk"; import { CopilotClient, approveAll } from "@github/copilot-sdk";
import * as os from "node:os"; import * as os from "node:os";
import * as path from "node:path"; import * as path from "node:path";
@@ -27,6 +27,7 @@ await client.start();
// Create session // Create session
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5", model: "gpt-5",
}); });

View File

@@ -17,15 +17,24 @@ You need to run multiple conversations in parallel, each with its own context an
## Node.js ## Node.js
```typescript ```typescript
import { CopilotClient } from "@github/copilot-sdk"; import { CopilotClient, approveAll } from "@github/copilot-sdk";
const client = new CopilotClient(); const client = new CopilotClient();
await client.start(); await client.start();
// Create multiple independent sessions // Create multiple independent sessions
const session1 = await client.createSession({ model: "gpt-5" }); const session1 = await client.createSession({
const session2 = await client.createSession({ model: "gpt-5" }); onPermissionRequest: approveAll,
const session3 = await client.createSession({ model: "claude-sonnet-4.5" }); model: "gpt-5",
});
const session2 = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5",
});
const session3 = await client.createSession({
onPermissionRequest: approveAll,
model: "claude-sonnet-4.5",
});
// Each session maintains its own conversation history // Each session maintains its own conversation history
await session1.sendAndWait({ prompt: "You are helping with a Python project" }); await session1.sendAndWait({ prompt: "You are helping with a Python project" });
@@ -50,6 +59,7 @@ Use custom IDs for easier tracking:
```typescript ```typescript
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
sessionId: "user-123-chat", sessionId: "user-123-chat",
model: "gpt-5", model: "gpt-5",
}); });

View File

@@ -17,13 +17,14 @@ You want users to be able to continue a conversation even after closing and reop
### Creating a session with a custom ID ### Creating a session with a custom ID
```typescript ```typescript
import { CopilotClient } from "@github/copilot-sdk"; import { CopilotClient, approveAll } from "@github/copilot-sdk";
const client = new CopilotClient(); const client = new CopilotClient();
await client.start(); await client.start();
// Create session with a memorable ID // Create session with a memorable ID
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
sessionId: "user-123-conversation", sessionId: "user-123-conversation",
model: "gpt-5", model: "gpt-5",
}); });
@@ -45,7 +46,7 @@ const client = new CopilotClient();
await client.start(); await client.start();
// Resume the previous session // Resume the previous session
const session = await client.resumeSession("user-123-conversation"); const session = await client.resumeSession("user-123-conversation", { onPermissionRequest: approveAll });
// Previous context is restored // Previous context is restored
await session.sendAndWait({ prompt: "What were we discussing?" }); await session.sendAndWait({ prompt: "What were we discussing?" });

View File

@@ -42,7 +42,7 @@ npx tsx pr-visualization.ts --repo github/copilot-sdk
import { execSync } from "node:child_process"; import { execSync } from "node:child_process";
import * as readline from "node:readline"; import * as readline from "node:readline";
import { CopilotClient } from "@github/copilot-sdk"; import { CopilotClient, approveAll } from "@github/copilot-sdk";
// ============================================================================ // ============================================================================
// Git & GitHub Detection // Git & GitHub Detection
@@ -138,6 +138,7 @@ async function main() {
const client = new CopilotClient({ logLevel: "error" }); const client = new CopilotClient({ logLevel: "error" });
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5", model: "gpt-5",
systemMessage: { systemMessage: {
content: ` content: `

View File

@@ -43,7 +43,7 @@ The minimal Ralph loop — the SDK equivalent of `while :; do cat PROMPT.md | co
```typescript ```typescript
import { readFile } from "fs/promises"; import { readFile } from "fs/promises";
import { CopilotClient } from "@github/copilot-sdk"; import { CopilotClient, approveAll } from "@github/copilot-sdk";
async function ralphLoop(promptFile: string, maxIterations: number = 50) { async function ralphLoop(promptFile: string, maxIterations: number = 50) {
const client = new CopilotClient(); const client = new CopilotClient();
@@ -56,7 +56,10 @@ async function ralphLoop(promptFile: string, maxIterations: number = 50) {
console.log(`\n=== Iteration ${i}/${maxIterations} ===`); console.log(`\n=== Iteration ${i}/${maxIterations} ===`);
// Fresh session each iteration — context isolation is the point // Fresh session each iteration — context isolation is the point
const session = await client.createSession({ model: "gpt-5.1-codex-mini" }); const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5.1-codex-mini",
});
try { try {
await session.sendAndWait({ prompt }, 600_000); await session.sendAndWait({ prompt }, 600_000);
} finally { } finally {

View File

@@ -1,6 +1,6 @@
#!/usr/bin/env tsx #!/usr/bin/env tsx
import { CopilotClient } from "@github/copilot-sdk"; import { CopilotClient, approveAll } from "@github/copilot-sdk";
import * as readline from "node:readline"; import * as readline from "node:readline";
// ============================================================================ // ============================================================================
@@ -38,6 +38,7 @@ async function main() {
const client = new CopilotClient(); const client = new CopilotClient();
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
model: "claude-opus-4.6", model: "claude-opus-4.6",
streaming: true, streaming: true,
mcpServers: { mcpServers: {

View File

@@ -1,10 +1,13 @@
import { CopilotClient } from "@github/copilot-sdk"; import { CopilotClient, approveAll } from "@github/copilot-sdk";
const client = new CopilotClient(); const client = new CopilotClient();
try { try {
await client.start(); await client.start();
const session = await client.createSession({ model: "gpt-5" }); const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5",
});
const response = await session.sendAndWait({ prompt: "Hello!" }); const response = await session.sendAndWait({ prompt: "Hello!" });
console.log(response?.data.content); console.log(response?.data.content);

View File

@@ -1,4 +1,4 @@
import { CopilotClient } from "@github/copilot-sdk"; import { CopilotClient, approveAll } from "@github/copilot-sdk";
import * as os from "node:os"; import * as os from "node:os";
import * as path from "node:path"; import * as path from "node:path";
@@ -8,6 +8,7 @@ await client.start();
// Create session // Create session
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5", model: "gpt-5",
}); });

View File

@@ -1,12 +1,21 @@
import { CopilotClient } from "@github/copilot-sdk"; import { CopilotClient, approveAll } from "@github/copilot-sdk";
const client = new CopilotClient(); const client = new CopilotClient();
await client.start(); await client.start();
// Create multiple independent sessions // Create multiple independent sessions
const session1 = await client.createSession({ model: "gpt-5" }); const session1 = await client.createSession({
const session2 = await client.createSession({ model: "gpt-5" }); onPermissionRequest: approveAll,
const session3 = await client.createSession({ model: "claude-sonnet-4.5" }); model: "gpt-5",
});
const session2 = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5",
});
const session3 = await client.createSession({
onPermissionRequest: approveAll,
model: "claude-sonnet-4.5",
});
console.log("Created 3 independent sessions"); console.log("Created 3 independent sessions");

View File

@@ -1,10 +1,11 @@
import { CopilotClient } from "@github/copilot-sdk"; import { CopilotClient, approveAll } from "@github/copilot-sdk";
const client = new CopilotClient(); const client = new CopilotClient();
await client.start(); await client.start();
// Create a session with a memorable ID // Create a session with a memorable ID
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
sessionId: "user-123-conversation", sessionId: "user-123-conversation",
model: "gpt-5", model: "gpt-5",
}); });
@@ -17,7 +18,7 @@ await session.destroy();
console.log("Session destroyed (state persisted)"); console.log("Session destroyed (state persisted)");
// Resume the previous session // Resume the previous session
const resumed = await client.resumeSession("user-123-conversation"); const resumed = await client.resumeSession("user-123-conversation", { onPermissionRequest: approveAll });
console.log(`Resumed: ${resumed.sessionId}`); console.log(`Resumed: ${resumed.sessionId}`);
await resumed.sendAndWait({ prompt: "What were we discussing?" }); await resumed.sendAndWait({ prompt: "What were we discussing?" });

View File

@@ -1,6 +1,6 @@
#!/usr/bin/env tsx #!/usr/bin/env tsx
import { CopilotClient } from "@github/copilot-sdk"; import { CopilotClient, approveAll } from "@github/copilot-sdk";
import { execSync } from "node:child_process"; import { execSync } from "node:child_process";
import * as readline from "node:readline"; import * as readline from "node:readline";
@@ -98,6 +98,7 @@ async function main() {
const client = new CopilotClient({ logLevel: "error" }); const client = new CopilotClient({ logLevel: "error" });
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5", model: "gpt-5",
systemMessage: { systemMessage: {
content: ` content: `

View File

@@ -1,5 +1,5 @@
import { readFile } from "fs/promises"; import { readFile } from "fs/promises";
import { CopilotClient } from "@github/copilot-sdk"; import { CopilotClient, approveAll } from "@github/copilot-sdk";
/** /**
* Ralph loop: autonomous AI task loop with fresh context per iteration. * Ralph loop: autonomous AI task loop with fresh context per iteration.
@@ -44,7 +44,7 @@ async function ralphLoop(mode: Mode, maxIterations: number) {
// Pin the agent to the project directory // Pin the agent to the project directory
workingDirectory: process.cwd(), workingDirectory: process.cwd(),
// Auto-approve tool calls for unattended operation // Auto-approve tool calls for unattended operation
onPermissionRequest: async () => ({ allow: true }), onPermissionRequest: approveAll,
}); });
// Log tool usage for visibility // Log tool usage for visibility

View File

@@ -35,8 +35,11 @@ python accessibility_report.py
import asyncio import asyncio
from copilot import ( from copilot import (
CopilotClient, SessionConfig, MessageOptions, CopilotClient,
SessionConfig,
MessageOptions,
SessionEvent, SessionEvent,
PermissionHandler,
) )
# ============================================================================ # ============================================================================
@@ -74,7 +77,7 @@ async def main():
"tools": ["*"], "tools": ["*"],
} }
}, },
)) on_permission_request=PermissionHandler.approve_all))
done = asyncio.Event() done = asyncio.Event()
@@ -187,7 +190,7 @@ session = await client.create_session(SessionConfig(
"tools": ["*"], "tools": ["*"],
} }
}, },
)) on_permission_request=PermissionHandler.approve_all))
``` ```
This gives the model access to Playwright browser tools like `browser_navigate`, `browser_snapshot`, and `browser_click`. This gives the model access to Playwright browser tools like `browser_navigate`, `browser_snapshot`, and `browser_click`.

View File

@@ -17,14 +17,15 @@ You need to handle various error conditions like connection failures, timeouts,
```python ```python
import asyncio import asyncio
from copilot import CopilotClient, SessionConfig, MessageOptions from copilot import CopilotClient, SessionConfig, MessageOptions, PermissionHandler
async def main(): async def main():
client = CopilotClient() client = CopilotClient()
try: try:
await client.start() await client.start()
session = await client.create_session(SessionConfig(model="gpt-5")) session = await client.create_session(SessionConfig(model="gpt-5",
on_permission_request=PermissionHandler.approve_all))
response = await session.send_and_wait(MessageOptions(prompt="Hello!")) response = await session.send_and_wait(MessageOptions(prompt="Hello!"))
@@ -57,7 +58,8 @@ except Exception as e:
## Timeout handling ## Timeout handling
```python ```python
session = await client.create_session(SessionConfig(model="gpt-5")) session = await client.create_session(SessionConfig(model="gpt-5",
on_permission_request=PermissionHandler.approve_all))
try: try:
# send_and_wait accepts an optional timeout in seconds # send_and_wait accepts an optional timeout in seconds
@@ -73,7 +75,8 @@ except TimeoutError:
## Aborting a request ## Aborting a request
```python ```python
session = await client.create_session(SessionConfig(model="gpt-5")) session = await client.create_session(SessionConfig(model="gpt-5",
on_permission_request=PermissionHandler.approve_all))
# Start a request (non-blocking send) # Start a request (non-blocking send)
await session.send(MessageOptions(prompt="Write a very long story...")) await session.send(MessageOptions(prompt="Write a very long story..."))

View File

@@ -19,8 +19,11 @@ You have a folder with many files and want to organize them into subfolders base
import asyncio import asyncio
import os import os
from copilot import ( from copilot import (
CopilotClient, SessionConfig, MessageOptions, CopilotClient,
SessionConfig,
MessageOptions,
SessionEvent, SessionEvent,
PermissionHandler,
) )
async def main(): async def main():
@@ -29,7 +32,8 @@ async def main():
await client.start() await client.start()
# Create session # Create session
session = await client.create_session(SessionConfig(model="gpt-5")) session = await client.create_session(SessionConfig(model="gpt-5",
on_permission_request=PermissionHandler.approve_all))
done = asyncio.Event() done = asyncio.Event()

View File

@@ -17,16 +17,19 @@ You need to run multiple conversations in parallel, each with its own context an
```python ```python
import asyncio import asyncio
from copilot import CopilotClient, SessionConfig, MessageOptions from copilot import CopilotClient, SessionConfig, MessageOptions, PermissionHandler
async def main(): async def main():
client = CopilotClient() client = CopilotClient()
await client.start() await client.start()
# Create multiple independent sessions # Create multiple independent sessions
session1 = await client.create_session(SessionConfig(model="gpt-5")) session1 = await client.create_session(SessionConfig(model="gpt-5",
session2 = await client.create_session(SessionConfig(model="gpt-5")) on_permission_request=PermissionHandler.approve_all))
session3 = await client.create_session(SessionConfig(model="claude-sonnet-4.5")) session2 = await client.create_session(SessionConfig(model="gpt-5",
on_permission_request=PermissionHandler.approve_all))
session3 = await client.create_session(SessionConfig(model="claude-sonnet-4.5",
on_permission_request=PermissionHandler.approve_all))
# Each session maintains its own conversation history # Each session maintains its own conversation history
await session1.send(MessageOptions(prompt="You are helping with a Python project")) await session1.send(MessageOptions(prompt="You are helping with a Python project"))
@@ -55,8 +58,8 @@ Use custom IDs for easier tracking:
```python ```python
session = await client.create_session(SessionConfig( session = await client.create_session(SessionConfig(
session_id="user-123-chat", session_id="user-123-chat",
model="gpt-5" model="gpt-5",
)) on_permission_request=PermissionHandler.approve_all))
print(session.session_id) # "user-123-chat" print(session.session_id) # "user-123-chat"
``` ```

View File

@@ -17,7 +17,7 @@ You want users to be able to continue a conversation even after closing and reop
```python ```python
import asyncio import asyncio
from copilot import CopilotClient, SessionConfig, MessageOptions from copilot import CopilotClient, SessionConfig, MessageOptions, PermissionHandler
async def main(): async def main():
client = CopilotClient() client = CopilotClient()
@@ -27,7 +27,7 @@ async def main():
session = await client.create_session(SessionConfig( session = await client.create_session(SessionConfig(
session_id="user-123-conversation", session_id="user-123-conversation",
model="gpt-5", model="gpt-5",
)) on_permission_request=PermissionHandler.approve_all))
await session.send_and_wait(MessageOptions(prompt="Let's discuss TypeScript generics")) await session.send_and_wait(MessageOptions(prompt="Let's discuss TypeScript generics"))
@@ -49,7 +49,7 @@ client = CopilotClient()
await client.start() await client.start()
# Resume the previous session # Resume the previous session
session = await client.resume_session("user-123-conversation") session = await client.resume_session("user-123-conversation", on_permission_request=PermissionHandler.approve_all)
# Previous context is restored # Previous context is restored
await session.send_and_wait(MessageOptions(prompt="What were we discussing?")) await session.send_and_wait(MessageOptions(prompt="What were we discussing?"))

View File

@@ -44,8 +44,11 @@ import sys
import os import os
import re import re
from copilot import ( from copilot import (
CopilotClient, SessionConfig, MessageOptions, CopilotClient,
SessionConfig,
MessageOptions,
SessionEvent, SessionEvent,
PermissionHandler,
) )
# ============================================================================ # ============================================================================
@@ -150,8 +153,8 @@ The current working directory is: {os.getcwd()}
- Be concise in your responses - Be concise in your responses
</instructions> </instructions>
""" """
} },
)) on_permission_request=PermissionHandler.approve_all))
done = asyncio.Event() done = asyncio.Event()

View File

@@ -48,7 +48,7 @@ The minimal Ralph loop — the SDK equivalent of `while :; do cat PROMPT.md | co
```python ```python
import asyncio import asyncio
from pathlib import Path from pathlib import Path
from copilot import CopilotClient, MessageOptions, SessionConfig from copilot import CopilotClient, MessageOptions, SessionConfig, PermissionHandler
async def ralph_loop(prompt_file: str, max_iterations: int = 50): async def ralph_loop(prompt_file: str, max_iterations: int = 50):
@@ -63,7 +63,8 @@ async def ralph_loop(prompt_file: str, max_iterations: int = 50):
# Fresh session each iteration — context isolation is the point # Fresh session each iteration — context isolation is the point
session = await client.create_session( session = await client.create_session(
SessionConfig(model="gpt-5.1-codex-mini") SessionConfig(model="gpt-5.1-codex-mini",
on_permission_request=PermissionHandler.approve_all)
) )
try: try:
await session.send_and_wait( await session.send_and_wait(

View File

@@ -2,8 +2,11 @@
import asyncio import asyncio
from copilot import ( from copilot import (
CopilotClient, SessionConfig, MessageOptions, CopilotClient,
SessionConfig,
MessageOptions,
SessionEvent, SessionEvent,
PermissionHandler,
) )
# ============================================================================ # ============================================================================
@@ -41,7 +44,7 @@ async def main():
"tools": ["*"], "tools": ["*"],
} }
}, },
)) on_permission_request=PermissionHandler.approve_all))
done = asyncio.Event() done = asyncio.Event()

View File

@@ -1,14 +1,15 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import asyncio import asyncio
from copilot import CopilotClient, SessionConfig, MessageOptions from copilot import CopilotClient, SessionConfig, MessageOptions, PermissionHandler
async def main(): async def main():
client = CopilotClient() client = CopilotClient()
try: try:
await client.start() await client.start()
session = await client.create_session(SessionConfig(model="gpt-5")) session = await client.create_session(SessionConfig(model="gpt-5",
on_permission_request=PermissionHandler.approve_all))
response = await session.send_and_wait(MessageOptions(prompt="Hello!")) response = await session.send_and_wait(MessageOptions(prompt="Hello!"))

View File

@@ -3,8 +3,11 @@
import asyncio import asyncio
import os import os
from copilot import ( from copilot import (
CopilotClient, SessionConfig, MessageOptions, CopilotClient,
SessionConfig,
MessageOptions,
SessionEvent, SessionEvent,
PermissionHandler,
) )
async def main(): async def main():
@@ -13,7 +16,8 @@ async def main():
await client.start() await client.start()
# Create session # Create session
session = await client.create_session(SessionConfig(model="gpt-5")) session = await client.create_session(SessionConfig(model="gpt-5",
on_permission_request=PermissionHandler.approve_all))
done = asyncio.Event() done = asyncio.Event()

View File

@@ -1,16 +1,19 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import asyncio import asyncio
from copilot import CopilotClient, SessionConfig, MessageOptions from copilot import CopilotClient, SessionConfig, MessageOptions, PermissionHandler
async def main(): async def main():
client = CopilotClient() client = CopilotClient()
await client.start() await client.start()
# Create multiple independent sessions # Create multiple independent sessions
session1 = await client.create_session(SessionConfig(model="gpt-5")) session1 = await client.create_session(SessionConfig(model="gpt-5",
session2 = await client.create_session(SessionConfig(model="gpt-5")) on_permission_request=PermissionHandler.approve_all))
session3 = await client.create_session(SessionConfig(model="claude-sonnet-4.5")) session2 = await client.create_session(SessionConfig(model="gpt-5",
on_permission_request=PermissionHandler.approve_all))
session3 = await client.create_session(SessionConfig(model="claude-sonnet-4.5",
on_permission_request=PermissionHandler.approve_all))
print("Created 3 independent sessions") print("Created 3 independent sessions")

View File

@@ -1,7 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import asyncio import asyncio
from copilot import CopilotClient, SessionConfig, MessageOptions from copilot import CopilotClient, SessionConfig, MessageOptions, PermissionHandler
async def main(): async def main():
client = CopilotClient() client = CopilotClient()
@@ -11,7 +11,7 @@ async def main():
session = await client.create_session(SessionConfig( session = await client.create_session(SessionConfig(
session_id="user-123-conversation", session_id="user-123-conversation",
model="gpt-5", model="gpt-5",
)) on_permission_request=PermissionHandler.approve_all))
await session.send_and_wait(MessageOptions(prompt="Let's discuss TypeScript generics")) await session.send_and_wait(MessageOptions(prompt="Let's discuss TypeScript generics"))
print(f"Session created: {session.session_id}") print(f"Session created: {session.session_id}")
@@ -21,7 +21,7 @@ async def main():
print("Session destroyed (state persisted)") print("Session destroyed (state persisted)")
# Resume the previous session # Resume the previous session
resumed = await client.resume_session("user-123-conversation") resumed = await client.resume_session("user-123-conversation", on_permission_request=PermissionHandler.approve_all)
print(f"Resumed: {resumed.session_id}") print(f"Resumed: {resumed.session_id}")
await resumed.send_and_wait(MessageOptions(prompt="What were we discussing?")) await resumed.send_and_wait(MessageOptions(prompt="What were we discussing?"))

View File

@@ -6,8 +6,11 @@ import sys
import os import os
import re import re
from copilot import ( from copilot import (
CopilotClient, SessionConfig, MessageOptions, CopilotClient,
SessionConfig,
MessageOptions,
SessionEvent, SessionEvent,
PermissionHandler,
) )
# ============================================================================ # ============================================================================
@@ -112,8 +115,8 @@ The current working directory is: {os.getcwd()}
- Be concise in your responses - Be concise in your responses
</instructions> </instructions>
""" """
} },
)) on_permission_request=PermissionHandler.approve_all))
done = asyncio.Event() done = asyncio.Event()

View File

@@ -22,7 +22,7 @@ import asyncio
import sys import sys
from pathlib import Path from pathlib import Path
from copilot import CopilotClient, MessageOptions, SessionConfig from copilot import CopilotClient, MessageOptions, SessionConfig, PermissionHandler
async def ralph_loop(mode: str = "build", max_iterations: int = 50): async def ralph_loop(mode: str = "build", max_iterations: int = 50):
@@ -48,10 +48,7 @@ async def ralph_loop(mode: str = "build", max_iterations: int = 50):
# Pin the agent to the project directory # Pin the agent to the project directory
working_directory=str(Path.cwd()), working_directory=str(Path.cwd()),
# Auto-approve tool calls for unattended operation # Auto-approve tool calls for unattended operation
on_permission_request=lambda _req, _ctx: { on_permission_request=PermissionHandler.approve_all,
"kind": "approved",
"rules": [],
},
)) ))
# Log tool usage for visibility # Log tool usage for visibility

View File

@@ -65,6 +65,7 @@ Use `SessionConfig` for configuration:
```csharp ```csharp
await using var session = await client.CreateSessionAsync(new SessionConfig await using var session = await client.CreateSessionAsync(new SessionConfig
{ {
OnPermissionRequest = PermissionHandler.ApproveAll,
Model = "gpt-5", Model = "gpt-5",
Streaming = true, Streaming = true,
Tools = [...], Tools = [...],
@@ -89,7 +90,11 @@ await using var session = await client.CreateSessionAsync(new SessionConfig
### Resuming Sessions ### Resuming Sessions
```csharp ```csharp
var session = await client.ResumeSessionAsync(sessionId, new ResumeSessionConfig { ... }); var session = await client.ResumeSessionAsync(sessionId, new ResumeSessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
// ...
});
``` ```
### Session Operations ### Session Operations
@@ -178,6 +183,7 @@ Set `Streaming = true` in SessionConfig:
```csharp ```csharp
var session = await client.CreateSessionAsync(new SessionConfig var session = await client.CreateSessionAsync(new SessionConfig
{ {
OnPermissionRequest = PermissionHandler.ApproveAll,
Model = "gpt-5", Model = "gpt-5",
Streaming = true Streaming = true
}); });
@@ -236,6 +242,7 @@ using System.ComponentModel;
var session = await client.CreateSessionAsync(new SessionConfig var session = await client.CreateSessionAsync(new SessionConfig
{ {
OnPermissionRequest = PermissionHandler.ApproveAll,
Model = "gpt-5", Model = "gpt-5",
Tools = [ Tools = [
AIFunctionFactory.Create( AIFunctionFactory.Create(
@@ -268,6 +275,7 @@ When Copilot invokes a tool, the client automatically:
```csharp ```csharp
var session = await client.CreateSessionAsync(new SessionConfig var session = await client.CreateSessionAsync(new SessionConfig
{ {
OnPermissionRequest = PermissionHandler.ApproveAll,
Model = "gpt-5", Model = "gpt-5",
SystemMessage = new SystemMessageConfig SystemMessage = new SystemMessageConfig
{ {
@@ -287,6 +295,7 @@ var session = await client.CreateSessionAsync(new SessionConfig
```csharp ```csharp
var session = await client.CreateSessionAsync(new SessionConfig var session = await client.CreateSessionAsync(new SessionConfig
{ {
OnPermissionRequest = PermissionHandler.ApproveAll,
Model = "gpt-5", Model = "gpt-5",
SystemMessage = new SystemMessageConfig SystemMessage = new SystemMessageConfig
{ {
@@ -336,8 +345,16 @@ await session.SendAsync(new MessageOptions
Sessions are independent and can run concurrently: Sessions are independent and can run concurrently:
```csharp ```csharp
var session1 = await client.CreateSessionAsync(new SessionConfig { Model = "gpt-5" }); var session1 = await client.CreateSessionAsync(new SessionConfig
var session2 = await client.CreateSessionAsync(new SessionConfig { Model = "claude-sonnet-4.5" }); {
OnPermissionRequest = PermissionHandler.ApproveAll,
Model = "gpt-5",
});
var session2 = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
Model = "claude-sonnet-4.5",
});
await session1.SendAsync(new MessageOptions { Prompt = "Hello from session 1" }); await session1.SendAsync(new MessageOptions { Prompt = "Hello from session 1" });
await session2.SendAsync(new MessageOptions { Prompt = "Hello from session 2" }); await session2.SendAsync(new MessageOptions { Prompt = "Hello from session 2" });
@@ -350,6 +367,7 @@ Use custom API providers via `ProviderConfig`:
```csharp ```csharp
var session = await client.CreateSessionAsync(new SessionConfig var session = await client.CreateSessionAsync(new SessionConfig
{ {
OnPermissionRequest = PermissionHandler.ApproveAll,
Provider = new ProviderConfig Provider = new ProviderConfig
{ {
Type = "openai", Type = "openai",
@@ -390,7 +408,7 @@ var state = client.State;
```csharp ```csharp
try try
{ {
var session = await client.CreateSessionAsync(); var session = await client.CreateSessionAsync(new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll });
await session.SendAsync(new MessageOptions { Prompt = "Hello" }); await session.SendAsync(new MessageOptions { Prompt = "Hello" });
} }
catch (StreamJsonRpc.RemoteInvocationException ex) catch (StreamJsonRpc.RemoteInvocationException ex)
@@ -433,7 +451,7 @@ ALWAYS use `await using` for automatic disposal:
```csharp ```csharp
await using var client = new CopilotClient(); await using var client = new CopilotClient();
await using var session = await client.CreateSessionAsync(); await using var session = await client.CreateSessionAsync(new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll });
// Resources automatically cleaned up // Resources automatically cleaned up
``` ```
@@ -477,6 +495,7 @@ await client.StartAsync();
await using var session = await client.CreateSessionAsync(new SessionConfig await using var session = await client.CreateSessionAsync(new SessionConfig
{ {
OnPermissionRequest = PermissionHandler.ApproveAll,
Model = "gpt-5" Model = "gpt-5"
}); });
@@ -501,7 +520,7 @@ await done.Task;
### Multi-Turn Conversation ### Multi-Turn Conversation
```csharp ```csharp
await using var session = await client.CreateSessionAsync(); await using var session = await client.CreateSessionAsync(new SessionConfig { OnPermissionRequest = PermissionHandler.ApproveAll });
async Task SendAndWait(string prompt) async Task SendAndWait(string prompt)
{ {
@@ -532,6 +551,7 @@ await SendAndWait("What is its population?");
```csharp ```csharp
var session = await client.CreateSessionAsync(new SessionConfig var session = await client.CreateSessionAsync(new SessionConfig
{ {
OnPermissionRequest = PermissionHandler.ApproveAll,
Tools = [ Tools = [
AIFunctionFactory.Create( AIFunctionFactory.Create(
([Description("User ID")] string userId) => { ([Description("User ID")] string userId) => {

View File

@@ -72,6 +72,7 @@ Use `SessionConfig` for configuration:
```go ```go
session, err := client.CreateSession(&copilot.SessionConfig{ session, err := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5", Model: "gpt-5",
Streaming: true, Streaming: true,
Tools: []copilot.Tool{...}, Tools: []copilot.Tool{...},
@@ -104,7 +105,7 @@ if err != nil {
### Resuming Sessions ### Resuming Sessions
```go ```go
session, err := client.ResumeSession("session-id") session, err := client.ResumeSession("session-id", &copilot.ResumeSessionConfig{OnPermissionRequest: copilot.PermissionHandler.ApproveAll})
// Or with options: // Or with options:
session, err := client.ResumeSessionWithOptions("session-id", &copilot.ResumeSessionConfig{ ... }) session, err := client.ResumeSessionWithOptions("session-id", &copilot.ResumeSessionConfig{ ... })
``` ```
@@ -190,6 +191,7 @@ Set `Streaming: true` in SessionConfig:
```go ```go
session, err := client.CreateSession(&copilot.SessionConfig{ session, err := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5", Model: "gpt-5",
Streaming: true, Streaming: true,
}) })
@@ -243,6 +245,7 @@ Note: Final events (`AssistantMessage`, `AssistantReasoning`) are ALWAYS sent re
```go ```go
session, err := client.CreateSession(&copilot.SessionConfig{ session, err := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5", Model: "gpt-5",
Tools: []copilot.Tool{ Tools: []copilot.Tool{
{ {
@@ -300,6 +303,7 @@ When Copilot invokes a tool, the client automatically:
```go ```go
session, err := client.CreateSession(&copilot.SessionConfig{ session, err := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5", Model: "gpt-5",
SystemMessage: &copilot.SystemMessageConfig{ SystemMessage: &copilot.SystemMessageConfig{
Mode: "append", Mode: "append",
@@ -317,6 +321,7 @@ session, err := client.CreateSession(&copilot.SessionConfig{
```go ```go
session, err := client.CreateSession(&copilot.SessionConfig{ session, err := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5", Model: "gpt-5",
SystemMessage: &copilot.SystemMessageConfig{ SystemMessage: &copilot.SystemMessageConfig{
Mode: "replace", Mode: "replace",
@@ -361,8 +366,14 @@ session.Send(copilot.MessageOptions{
Sessions are independent and can run concurrently: Sessions are independent and can run concurrently:
```go ```go
session1, _ := client.CreateSession(&copilot.SessionConfig{Model: "gpt-5"}) session1, _ := client.CreateSession(&copilot.SessionConfig{
session2, _ := client.CreateSession(&copilot.SessionConfig{Model: "claude-sonnet-4.5"}) OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
})
session2, _ := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "claude-sonnet-4.5",
})
session1.Send(copilot.MessageOptions{Prompt: "Hello from session 1"}) session1.Send(copilot.MessageOptions{Prompt: "Hello from session 1"})
session2.Send(copilot.MessageOptions{Prompt: "Hello from session 2"}) session2.Send(copilot.MessageOptions{Prompt: "Hello from session 2"})
@@ -374,6 +385,7 @@ Use custom API providers via `ProviderConfig`:
```go ```go
session, err := client.CreateSession(&copilot.SessionConfig{ session, err := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Provider: &copilot.ProviderConfig{ Provider: &copilot.ProviderConfig{
Type: "openai", Type: "openai",
BaseURL: "https://api.openai.com/v1", BaseURL: "https://api.openai.com/v1",
@@ -396,7 +408,9 @@ state := client.GetState()
### Standard Exception Handling ### Standard Exception Handling
```go ```go
session, err := client.CreateSession(&copilot.SessionConfig{}) session, err := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
})
if err != nil { if err != nil {
log.Fatalf("Failed to create session: %v", err) log.Fatalf("Failed to create session: %v", err)
} }
@@ -447,7 +461,7 @@ if err := client.Start(); err != nil {
} }
defer client.Stop() defer client.Stop()
session, err := client.CreateSession(nil) session, err := client.CreateSession(&copilot.SessionConfig{OnPermissionRequest: copilot.PermissionHandler.ApproveAll})
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@@ -465,7 +479,7 @@ if err != nil {
log.Fatal(err) log.Fatal(err)
} }
session, err := client.CreateSession(nil) session, err := client.CreateSession(&copilot.SessionConfig{OnPermissionRequest: copilot.PermissionHandler.ApproveAll})
if err != nil { if err != nil {
client.Stop() client.Stop()
log.Fatal(err) log.Fatal(err)
@@ -504,7 +518,10 @@ if err := client.Start(); err != nil {
} }
defer client.Stop() defer client.Stop()
session, err := client.CreateSession(&copilot.SessionConfig{Model: "gpt-5"}) session, err := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-5",
})
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@@ -527,7 +544,7 @@ session.Send(copilot.MessageOptions{Prompt: "What is 2+2?"})
### Multi-Turn Conversation ### Multi-Turn Conversation
```go ```go
session, _ := client.CreateSession(nil) session, _ := client.CreateSession(&copilot.SessionConfig{OnPermissionRequest: copilot.PermissionHandler.ApproveAll})
defer session.Destroy() defer session.Destroy()
sendAndWait := func(prompt string) error { sendAndWait := func(prompt string) error {
@@ -588,6 +605,7 @@ type UserInfo struct {
} }
session, _ := client.CreateSession(&copilot.SessionConfig{ session, _ := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Tools: []copilot.Tool{ Tools: []copilot.Tool{
{ {
Name: "get_user", Name: "get_user",

View File

@@ -30,7 +30,7 @@ yarn add @github/copilot-sdk
### Basic Client Setup ### Basic Client Setup
```typescript ```typescript
import { CopilotClient } from "@github/copilot-sdk"; import { CopilotClient, approveAll } from "@github/copilot-sdk";
const client = new CopilotClient(); const client = new CopilotClient();
await client.start(); await client.start();
@@ -74,6 +74,7 @@ Use `SessionConfig` for configuration:
```typescript ```typescript
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5", model: "gpt-5",
streaming: true, streaming: true,
tools: [...], tools: [...],
@@ -106,6 +107,7 @@ const session = await client.createSession({
```typescript ```typescript
const session = await client.resumeSession("session-id", { const session = await client.resumeSession("session-id", {
tools: [myNewTool], tools: [myNewTool],
onPermissionRequest: approveAll,
}); });
``` ```
@@ -190,6 +192,7 @@ Set `streaming: true` in SessionConfig:
```typescript ```typescript
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5", model: "gpt-5",
streaming: true, streaming: true,
}); });
@@ -243,6 +246,7 @@ Use `defineTool` for type-safe tool definitions:
import { defineTool } from "@github/copilot-sdk"; import { defineTool } from "@github/copilot-sdk";
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5", model: "gpt-5",
tools: [ tools: [
defineTool({ defineTool({
@@ -272,6 +276,7 @@ The SDK supports Zod schemas for parameters:
import { z } from "zod"; import { z } from "zod";
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
tools: [ tools: [
defineTool({ defineTool({
name: "get_weather", name: "get_weather",
@@ -316,6 +321,7 @@ When Copilot invokes a tool, the client automatically:
```typescript ```typescript
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5", model: "gpt-5",
systemMessage: { systemMessage: {
mode: "append", mode: "append",
@@ -333,6 +339,7 @@ const session = await client.createSession({
```typescript ```typescript
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5", model: "gpt-5",
systemMessage: { systemMessage: {
mode: "replace", mode: "replace",
@@ -377,8 +384,14 @@ await session.send({
Sessions are independent and can run concurrently: Sessions are independent and can run concurrently:
```typescript ```typescript
const session1 = await client.createSession({ model: "gpt-5" }); const session1 = await client.createSession({
const session2 = await client.createSession({ model: "claude-sonnet-4.5" }); onPermissionRequest: approveAll,
model: "gpt-5",
});
const session2 = await client.createSession({
onPermissionRequest: approveAll,
model: "claude-sonnet-4.5",
});
await Promise.all([ await Promise.all([
session1.send({ prompt: "Hello from session 1" }), session1.send({ prompt: "Hello from session 1" }),
@@ -392,6 +405,7 @@ Use custom API providers via `provider`:
```typescript ```typescript
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
provider: { provider: {
type: "openai", type: "openai",
baseUrl: "https://api.openai.com/v1", baseUrl: "https://api.openai.com/v1",
@@ -422,7 +436,7 @@ await client.deleteSession(sessionId);
```typescript ```typescript
const lastId = await client.getLastSessionId(); const lastId = await client.getLastSessionId();
if (lastId) { if (lastId) {
const session = await client.resumeSession(lastId); const session = await client.resumeSession(lastId, { onPermissionRequest: approveAll });
} }
``` ```
@@ -439,7 +453,7 @@ const state = client.getState();
```typescript ```typescript
try { try {
const session = await client.createSession(); const session = await client.createSession({ onPermissionRequest: approveAll });
await session.send({ prompt: "Hello" }); await session.send({ prompt: "Hello" });
} catch (error) { } catch (error) {
console.error(`Error: ${error.message}`); console.error(`Error: ${error.message}`);
@@ -477,7 +491,7 @@ ALWAYS use try-finally or cleanup in a finally block:
const client = new CopilotClient(); const client = new CopilotClient();
try { try {
await client.start(); await client.start();
const session = await client.createSession(); const session = await client.createSession({ onPermissionRequest: approveAll });
try { try {
// Use session... // Use session...
} finally { } finally {
@@ -507,7 +521,7 @@ async function withSession<T>(
client: CopilotClient, client: CopilotClient,
fn: (session: CopilotSession) => Promise<T>, fn: (session: CopilotSession) => Promise<T>,
): Promise<T> { ): Promise<T> {
const session = await client.createSession(); const session = await client.createSession({ onPermissionRequest: approveAll });
try { try {
return await fn(session); return await fn(session);
} finally { } finally {
@@ -542,13 +556,16 @@ await withClient(async (client) => {
### Simple Query-Response ### Simple Query-Response
```typescript ```typescript
import { CopilotClient } from "@github/copilot-sdk"; import { CopilotClient, approveAll } from "@github/copilot-sdk";
const client = new CopilotClient(); const client = new CopilotClient();
try { try {
await client.start(); await client.start();
const session = await client.createSession({ model: "gpt-5" }); const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5",
});
try { try {
await new Promise<void>((resolve) => { await new Promise<void>((resolve) => {
session.on((event) => { session.on((event) => {
@@ -572,7 +589,7 @@ try {
### Multi-Turn Conversation ### Multi-Turn Conversation
```typescript ```typescript
const session = await client.createSession(); const session = await client.createSession({ onPermissionRequest: approveAll });
async function sendAndWait(prompt: string): Promise<void> { async function sendAndWait(prompt: string): Promise<void> {
await new Promise<void>((resolve, reject) => { await new Promise<void>((resolve, reject) => {
@@ -621,6 +638,7 @@ interface UserInfo {
} }
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
tools: [ tools: [
defineTool({ defineTool({
name: "get_user", name: "get_user",

View File

@@ -30,7 +30,7 @@ uv add github-copilot-sdk
### Basic Client Setup ### Basic Client Setup
```python ```python
from copilot import CopilotClient from copilot import CopilotClient, PermissionHandler
import asyncio import asyncio
async def main(): async def main():
@@ -82,6 +82,7 @@ Use a dict for SessionConfig:
```python ```python
session = await client.create_session({ session = await client.create_session({
"on_permission_request": PermissionHandler.approve_all,
"model": "gpt-5", "model": "gpt-5",
"streaming": True, "streaming": True,
"tools": [...], "tools": [...],
@@ -113,6 +114,7 @@ session = await client.create_session({
```python ```python
session = await client.resume_session("session-id", { session = await client.resume_session("session-id", {
"on_permission_request": PermissionHandler.approve_all,
"tools": [my_new_tool] "tools": [my_new_tool]
}) })
``` ```
@@ -195,6 +197,7 @@ Set `streaming: True` in SessionConfig:
```python ```python
session = await client.create_session({ session = await client.create_session({
"on_permission_request": PermissionHandler.approve_all,
"model": "gpt-5", "model": "gpt-5",
"streaming": True "streaming": True
}) })
@@ -248,6 +251,7 @@ async def fetch_issue(issue_id: str):
return {"id": issue_id, "status": "open"} return {"id": issue_id, "status": "open"}
session = await client.create_session({ session = await client.create_session({
"on_permission_request": PermissionHandler.approve_all,
"model": "gpt-5", "model": "gpt-5",
"tools": [ "tools": [
define_tool( define_tool(
@@ -281,6 +285,7 @@ async def get_weather(args: WeatherArgs, inv):
return {"temperature": 72, "units": args.units} return {"temperature": 72, "units": args.units}
session = await client.create_session({ session = await client.create_session({
"on_permission_request": PermissionHandler.approve_all,
"tools": [ "tools": [
define_tool( define_tool(
name="get_weather", name="get_weather",
@@ -331,6 +336,7 @@ When Copilot invokes a tool, the client automatically:
```python ```python
session = await client.create_session({ session = await client.create_session({
"on_permission_request": PermissionHandler.approve_all,
"model": "gpt-5", "model": "gpt-5",
"system_message": { "system_message": {
"mode": "append", "mode": "append",
@@ -348,6 +354,7 @@ session = await client.create_session({
```python ```python
session = await client.create_session({ session = await client.create_session({
"on_permission_request": PermissionHandler.approve_all,
"model": "gpt-5", "model": "gpt-5",
"system_message": { "system_message": {
"mode": "replace", "mode": "replace",
@@ -392,8 +399,14 @@ await session.send({
Sessions are independent and can run concurrently: Sessions are independent and can run concurrently:
```python ```python
session1 = await client.create_session({"model": "gpt-5"}) session1 = await client.create_session({
session2 = await client.create_session({"model": "claude-sonnet-4.5"}) "on_permission_request": PermissionHandler.approve_all,
"model": "gpt-5",
})
session2 = await client.create_session({
"on_permission_request": PermissionHandler.approve_all,
"model": "claude-sonnet-4.5",
})
await asyncio.gather( await asyncio.gather(
session1.send({"prompt": "Hello from session 1"}), session1.send({"prompt": "Hello from session 1"}),
@@ -407,6 +420,7 @@ Use custom API providers via `provider`:
```python ```python
session = await client.create_session({ session = await client.create_session({
"on_permission_request": PermissionHandler.approve_all,
"provider": { "provider": {
"type": "openai", "type": "openai",
"base_url": "https://api.openai.com/v1", "base_url": "https://api.openai.com/v1",
@@ -436,7 +450,7 @@ await client.delete_session(session_id)
```python ```python
last_id = await client.get_last_session_id() last_id = await client.get_last_session_id()
if last_id: if last_id:
session = await client.resume_session(last_id) session = await client.resume_session(last_id, on_permission_request=PermissionHandler.approve_all)
``` ```
### Checking Connection State ### Checking Connection State
@@ -452,7 +466,7 @@ state = client.get_state()
```python ```python
try: try:
session = await client.create_session() session = await client.create_session(on_permission_request=PermissionHandler.approve_all)
await session.send({"prompt": "Hello"}) await session.send({"prompt": "Hello"})
except Exception as e: except Exception as e:
print(f"Error: {e}") print(f"Error: {e}")
@@ -487,7 +501,7 @@ ALWAYS use async context managers for automatic cleanup:
```python ```python
async with CopilotClient() as client: async with CopilotClient() as client:
async with await client.create_session() as session: async with await client.create_session(on_permission_request=PermissionHandler.approve_all) as session:
# Use session... # Use session...
await session.send({"prompt": "Hello"}) await session.send({"prompt": "Hello"})
# Session automatically destroyed # Session automatically destroyed
@@ -500,7 +514,7 @@ async with CopilotClient() as client:
client = CopilotClient() client = CopilotClient()
try: try:
await client.start() await client.start()
session = await client.create_session() session = await client.create_session(on_permission_request=PermissionHandler.approve_all)
try: try:
# Use session... # Use session...
pass pass
@@ -529,12 +543,15 @@ finally:
### Simple Query-Response ### Simple Query-Response
```python ```python
from copilot import CopilotClient from copilot import CopilotClient, PermissionHandler
import asyncio import asyncio
async def main(): async def main():
async with CopilotClient() as client: async with CopilotClient() as client:
async with await client.create_session({"model": "gpt-5"}) as session: async with await client.create_session({
"on_permission_request": PermissionHandler.approve_all,
"model": "gpt-5",
}) as session:
done = asyncio.Event() done = asyncio.Event()
def handler(event): def handler(event):
@@ -574,7 +591,7 @@ async def send_and_wait(session, prompt: str):
return result[0] if result else None return result[0] if result else None
async with await client.create_session() as session: async with await client.create_session(on_permission_request=PermissionHandler.approve_all) as session:
await send_and_wait(session, "What is the capital of France?") await send_and_wait(session, "What is the capital of France?")
await send_and_wait(session, "What is its population?") await send_and_wait(session, "What is its population?")
``` ```
@@ -583,7 +600,7 @@ async with await client.create_session() as session:
```python ```python
# Use built-in send_and_wait for simpler synchronous interaction # Use built-in send_and_wait for simpler synchronous interaction
async with await client.create_session() as session: async with await client.create_session(on_permission_request=PermissionHandler.approve_all) as session:
response = await session.send_and_wait( response = await session.send_and_wait(
{"prompt": "What is 2+2?"}, {"prompt": "What is 2+2?"},
timeout=60.0 timeout=60.0
@@ -616,6 +633,7 @@ async def get_user(args, inv) -> dict:
return asdict(user) return asdict(user)
session = await client.create_session({ session = await client.create_session({
"on_permission_request": PermissionHandler.approve_all,
"tools": [ "tools": [
define_tool( define_tool(
name="get_user", name="get_user",
@@ -697,6 +715,7 @@ options: MessageOptions = {
await session.send(options) await session.send(options)
config: SessionConfig = { config: SessionConfig = {
"on_permission_request": PermissionHandler.approve_all,
"model": "gpt-5", "model": "gpt-5",
"streaming": True "streaming": True
} }
@@ -775,7 +794,9 @@ def copilot_tool(
def calculate(expression: str) -> float: def calculate(expression: str) -> float:
return eval(expression) return eval(expression)
session = await client.create_session({"tools": [calculate]}) session = await client.create_session({
"on_permission_request": PermissionHandler.approve_all,
"tools": [calculate]})
``` ```
## Python-Specific Features ## Python-Specific Features

View File

@@ -49,10 +49,13 @@ dotnet add package GitHub.Copilot.SDK
### TypeScript ### TypeScript
```typescript ```typescript
import { CopilotClient } from "@github/copilot-sdk"; import { CopilotClient, approveAll } from "@github/copilot-sdk";
const client = new CopilotClient(); const client = new CopilotClient();
const session = await client.createSession({ model: "gpt-4.1" }); const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-4.1",
});
const response = await session.sendAndWait({ prompt: "What is 2 + 2?" }); const response = await session.sendAndWait({ prompt: "What is 2 + 2?" });
console.log(response?.data.content); console.log(response?.data.content);
@@ -66,13 +69,16 @@ Run: `npx tsx index.ts`
### Python ### Python
```python ```python
import asyncio import asyncio
from copilot import CopilotClient from copilot import CopilotClient, PermissionHandler
async def main(): async def main():
client = CopilotClient() client = CopilotClient()
await client.start() await client.start()
session = await client.create_session({"model": "gpt-4.1"}) session = await client.create_session({
"on_permission_request": PermissionHandler.approve_all,
"model": "gpt-4.1",
})
response = await session.send_and_wait({"prompt": "What is 2 + 2?"}) response = await session.send_and_wait({"prompt": "What is 2 + 2?"})
print(response.data.content) print(response.data.content)
@@ -99,7 +105,10 @@ func main() {
} }
defer client.Stop() defer client.Stop()
session, err := client.CreateSession(&copilot.SessionConfig{Model: "gpt-4.1"}) session, err := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-4.1",
})
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
@@ -119,7 +128,11 @@ func main() {
using GitHub.Copilot.SDK; using GitHub.Copilot.SDK;
await using var client = new CopilotClient(); await using var client = new CopilotClient();
await using var session = await client.CreateSessionAsync(new SessionConfig { Model = "gpt-4.1" }); await using var session = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
Model = "gpt-4.1",
});
var response = await session.SendAndWaitAsync(new MessageOptions { Prompt = "What is 2 + 2?" }); var response = await session.SendAndWaitAsync(new MessageOptions { Prompt = "What is 2 + 2?" });
Console.WriteLine(response?.Data.Content); Console.WriteLine(response?.Data.Content);
@@ -133,10 +146,11 @@ Enable real-time output for better UX:
### TypeScript ### TypeScript
```typescript ```typescript
import { CopilotClient, SessionEvent } from "@github/copilot-sdk"; import { CopilotClient, approveAll, SessionEvent } from "@github/copilot-sdk";
const client = new CopilotClient(); const client = new CopilotClient();
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-4.1", model: "gpt-4.1",
streaming: true, streaming: true,
}); });
@@ -160,7 +174,7 @@ process.exit(0);
```python ```python
import asyncio import asyncio
import sys import sys
from copilot import CopilotClient from copilot import CopilotClient, PermissionHandler
from copilot.generated.session_events import SessionEventType from copilot.generated.session_events import SessionEventType
async def main(): async def main():
@@ -168,6 +182,7 @@ async def main():
await client.start() await client.start()
session = await client.create_session({ session = await client.create_session({
"on_permission_request": PermissionHandler.approve_all,
"model": "gpt-4.1", "model": "gpt-4.1",
"streaming": True, "streaming": True,
}) })
@@ -189,6 +204,7 @@ asyncio.run(main())
### Go ### Go
```go ```go
session, err := client.CreateSession(&copilot.SessionConfig{ session, err := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-4.1", Model: "gpt-4.1",
Streaming: true, Streaming: true,
}) })
@@ -209,6 +225,7 @@ _, err = session.SendAndWait(copilot.MessageOptions{Prompt: "Tell me a short jok
```csharp ```csharp
await using var session = await client.CreateSessionAsync(new SessionConfig await using var session = await client.CreateSessionAsync(new SessionConfig
{ {
OnPermissionRequest = PermissionHandler.ApproveAll,
Model = "gpt-4.1", Model = "gpt-4.1",
Streaming = true, Streaming = true,
}); });
@@ -233,7 +250,7 @@ Define tools that Copilot can invoke during reasoning. When you define a tool, y
### TypeScript (JSON Schema) ### TypeScript (JSON Schema)
```typescript ```typescript
import { CopilotClient, defineTool, SessionEvent } from "@github/copilot-sdk"; import { CopilotClient, approveAll, defineTool, SessionEvent } from "@github/copilot-sdk";
const getWeather = defineTool("get_weather", { const getWeather = defineTool("get_weather", {
description: "Get the current weather for a city", description: "Get the current weather for a city",
@@ -256,6 +273,7 @@ const getWeather = defineTool("get_weather", {
const client = new CopilotClient(); const client = new CopilotClient();
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-4.1", model: "gpt-4.1",
streaming: true, streaming: true,
tools: [getWeather], tools: [getWeather],
@@ -280,7 +298,7 @@ process.exit(0);
import asyncio import asyncio
import random import random
import sys import sys
from copilot import CopilotClient from copilot import CopilotClient, PermissionHandler
from copilot.tools import define_tool from copilot.tools import define_tool
from copilot.generated.session_events import SessionEventType from copilot.generated.session_events import SessionEventType
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
@@ -301,6 +319,7 @@ async def main():
await client.start() await client.start()
session = await client.create_session({ session = await client.create_session({
"on_permission_request": PermissionHandler.approve_all,
"model": "gpt-4.1", "model": "gpt-4.1",
"streaming": True, "streaming": True,
"tools": [get_weather], "tools": [get_weather],
@@ -350,6 +369,7 @@ getWeather := copilot.DefineTool(
) )
session, _ := client.CreateSession(&copilot.SessionConfig{ session, _ := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-4.1", Model: "gpt-4.1",
Streaming: true, Streaming: true,
Tools: []copilot.Tool{getWeather}, Tools: []copilot.Tool{getWeather},
@@ -376,6 +396,7 @@ var getWeather = AIFunctionFactory.Create(
await using var session = await client.CreateSessionAsync(new SessionConfig await using var session = await client.CreateSessionAsync(new SessionConfig
{ {
OnPermissionRequest = PermissionHandler.ApproveAll,
Model = "gpt-4.1", Model = "gpt-4.1",
Streaming = true, Streaming = true,
Tools = [getWeather], Tools = [getWeather],
@@ -398,7 +419,7 @@ Build a complete interactive assistant:
### TypeScript ### TypeScript
```typescript ```typescript
import { CopilotClient, defineTool, SessionEvent } from "@github/copilot-sdk"; import { CopilotClient, approveAll, defineTool, SessionEvent } from "@github/copilot-sdk";
import * as readline from "readline"; import * as readline from "readline";
const getWeather = defineTool("get_weather", { const getWeather = defineTool("get_weather", {
@@ -420,6 +441,7 @@ const getWeather = defineTool("get_weather", {
const client = new CopilotClient(); const client = new CopilotClient();
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-4.1", model: "gpt-4.1",
streaming: true, streaming: true,
tools: [getWeather], tools: [getWeather],
@@ -462,7 +484,7 @@ prompt();
import asyncio import asyncio
import random import random
import sys import sys
from copilot import CopilotClient from copilot import CopilotClient, PermissionHandler
from copilot.tools import define_tool from copilot.tools import define_tool
from copilot.generated.session_events import SessionEventType from copilot.generated.session_events import SessionEventType
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
@@ -482,6 +504,7 @@ async def main():
await client.start() await client.start()
session = await client.create_session({ session = await client.create_session({
"on_permission_request": PermissionHandler.approve_all,
"model": "gpt-4.1", "model": "gpt-4.1",
"streaming": True, "streaming": True,
"tools": [get_weather], "tools": [get_weather],
@@ -522,6 +545,7 @@ Connect to MCP (Model Context Protocol) servers for pre-built tools. Connect to
### TypeScript ### TypeScript
```typescript ```typescript
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-4.1", model: "gpt-4.1",
mcpServers: { mcpServers: {
github: { github: {
@@ -535,6 +559,7 @@ const session = await client.createSession({
### Python ### Python
```python ```python
session = await client.create_session({ session = await client.create_session({
"on_permission_request": PermissionHandler.approve_all,
"model": "gpt-4.1", "model": "gpt-4.1",
"mcp_servers": { "mcp_servers": {
"github": { "github": {
@@ -548,6 +573,7 @@ session = await client.create_session({
### Go ### Go
```go ```go
session, _ := client.CreateSession(&copilot.SessionConfig{ session, _ := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-4.1", Model: "gpt-4.1",
MCPServers: map[string]copilot.MCPServerConfig{ MCPServers: map[string]copilot.MCPServerConfig{
"github": { "github": {
@@ -562,6 +588,7 @@ session, _ := client.CreateSession(&copilot.SessionConfig{
```csharp ```csharp
await using var session = await client.CreateSessionAsync(new SessionConfig await using var session = await client.CreateSessionAsync(new SessionConfig
{ {
OnPermissionRequest = PermissionHandler.ApproveAll,
Model = "gpt-4.1", Model = "gpt-4.1",
McpServers = new Dictionary<string, McpServerConfig> McpServers = new Dictionary<string, McpServerConfig>
{ {
@@ -581,6 +608,7 @@ Define specialized AI personas for specific tasks:
### TypeScript ### TypeScript
```typescript ```typescript
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-4.1", model: "gpt-4.1",
customAgents: [{ customAgents: [{
name: "pr-reviewer", name: "pr-reviewer",
@@ -594,6 +622,7 @@ const session = await client.createSession({
### Python ### Python
```python ```python
session = await client.create_session({ session = await client.create_session({
"on_permission_request": PermissionHandler.approve_all,
"model": "gpt-4.1", "model": "gpt-4.1",
"custom_agents": [{ "custom_agents": [{
"name": "pr-reviewer", "name": "pr-reviewer",
@@ -611,6 +640,7 @@ Customize the AI's behavior and personality:
### TypeScript ### TypeScript
```typescript ```typescript
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-4.1", model: "gpt-4.1",
systemMessage: { systemMessage: {
content: "You are a helpful assistant for our engineering team. Always be concise.", content: "You are a helpful assistant for our engineering team. Always be concise.",
@@ -621,6 +651,7 @@ const session = await client.createSession({
### Python ### Python
```python ```python
session = await client.create_session({ session = await client.create_session({
"on_permission_request": PermissionHandler.approve_all,
"model": "gpt-4.1", "model": "gpt-4.1",
"system_message": { "system_message": {
"content": "You are a helpful assistant for our engineering team. Always be concise.", "content": "You are a helpful assistant for our engineering team. Always be concise.",
@@ -645,7 +676,10 @@ const client = new CopilotClient({
cliUrl: "localhost:4321" cliUrl: "localhost:4321"
}); });
const session = await client.createSession({ model: "gpt-4.1" }); const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-4.1",
});
``` ```
#### Python #### Python
@@ -655,7 +689,10 @@ client = CopilotClient({
}) })
await client.start() await client.start()
session = await client.create_session({"model": "gpt-4.1"}) session = await client.create_session({
"on_permission_request": PermissionHandler.approve_all,
"model": "gpt-4.1",
})
``` ```
#### Go #### Go
@@ -668,7 +705,10 @@ if err := client.Start(); err != nil {
log.Fatal(err) log.Fatal(err)
} }
session, _ := client.CreateSession(&copilot.SessionConfig{Model: "gpt-4.1"}) session, _ := client.CreateSession(&copilot.SessionConfig{
OnPermissionRequest: copilot.PermissionHandler.ApproveAll,
Model: "gpt-4.1",
})
``` ```
#### .NET #### .NET
@@ -678,7 +718,11 @@ using var client = new CopilotClient(new CopilotClientOptions
CliUrl = "localhost:4321" CliUrl = "localhost:4321"
}); });
await using var session = await client.CreateSessionAsync(new SessionConfig { Model = "gpt-4.1" }); await using var session = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
Model = "gpt-4.1",
});
``` ```
**Note:** When `cliUrl` is provided, the SDK will not spawn or manage a CLI process - it only connects to the existing server. **Note:** When `cliUrl` is provided, the SDK will not spawn or manage a CLI process - it only connects to the existing server.
@@ -731,6 +775,7 @@ Save and resume conversations across restarts:
### Create with Custom ID ### Create with Custom ID
```typescript ```typescript
const session = await client.createSession({ const session = await client.createSession({
onPermissionRequest: approveAll,
sessionId: "user-123-conversation", sessionId: "user-123-conversation",
model: "gpt-4.1" model: "gpt-4.1"
}); });
@@ -738,7 +783,7 @@ const session = await client.createSession({
### Resume Session ### Resume Session
```typescript ```typescript
const session = await client.resumeSession("user-123-conversation"); const session = await client.resumeSession("user-123-conversation", { onPermissionRequest: approveAll });
await session.send({ prompt: "What did we discuss earlier?" }); await session.send({ prompt: "What did we discuss earlier?" });
``` ```
@@ -753,7 +798,10 @@ await client.deleteSession("old-session-id");
```typescript ```typescript
try { try {
const client = new CopilotClient(); const client = new CopilotClient();
const session = await client.createSession({ model: "gpt-4.1" }); const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-4.1",
});
const response = await session.sendAndWait( const response = await session.sendAndWait(
{ prompt: "Hello!" }, { prompt: "Hello!" },
30000 // timeout in ms 30000 // timeout in ms
@@ -785,7 +833,10 @@ process.on("SIGINT", async () => {
### Multi-turn Conversation ### Multi-turn Conversation
```typescript ```typescript
const session = await client.createSession({ model: "gpt-4.1" }); const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-4.1",
});
await session.sendAndWait({ prompt: "My name is Alice" }); await session.sendAndWait({ prompt: "My name is Alice" });
await session.sendAndWait({ prompt: "What's my name?" }); await session.sendAndWait({ prompt: "What's my name?" });