How It Works

  1. Import the client - Get direct API access
  2. Configure authentication - Set your API key
  3. Call file operations - Use methods directly
  4. Handle responses - Process results as needed

Features

  • Direct API Access - No AI dependencies or abstractions
  • Complete Control - Full access to all 8 file operations
  • Type Safety - Full TypeScript support with Pydantic models
  • Custom Integration - Build your own tools and workflows
  • Performance - Minimal overhead, maximum speed

Installation

Refer to the SDK Overview for installation instructions and import paths.

Basic Usage

import { OpenFilesClient } from '@openfiles-ai/sdk/core'

const client = new OpenFilesClient({
  apiKey: process.env.OPENFILES_API_KEY,
  basePath: 'my-project'  // Optional: organize files
})

// Write a file
const writeResult = await client.writeFile({
  path: 'reports/quarterly-summary.md',
  content: '# Q1 2025 Summary\n\nRevenue increased 25%...',
  contentType: 'text/markdown'
})
console.log(`Created file: ${writeResult.data.path}, version ${writeResult.data.version}`)

// Read the file back
const readResult = await client.readFile({ path: 'reports/quarterly-summary.md' })
console.log(`Content: ${readResult.data.content}`)

// Edit the file
await client.editFile({
  path: 'reports/quarterly-summary.md',
  oldString: 'Revenue increased 25%',
  newString: 'Revenue increased 28%'
})

// List all files
const listResult = await client.listFiles({ directory: 'reports' })
console.log(`Found ${listResult.data.files.length} files`)

File Operations

Write File

Create a new file or new version of existing file:
const result = await client.writeFile({
  path: 'docs/api-guide.md',
  content: '# API Guide\n\nThis guide covers...',
  contentType: 'text/markdown'
})
// Creates version 1, or increments version if file exists

Read File

Get file content and metadata:
// Read latest version
const latest = await client.readFile({ path: 'docs/api-guide.md' })

// Read specific version
const v1 = await client.readFile({ 
  path: 'docs/api-guide.md', 
  version: 1 
})

// Get only metadata (no content)
const metadata = await client.getMetadata({ path: 'docs/api-guide.md' })

Edit File

Find and replace specific content:
await client.editFile({
  path: 'config/settings.json',
  oldString: '"debug": false',
  newString: '"debug": true'
})
// Creates new version with the change

List Files

Browse files and directories:
// List all files
const allFiles = await client.listFiles()

// List files in specific directory
const docs = await client.listFiles({ directory: 'docs' })

// Filter by content type
const markdownFiles = await client.listFiles({ 
  contentType: 'text/markdown' 
})

// Paginated results
const page1 = await client.listFiles({ 
  limit: 10, 
  offset: 0 
})

Append to File

Add content to the end of a file:
await client.appendToFile({
  path: 'logs/application.log',
  content: '\n2025-01-15 10:30:00 - User authenticated successfully'
})

Overwrite File

Replace entire file content:
await client.overwriteFile({
  path: 'config/environment.json',
  content: JSON.stringify({ env: 'production', debug: false }, null, 2)
})

Get File Versions

Access complete version history:
const versions = await client.getVersions({ 
  path: 'docs/changelog.md',
  limit: 20 
})

console.log(`File has ${versions.data.total} versions`)
for (const version of versions.data.versions) {
  console.log(`Version ${version.version}: ${version.size} bytes, ${version.createdAt}`)
}

Advanced Configuration

Custom Base URL and Timeouts

const client = new OpenFilesClient({
  apiKey: 'oa-...',
  baseUrl: 'https://api.openfiles.ai/functions/v1/api',
  timeout: 60000,     // 60 second timeout
  retries: 3,         // Retry failed requests
  debug: true         // Enable debug logging
})

File Organization with BasePath

// Separate clients for different projects
const projectA = new OpenFilesClient({
  apiKey: 'oa-...',
  basePath: 'clients/project-a'
})

const projectB = new OpenFilesClient({
  apiKey: 'oa-...',
  basePath: 'clients/project-b'
})

// Files are automatically organized:
// clients/project-a/documents/contract.pdf
// clients/project-b/documents/contract.pdf

Error Handling

import { FileOperationError } from '@openfiles-ai/sdk/core'

try {
  await client.writeFile({
    path: 'documents/report.md',
    content: 'Report content...'
  })
} catch (error) {
  if (error instanceof FileOperationError) {
    console.error(`File operation failed: ${error.message}`)
    console.error(`Error code: ${error.code}`)
    console.error(`HTTP status: ${error.statusCode}`)
    
    if (error.statusCode === 409) {
      // File already exists - use editFile or overwriteFile instead
      console.log('File exists, trying overwrite...')
      await client.overwriteFile({
        path: 'documents/report.md',
        content: 'Updated report content...'
      })
    }
  } else {
    console.error('Unexpected error:', error)
  }
}

Use Cases

Custom CMS Integration

class DocumentManager {
  constructor(private client: OpenFilesClient) {}
  
  async createPost(title: string, content: string, author: string) {
    const slug = title.toLowerCase().replace(/\s+/g, '-')
    const frontmatter = `---
title: "${title}"
author: "${author}"
created: "${new Date().toISOString()}"
---

`
    
    return await this.client.writeFile({
      path: `blog/posts/${slug}.md`,
      content: frontmatter + content,
      contentType: 'text/markdown'
    })
  }
  
  async updatePost(slug: string, newContent: string) {
    // Read current post to preserve frontmatter
    const current = await this.client.readFile({ 
      path: `blog/posts/${slug}.md` 
    })
    
    // Extract frontmatter and update content
    const [, frontmatter, ] = current.data.content.match(/(---[\s\S]*?---)\n\n([\s\S]*)/)
    
    return await this.client.overwriteFile({
      path: `blog/posts/${slug}.md`,
      content: frontmatter + '\n\n' + newContent
    })
  }
}

File Backup System

class BackupManager {
  constructor(private client: OpenFilesClient) {}
  
  async backupFile(sourcePath: string) {
    const file = await this.client.readFile({ path: sourcePath })
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
    const backupPath = `backups/${sourcePath.replace('/', '_')}_${timestamp}`
    
    return await this.client.writeFile({
      path: backupPath,
      content: file.data.content,
      contentType: file.data.mimeType
    })
  }
  
  async restoreFromBackup(backupPath: string, targetPath: string) {
    const backup = await this.client.readFile({ path: backupPath })
    
    return await this.client.overwriteFile({
      path: targetPath,
      content: backup.data.content
    })
  }
}

When to Use Core Client

Choose Core Client when you need:
  • Direct API control without AI abstractions
  • Custom file operation workflows
  • Integration with non-AI systems
  • Building your own tools and abstractions
Consider alternatives:

Next Steps