TypeScript/JavaScript SDK
Vollständige Referenz für das AgentFS TypeScript- und JavaScript SDK
Erstellen Sie zustandsbehaftete KI-Agenten mit dem AgentFS TypeScript SDK, das sowohl Node.js- als auch Browser-Umgebungen unterstützt.
Installation
npm install agentfs-sdk
bun add agentfs-sdk
import { AgentFS } from "npm:agentfs-sdk";
Schnellstart
import { AgentFS } from 'agentfs-sdk';
// Persistent storage with identifier
const agent = await AgentFS.open({ id: 'my-agent' });
// Creates: .agentfs/my-agent.db
// Or use ephemeral in-memory database
const ephemeralAgent = await AgentFS.open();
// 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(...);
Kern-APIs
AgentFS-Klasse
Der zentrale Einstiegspunkt für alle AgentFS-Operationen.
AgentFS.open(options?: AgentFSOptions)
Erstellt eine AgentFS-Datenbank oder öffnet eine bestehende.
interface AgentFSOptions {
/**
* Optional unique identifier for the agent.
* - If provided: Creates persistent storage at `.agentfs/{id}.db`
* - If omitted: Uses ephemeral in-memory database
*/
id?: string;
}
// Persistent storage
const agent = await AgentFS.open({ id: 'my-agent' });
// Creates: .agentfs/my-agent.db
// Ephemeral in-memory database
const ephemeralAgent = await AgentFS.open();
Eigenschaften
kv: Schnittstelle für den Key-Value Storefs: Schnittstelle für das Dateisystemtools: Schnittstelle für die Tool-Call-Verfolgungdb: Direkter Zugriff auf die zugrunde liegende Turso-Datenbank
Key-Value-Store-API
Schneller, typisierter Speicher für Agentenstatus und -konfiguration.
kv.set(key: string, value: any)
Speichert einen Wert mit automatischer JSON-Serialisierung.
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 | undefined>
Ruft einen Wert mit automatischer Deserialisierung ab.
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)
Entfernt ein Key-Value-Paar.
await agent.kv.delete('session:expired');
kv.list(prefix: string): Promise<{ key: string, value: any }[]>
Listet Schlüssel auf, die einem Präfix entsprechen.
// List all user keys
const userEntries = await agent.kv.list('user:');
for (const { key, value } of userEntries) {
console.log(key, value);
}
// List all keys (empty prefix)
const allEntries = await agent.kv.list('');
Dateisystem-API
POSIX-ähnliche Dateisystemoperationen zur Verwaltung von Agentendaten.
fs.writeFile(path: string, data: string | Buffer)
Schreibt Daten in eine Datei und erstellt bei Bedarf übergeordnete Verzeichnisse.
// 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, options?: BufferEncoding): Promise<Buffer | string>
Liest Dateiinhalte. Gibt standardmäßig einen Buffer zurück oder einen String, wenn eine Kodierung angegeben wurde.
// Read as Buffer (default)
const data = await agent.fs.readFile('/reports/summary.md');
const text = data.toString('utf-8');
// Read as string with encoding
const content = await agent.fs.readFile('/reports/summary.md', 'utf-8');
// For JSON files
const jsonData = await agent.fs.readFile('/config.json');
const config = JSON.parse(jsonData.toString());
fs.readdir(path: string): Promise<string[]>
Listet den Inhalt eines Verzeichnisses auf.
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>
Ruft Metadaten einer Datei oder eines Verzeichnisses ab.
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>
Prüft, ob eine Datei oder ein Verzeichnis existiert.
if (await agent.fs.exists('/reports/draft.md')) {
console.log('Draft exists');
}
fs.deleteFile(path: string)
Löscht eine Datei.
await agent.fs.deleteFile('/reports/old.md');
Tool-Call-Verfolgungs-API
Zeichnet Tool-Aufrufe von Agenten auf und fragt sie ab – für Debugging und Compliance.
tools.record(name, started_at, completed_at, parameters?, result?, error?): Promise<number>
Zeichnet einen Tool-Aufruf auf.
await agent.tools.record(
name: string, // Tool identifier
started_at: number, // Unix timestamp (seconds)
completed_at: number, // Unix timestamp (seconds)
parameters?: any, // Tool parameters (JSON-serializable)
result?: any, // Tool result (JSON-serializable)
error?: string // Error message if failed
);
// Example: Track an API call
const start = Date.now() / 1000;
const response = await callOpenAI(prompt);
const id = await agent.tools.record(
'openai_completion',
start,
Date.now() / 1000,
{ prompt, model: 'gpt-4', temperature: 0.7 },
{ response, tokensUsed: 150 }
);
tools.get(id: number): Promise<ToolCall | undefined>
Ruft Details zu einem bestimmten Tool-Aufruf ab.
const toolCall = await agent.tools.get(42);
if (toolCall) {
console.log('Duration:', toolCall.duration_ms, 'ms');
}
Browser-Unterstützung
AgentFS funktioniert in Browser-Umgebungen mithilfe von WebAssembly:
<!DOCTYPE html>
<html>
<head>
<script type="module">
import { AgentFS } from 'https://unpkg.com/agentfs-sdk/dist/browser.js';
const agent = await AgentFS.open({ id: 'browser-agent' });
// 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
- GitHub Issues – Fehlerberichte und Feature-Anfragen
- Discord – Community-Support und Diskussionen
- Examples – Beispielanwendungen