Liking cljdoc? Tell your friends :D

SDK and CLI compatibility

This document outlines which Copilot CLI features are available through the SDK and which are CLI-only.

Overview

The Copilot SDK communicates with the Copilot runtime via JSON-RPC protocol. Features must be explicitly exposed through this protocol to be available in the SDK. Many interactive CLI features are terminal-specific and not available programmatically.

Feature comparison

✅ Available in SDK

FeatureSDK MethodNotes
Session Management
Create sessioncreateSession()Full config support
Resume sessionresumeSession()With infinite session workspaces
Disconnect sessiondisconnect()Release in-memory resources
Delete sessiondeleteSession()Remove from storage
List sessionslistSessions()All stored sessions
Get last sessiongetLastSessionId()For quick resume
Get foreground sessiongetForegroundSessionId()Multi-session coordination
Set foreground sessionsetForegroundSessionId()Multi-session coordination
Messaging
Send messagesend()With attachments
Send and waitsendAndWait()Blocks until complete
Steering (immediate mode)send({ mode: "immediate" })Inject mid-turn without aborting
Queueing (enqueue mode)send({ mode: "enqueue" })Buffer for sequential processing (default)
File attachmentssend({ attachments: [{ type: "file", path }] })Images auto-encoded and resized
Directory attachmentssend({ attachments: [{ type: "directory", path }] })Attach directory context
Get historygetEvents()All session events
Abortabort()Cancel in-flight request
Tools
Register custom toolstools.definitions in session configFull JSON Schema support
Replace custom tools (mid-session)session.setTools()Experimental; see Changing tools during a session
Tool permission controlonPreToolUse hookAllow/deny/ask
Tool result modificationonPostToolUse hookTransform results
Available/excluded toolstools.availableTools, tools.excludedTools configFilter tools
Models
List modelslistModels()With capabilities, billing, policy
Set model (at creation)model in session configPer-session
Switch model (mid-session)session.setModel()Also via session.rpc.model.switchTo()
Get current modelsession.rpc.model.getCurrent()Query active model
Reasoning effortinference.reasoningEffort configFor supported models
Agent Mode
Get current modesession.rpc.mode.get()Returns current mode
Set modesession.rpc.mode.set()Switch between modes
Plan Management
Read plansession.rpc.plan.read()Get plan.md content and path
Update plansession.rpc.plan.update()Write plan.md content
Delete plansession.rpc.plan.delete()Remove plan.md
Workspace Files
List workspace filessession.rpc.workspaces.listFiles()Files in session workspace
Read workspace filesession.rpc.workspaces.readFile()Read file content
Create workspace filesession.rpc.workspaces.createFile()Create file in workspace
Authentication
Get auth statusgetAuthStatus()Check login state
Use tokengithub.token optionProgrammatic auth
Connectivity
Pingclient.ping()Health check with runtime timestamp
Get runtime statusclient.getStatus()Runtime version and protocol version
MCP Servers
Local/stdio serversmcp.servers configSpawn processes
Remote HTTP/SSEmcp.servers configConnect to services
Hooks
Pre-tool useonPreToolUsePermission, modify args
Pre-MCP tool callonPreMcpToolCallAttach or remove MCP request metadata
Post-tool use (success)onPostToolUseModify results
Post-tool use (failure)onPostToolUseFailureObserve failed tool calls, inject retry guidance
User promptonUserPromptSubmittedModify prompts
User prompt transformedonUserPromptTransformedInspect or replace model-facing content
Session start/endonSessionStart, onSessionEndLifecycle with source/reason
Error handlingonErrorOccurredCustom handling
Agent stoponAgentStopValidate completion or request another turn
Sub-agent lifecycleonSubagentStart, onSubagentStopPrepend context to a sub-agent's prompt, request another turn or replace its response
Events
All session eventson()40+ event types
Streamingevents.streaming: trueDelta events
Session Config
Custom agentsagents.definitions configDefine specialized agents
System messagesystemMessage configAppend or replace
Named providersinference.providers connectionsBYOK support
Infinite sessionsstate.infiniteSessions configAuto-compaction
Permission handlerpermissions.onRequestApprove/deny; decisionContext.userFeedback collects explanations only in restricted telemetry
User input handlerinteraction.onUserInputRequestHandle ask_user
Shell authentication handlerinteraction.onShellAuthenticationRequestAnswer shell password prompts; see Shell password prompts
Skillsskills.directories configCustom skills
Disabled skillsskills.disabledSkills configDisable specific skills
Config directoryconfigDirectory configOverride default config location
Client nameclientName configIdentify app in User-Agent
Working directoryworkingDirectory configSet session cwd
Additional directoriesfilesystem.additionalDirectories configGrant session access beyond the working directory; re-supply on resume
Experimental
Agent managementsession.rpc.agent.*List, select, deselect, get current agent
Fleet modesession.rpc.fleet.start()Parallel sub-agent execution; see Fleet mode
Manual compactionsession.rpc.history.compact()Trigger compaction on demand
Compaction settingssession.rpc.history.setCompactionConfig()Override the compaction model, prompt and reasoning effort for a live session; {} restores defaults; re-apply after resume
Context clearingsession.rpc.history.clearContext()Replace conversation context from a terminal tool
History truncationsession.rpc.history.truncate()Remove events from a point onward
Session forkingclient.rpc.sessions.fork()Fork a session at a point in history

