npm package: @limo-labs/deity-adapter-copilot
Description: GitHub Copilot SDK adapter for Deity framework
Author: Limo Labs
Latest version: 0.2.2

# @limo-labs/deity-adapter-copilot

GitHub Copilot SDK adapter for the Deity framework.

## Overview

This adapter enables Deity agents to use GitHub Copilot's language models (GPT-4o, Claude Opus, o1, etc.) through the Copilot SDK. It implements Deity's `LLMAdapter` interface and handles the conversion between Deity's tool format and Copilot SDK's native tool calling.

## Features

- **Native Tool Support**: Uses Copilot SDK's built-in tool calling for reliable execution
- **Disposable Sessions**: Creates fresh sessions for each request, optimized for Deity's stateless design
- **Multiple Models**: Support for GPT-4o, Claude Opus 4.6, o1, o1-mini, and other Copilot-supported models
- **Tool Call Tracking**: Automatically tracks tool executions via hooks
- **Environment Isolation**: Blocks environment tools to ensure only registered tools are used

## Installation

```bash
npm install @limo-labs/deity-adapter-copilot
```

**Peer Dependencies:**
- `@limo-labs/deity`: ^0.2.0-alpha.0
- `@github/copilot-sdk`: ^0.1.25

## Basic Usage

```typescript
import { CopilotSDKAdapter } from '@limo-labs/deity-adapter-copilot';
import { Agent, createTool } from '@limo-labs/deity';
import { z } from 'zod';

// Create adapter
const adapter = new CopilotSDKAdapter({
  model: 'claude-opus-4.6',  // or 'gpt-4o', 'o1', etc.
  debug: true  // Enable logging
});

// Initialize adapter
await adapter.initialize();

// Define a tool
const searchTool = createTool({
  name: 'search',
  description: 'Search for information',
  inputSchema: z.object({
    query: z.string()
  }),
  execute: async (input, ctx) => {
    // Your search implementation
    return `Results for: ${input.query}`;
  }
});

// Create agent with adapter
const agent = new Agent({
  name: 'research-agent',
  systemPrompt: 'You are a helpful research assistant.',
  tools: [searchTool],
  llmAdapter: adapter
});

// Execute agent
const result = await agent.execute({
  input: { topic: 'AI agents' }
});

// Cleanup
await adapter.cleanup();
```

## Configuration Options

```typescript
interface CopilotSDKAdapterConfig {
  /**
   * Model to use (default: 'gpt-4o')
   * Options: 'gpt-4o', 'claude-opus-4.6', 'o1', 'o1-mini', etc.
   */
  model?: string;

  /**
   * Custom Copilot CLI URL (optional)
   * If not provided, SDK will auto-manage the CLI
   */
  cliUrl?: string;

  /**
   * Callback for streaming response chunks (optional)
   */
  onStreamChunk?: (chunk: string) => void;

  /**
   * Callback for reasoning/thinking chunks (optional)
   */
  onReasoningChunk?: (chunk: string) => void;

  /**
   * Enable debug logging (default: false)
   */
  debug?: boolean;
}
```

## Architecture

### Disposable Session Pattern

This adapter uses a **disposable session pattern** optimized for Deity's stateless design:

1. **Create**: A new session is created for each `generate()` call
2. **Use**: Session executes the request and tool calls
3. **Destroy**: Session is immediately destroyed in a `finally` block

**Why disposable sessions?**

- Deity uses an intelligent memory system instead of traditional chat history
- Retaining full chat history consumes significant context with low information density
- Each request should be self-contained based on dynamically reconstructed context
- Sessions are lightweight to create/destroy

```typescript
async generate(messages, tools, config, ctx) {
  const session = await this.client.createSession({...});

  try {
    // Execute request
    const result = await session.sendAndWait({ prompt });
    return result;
  } catch (error) {
    await session.destroy();
    throw error;
  } finally {
    // Always destroy session
    await session.destroy();
  }
}
```

### Tool Execution Model

The adapter uses Copilot SDK's native tool support:

1. **Registration**: Deity tools are converted to SDK tools using `defineTool()`
2. **Execution**: SDK handles the tool calling loop automatically
3. **Tracking**: `onPostToolUse` hook tracks tool calls for Deity compatibility
4. **Return**: Tool calls are marked as `_alreadyExecuted` to prevent re-execution

```typescript
// Tool conversion
const copilotTool = defineTool(tool.name, {
  description: tool.description,
  parameters: tool.inputSchema,  // Zod schema (v4 has native toJSONSchema())
  handler: async (args) => {
    // Execute Deity tool
    return await tool.execute(args, ctx);
  }
});

// Hook for tracking
hooks: {
  onPostToolUse: async (input) => {
    this.toolCallHistory.push({
      id: `call_${Date.now()}_${Math.random()}`,
      name: input.toolName,
      arguments: input.toolArgs,
      _alreadyExecuted: true  // Prevent re-execution
    });
  }
}
```

### Environment Tool Isolation

The adapter excludes all environment tools to ensure only registered tools are used:

```typescript
excludedTools: [
  'bash', 'shell', 'view', 'create', 'edit',
  'web_fetch', 'sql', 'grep', 'glob', 'task',
  // ... and more
]
```

This prevents the LLM from calling tools you haven't explicitly registered.

## Supported Models

- `gpt-4o` (default)
- `claude-opus-4.6`
- `o1`
- `o1-mini`
- Other models supported by Copilot SDK

## Advanced Usage

### Custom CLI Management

```typescript
const adapter = new CopilotSDKAdapter({
  cliUrl: 'http://localhost:9090',  // Custom CLI server
  model: 'gpt-4o'
});
```

### Streaming Responses

```typescript
const adapter = new CopilotSDKAdapter({
  model: 'gpt-4o',
  onStreamChunk: (chunk) => {
    process.stdout.write(chunk);
  },
  onReasoningChunk: (chunk) => {
    console.log('[Reasoning]', chunk);
  }
});
```

### Debug Logging

```typescript
const adapter = new CopilotSDKAdapter({
  debug: true  // Enables detailed logging
});
```

## Validation

This adapter has been validated with multi-turn tool calling conversations, long system messages, multiple tool registrations, complex Zod schemas, and error handling.

## Troubleshooting

### Tools not being called

1. Check that `excludedTools` includes environment tools
2. Verify tool schemas are valid Zod v4 schemas
3. Enable debug logging to see tool registration

### Session errors

1. Ensure `initialize()` is called before `generate()`
2. Check that CLI is accessible (if using custom cliUrl)
3. Verify Copilot SDK is properly installed

### Tool execution failures

1. Check that ExecutionContext is available
2. Verify tool handler implementation
3. Enable debug logging to see execution details

## Development

```bash
# Install dependencies
npm install

# Build
npm run build

# Type check
npm run type-check

# Lint
npm run lint

# Test
npm test
```

## License

MIT

## Related

- [Deity Framework](https://github.com/Limo-Labs/Limo-Deity)
- [GitHub Copilot SDK](https://github.com/github/copilot-sdk)