Skip to main content
Experimental API - Context Engine SDK is experimental and subject to breaking changes.

DirectContext

This class provides explicit file indexing via API calls with the ability to import and export state to avoid re-indexing between sessions.

Examples

Example 1: Simple Usage

Upload files and ask questions immediately:
import { DirectContext } from '@augmentcode/auggie-sdk';

async function simpleExample() {
  // Create context (authentication is automatic)
  const context = await DirectContext.create();

  // Add files and wait for indexing (default behavior)
  const result = await context.addToIndex([
    { path: 'src/auth.ts', contents: 'export function login(user, pass) { ... }' },
    { path: 'src/user.ts', contents: 'export class User { constructor(id) { ... } }' },
    { path: 'README.md', contents: '# My Project\nAuthentication system' }
  ]);

  console.log(`Newly uploaded: ${result.newlyUploaded.length}`);

  // Ask questions about the code - files are already indexed
  const answer = await context.searchAndAsk(
    'How does the login system work?'
  );
  console.log('Answer:', answer);
}

simpleExample().catch(console.error);

Example 2: Persistent Index

Persist state between sessions to avoid re-indexing. This is useful when you want to save the index state to disk and reload it later without having to re-upload and re-index all files. The saved state file contains metadata about which files are indexed, allowing you to resume from where you left off:
import { DirectContext } from '@augmentcode/auggie-sdk';

// First session: Upload and save
async function uploadAndSave() {
  const context = await DirectContext.create();

  // Upload files
  await context.addToIndex([
    { path: 'src/auth.ts', contents: 'export function login() { ... }' },
    { path: 'src/user.ts', contents: 'export class User { ... }' },
    { path: 'src/database.ts', contents: 'export function connect() { ... }' }
  ]);

  // Save state for later use - this creates a JSON file containing the index metadata
  // so you can reload it later without re-indexing all files
  await context.exportToFile('./my-project-context.json');
  console.log('Context saved!');
  console.log('You can now reload this state in a future session using importFromFile()');
}

// Second session: Load, update incrementally, and save again
async function updateAndSave() {
  // Load previous state - this restores the index without re-uploading files
  const context = await DirectContext.importFromFile('./my-project-context.json');
  console.log('Context loaded from previous session - no re-indexing needed!');

  // Make incremental changes - remove old file and add new one
  await context.removeFromIndex(['src/user.ts']);
  await context.addToIndex([
    { path: 'src/profile.ts', contents: 'export class Profile { /* profile logic */ }' },
    { path: 'src/settings.ts', contents: 'export function updateSettings() { /* settings */ }' }
  ]);
  console.log('Index updated incrementally');

  // Save updated state
  await context.exportToFile('./my-project-context.json');
  console.log('Updated context saved!');
}

// Third session: Load and search
async function loadAndSearch() {
  // Load the updated state
  const context = await DirectContext.importFromFile('./my-project-context.json');
  console.log('Updated context loaded');

  // Search immediately - files are already indexed
  const answer = await context.searchAndAsk(
    'What user management features are implemented?'
  );
  console.log('Answer:', answer);
}

// Run the complete workflow: upload → update → search
uploadAndSave()
  .then(() => updateAndSave())
  .then(() => loadAndSearch())
  .catch(console.error);

Example 3: Batch Upload Then Wait

When you need to upload many files in multiple batches, you can optimize performance by uploading all files first without waiting for indexing, then waiting once at the end. This approach is faster than waiting for indexing after each batch:
import { DirectContext } from '@augmentcode/auggie-sdk';

async function batchExample() {
  const context = await DirectContext.create();

  // Upload multiple batches without waiting for indexing
  await context.addToIndex([
    { path: 'src/auth.ts', contents: 'export function login() { ... }' },
    { path: 'src/user.ts', contents: 'export class User { ... }' }
  ], { waitForIndexing: false });

  await context.addToIndex([
    { path: 'src/database.ts', contents: 'export function connect() { ... }' },
    { path: 'src/api.ts', contents: 'export function createServer() { ... }' }
  ], { waitForIndexing: false });

  // Wait for all files to be indexed
  console.log('Waiting for indexing to complete...');
  await context.waitForIndexing();
  console.log('All files indexed!');

  // Now search - all files are guaranteed to be indexed
  const answer = await context.searchAndAsk(
    'How do the database and auth systems work together?'
  );
  console.log('Answer:', answer);
}

batchExample().catch(console.error);

Example 4: Custom Prompts

Use searchAndAsk with custom prompts for diverse tasks:
import { DirectContext } from '@augmentcode/auggie-sdk';

