TypeScript/JavaScript SDK
AgentFS TypeScript/JavaScript SDK의 전체 참조예요. Node.js와 브라우저 환경을 모두 지원하며, 이 SDK로 상태 저장(stateful) AI 에이전트를 만들 수 있어요.
출처: 문서
본문
설치
npm:
npm install agentfs-sdk
bun:
bun add agentfs-sdk
deno:
import { AgentFS } from "npm:agentfs-sdk";
빠른 시작
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(...);
핵심 API
AgentFS 클래스
모든 AgentFS 작업의 주 진입점이에요.
AgentFS.open(options?: AgentFSOptions)
AgentFS 데이터베이스를 만들거나 열어요.
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();
속성
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); // Type-safe access
}
kv.delete(key: string)
키-값 쌍을 제거해요.
await agent.kv.delete('session:expired');
kv.list(prefix: string): Promise<{ key: string, value: any }[]>
접두어와 일치하는 키를 나열해요.
// 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('');
파일시스템 API
에이전트 데이터를 관리하는 POSIX 스타일 파일시스템 작업이에요.
fs.writeFile(path: string, data: string | Buffer)
필요하면 부모 디렉터리를 만들면서 파일에 데이터를 기록해요.
// 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>
파일 내용을 읽어요. 기본값은 Buffer이고, 인코딩을 지정하면 문자열을 반환해요.
// 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[]>
디렉터리 내용을 나열해요.
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>
파일 또는 디렉터리 메타데이터를 가져와요.
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>
파일이나 디렉터리가 존재하는지 확인해요.
if (await agent.fs.exists('/reports/draft.md')) {
console.log('Draft exists');
}
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, // 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>
특정 도구 호출의 상세 정보를 가져와요.
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' });
// 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>
지원
- GitHub Issues - 버그 보고 및 기능 요청
- Discord - 커뮤니티 지원 및 토론
- Examples - 샘플 애플리케이션
더 알아보기 (Learn more)
- Python SDK — Python SDK 참조
- Rust SDK — Rust SDK 참조
- CLI 참조 — agentfs CLI 전체 참조
- AgentFS 소개 — AgentFS 개념 살펴보기