TypeScript SDK for programmatic control of GitHub Copilot CLI via JSON-RPC.Documentation Index
Fetch the complete documentation index at: https://bastani.mintlify.app/llms.txt
Use this file to discover all available pages before exploring further.
Note: This SDK is in public preview and may change in breaking ways.
Installation
Run the Sample
Try the interactive chat sample (from the repo root):Quick Start
Symbol.asyncDispose for use with await using (TypeScript 5.2+/Node.js 18.0+):
API Reference
CopilotClient
Constructor
cliPath?: string- Path to CLI executable (default: uses COPILOT_CLI_PATH env var or bundled instance)cliArgs?: string[]- Extra arguments prepended before SDK-managed flags (e.g.["./dist-cli/index.js"]when usingnode)cliUrl?: string- URL of existing CLI server to connect to (e.g.,"localhost:8080","http://127.0.0.1:9000", or just"8080"). When provided, the client will not spawn a CLI process.port?: number- Server port (default: 0 for random)useStdio?: boolean- Use stdio transport instead of TCP (default: true)logLevel?: string- Log level (default: “info”)autoStart?: boolean- Auto-start server (default: true)gitHubToken?: string- GitHub token for authentication. When provided, takes priority over other auth methods.useLoggedInUser?: boolean- Whether to use logged-in user for authentication (default: true, but false whengitHubTokenis provided). Cannot be used withcliUrl.telemetry?: TelemetryConfig- OpenTelemetry configuration for the CLI process. Providing this object enables telemetry — no separate flag needed. See Telemetry below.onGetTraceContext?: TraceContextProvider- Advanced: callback for linking your application’s own OpenTelemetry spans into the same distributed trace as the CLI’s spans. Not needed for normal telemetry collection. See Telemetry below.
Methods
start(): Promise<void>
Start the CLI server and establish connection.
stop(): Promise<Error[]>
Stop the server and close all sessions. Returns a list of any errors encountered during cleanup.
forceStop(): Promise<void>
Force stop the CLI server without graceful cleanup. Use when stop() takes too long.
createSession(config?: SessionConfig): Promise<CopilotSession>
Create a new conversation session.
Config:
sessionId?: string- Custom session ID.model?: string- Model to use (“gpt-5”, “claude-sonnet-4.5”, etc.). Required when using custom provider.reasoningEffort?: "low" | "medium" | "high" | "xhigh"- Reasoning effort level for models that support it. UselistModels()to check which models support this option.tools?: Tool[]- Custom tools exposed to the CLIsystemMessage?: SystemMessageConfig- System message customization (see below)infiniteSessions?: InfiniteSessionConfig- Configure automatic context compaction (see below)provider?: ProviderConfig- Custom API provider configuration (BYOK - Bring Your Own Key). See Custom Providers section.onPermissionRequest: PermissionHandler- Required. Handler called before each tool execution to approve or deny it. UseapproveAllto allow everything, or provide a custom function for fine-grained control. See Permission Handling section.gitHubToken?: string- Per-session GitHub token for authentication. This is the supported token option when connecting through an existingcliUrlserver.onUserInputRequest?: UserInputHandler- Handler for user input requests from the agent. Enables theask_usertool. See User Input Requests section.onElicitationRequest?: ElicitationHandler- Handler for elicitation requests dispatched by the server. Enables this client to present form-based UI dialogs on behalf of the agent or other session participants. See Elicitation Requests section.hooks?: SessionHooks- Hook handlers for session lifecycle events. See Session Hooks section.
resumeSession(sessionId: string, config?: ResumeSessionConfig): Promise<CopilotSession>
Resume an existing session. Returns the session with workspacePath populated if infinite sessions were enabled.
ping(message?: string): Promise<{ message: string; timestamp: number }>
Ping the server to check connectivity.
getState(): ConnectionState
Get current connection state.
listSessions(filter?: SessionListFilter): Promise<SessionMetadata[]>
List all available sessions. Optionally filter by working directory context.
SessionMetadata:
sessionId: string- Unique session identifierstartTime: Date- When the session was createdmodifiedTime: Date- When the session was last modifiedsummary?: string- Optional session summaryisRemote: boolean- Whether the session is remotecontext?: SessionContext- Working directory context from session creation
cwd: string- Working directory where the session was createdgitRoot?: string- Git repository root (if in a git repo)repository?: string- GitHub repository in “owner/repo” formatbranch?: string- Current git branch
deleteSession(sessionId: string): Promise<void>
Delete a session and its data from disk.
getForegroundSessionId(): Promise<string | undefined>
Get the ID of the session currently displayed in the TUI. Only available when connecting to a server running in TUI+server mode (--ui-server).
setForegroundSessionId(sessionId: string): Promise<void>
Request the TUI to switch to displaying the specified session. Only available in TUI+server mode.
on(eventType: SessionLifecycleEventType, handler): () => void
Subscribe to a specific session lifecycle event type. Returns an unsubscribe function.
on(handler: SessionLifecycleHandler): () => void
Subscribe to all session lifecycle events. Returns an unsubscribe function.
session.created- A new session was createdsession.deleted- A session was deletedsession.updated- A session was updated (e.g., new messages)session.foreground- A session became the foreground session in TUIsession.background- A session is no longer the foreground session
CopilotSession
Represents a single conversation session.Properties
sessionId: string
The unique identifier for this session.
workspacePath?: string
Path to the session workspace directory when infinite sessions are enabled. Contains checkpoints/, plan.md, and files/ subdirectories. Undefined if infinite sessions are disabled.
Methods
send(options: MessageOptions): Promise<string>
Send a message to the session. Returns immediately after the message is queued; use event handlers or sendAndWait() to wait for completion.
Options:
prompt: string- The message/prompt to sendattachments?: Array<{type, path, displayName}>- File attachmentsmode?: "enqueue" | "immediate"- Delivery mode
sendAndWait(options: MessageOptions, timeout?: number): Promise<AssistantMessageEvent | undefined>
Send a message and wait until the session becomes idle.
Options:
prompt: string- The message/prompt to sendattachments?: Array<{type, path, displayName}>- File attachmentsmode?: "enqueue" | "immediate"- Delivery modetimeout?: number- Optional timeout in milliseconds
on(eventType: string, handler: TypedSessionEventHandler): () => void
Subscribe to a specific event type. The handler receives properly typed events.
on(handler: SessionEventHandler): () => void
Subscribe to all session events. Returns an unsubscribe function.
abort(): Promise<void>
Abort the currently processing message in this session.
getMessages(): Promise<SessionEvent[]>
Get all events/messages from this session.
disconnect(): Promise<void>
Disconnect the session and free resources. Session data on disk is preserved for later resumption.
capabilities: SessionCapabilities
Host capabilities reported when the session was created or resumed. Use this to check feature support before calling capability-gated APIs.
capabilities.changed events, so this property always reflects the current state.
ui: SessionUiApi
Interactive UI methods for showing dialogs to the user. Only available when the CLI host supports elicitation (session.capabilities.ui?.elicitation === true). See UI Elicitation for full details.
destroy(): Promise<void> (deprecated)
Deprecated — use disconnect() instead.
Event Types
Sessions emit various events during processing:user.message- User message addedassistant.message- Assistant responseassistant.message_delta- Streaming response chunktool.execution_start- Tool execution startedtool.execution_complete- Tool execution completedcommand.execute- Command dispatch request (handled internally by the SDK)commands.changed- Command registration changed- And more…
SessionEvent type in the source for full details.
Image Support
The SDK supports image attachments via theattachments parameter. You can attach images by providing their file path, or by passing base64-encoded data directly using a blob attachment:
view tool can also read images directly from the filesystem, so you can also ask questions like:
Streaming
Enable streaming to receive assistant response chunks as they’re generated:streaming: true:
assistant.message_deltaevents are sent withdeltaContentcontaining incremental textassistant.reasoning_deltaevents are sent withdeltaContentfor reasoning/chain-of-thought (model-dependent)- Accumulate
deltaContentvalues to build the full response progressively - The final
assistant.messageandassistant.reasoningevents contain the complete content
assistant.message and assistant.reasoning (final events) are always sent regardless of streaming setting.
Advanced Usage
Manual Server Control
Tools
You can let the CLI call back into your process when the model needs capabilities you own. UsedefineTool with Zod schemas for type-safe tool definitions:
lookup_issue, the client automatically runs your handler and responds to the CLI. Handlers can return any JSON-serializable value (automatically wrapped), a simple string, or a ToolResultObject for full control over result metadata. Raw JSON schemas are also supported if Zod isn’t desired.
Overriding Built-in Tools
If you register a tool with the same name as a built-in CLI tool (e.g.edit_file, read_file), the SDK will throw an error unless you explicitly opt in by setting overridesBuiltInTool: true. This flag signals that you intend to replace the built-in tool with your custom implementation.
Skipping Permission Prompts
SetskipPermission: true on a tool definition to allow it to execute without triggering a permission prompt:
Commands
Register slash commands so that users of the CLI’s TUI can invoke custom actions via/commandName. Each command has a name, optional description, and a handler called when the user executes it.
/deploy staging in the CLI, the SDK receives a command.execute event, routes it to your handler, and automatically responds to the CLI. If the handler throws, the error message is forwarded.
Commands are sent to the CLI on both createSession and resumeSession, so you can update the command set when resuming.
UI Elicitation
When the session has elicitation support — either from the CLI’s TUI or from another client that registered anonElicitationRequest handler (see Elicitation Requests) — the SDK can request interactive form dialogs from the user. The session.ui object provides convenience methods built on a single generic elicitation RPC.
Capability check: Elicitation is only available when at least one connected participant advertises support. Always check session.capabilities.ui?.elicitation before calling UI methods — this property updates automatically as participants join and leave.
System Message Customization
Control the system prompt usingsystemMessage in session config:
content is appended after SDK-managed sections. To change the persona or fully redefine the prompt, use mode: "replace" or mode: "customize".
Customize Mode
Usemode: "customize" to selectively override individual sections of the prompt while preserving the rest:
identity, tone, tool_efficiency, environment_context, code_change_rules, guidelines, safety, tool_instructions, custom_instructions, last_instructions. Use the SYSTEM_PROMPT_SECTIONS constant for descriptions of each section.
Each section override supports four actions:
replace— Replace the section content entirelyremove— Remove the section from the promptappend— Add content after the existing sectionprepend— Add content before the existing section
replace/append/prepend overrides is appended to additional instructions, and remove overrides are silently ignored.
Replace Mode
For full control (removes all guardrails), usemode: "replace":
Infinite Sessions
By default, sessions use infinite sessions which automatically manage context window limits through background compaction and persist state to a workspace directory.session.compaction_start- Background compaction startedsession.compaction_complete- Compaction finished (includes token counts)
Multiple Sessions
Custom Session IDs
File Attachments
Custom Providers
The SDK supports custom OpenAI-compatible API providers (BYOK - Bring Your Own Key), including local providers like Ollama. When using a custom provider, you must specify themodel explicitly.
ProviderConfig:
type?: "openai" | "azure" | "anthropic"- Provider type (default: “openai”)baseUrl: string- API endpoint URL (required)apiKey?: string- API key (optional for local providers like Ollama)bearerToken?: string- Bearer token for authentication (takes precedence over apiKey)wireApi?: "completions" | "responses"- API format for OpenAI/Azure (default: “completions”)azure?.apiVersion?: string- Azure API version (default: “2024-10-21”)
Important notes:
- When using a custom provider, the
modelparameter is required. The SDK will throw an error if no model is specified.- For Azure OpenAI endpoints (
*.openai.azure.com), you must usetype: "azure", nottype: "openai".- The
baseUrlshould be just the host (e.g.,https://my-resource.openai.azure.com). Do not include/openai/v1in the URL - the SDK handles path construction automatically.
Telemetry
The SDK supports OpenTelemetry for distributed tracing. Provide atelemetry config to enable trace export from the CLI process — this is all most users need:
otlpEndpoint?: string- OTLP HTTP endpoint URLfilePath?: string- File path for JSON-lines trace outputexporterType?: string-"otlp-http"or"file"sourceName?: string- Instrumentation scope namecaptureContent?: boolean- Whether to capture message content
Advanced: Trace Context Propagation
You don’t need this for normal telemetry collection. The telemetry config above is sufficient to get full traces from the CLI.
onGetTraceContext is only needed if your application creates its own OpenTelemetry spans and you want them to appear in the same distributed trace as the CLI’s spans — for example, to nest a “handle tool call” span inside the CLI’s “execute tool” span, or to show the SDK call as a child of your application’s request-handling span.
If you’re already using @opentelemetry/api in your app and want this linkage, provide a callback:
ToolInvocation object passed to tool handlers as traceparent and tracestate fields. See the OpenTelemetry guide for a full wire-up example.
Permission Handling
AnonPermissionRequest handler is required whenever you create or resume a session. The handler is called before the agent executes each tool (file writes, shell commands, custom tools, etc.) and must return a decision.
Approve All (simplest)
Use the built-inapproveAll helper to allow every tool call without any checks:
Custom Permission Handler
Provide your own function to inspect each request and apply custom logic:Permission Result Kinds
| Kind | Meaning |
|---|---|
"approved" | Allow the tool to run |
"denied-interactively-by-user" | User explicitly denied the request |
"denied-no-approval-rule-and-could-not-request-from-user" | No approval rule matched and user could not be asked |
"denied-by-rules" | Denied by a policy rule |
"denied-by-content-exclusion-policy" | Denied due to a content exclusion policy |
"no-result" | Leave the request unanswered (only valid with protocol v1; rejected by protocol v2 servers) |
Resuming Sessions
PassonPermissionRequest when resuming a session too — it is required:
Per-Tool Skip Permission
To let a specific custom tool bypass the permission prompt entirely, setskipPermission: true on the tool definition. See Skipping Permission Prompts under Tools.
User Input Requests
Enable the agent to ask questions to the user using theask_user tool by providing an onUserInputRequest handler:
Elicitation Requests
Register anonElicitationRequest handler to let your client act as an elicitation provider — presenting form-based UI dialogs on behalf of the agent. When provided, the server notifies your client whenever a tool or MCP server needs structured user input.
onElicitationRequest is provided, the SDK sends requestElicitation: true during session create/resume, which enables session.capabilities.ui.elicitation on the session.
In multi-client scenarios:
- If no connected client was previously providing an elicitation capability, but a new client joins that can, all clients will receive a
capabilities.changedevent to notify them that elicitation is now possible. The SDK automatically updatessession.capabilitieswhen these events arrive. - Similarly, if the last elicitation provider disconnects, all clients receive a
capabilities.changedevent indicating elicitation is no longer available. - The server fans out elicitation requests to all connected clients that registered a handler — the first response wins.
Session Hooks
Hook into session lifecycle events by providing handlers in thehooks configuration:
onPreToolUse- Intercept tool calls before execution. Can allow/deny or modify arguments.onPostToolUse- Process tool results after execution. Can modify results or add context.onUserPromptSubmitted- Intercept user prompts. Can modify the prompt before processing.onSessionStart- Run logic when a session starts or resumes.onSessionEnd- Cleanup or logging when session ends.onErrorOccurred- Handle errors with retry/skip/abort strategies.
Error Handling
Requirements
- Node.js >= 18.0.0
- GitHub Copilot CLI installed and in PATH (or provide custom
cliPath)