# TypeScript/JavaScript SDK

> Vollständige Referenz für das AgentFS TypeScript- und JavaScript SDK
> Canonical HTML: https://tursodb.cn/de/docs/agentfs/sdk/typescript/
> Upstream Source (MIT): https://docs.turso.tech/agentfs/sdk/typescript
> Language: de

---
Erstellen Sie zustandsbehaftete KI-Agenten mit dem AgentFS TypeScript SDK, das sowohl Node.js- als auch Browser-Umgebungen unterstützt.

## Installation

<div class="doc-tabs" data-doc-tabs>
<div class="doc-tab-list" role="tablist">
<button type="button" role="tab" class="doc-tab-btn is-active" aria-selected="true" data-tab-idx="0">npm</button>
<button type="button" role="tab" class="doc-tab-btn" aria-selected="false" data-tab-idx="1">bun</button>
<button type="button" role="tab" class="doc-tab-btn" aria-selected="false" data-tab-idx="2">deno</button>
</div>
<div class="doc-tab-panel is-active" role="tabpanel" data-tab-panel="0">

```bash
npm install agentfs-sdk
```

</div>
<div class="doc-tab-panel" role="tabpanel" data-tab-panel="1" hidden>

```bash
bun add agentfs-sdk
```

</div>
<div class="doc-tab-panel" role="tabpanel" data-tab-panel="2" hidden>

```typescript
import { AgentFS } from "npm:agentfs-sdk";
```

</div>
</div>


## Schnellstart

```typescript
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.

```typescript
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 Store
* `fs`: Schnittstelle für das Dateisystem
* `tools`: Schnittstelle für die Tool-Call-Verfolgung
* `db`: 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.

```typescript
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.

```typescript
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.

```typescript
await agent.kv.delete('session:expired');
```

#### `kv.list(prefix: string): Promise<{ key: string, value: any }[]>`

Listet Schlüssel auf, die einem Präfix entsprechen.

```typescript
// 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.

```typescript
// 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.

```typescript
// 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.

```typescript
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.

```typescript
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.

```typescript
if (await agent.fs.exists('/reports/draft.md')) {
  console.log('Draft exists');
}
```

#### `fs.deleteFile(path: string)`

Löscht eine Datei.

```typescript
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.

```typescript
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.

```typescript
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:

```html
<!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](https://github.com/tursodatabase/agentfs/issues) – Fehlerberichte und Feature-Anfragen
* [Discord](https://tur.so/discord) – Community-Support und Diskussionen
* [Examples](https://github.com/tursodatabase/agentfs/tree/main/examples) – Beispielanwendungen
