> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sammylabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Migration Guide

> Upgrade from legacy versions of SAMMY Three to the latest release

# Migration Guide

Smoothly upgrade from legacy versions of SAMMY Three to take advantage of new features and improvements.

## Overview

The latest version of SAMMY Three includes significant improvements and new features. This guide will help you migrate your existing implementation.

<Columns cols={3}>
  <Card title="Breaking Changes" icon="triangle-exclamation">
    Important API changes that require updates
  </Card>

  <Card title="New Features" icon="sparkles">
    Exciting capabilities to adopt
  </Card>

  <Card title="Deprecations" icon="clock">
    Features being phased out
  </Card>
</Columns>

## Version Comparison

### What's New

<Steps>
  <Step title="Audio Processing" icon="waveform">
    Advanced noise suppression with AI-powered filtering and environment presets
  </Step>

  <Step title="Interactive Guides" icon="map">
    Built-in walkthrough system with URL activation and progress tracking
  </Step>

  <Step title="MCP Integration" icon="plug">
    Model Context Protocol support for dynamic tool discovery
  </Step>

  <Step title="Worker Architecture" icon="network-wired">
    Improved performance with background workers and CSP compliance
  </Step>

  <Step title="Critical DOM Renders" icon="crosshairs">
    Automatic capture at conversation boundaries for better context
  </Step>
</Steps>

## Migration Steps

### Step 1: Update Package

<CodeGroup>
  ```bash npm theme={null}
  npm uninstall @sammy-labs/sammy-three-legacy
  npm install @sammy-labs/sammy-three
  ```

  ```bash yarn theme={null}
  yarn remove @sammy-labs/sammy-three-legacy
  yarn add @sammy-labs/sammy-three
  ```

  ```bash pnpm theme={null}
  pnpm remove @sammy-labs/sammy-three-legacy
  pnpm add @sammy-labs/sammy-three
  ```
</CodeGroup>

### Step 2: Update Imports

<Tabs>
  <Tab title="Components">
    ```tsx theme={null}
    // ❌ Old
    import { SammyAgent } from '@sammy-labs/sammy-three-legacy';

    // ✅ New
    import { 
      SammyAgentProvider, 
      useSammyAgentContext 
    } from '@sammy-labs/sammy-three';
    ```
  </Tab>

  <Tab title="Styles">
    ```tsx theme={null}
    // ❌ Old
    import '@sammy-labs/sammy-three-legacy/dist/styles.css';

    // ✅ New
    import '@sammy-labs/sammy-three/styles.css';
    ```
  </Tab>

  <Tab title="Types">
    ```tsx theme={null}
    // ❌ Old
    import type { 
      AgentConfig,
      AgentState 
    } from '@sammy-labs/sammy-three-legacy';

    // ✅ New
    import type { 
      SammyAgentConfig,
      AgentSession 
    } from '@sammy-labs/sammy-three';
    ```
  </Tab>
</Tabs>

### Step 3: Update Configuration

The configuration structure has been updated for better organization.

<CodeGroup>
  ```tsx Old Configuration theme={null}
  const agent = new SammyAgent({
    apiKey: 'your-api-key',
    apiUrl: 'https://api.example.com',
    model: 'gemini-1.5',
    voice: 'default',
    quality: 'high',
    debug: true,
  });
  ```

  ```tsx New Configuration theme={null}
  const config = {
    auth: {
      token: 'your-jwt-token',
      baseUrl: 'https://api.example.com',
      onTokenExpired: () => refreshToken(),
    },
    model: 'models/gemini-2.5-flash-preview-native-audio-dialog',
    defaultVoice: 'aoede',
    captureConfig: {
      quality: 0.9,
    },
    debugLogs: true,
  };
  ```
</CodeGroup>

### Step 4: Update Component Structure