❌ Not available in SDK (CLI-only)

FeatureCLI Command/OptionReason
Session Export
Export to file--share, /shareNot in protocol
Export to gist--share-gist, /share gistNot in protocol
Interactive UI
Slash commands/help, /clear, /exit, etc.TUI-only
Agent picker dialog/agentInteractive UI
Diff mode dialog/diffInteractive UI
Feedback dialog/feedbackInteractive UI
Theme picker/themeTerminal UI
Model picker/modelInteractive UI (use SDK setModel() instead)
Copy to clipboard/copyTerminal-specific
Context management/contextInteractive UI (use SDK session.rpc.metadata.contextInfo() instead)
Research & History
Deep research/researchTUI workflow with web search
Session history tools/chronicleStandup, tips, improve, reindex
Terminal Features
Color output--no-colorTerminal-specific
Screen reader mode--screen-readerAccessibility
Startup banner--bannerVisual element
Mouse support--mouse, --no-mouseTerminal input
Path/Permission Shortcuts
Allow all paths--allow-all-pathsUse permission handler
Allow all URLs--allow-all-urlsUse permission handler
Allow all permissions--yolo, --allow-all, /allow-allUse permission handler
Granular tool permissions--allow-tool, --deny-toolUse onPreToolUse hook
URL access control--allow-url, --deny-urlUse permission handler
Reset allowed tools/reset-allowed-toolsTUI command
Directory Management
Add directory/add-dir, --add-dirConfigure in session
List directories/list-dirsTUI command
Change directory/cwdTUI command (use SDK session.rpc.metadata.setWorkingDirectory() instead)
Plugin/MCP Management
Plugin commands/pluginInteractive management (use SDK client.rpc.plugins.* for installed plugins and marketplaces, or session.rpc.plugins.* to change plugins in a live session)
MCP server management/mcpInteractive UI (use SDK client.rpc.mcp.config.* to edit saved MCP configuration, which does not restart running servers, or session.rpc.mcp.* to list, start, stop and reload servers in a live session)
Account Management
Login flow/login, copilot loginOAuth device flow
Logout/logoutDirect CLI
User info/userTUI command
Session Operations
Clear conversation/clearTUI-only
Plan view/planTUI-only (use SDK session.rpc.plan.* instead)
Session management/session, /resume, /renameTUI workflow (use SDK resumeSession() to resume and session.rpc.name.set() to rename)
Fleet mode (interactive)/fleetTUI-only (use SDK session.rpc.fleet.start() instead)
Skills Management
Manage skills/skillsInteractive UI (use SDK session.rpc.skills.* instead)
Task Management
View background tasks/tasksTUI command (use SDK session.rpc.tasks.* instead)
Usage & Stats
Token usage/usageSubscribe to usage events
Code Review
Review changes/reviewTUI command
Delegation
Delegate to PR/delegateTUI workflow
Terminal Setup
Shell integration/terminal-setupShell-specific
Development
Toggle experimental/experimental, --experimentalRuntime flag
Custom instructions control--no-custom-instructionsCLI flag (use SDK instructions.skipCustomInstructions config instead)
Diagnose session/diagnoseTUI command
View/manage instructions/instructionsTUI command (use SDK session.rpc.instructions.getSources() instead)
Collect debug logs/collect-debug-logsDiagnostic tool (use SDK session.rpc.debug.collectLogs() instead)
IDE integration/ideIDE-specific workflow
Non-interactive Mode
Prompt mode-p, --promptSingle-shot execution
Interactive prompt-i, --interactiveAuto-execute then interactive
Silent output-s, --silentScript-friendly
Continue session--continueResume most recent (use SDK client.rpc.sessions.getLastForContext({ context }) with resumeSession() to prefer sessions from the working directory, or getLastSessionId() for the most recent session overall)
Agent selection--agent <agent>CLI flag (use SDK agents.selected config or session.rpc.agent.select() instead)

