/vibe:ghcopilot-instr-copilot-sdk-nodejsfrom vibe
Provides guidance on using the @github/copilot-sdk Node.js package for building Copilot extensions. Covers client initialization, session management, and configuration options.
Ships in vibe. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Always install via npm/pnpm/yarn:
npm install @github/copilot-sdk
# or
pnpm add @github/copilot-sdk
# or
yarn add @github/copilot-sdk
import { CopilotClient, approveAll } from "@github/copilot-sdk";
const client = new CopilotClient();
await client.start();
// Use client...
await client.stop();
When creating a CopilotClient, use CopilotClientOptions:
cliPath - Path to CLI executable (default: "copilot" from PATH)cliArgs - Extra arguments prepended before SDK-managed flags (string[])cliUrl - URL of existing CLI server (e.g., "localhost:8080"). When provided, client won't spawn a processport - Server port (default: 0 for random)useStdio - Use stdio transport instead of TCP (default: true)logLevel - Log level (default: "debug")autoStart - Auto-start server (default: true)autoRestart - Auto-restart on crash (default: true)cwd - Working directory for the CLI process (default: process.cwd())env - Environment variables for the CLI process (default: process.env)For explicit control:
const client = new CopilotClient({ autoStart: false });
await client.start();
// Use client...
await client.stop();
Use forceStop() when stop() takes too long.
Use SessionConfig for configuration:
const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5",
streaming: true,
tools: [...],
systemMessage: { ... },
availableTools: ["tool1", "tool2"],
excludedTools: ["tool3"],
provider: { ... }
});
sessionId - Custom session ID (string)model - Model name ("gpt-5", "claude-sonnet-4.5", etc.)tools - Custom tools exposed to the CLI (Tool[])systemMessage - System message customization (SystemMessageConfig)availableTools - Allowlist of tool names (string[])excludedTools - Blocklist of tool names (string[])provider - Custom API provider configuration (BYOK) (ProviderConfig)streaming - Enable streaming response chunks (boolean)mcpServers - MCP server configurations (MCPServerConfig[])customAgents - Custom agent configurations (CustomAgentConfig[])configDir - Config directory override (string)skillDirectories - Skill directories (string[])disabledSkills - Disabled skills (string[])onPermissionRequest - Permission request handler (PermissionHandler)const session = await client.resumeSession("session-id", {
tools: [myNewTool],
onPermissionRequest: approveAll,
});
session.sessionId - Get session identifier (string)await session.send({ prompt: "...", attachments: [...] }) - Send message, returns Promiseawait session.sendAndWait({ prompt: "..." }, timeout) - Send and wait for idle, returns Promise<AssistantMessageEvent | null>await session.abort() - Abort current processingawait session.getMessages() - Get all events/messages, returns Promise<SessionEvent[]>await session.destroy() - Clean up sessionALWAYS use async/await or Promises for waiting on session events:
await new Promise<void>((resolve) => {
session.on((event) => {
if (event.type === "assistant.message") {
console.log(event.data.content);
} else if (event.type === "session.idle") {
resolve();
}
});
session.send({ prompt: "..." });
});
The on() method returns a function that unsubscribes:
const unsubscribe = session.on((event) => {
// handler
});
// Later...
unsubscribe();
Use discriminated unions with type guards for event handling:
session.on((event) => {
switch (event.type) {
case "user.message":
// Handle user message
break;
case "assistant.message":
console.log(event.data.content);
break;
case "tool.executionStart":
// Tool execution started
break;
case "tool.executionComplete":
// Tool execution completed
break;
case "session.start":
// Session started
break;
case "session.idle":
// Session is idle (processing complete)
break;
case "session.error":
console.error(`Error: ${event.data.message}`);
break;
}
});
Set streaming: true in SessionConfig:
const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5",
streaming: true,
});
Handle both delta events (incremental) and final events:
await new Promise<void>((resolve) => {
session.on((event) => {
switch (event.type) {
case "assistant.message_delta":
// Incremental text chunk
process.stdout.write(event.data.deltaContent);
break;
case "assistant.reasoning_delta":
// Incremental reasoning chunk (model-dependent)
process.stdout.write(event.data.deltaContent);
break;
case "assistant.message":
// Final complete message
console.log("\n--- Final ---");
console.log(event.data.content);
break;
case "assistant.reasoning":
// Final reasoning content
console.log("--- Reasoning ---");
console.log(event.data.content);
break;
case "session.idle":
resolve();
break;
}
});
session.send({ prompt: "Tell me a story" });
});
Note: Final events (assistant.message, assistant.reasoning) are ALWAYS sent regardless of streaming setting.
Use defineTool for type-safe tool definitions:
import { defineTool } from "@github/copilot-sdk";
const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5",
tools: [
defineTool({
name: "lookup_issue",
description: "Fetch issue details from tracker",
parameters: {
type: "object",
properties: {
id: { type: "string", description: "Issue ID" },
},
required: ["id"],
},
handler: async (args) => {
const issue = await fetchIssue(args.id);
return issue;
},
}),
],
});
The SDK supports Zod schemas for parameters:
import { z } from "zod";
const session = await client.createSession({
onPermissionRequest: approveAll,
tools: [
defineTool({
name: "get_weather",
description: "Get weather for a location",
parameters: z.object({
location: z.string().describe("City name"),
units: z.enum(["celsius", "fahrenheit"]).optional(),
}),
handler: async (args) => {
return { temperature: 72, units: args.units || "fahrenheit" };
},
}),
],
});
ToolResultObject for full control over metadata:{
textResultForLlm: string; // Result shown to LLM
resultType: "success" | "failure";
error?: string; // Internal error (not shown to LLM)
toolTelemetry?: Record<string, unknown>;
}
When Copilot invokes a tool, the client automatically:
const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5",
systemMessage: {
mode: "append",
content: `
<workflow_rules>
- Always check for security vulnerabilities
- Suggest performance improvements when applicable
</workflow_rules>
`,
},
});
const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5",
systemMessage: {
mode: "replace",
content: "You are a helpful assistant.",
},
});
Attach files to messages:
await session.send({
prompt: "Analyze this file",
attachments: [
{
type: "file",
path: "/path/to/file.ts",
displayName: "My File",
},
],
});
Use the mode property in message options:
"enqueue" - Queue message for processing"immediate" - Process message immediatelyawait session.send({
prompt: "...",
mode: "enqueue",
});
Sessions are independent and can run concurrently:
const session1 = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5",
});
const session2 = await client.createSession({
onPermissionRequest: approveAll,
model: "claude-sonnet-4.5",
});
await Promise.all([
session1.send({ prompt: "Hello from session 1" }),
session2.send({ prompt: "Hello from session 2" }),
]);
Use custom API providers via provider:
const session = await client.createSession({
onPermissionRequest: approveAll,
provider: {
type: "openai",
baseUrl: "https://api.openai.com/v1",
apiKey: "your-api-key",
},
});
const sessions = await client.listSessions();
for (const metadata of sessions) {
console.log(`${metadata.sessionId}: ${metadata.summary}`);
}
await client.deleteSession(sessionId);
const lastId = await client.getLastSessionId();
if (lastId) {
const session = await client.resumeSession(lastId, { onPermissionRequest: approveAll });
}
const state = client.getState();
// Returns: "disconnected" | "connecting" | "connected" | "error"
try {
const session = await client.createSession({ onPermissionRequest: approveAll });
await session.send({ prompt: "Hello" });
} catch (error) {
console.error(`Error: ${error.message}`);
}
Monitor session.error event type for runtime errors:
session.on((event) => {
if (event.type === "session.error") {
console.error(`Session Error: ${event.data.message}`);
}
});
Use ping to verify server connectivity:
const response = await client.ping("health check");
console.log(`Server responded at ${new Date(response.timestamp)}`);
ALWAYS use try-finally or cleanup in a finally block:
const client = new CopilotClient();
try {
await client.start();
const session = await client.createSession({ onPermissionRequest: approveAll });
try {
// Use session...
} finally {
await session.destroy();
}
} finally {
await client.stop();
}
async function withClient<T>(
fn: (client: CopilotClient) => Promise<T>,
): Promise<T> {
const client = new CopilotClient();
try {
await client.start();
return await fn(client);
} finally {
await client.stop();
}
}
async function withSession<T>(
client: CopilotClient,
fn: (session: CopilotSession) => Promise<T>,
): Promise<T> {
const session = await client.createSession({ onPermissionRequest: approveAll });
try {
return await fn(session);
} finally {
await session.destroy();
}
}
// Usage
await withClient(async (client) => {
await withSession(client, async (session) => {
await session.send({ prompt: "Hello!" });
});
});
import { CopilotClient, approveAll } from "@github/copilot-sdk";
const client = new CopilotClient();
try {
await client.start();
const session = await client.createSession({
onPermissionRequest: approveAll,
model: "gpt-5",
});
try {
await new Promise<void>((resolve) => {
session.on((event) => {
if (event.type === "assistant.message") {
console.log(event.data.content);
} else if (event.type === "session.idle") {
resolve();
}
});
session.send({ prompt: "What is 2+2?" });
});
} finally {
await session.destroy();
}
} finally {
await client.stop();
}
const session = await client.createSession({ onPermissionRequest: approveAll });
async function sendAndWait(prompt: string): Promise<void> {
await new Promise<void>((resolve, reject) => {
const unsubscribe = session.on((event) => {
if (event.type === "assistant.message") {
console.log(event.data.content);
} else if (event.type === "session.idle") {
unsubscribe();
resolve();
} else if (event.type === "session.error") {
unsubscribe();
reject(new Error(event.data.message));
}
});
session.send({ prompt });
});
}
await sendAndWait("What is the capital of France?");
await sendAndWait("What is its population?");
// Use built-in sendAndWait for simpler synchronous interaction
const response = await session.sendAndWait({ prompt: "What is 2+2?" }, 60000);
if (response) {
console.log(response.data.content);
}
import { z } from "zod";
import { defineTool } from "@github/copilot-sdk";
interface UserInfo {
id: string;
name: string;
email: string;
role: string;
}
const session = await client.createSession({
onPermissionRequest: approveAll,
tools: [
defineTool({
name: "get_user",
description: "Retrieve user information",
parameters: z.object({
userId: z.string().describe("User ID"),
}),
handler: async (args): Promise<UserInfo> => {
return {
id: args.userId,
name: "John Doe",
email: "[email protected]",
role: "Developer",
};
},
}),
],
});
let currentMessage = "";
const unsubscribe = session.on((event) => {
if (event.type === "assistant.message_delta") {
currentMessage += event.data.deltaContent;
process.stdout.write(event.data.deltaContent);
} else if (event.type === "assistant.message") {
console.log("\n\n=== Complete ===");
console.log(`Total length: ${event.data.content.length} chars`);
} else if (event.type === "session.idle") {
unsubscribe();
}
});
await session.send({ prompt: "Write a long story" });
session.on((event) => {
if (event.type === "session.error") {
console.error("Session error:", event.data.message);
// Optionally retry or handle error
}
});
try {
await session.send({ prompt: "risky operation" });
} catch (error) {
// Handle send errors
console.error("Failed to send:", error);
}
import type { SessionEvent, AssistantMessageEvent } from "@github/copilot-sdk";
session.on((event: SessionEvent) => {
if (event.type === "assistant.message") {
// TypeScript knows event is AssistantMessageEvent here
const content: string = event.data.content;
}
});
async function waitForEvent<T extends SessionEvent["type"]>(
session: CopilotSession,
eventType: T,
): Promise<Extract<SessionEvent, { type: T }>> {
return new Promise((resolve) => {
const unsubscribe = session.on((event) => {
if (event.type === eventType) {
unsubscribe();
resolve(event as Extract<SessionEvent, { type: T }>);
}
});
});
}
// Usage
const message = await waitForEvent(session, "assistant.message");
console.log(message.data.content);
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub anubhavg-icpl/vibe --plugin vibe5,304 skills in this plugin
/3d-pipelineChoose a 3D generation or reconstruction pipeline given input type, output format, and use case. Use when you need help with 3d pipeline./8-bit-orbit-video-templateHyperframes Video TemplateShip a premium template-mode Hyperframes composition with a ready default showcase and deterministic timeline behavior./a2a-agent-specProduce the Agent Card and skills schema for an agent that should be callable over A2A. Use when you need help with a2a agent spec.Other plugins' skills for the same job