Skip to main content

Node.js / TypeScript SDK Cookbook

Short, practical recipes for using the GitHub Copilot SDK with Node.js and TypeScript. Each recipe is concise, copy-pasteable, and points to complete runnable examples.

Setup

Install the GitHub Copilot SDK:
npm install @github/copilot-sdk
Import in your code:
import { CopilotClient } from "@github/copilot-sdk";

Error Handling

Handle errors gracefully including connection failures, timeouts, and cleanup.

Basic try-catch Pattern

import { CopilotClient } from "@github/copilot-sdk";

const client = new CopilotClient();

try {
    await client.start();
    const session = await client.createSession({ model: "gpt-5" });

    const response = await session.sendAndWait({ prompt: "Hello!" });
    console.log(response?.data.content);

    await session.destroy();
} catch (error: any) {
    console.error("Error:", error.message);
} finally {
    await client.stop();
}

Timeout Handling

const session = await client.createSession({ model: "gpt-5" });

try {
    // sendAndWait with timeout (in milliseconds)
    const response = await session.sendAndWait(
        { prompt: "Complex question..." },
        30000 // 30 second timeout
    );

    if (response) {
        console.log(response.data.content);
    } else {
        console.log("No response received");
    }
} catch (error) {
    if (error.message.includes("timeout")) {
        console.error("Request timed out");
    }
}

Aborting Requests

const session = await client.createSession({ model: "gpt-5" });

// Start a request
session.send({ prompt: "Write a very long story..." });

// Abort it after some condition
setTimeout(async () => {
    await session.abort();
    console.log("Request aborted");
}, 5000);

Graceful Shutdown

process.on("SIGINT", async () => {
    console.log("Shutting down...");

    const errors = await client.stop();
    if (errors.length > 0) {
        console.error("Cleanup errors:", errors);
    }

    process.exit(0);
});
Always use try-finally to ensure client.stop() is called. This prevents resource leaks and ensures the Copilot CLI process is properly terminated.

Multiple Sessions

Manage multiple independent conversations simultaneously.
import { CopilotClient } from "@github/copilot-sdk";

const client = new CopilotClient();
await client.start();

// Create multiple independent sessions
const session1 = await client.createSession({ model: "gpt-5" });
const session2 = await client.createSession({ model: "gpt-5" });
const session3 = await client.createSession({ model: "claude-sonnet-4.5" });

// Each session maintains its own conversation history
await session1.sendAndWait({ prompt: "You are helping with a Python project" });
await session2.sendAndWait({ prompt: "You are helping with a TypeScript project" });
await session3.sendAndWait({ prompt: "You are helping with a Go project" });

// Follow-up messages stay in their respective contexts
await session1.sendAndWait({ prompt: "How do I create a virtual environment?" });
await session2.sendAndWait({ prompt: "How do I set up tsconfig?" });
await session3.sendAndWait({ prompt: "How do I initialize a module?" });

// Clean up all sessions
await session1.destroy();
await session2.destroy();
await session3.destroy();
await client.stop();

Custom Session IDs

const session = await client.createSession({
    sessionId: "user-123-chat",
    model: "gpt-5",
});

console.log(session.sessionId); // "user-123-chat"

Listing and Deleting Sessions

const sessions = await client.listSessions();
console.log(sessions);
// [{ sessionId: "user-123-chat", ... }, ...]

Use Cases

Multi-User Apps

One session per user in web servers

Multi-Task Workflows

Separate sessions for different tasks

A/B Testing

Compare responses from different models

Session Persistence

Save and resume sessions across application restarts.
import { CopilotClient } from "@github/copilot-sdk";
import { writeFile, readFile } from "fs/promises";

// Save session state
const client = new CopilotClient();
await client.start();

const session = await client.createSession({ model: "gpt-5" });
await session.sendAndWait({ prompt: "Remember: my name is Alice" });

const sessionState = session.getState();
await writeFile("session.json", JSON.stringify(sessionState, null, 2));

await session.destroy();
await client.stop();

// Later: restore session state
const client2 = new CopilotClient();
await client2.start();

const savedState = await readFile("session.json", "utf-8");
const state = JSON.parse(savedState);

const restoredSession = await client2.createSession({
    model: "gpt-5",
    state: state,
});

// Session remembers previous context
const response = await restoredSession.sendAndWait({ prompt: "What's my name?" });
console.log(response?.data.content); // "Your name is Alice"
Session persistence is perfect for maintaining long-running conversations or implementing user session management in web applications.

Managing Local Files

Use AI to organize and categorize files.
import { CopilotClient } from "@github/copilot-sdk";

const client = new CopilotClient();
await client.start();

const session = await client.createSession({ model: "gpt-5" });

const response = await session.sendAndWait({
    prompt: `
        I have these files in a directory:
        - report.pdf
        - meeting-notes.txt
        - photo.jpg
        - invoice.xlsx
        - presentation.pptx
        
        Please organize them into folders by type.
        Return JSON with the folder structure.
    `,
});

console.log(response?.data.content);

// Parse the AI response and execute file operations
// ...

Running Examples

All complete, runnable examples are available in the cookbook/copilot-sdk/nodejs/recipe directory.
1

Navigate to the recipe directory

cd cookbook/copilot-sdk/nodejs/recipe
2

Install dependencies

npm install
3

Run any example

npx tsx error-handling.ts
npx tsx multiple-sessions.ts
npx tsx persisting-sessions.ts

Best Practices

Use try-finally to ensure client.stop() is called, preventing resource leaks.
try {
    await client.start();
    // ... work ...
} finally {
    await client.stop();
}
The Copilot CLI might not be installed or running. Check for ENOENT and ECONNREFUSED errors.
if (error.message.includes("ENOENT")) {
    console.error("Please install GitHub Copilot CLI");
}
Always provide a timeout to sendAndWait() for long-running requests.
await session.sendAndWait({ prompt }, 30000); // 30s timeout
Use TypeScript types for better IDE support and type safety.
const response: AssistantMessageEvent | null = await session.sendAndWait(...);

Additional Recipes

Explore more advanced recipes in the source repository:

Resources

Build docs developers (and LLMs) love