<CodeGroup>
  ```tsx Old Pattern theme={null}
  class App extends Component {
    constructor() {
      this.agent = new SammyAgent(config);
    }
    
    componentDidMount() {
      this.agent.connect();
    }
    
    componentWillUnmount() {
      this.agent.disconnect();
    }
    
    render() {
      return <ChatInterface agent={this.agent} />;
    }
  }
  ```

  ```tsx New Pattern theme={null}
  function App() {
    const auth = useAuth();
    
    return (
      <SammyAgentProvider
        config={{
          auth: auth,
          captureMethod: 'render',
        }}
        onError={handleError}
      >
        <ChatInterface />
      </SammyAgentProvider>
    );
  }

  function ChatInterface() {
    const { startAgent, stopAgent } = useSammyAgentContext();
    
    return (
      <div>
        <button onClick={() => startAgent({ agentMode: 'user' })}>
          Start
        </button>
      </div>
    );
  }
  ```
</CodeGroup>

### Step 5: Update Method Calls

<Tabs>
  <Tab title="Connection">
    ```tsx theme={null}
    // ❌ Old
    agent.connect();
    agent.disconnect();

    // ✅ New
    await startAgent({ agentMode: 'user' });
    stopAgent();
    ```
  </Tab>

  <Tab title="Messaging">
    ```tsx theme={null}
    // ❌ Old
    agent.sendMessage('Hello');
    agent.onMessage((msg) => console.log(msg));

    // ✅ New
    sendMessage('Hello');
    // Messages handled via provider callbacks
    ```
  </Tab>

  <Tab title="Audio">
    ```tsx theme={null}
    // ❌ Old
    agent.mute();
    agent.unmute();
    agent.getVolume();

    // ✅ New
    toggleMuted();
    // Access volume via context
    const { agentVolume, userVolume } = useSammyAgentContext();
    ```
  </Tab>
</Tabs>

## Breaking Changes

### Authentication

<Warning>
  API keys are no longer supported. You must use JWT tokens for authentication.
</Warning>

```tsx theme={null}
// ❌ Old: API Key
const agent = new SammyAgent({
  apiKey: 'sk_live_abc123',
});

// ✅ New: JWT Token
const config = {
  auth: {
    token: 'eyJhbGciOiJIUzI1NiIs...',
    onTokenExpired: async () => {
      const newToken = await refreshToken();
      // Update configuration
    },
  },
};
```

### Event Handling

Events are now handled through provider callbacks instead of event emitters.

```tsx theme={null}
// ❌ Old: Event Emitters
agent.on('error', handleError);
agent.on('connected', handleConnected);
agent.on('message', handleMessage);

// ✅ New: Provider Callbacks
<SammyAgentProvider
  onError={handleError}
  onConnectionStateChange={handleConnectionChange}
  onTurnComplete={handleTurnComplete}
>
```

### Screen Capture

Capture configuration has been restructured.

```tsx theme={null}
// ❌ Old
const agent = new SammyAgent({
  capture: true,
  captureQuality: 'high',
  captureRate: 30,
});

// ✅ New
const config = {
  captureMethod: 'render', // or 'video'
  captureConfig: {
    quality: 0.9,
    frameRate: 30,
    enableAudioAdaptation: true,
  },
};
```

## New Features to Adopt

### Audio Processing

Take advantage of the new audio processing capabilities:

```tsx theme={null}
const config = {
  audioConfig: {
    noiseSuppression: {
      enabled: true,
      enhancementLevel: 'medium',
    },
    noiseGate: {
      enabled: true,
      threshold: 0.04,
    },
    environmentPreset: 'office',
  },
};
```

### Interactive Guides

Implement the new guides system:

```tsx theme={null}
import { useGuidesManager } from '@sammy-labs/sammy-three';

const guides = useGuidesManager({
  enabled: true,
  authConfig: auth,
  autoStartFromURL: true,
  onStartAgent: startAgent,
});

// Start a guide
await guides.startWalkthrough('onboarding-v1');
```

### MCP Tools

Enable dynamic tool discovery:

```tsx theme={null}
const config = {
  mcp: {
    enabled: true,
    servers: [{
      name: 'hubspot',
      type: 'sse',
      sse: {
        url: 'https://mcp.example.com/sse',
        apiKey: process.env.MCP_API_KEY,
      },
    }],
  },
};
```

### Worker Mode

Enable for better performance:

```tsx theme={null}
const config = {
  observability: {
    enabled: true,
    useWorker: true,
    workerConfig: {
      batchSize: 50,
      batchIntervalMs: 5000,
    },
  },
};
```