async function creativeExample() {
  const context = await DirectContext.create();

  // Upload some code
  await context.addToIndex([
    { path: 'src/auth.ts', contents: 'export function login(user, pass) { /* auth logic */ }' },
    { path: 'src/database.ts', contents: 'export function connect() { /* db connection */ }' },
    { path: 'README.md', contents: '# My App\nA secure authentication system' }
  ]);

  // Creative prompts with searchAndAsk
  const poem = await context.searchAndAsk(
    'authentication system',
    'Write a haiku about this authentication code'
  );
  console.log('Haiku:', poem);

  // Generate documentation
  const docs = await context.searchAndAsk(
    'database authentication flow',
    'Write a brief user guide explaining how to use the database authentication flow'
  );
  console.log('Documentation:', docs);

  // Code review style analysis
  const review = await context.searchAndAsk(
    'authentication logic',
    'Provide a code review focusing on security best practices'
  );
  console.log('Code Review:', review);
}

creativeExample().catch(console.error);

Example 5: External LLM Integration

Use search() results with external LLM APIs:
import { DirectContext } from '@augmentcode/auggie-sdk';
// import { Anthropic } from '@anthropic-ai/sdk';
// import OpenAI from 'openai';

async function externalLLMExample() {
  const context = await DirectContext.create();

  // Upload code
  await context.addToIndex([
    { path: 'src/api.ts', contents: 'export function handleRequest() { /* API logic */ }' },
    { path: 'src/auth.ts', contents: 'export function authenticate() { /* auth */ }' },
    { path: 'src/database.ts', contents: 'export function query() { /* db query */ }' }
  ]);

  // Get formatted search results for external LLMs
  const codeContext = await context.search('API request handling');

  // codeContext is a formatted string ready to embed in prompts for
  // Anthropic, OpenAI, or other LLM APIs
  console.log('Code context for LLM:', codeContext);

  // Example: Use with Anthropic Claude (uncomment to use)
  // const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY });
  // const response = await anthropic.messages.create({
  //   model: 'claude-sonnet-4-5-20250929',
  //   max_tokens: 1000,
  //   messages: [{
  //     role: 'user',
  //     content: `Based on this code:\n\n${codeContext}\n\nHow can I improve the error handling in the API?`
  //   }]
  // });
  // console.log('Claude response:', response.content[0].text);

  // Example: Use with OpenAI GPT-5.1 (uncomment to use)
  // const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
  // const completion = await openai.chat.completions.create({
  //   model: 'gpt-5.1',
  //   messages: [{
  //     role: 'user',
  //     content: `Based on this code:\n\n${codeContext}\n\nSuggest performance optimizations for this API.`
  //   }]
  // });
  // console.log('GPT-5.1 response:', completion.choices[0].message.content);


}

externalLLMExample().catch(console.error);

API Reference

DirectContext.create()

Create and initialize a new DirectContext instance.
static async create(options?: DirectContextOptions): Promise<DirectContext>

interface DirectContextOptions {
  apiKey?: string;      // Optional - falls back to env vars or session.json
  apiUrl?: string;      // Optional - falls back to env vars or session.json
  debug?: boolean;      // Enable debug logging (default: false)
}
Parameters:
  • options - Optional configuration object
    • apiKey - API key for authentication (optional)
    • apiUrl - API URL for your tenant (optional)
    • debug - Enable debug logging (optional, default: false)
Authentication Priority:
  1. options.apiKey / options.apiUrl (passed to create())
  2. AUGMENT_API_TOKEN / AUGMENT_API_URL environment variables
  3. ~/.augment/session.json (created by auggie login)
Usage: See complete examples above for full implementation details. Notes:
  • The SDK is source-agnostic - you provide files as {path, contents} objects
  • Files larger than 1MB are rejected during indexing
  • All indexing operations are serialized to ensure consistency
  • State can be saved and loaded to avoid re-indexing

DirectContext.importFromFile()

Create a DirectContext instance from a saved state file (Node.js only).
static async importFromFile(
  filePath: string,
  options?: DirectContextOptions
): Promise<DirectContext>
Parameters:
  • filePath - Path to the saved state file
  • options - Optional configuration object (same as create())
Returns: A DirectContext instance with restored state Usage:
// Load context from saved state
const context = await DirectContext.importFromFile('./my-context.json');
// Files are already indexed, ready to search

DirectContext.import()

Create a DirectContext instance from a saved state object.
static async import(
  state: DirectContextState,
  options?: DirectContextOptions
): Promise<DirectContext>
Parameters:
  • state - The state object to restore from
  • options - Optional configuration object (same as create())
Returns: A DirectContext instance with restored state Usage:
// Load context from state object
const savedState = JSON.parse(stateJson);
const context = await DirectContext.import(savedState);

DirectContext Methods

addToIndex()

Add files to the index. Files can come from any source - memory, disk, API, database, etc.
async addToIndex(
  files: File[],
  options?: { waitForIndexing?: boolean }
): Promise<IndexingResult>

interface File {
  path: string;      // Relative path (e.g., "src/main.ts")
  contents: string;  // File contents as string
}

