跳至正文內容
TursoDB.cn 獨立社群 · MVCC 並行寫入與每 Agent 獨立庫實戰 閱讀解析 →
AgentFS(測試版) SDK 開發套件

TypeScript/JavaScript SDK

AgentFS TypeScript 與 JavaScript SDK 的完整參考文件

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

安裝

npm install agentfs-sdk

快速開始

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 資料庫。

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 序列化。

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>

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

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)

移除鍵值對。

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

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

列出符合指定前綴的鍵。

// 列出所有使用者鍵
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)

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

// 寫入文字
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,若指定編碼則回傳字串。

// 以 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[]>

列出目錄內容。

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>

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

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>

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

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

fs.deleteFile(path: string)

刪除檔案。

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

工具呼叫追蹤 API

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

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

記錄一次工具叫用。

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>

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

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

瀏覽器支援

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

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

支援

同步自官方 Turso 文件倉庫 ( tursodatabase/turso-docs · MIT 開源授權) 檢視官方原文 ↗
搜尋
按 Esc 關閉 · 由 Pagefind 靜態索引驅動