## Deprecated Features

### Features Being Removed

<Tabs>
  <Tab title="Direct API Access">
    **Deprecated:** Direct API client access

    ```tsx theme={null}
    // ❌ Deprecated
    agent.api.get('/endpoint');

    // ✅ Use API client separately
    import { SammyApiClient } from '@sammy-labs/sammy-three';
    const apiClient = new SammyApiClient(config);
    ```
  </Tab>

  <Tab title="Synchronous Methods">
    **Deprecated:** Synchronous connection methods

    ```tsx theme={null}
    // ❌ Deprecated
    agent.connect();
    const status = agent.getStatus();

    // ✅ Use async methods
    await startAgent({ agentMode: 'user' });
    const { agentStatus } = useSammyAgentContext();
    ```
  </Tab>

  <Tab title="Global State">
    **Deprecated:** Global agent instance

    ```tsx theme={null}
    // ❌ Deprecated
    window.sammyAgent = new SammyAgent();

    // ✅ Use React context
    const agent = useSammyAgentContext();
    ```
  </Tab>
</Tabs>

## Common Migration Issues

### Issue: Token Expiration

<Note>
  The new version requires proper token refresh handling.
</Note>

```tsx theme={null}
// Solution: Implement token refresh
const config = {
  auth: {
    token: currentToken,
    onTokenExpired: async () => {
      const newToken = await fetch('/refresh-token');
      updateConfig({ auth: { token: newToken } });
    },
  },
};
```

### Issue: Missing Microphone Permission

<Note>
  Permission handling is now more explicit.
</Note>

```tsx theme={null}
// Solution: Use permission hook
import { useMicrophonePermission } from '@sammy-labs/sammy-three';

const { permission, requestPermission } = useMicrophonePermission();
if (permission !== 'granted') {
  await requestPermission();
}
```

### Issue: Worker Initialization Failed

<Note>
  Some environments may not support workers.
</Note>

```tsx theme={null}
// Solution: Disable workers if needed
const config = {
  observability: {
    useWorker: false, // Fallback to main thread
  },
};
```

## Testing Your Migration

### Migration Checklist

<Check>
  Update all package imports
</Check>

<Check>
  Replace class components with hooks
</Check>

<Check>
  Update authentication to use JWT tokens
</Check>

<Check>
  Convert event handlers to callbacks
</Check>

<Check>
  Test audio in target environments
</Check>

<Check>
  Verify screen capture works correctly
</Check>

<Check>
  Test error handling flows
</Check>

<Check>
  Validate performance improvements
</Check>

### Testing Script

```tsx theme={null}
// Test your migration with this script
async function testMigration() {
  const tests = {
    authentication: false,
    connection: false,
    audio: false,
    capture: false,
    tools: false,
  };
  
  try {
    // Test authentication
    const auth = await getAuthToken();
    tests.authentication = !!auth;
    
    // Test connection
    const success = await startAgent({ agentMode: 'user' });
    tests.connection = success;
    
    // Test audio
    const { permission } = await checkMicrophonePermission();
    tests.audio = permission === 'granted';
    
    // Add more tests...
    
  } catch (error) {
    console.error('Migration test failed:', error);
  }
  
  console.table(tests);
}
```

## Support Resources

<Columns cols={3}>
  <Card title="Documentation" icon="book" href="/implementation">
    Complete implementation guide
  </Card>

  <Card title="API Reference" icon="code" href="/features/api-reference">
    Detailed API documentation
  </Card>

  <Card title="GitHub Issues" icon="github" href="https://github.com/SammyClub/package/issues">
    Report migration issues
  </Card>
</Columns>

## Version History

| Version | Release Date | Key Changes                       |
| ------- | ------------ | --------------------------------- |
| 3.0.0   | 2024-01      | Complete rewrite with React hooks |
| 2.5.0   | 2023-12      | Added MCP support                 |
| 2.4.0   | 2023-11      | Audio processing improvements     |
| 2.3.0   | 2023-10      | Worker architecture               |
| 2.2.0   | 2023-09      | Interactive guides                |
| 2.1.0   | 2023-08      | Critical DOM renders              |
| 2.0.0   | 2023-07      | JWT authentication                |