interface IndexingResult {
  newlyUploaded: string[];     // Paths that were uploaded and indexed
  alreadyUploaded: string[];   // Paths that were skipped (already on server)
}
Parameters:
  • files - Array of file objects with path and contents
  • options - Optional configuration
    • waitForIndexing - If true (default), waits for the newly added files to be indexed before returning
Returns: IndexingResult object with details about what was indexed Notes:
  • Files larger than 1MB will throw an error
  • By default, waits for backend indexing to complete before returning (set waitForIndexing: false to return immediately after upload)
  • If a file with the same path already exists, it will be updated
  • All operations are serialized to ensure consistency
  • The SDK optimizes uploads by checking which blobs the server already has and only uploading missing ones

removeFromIndex()

Remove files from the index by path.
async removeFromIndex(paths: string[]): Promise<void>
Parameters:
  • paths - Array of file paths to remove

clearIndex()

Clear the entire index, removing all files.
async clearIndex(): Promise<void>

getIndexedPaths()

Get the list of currently indexed file paths.
getIndexedPaths(): string[]
Returns: Array of relative file paths that are currently indexed Use Cases:
  • Display indexed files to users
  • Verify which files are included in the index
  • Filter files for targeted searches

Search the codebase and return formatted results as a string.
async search(
  query: string,
  options?: { maxOutputLength?: number }
): Promise<string>
Parameters:
  • query - Natural language search query
  • options - Optional search options
    • maxOutputLength - Maximum character length of the formatted output (default: 20000, max: 80000)
Returns: Formatted string containing the search results, ready for LLM consumption Notes:
  • Returns a formatted string designed for use in LLM prompts
  • The format includes file paths, line numbers, and code content
  • Does NOT wait for indexing - ensure files are indexed before searching by either:
    • Using addToIndex() with waitForIndexing: true (default)
    • Calling waitForIndexing() explicitly before searching
  • Throws an error if the index is empty

searchAndAsk()

Search the indexed codebase and ask an LLM a question about the results. This is a convenience method that combines search() with an LLM call to answer questions about your codebase.
async searchAndAsk(
  searchQuery: string,
  prompt?: string
): Promise<string>
Parameters:
  • searchQuery - The semantic search query to find relevant code (also used as the prompt if no separate prompt is provided)
  • prompt - Optional prompt to ask the LLM about the search results. If not provided, searchQuery is used as the prompt.
Returns: The LLM’s answer to your question Notes:
  • Does NOT wait for indexing - ensure files are indexed before searching by either:
    • Using addToIndex() with waitForIndexing: true (default)
    • Calling waitForIndexing() explicitly before searching
  • Requires AUGMENT_API_TOKEN and AUGMENT_API_URL environment variables for LLM access
Use Cases:
  • Quick Q&A about your codebase
  • Building conversational interfaces
  • Automated code analysis and documentation

waitForIndexing()

Wait for all indexed files to be fully indexed on the backend. This method polls the backend until all files that have been added to the index are confirmed to be indexed and searchable.
async waitForIndexing(): Promise<void>
Returns: Promise that resolves when all files are indexed Notes:
  • Throws an error if indexing times out (default: 10 minutes)
  • Only waits for files that have been added to the index
  • Useful when you want to control when to wait for indexing completion
Use Cases:
  • Batch upload multiple files quickly, then wait for all to be indexed
  • Ensure search results include all recently added files
  • Control timing of indexing waits in complex workflows

exportToFile()

Export the current state to a file (Node.js only).
async exportToFile(filePath: string): Promise<void>
Parameters:
  • filePath - Path to save the state file
Use Cases:
  • Persist indexing state between sessions
  • Avoid re-indexing large codebases
  • Share indexing state across different processes

export()

Export the current state as a JSON object (in-memory).
export(): DirectContextState

interface DirectContextState {
  checkpointId?: string;
  addedBlobs: string[];
  deletedBlobs: string[];
  blobs: BlobEntry[];  // Array of [blobName, path] tuples
}
Returns: State object that can be serialized and stored

FileSystemContext

This class provides automatic indexing and search capabilities for a local directory.

FileSystemContext.create()

Create and initialize a new FileSystemContext instance.
static async create(options: FileSystemContextOptions): Promise<FileSystemContext>

interface FileSystemContextOptions {
  directory: string;      // Path to the workspace directory to index
  auggiePath?: string;    // Path to auggie executable (default: "auggie")
  debug?: boolean;        // Enable debug logging (default: false)
}
Parameters:
  • options - Configuration object
    • directory - Path to the workspace directory to index (required)
    • auggiePath - Path to auggie executable (optional, default: “auggie”)
    • debug - Enable debug logging (optional, default: false)
Usage: See DirectContext examples above for similar patterns. Notes:
  • Automatically indexes the directory on startup
  • Requires auggie to be installed and accessible

