Skip to main content
Build stateful AI agents with the AgentFS TypeScript SDK, supporting both Node.js and browser environments.

Installation

bun add agentfs-sdk

Quick Start

import { AgentFS } from 'agentfs-sdk';

// Open or create an agent filesystem
const agent = await AgentFS.open('./agent.db');

// Use the three main APIs
// Key-value store
await agent.kv.set('key', 'value');
// Filesystem
await agent.fs.writeFile('/file.txt', 'data');
// Tool tracking
await agent.tools.record(...);

Core APIs

AgentFS Class

The main entry point for all AgentFS operations.

AgentFS.open(path: string, options?: AgentFSOptions)

Creates or opens an AgentFS database.
interface AgentFSOptions {
  // Optional configuration
  readonly?: boolean;  // Open in read-only mode
}

const agent = await AgentFS.open('./my-agent.db');
const readOnlyAgent = await AgentFS.open(
  './agent.db',
  { readonly: true }
);

Properties

  • kv: Key-value store interface
  • fs: Filesystem interface
  • tools: Tool call tracking interface
  • db: Direct access to the underlying Turso database

Key-Value Store API

Fast, typed storage for agent state and configuration.

kv.set(key: string, value: any)

Store a value with automatic JSON serialization.
await agent.kv.set('user:123', {
  name: 'Alice',
  preferences: { theme: 'dark' }
});

await agent.kv.set('session:current', 'abc-123');
await agent.kv.set('counter', 42);

kv.get<T>(key: string): Promise<T | null>

Retrieve a value with automatic deserialization.
interface UserData {
  name: string;
  preferences: { theme: string };
}

const user = await agent.kv.get<UserData>('user:123');
if (user) {
  console.log(user.name); // Type-safe access
}

kv.delete(key: string)

Remove a key-value pair.
await agent.kv.delete('session:expired');

kv.list(options?: ListOptions)

List keys with optional filtering.
interface ListOptions {
  prefix?: string;  // Filter by key prefix
  limit?: number;   // Maximum results
  cursor?: string;  // Pagination cursor
}

// List all user keys
const userKeys = await agent.kv.list(
  { prefix: 'user:' }
);

// Paginated listing
const page1 = await agent.kv.list({ limit: 10 });
const page2 = await agent.kv.list({
  limit: 10,
  cursor: page1.cursor
});

kv.clear()

Remove all key-value pairs.
await agent.kv.clear();

Filesystem API

POSIX-like filesystem operations for managing agent data.

fs.writeFile(path: string, data: string | Buffer)

Write data to a file, creating parent directories as needed.
// Write text
await agent.fs.writeFile('/reports/summary.md', '# Report\nContent...');

// Write binary data
const imageBuffer = await fetch(url).then(r => r.arrayBuffer());
await agent.fs.writeFile('/images/chart.png', Buffer.from(imageBuffer));

fs.readFile(path: string): Promise<Buffer>

Read file contents as a Buffer.
const data = await agent.fs.readFile('/reports/summary.md');
const text = data.toString('utf-8');

// For JSON files
const jsonData = await agent.fs.readFile('/config.json');
const config = JSON.parse(jsonData.toString());

fs.mkdir(path: string, options?: MkdirOptions)

Create a directory.
interface MkdirOptions {
  recursive?: boolean;  // Create parent directories if needed
}

await agent.fs.mkdir('/reports/2024/Q4', { recursive: true });

fs.readdir(path: string): Promise<string[]>

List directory contents.
const files = await agent.fs.readdir('/reports');
// Returns: ['summary.md', '2024/', 'archive/']

// Check each entry type
for (const entry of files) {
  const stats = await agent.fs.stat(`/reports/${entry}`);
  if (stats.isDirectory()) {
    console.log(`Directory: ${entry}`);
  } else {
    console.log(`File: ${entry} (${stats.size} bytes)`);
  }
}

fs.stat(path: string): Promise<Stats>

Get file or directory metadata.
interface Stats {
  size: number;        // File size in bytes
  mode: number;        // File mode/permissions
  mtime: number;       // Modified time (Unix timestamp)
  ctime: number;       // Created time (Unix timestamp)
  isFile(): boolean;
  isDirectory(): boolean;
}

const stats = await agent.fs.stat('/reports/summary.md');
console.log(`Size: ${stats.size} bytes`);
console.log(`Modified: ${new Date(stats.mtime * 1000)}`);

fs.exists(path: string): Promise<boolean>

Check if a file or directory exists.
if (await agent.fs.exists('/reports/draft.md')) {
  console.log('Draft exists');
}

fs.rm(path: string, options?: RmOptions)

Remove a file or directory.
interface RmOptions {
  recursive?: boolean;  // Remove directories and contents
  force?: boolean;     // Don't error if doesn't exist
}

// Remove a file
await agent.fs.rm('/reports/old.md');

// Remove directory tree
await agent.fs.rm('/archive', { recursive: true });

// Safe removal
await agent.fs.rm('/maybe-exists.txt', { force: true });

fs.rename(oldPath: string, newPath: string)

Move or rename a file or directory.
await agent.fs.rename('/reports/draft.md', '/reports/final.md');
await agent.fs.rename('/temp', '/archive/2024');

fs.copyFile(src: string, dest: string)

Copy a file to a new location.
await agent.fs.copyFile('/reports/template.md', '/reports/new-report.md');

Tool Call Tracking API

Record and query agent tool invocations for debugging and compliance.

tools.record(name, startTime, endTime, input, output)

Record a tool invocation.
await agent.tools.record(
  name: string,           // Tool identifier
  startTime: number,      // Unix timestamp (seconds)
  endTime: number,        // Unix timestamp (seconds)
  input: any,            // Tool input (JSON-serializable)
  output: any            // Tool output (JSON-serializable)
);

// Example: Track an API call
const start = Date.now() / 1000;
const response = await callOpenAI(prompt);

await agent.tools.record(
  'openai_completion',
  start,
  Date.now() / 1000,
  { prompt, model: 'gpt-4', temperature: 0.7 },
  { response, tokensUsed: 150 }
);

tools.list(options?: ToolListOptions)

Query recorded tool calls.
interface ToolListOptions {
  limit?: number;      // Maximum results
  offset?: number;     // Skip results
  name?: string;       // Filter by tool name
  since?: number;      // After timestamp
  until?: number;      // Before timestamp
}

// Get recent tool calls
const recent = await agent.tools.list({ limit: 10 });

// Get specific tool usage
const searches = await agent.tools.list({
  name: 'web_search',
  limit: 100
});

// Get calls from last hour
const lastHour = await agent.tools.list({
  since: Date.now() / 1000 - 3600
});

tools.get(id: string)

Get details of a specific tool call.
const toolCall = await agent.tools.get('call_123abc');
console.log('Duration:', toolCall.endTime - toolCall.startTime, 'seconds');

tools.delete(id: string)

Remove a tool call record.
await agent.tools.delete('call_123abc');

tools.clear()

Remove all tool call records.
await agent.tools.clear();

Browser Support

AgentFS works in browser environments using WebAssembly:
<!DOCTYPE html>
<html>
<head>
  <script type="module">
    import { AgentFS } from 'https://unpkg.com/agentfs-sdk/dist/browser.js';

    const agent = await AgentFS.open('browser-agent.db');

    // All APIs work the same in browser
    await agent.kv.set('browser:data', { platform: 'web' });
    await agent.fs.writeFile('/notes.txt', 'Hello from browser!');
  </script>
</head>
</html>

Support