# TypeScript/JavaScript SDK

> AgentFS TypeScript 與 JavaScript SDK 的完整參考文件
> Canonical HTML: https://tursodb.cn/zh-tw/docs/agentfs/sdk/typescript/
> Upstream Source (MIT): https://docs.turso.tech/agentfs/sdk/typescript
> Language: zh-TW

---
使用 AgentFS TypeScript SDK 建構具狀態的 AI 代理，同時支援 Node.js 與瀏覽器環境。

## 安裝

<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>


## 快速開始

```typescript
import { AgentFS } from 'agentfs-sdk';

// 以識別碼建立持久化儲存
const agent = await AgentFS.open({ id: 'my-agent' });
// 建立：.agentfs/my-agent.db

// 或使用短暫的記憶體內資料庫
const ephemeralAgent = await AgentFS.open();

// 使用三大主要 API
// 鍵值儲存
await agent.kv.set('key', 'value');
// 檔案系統
await agent.fs.writeFile('/file.txt', 'data');
// 工具追蹤
await agent.tools.record(...);
```

## 核心 API

### AgentFS 類別

所有 AgentFS 操作的主要進入點。

#### `AgentFS.open(options?: AgentFSOptions)`

建立或開啟 AgentFS 資料庫。

```typescript
interface AgentFSOptions {
  /**
   * 代理的選用唯一識別碼。
   * - 若提供：於 `.agentfs/{id}.db` 建立持久化儲存
   * - 若省略：使用短暫的記憶體內資料庫
   */
  id?: string;
}

// 持久化儲存
const agent = await AgentFS.open({ id: 'my-agent' });
// 建立：.agentfs/my-agent.db

// 短暫的記憶體內資料庫
const ephemeralAgent = await AgentFS.open();
```

#### 屬性

* `kv`：鍵值儲存介面
* `fs`：檔案系統介面
* `tools`：工具呼叫追蹤介面
* `db`：直接存取底層的 Turso 資料庫

### 鍵值儲存 API

用於代理狀態與設定的快速、具型別儲存。

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

儲存值並自動進行 JSON 序列化。

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

取得值並自動進行反序列化。

```typescript
interface UserData {
  name: string;
  preferences: { theme: string };
}

const user = await agent.kv.get<UserData>('user:123');
if (user) {
  console.log(user.name); // 型別安全的存取
}
```

#### `kv.delete(key: string)`

移除鍵值對。

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

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

列出符合指定前綴的鍵。

```typescript
// 列出所有使用者鍵
const userEntries = await agent.kv.list('user:');
for (const { key, value } of userEntries) {
  console.log(key, value);
}

// 列出所有鍵（空前綴）
const allEntries = await agent.kv.list('');
```

### 檔案系統 API

用於管理代理資料的類 POSIX 檔案系統操作。

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

將資料寫入檔案，並視需要建立父目錄。

```typescript
// 寫入文字
await agent.fs.writeFile('/reports/summary.md', '# Report\nContent...');

// 寫入二進位資料
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>`

讀取檔案內容。預設回傳 Buffer，若指定編碼則回傳字串。

```typescript
// 以 Buffer 讀取（預設）
const data = await agent.fs.readFile('/reports/summary.md');
const text = data.toString('utf-8');

// 以指定編碼讀取為字串
const content = await agent.fs.readFile('/reports/summary.md', 'utf-8');

// 用於 JSON 檔案
const jsonData = await agent.fs.readFile('/config.json');
const config = JSON.parse(jsonData.toString());
```

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

列出目錄內容。

```typescript
const files = await agent.fs.readdir('/reports');
// 回傳：['summary.md', '2024/', 'archive/']

// 檢查每個項目的類型
for (const entry of files) {
  const stats = await agent.fs.stat(`/reports/${entry}`);
  if (stats.isDirectory()) {
    console.log(`目錄：${entry}`);
  } else {
    console.log(`檔案：${entry}（${stats.size} 位元組）`);
  }
}
```

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

取得檔案或目錄的中繼資料。

```typescript
interface Stats {
  size: number;        // 檔案大小（位元組）
  mode: number;        // 檔案模式/權限
  mtime: number;       // 修改時間（Unix 時間戳）
  ctime: number;       // 建立時間（Unix 時間戳）
  isFile(): boolean;
  isDirectory(): boolean;
}

const stats = await agent.fs.stat('/reports/summary.md');
console.log(`大小：${stats.size} 位元組`);
console.log(`修改時間：${new Date(stats.mtime * 1000)}`);
```

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

檢查檔案或目錄是否存在。

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

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

刪除檔案。

```typescript
await agent.fs.deleteFile('/reports/old.md');
```

### 工具呼叫追蹤 API

記錄並查詢代理的工具叫用，以供除錯與合規用途。

#### `tools.record(name, started_at, completed_at, parameters?, result?, error?): Promise<number>`

記錄一次工具叫用。

```typescript
await agent.tools.record(
  name: string,           // 工具識別碼
  started_at: number,     // Unix 時間戳（秒）
  completed_at: number,   // Unix 時間戳（秒）
  parameters?: any,       // 工具參數（可 JSON 序列化）
  result?: any,           // 工具結果（可 JSON 序列化）
  error?: string          // 失敗時的錯誤訊息
);

// 範例：追蹤一次 API 呼叫
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>`

取得特定工具呼叫的詳細資料。

```typescript
const toolCall = await agent.tools.get(42);
if (toolCall) {
  console.log('Duration:', toolCall.duration_ms, 'ms');
}
```

## 瀏覽器支援

AgentFS 可透過 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' });

    // 所有 API 在瀏覽器中用法相同
    await agent.kv.set('browser:data', { platform: 'web' });
    await agent.fs.writeFile('/notes.txt', 'Hello from browser!');
  </script>
</head>
</html>
```

## 支援

* [GitHub Issues](https://github.com/tursodatabase/agentfs/issues) - 錯誤回報與功能請求
* [Discord](https://tur.so/discord) - 社群支援與討論
* [範例](https://github.com/tursodatabase/agentfs/tree/main/examples) - 範例應用程式