FileSystemContext Methods

search()

Search the codebase and return formatted results as a string.
async search(query: string): Promise<string>
Parameters:
  • query - Natural language search query
Returns: Formatted string containing the search results, ready for LLM consumption

searchAndAsk()

Search the indexed codebase and ask an LLM a question about the results.
async searchAndAsk(
  searchQuery: string,
  prompt?: string
): Promise<string>
Parameters:
  • searchQuery - The semantic search query to find relevant code (also used as the prompt if no separate prompt is provided)
  • prompt - Optional prompt to ask the LLM about the search results. If not provided, searchQuery is used as the prompt.
Returns: The LLM’s answer to your question Notes:
  • Requires AUGMENT_API_TOKEN and AUGMENT_API_URL environment variables for LLM access

close()

Close the connection and cleanup resources.
async close(): Promise<void>
Notes:
  • Always call close() when done to cleanup resources

Types

File

Represents a file to be indexed (input type for addToIndex).
interface File {
  path: string;      // Relative path (e.g., "src/main.ts")
  contents: string;  // File contents as string
}

IndexingResult

Result from addToIndex() operation showing what was indexed.
interface IndexingResult {
  newlyUploaded: string[];     // Paths that were uploaded and indexed
  alreadyUploaded: string[];   // Paths that were skipped (already on server)
}
Notes:
  • newlyUploaded: Files that were uploaded to the server and indexed
  • alreadyUploaded: Files that were skipped because:
    • They were already in the local cache with the same content, OR
    • The server already had the blob (detected via find-missing API)

DirectContextOptions

Options for configuring DirectContext.
interface DirectContextOptions {
  apiKey?: string;      // API key for authentication
  apiUrl?: string;      // API URL for your Augment tenant
  debug?: boolean;      // Enable debug logging (default: false)
}

DirectContextState

State for DirectContext that can be saved/loaded.
interface DirectContextState {
  checkpointId?: string;      // Current checkpoint ID
  addedBlobs: string[];       // Blob names added (pending checkpoint)
  deletedBlobs: string[];     // Blob names deleted (pending checkpoint)
  blobs: BlobEntry[];         // List of blobs as [blobName, path] tuples
}

type BlobEntry = [blobName: string, path: string];

FileSystemContextOptions

Options for FileSystem Context.
interface FileSystemContextOptions {
  directory: string;      // Path to the workspace directory to index
  auggiePath?: string;    // Path to auggie executable (default: "auggie")
  debug?: boolean;        // Enable debug logging (default: false)
}

Error Classes

The SDK exports specific error classes for better error handling:

APIError

Thrown when API requests fail.
import { APIError } from '@augmentcode/auggie-sdk';

try {
  const context = await DirectContext.create();
  await context.search('query');
} catch (error) {
  if (error instanceof APIError) {
    console.error('API request failed:', error.message);
    console.error('Status code:', error.status);
  }
}

BlobTooLargeError

Thrown when attempting to index files larger than 1MB.
import { BlobTooLargeError } from '@augmentcode/auggie-sdk';

try {
  await context.addToIndex([
    { path: 'large-file.txt', contents: '...' } // > 1MB
  ]);
} catch (error) {
  if (error instanceof BlobTooLargeError) {
    console.error('File too large:', error.message);
    console.error('File path:', error.path);
    console.error('File size:', error.size);
  }
}

Authentication

The SDK automatically loads credentials from multiple sources in this priority order:
  1. Options parameters: apiKey and apiUrl passed to DirectContext.create()
  2. Environment variables: AUGMENT_API_TOKEN and AUGMENT_API_URL
  3. Session file: ~/.augment/session.json (created by auggie login)
To get credentials:
  1. Sign in to Augment using the CLI: auggie login
  2. Your credentials will be stored in ~/.augment/session.json
  3. The SDK will automatically use them

Error Handling

The SDK throws specific error classes for better error handling:
import { DirectContext, APIError, BlobTooLargeError } from '@augmentcode/auggie-sdk';

try {
  const context = await DirectContext.create();
  await context.addToIndex([
    { path: 'test.ts', contents: '...' }
  ]);
  const results = await context.search('query');
} catch (error) {
  if (error instanceof BlobTooLargeError) {
    console.error('File too large (max 1MB):', error.path);
  } else if (error instanceof APIError) {
    console.error('API request failed:', error.message);
    console.error('Status code:', error.status);
  } else if (error.message.includes('API key is required')) {
    console.error('Missing credentials');
  } else if (error.message.includes('Index not initialized')) {
    console.error('No files indexed yet');
  } else {
    console.error('Operation failed:', error);
  }
}
Common error types:
  • BlobTooLargeError - File exceeds 1MB limit
  • APIError - Network or API request failures
  • Generic errors for missing credentials or uninitialized index