Workarounds

Fleet mode

Fleet mode is available through session.rpc.fleet.start() for SDK applications that want the runtime to dispatch parallel sub-agents for a larger objective. Use it when independent subtasks can run concurrently and then be summarized by the main session. For a full guide, see Fleet mode.

Session export

The --share option is not available via SDK. Workarounds:

  1. Collect events manually - Subscribe to session events and build your own export:

    import type { SessionEvent } from "copilot-sdk-supercharged";
    
    const events: SessionEvent[] = [];
    session.on((event) => events.push(event));
    // ... after conversation ...
    const messages = await session.getEvents();
    // Format as markdown yourself
    
  2. Use CLI directly for export - Run the CLI with --share for one-off exports.

Permission control

The SDK uses a deny-by-default permission model. All permission requests (file writes, shell commands, URL fetches, etc.) are denied unless your app provides a permissions.onRequest handler.

Instead of --allow-all-paths or --yolo, use the permission handler:

import { approveAll } from "copilot-sdk-supercharged";

const session = await client.createSession({
    permissions: {
        onRequest: approveAll,
    },
});

Token usage tracking

Instead of /usage, subscribe to usage events:

session.on("assistant.usage", (event) => {
  console.log("Tokens used:", {
    input: event.data.inputTokens,
    output: event.data.outputTokens,
  });
});

Context compaction

Instead of /compact, configure automatic compaction or trigger it manually:

// Automatic compaction via config
const session = await client.createSession({
    state: {
        infiniteSessions: {
            enabled: true,
            backgroundCompactionThreshold: 0.8, // Start background compaction at 80% context utilization
            bufferExhaustionThreshold: 0.95, // Block and compact at 95% context utilization
        },
    },
});

// Manual compaction (experimental)
const result = await session.rpc.history.compact();
console.log(`Removed ${result.tokensRemoved} tokens, ${result.messagesRemoved} messages`);

note

Thresholds are context utilization ratios (0.0-1.0), not absolute token counts.

Plan management

Read and write session plans programmatically:

// Read the current plan
const plan = await session.rpc.plan.read();
if (plan.exists) {
  console.log(plan.content);
}

// Update the plan
await session.rpc.plan.update({ content: "# My Plan\n- Step 1\n- Step 2" });

// Delete the plan
await session.rpc.plan.delete();

Message steering

Inject a message into the current LLM turn without aborting:

// Steer the agent mid-turn
await session.send({ prompt: "Focus on error handling first", mode: "immediate" });

// Default: enqueue for next turn
await session.send({ prompt: "Next, add tests" });

Protocol limitations

The SDK can only access features exposed through the runtime's JSON-RPC protocol. If you need a CLI feature that's not available:

  1. Check for alternatives - Many features have SDK equivalents (see workarounds above)
  2. Use the CLI directly - For one-off operations, invoke the CLI
  3. Request the feature - Open an issue to request protocol support

Version compatibility

SDKSupported runtime protocol versionsEarlier runtimes
Node.js, Python, Go, .NET, Rust, Javav4Not supported: startup fails with a protocol version mismatch error

Grouped options require protocol v4. Old SDKs reject a v4 runtime; new SDKs reject v3 or earlier before creating or resuming sessions. Neither flat option payloads nor legacy aliases are supported. This startup compatibility boundary does not change persisted-session compatibility: existing sessions and stored event formats remain supported.

If you run your own runtime server, upgrade it together with the SDK so that both use the same protocol version.

Check versions at runtime:

const status = await client.getStatus();
console.log("Protocol version:", status.protocolVersion);

See also

Can you improve this documentation? These fine people already did:
copilot-cli-release-app[bot], Patrick Nikoletich, copilot-sdk-mirror-writer[bot], Steve Sanderson, Don Jayamanne, github-actions[bot], Jeremiah Isaacson, Stephen Toub, examon, Sunbrye Ly & Aymen
Edit on GitHub

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
←Move to previous article
→Move to next article
Ctrl+/Jump to the search field
× close