참조SDKTypeScript SDK

SDK

TypeScript SDK

중복으로 memory semantics를 UI에 구현하지 않고 TypeScript SDK의 workflow helper와 capture policy를 사용합니다.

설치

참고: 프로그래밍 방식의 TypeScript SDK(MemoryOSClient)는 아직 npm에 게시되지 않았습니다. npm의 공식 @xmemo/client 패키지는 엄격히 CLI 오케스트레이터(계정 설정, 진단 및 xmemo-mcp 로컬 stdio 프록시)입니다. 프로그래밍 방식의 SDK가 출시될 때까지 REST API(/docs/api/authentication) 또는 Model Context Protocol(/docs/mcp/overview)을 통해 애플리케이션을 통합하세요. 계정 설정, 진단 및 로컬 MCP 서버 관리를 위해 공식 @xmemo/client CLI 패키지를 설치합니다:

npm install -g @xmemo/client
npx @xmemo/client setup --url https://xmemo.dev

클라이언트 생성 (미리보기 참조)

미리보기 참조: 다음 클라이언트 생성 코드는 향후 출시될 프로그래밍 방식 TypeScript SDK 인터페이스를 보여줍니다. 참고: MemoryOSClient는 아직 게시된 @xmemo/client npm 패키지에 배포되지 않았으며, 아래 import 문은 출시 후 향후 SDK 사용법을 보여줍니다. API 키는 환경에 보관하고 소스나 공개 설정에 인라인하지 마세요. 선택적인 agentId 및 agentInstanceId 값은 속성 필드이며 자격 증명이 아닙니다.

import { MemoryOSClient } from '@xmemo/client';

const client = new MemoryOSClient({
  baseUrl: 'https://xmemo.dev',
  apiKey: process.env.XMEMO_KEY!,
});

클라이언트 옵션 타입 (미리보기 참조)

미리보기 참조: 이 옵션 타입들은 향후 출시될 SDK 클라이언트 인터페이스를 나타냅니다. 워크플로 메서드는 AgentWorkflowOptions를 수락하고 recallContext는 RecallContextOptions를 수락합니다.

interface MemoryOSClientOptions {
  baseUrl: string;
  apiKey: string;
  fetchImpl?: typeof fetch;
  agentId?: string;
  agentInstanceId?: string;
}

interface AgentWorkflowOptions extends CaptureOptions {
  agentId?: string;
  agentInstanceId?: string;
  sessionId?: string;
  taskId?: string;
  status?: string;
  metadata?: Record<string, unknown>;
  memoryType?: MemoryType;
}

interface RecallContextOptions extends RecallPlanOptions {
  status?: string;
  threshold?: number;
  maxItems?: number;
  maxTokens?: number;
  limit?: number;
}

taskStart / taskEnd

두 method는 content: string과 선택적인 AgentWorkflowOptions object를 받고 모두 Promise<CaptureResult>를 반환합니다. taskStart의 기본값은 status started와 memoryType working이고 taskEnd의 기본값은 completed와 working입니다.

async taskStart(content: string, options: AgentWorkflowOptions = {}): Promise<CaptureResult>
async taskEnd(content: string, options: AgentWorkflowOptions = {}): Promise<CaptureResult>

await client.taskStart('Implement MCP token repair', { source: 'codex', sessionId: 's1', taskId: 'p0' });
await client.taskEnd('MCP token repair completed', { source: 'codex', sessionId: 's1', taskId: 'p0' });

recordDecision / recordBugFix

이 workflow helper는 동일한 signature와 return type을 사용합니다. recordDecision과 recordBugFix의 captured memory type 기본값은 semantic이며 event type이 기록된 lifecycle fact의 종류를 식별합니다.

async recordDecision(content: string, options: AgentWorkflowOptions = {}): Promise<CaptureResult>
async recordBugFix(content: string, options: AgentWorkflowOptions = {}): Promise<CaptureResult>

await client.recordDecision('Remote agents should use network MCP, not SSH stdio', { source: 'codex', scope: 'memory-os' });
await client.recordBugFix('Fixed streamable-http token identity fallback', { source: 'codex', taskId: 'p0' });

CaptureResult return shape

taskStart, taskEnd, recordDecision, recordBugFix, recordCorrection, captureEvent 및 recordEvent는 모두 CaptureResult로 resolve됩니다. policy는 low-signal event를 건너뛸 때 memory_id 없는 decision을 반환할 수 있으므로 모든 call이 write한다고 가정하지 않습니다.

interface CaptureResult extends CaptureDecision {
  event_id: string;
  memory_id?: string;
}

interface CaptureDecision {
  shouldCapture: boolean;
  reason: string;
  action: CaptureAction;
  qualityScore: number;
  event: AgentEvent;
  candidate?: MemoryCandidate;
}

recallContext signature와 request

recallContext는 /v1/recall/context에 POST request를 보내고 server JSON object를 반환합니다. SDK는 maxItems와 maxTokens 같은 camelCase option을 REST field인 max_items와 max_tokens로 매핑합니다. 기본값은 memory_type auto, status active, threshold 0.5 및 prefer_working true입니다.

async recallContext(query: string, options: RecallContextOptions = {}): Promise<Record<string, unknown>>

const context = await client.recallContext('current task and recent decisions', {
  scope: 'memory-os',
  maxItems: 6,
  maxTokens: 1200,
  preferWorking: true,
});

recallContext return shape

REST response에 additive field가 추가될 수 있으므로 TypeScript return type은 의도적으로 Record<string, unknown>입니다. 현재 server가 생성하는 핵심 shape는 다음 field를 가진 structured context object이며 items와 budget 값은 data에 따라 달라집니다.

{
  "version": "value-density-v2",
  "query": "current task and recent decisions",
  "retrieval_plan": {
    "query": "...",
    "selected_memory_types": ["working", "semantic"]
  },
  "budget": {
    "max_items": 6,
    "max_tokens": 1200,
    "used_items": <number>,
    "used_tokens": <number>,
    "skipped_items": <number>,
    "filtered_items": <number>,
    "structured_skipped_items": <number>,
    "budget_skipped_items": <number>,
    "truncated_items": <number>,
    "candidate_items": <number>,
    "selection_strategy": "top-primary-plus-stable-value-density",
    "budget_tradeoff": <boolean>,
    "token_scope": "context_text"
  },
  "items": [<structured context item>],
  "context_text": "<assembled context>",
  "answer_status": "primary_answer_available"
}

SDK recallContext와 MCP recall_context

두 surface는 동일한 bounded recall-context semantics와 underlying server assembly를 사용하지만 동일한 wire surface는 아닙니다. SDK method는 X-API-Key로 인증하는 /v1/recall/context REST client call이며 structured JSON을 반환합니다. MCP tool은 MCP client가 호출하고 ### XMemo Context로 시작하는 public text response를 렌더링합니다. underscore가 있는 MCP tool name은 MCP surface에서만 사용합니다.

  • SDK caller: client.recallContext(query, options)를 호출하는 TypeScript code.
  • MCP caller: MCP argument로 recall_context를 호출하는 MCP client.
  • SDK result: version, retrieval_plan, budget, items, context_text 및 answer_status 핵심 field를 가진 Record<string, unknown>.
  • MCP result: Reference, Type, Location line과 Context section이 있는 public text이며 retrieval internals는 노출되지 않습니다.

Workflow sequence

production hook은 기존 context를 recall하고 task lifecycle event를 capture한 뒤 task를 종료할 수 있습니다. 모든 workflow helper는 여전히 CaptureResult를 반환하므로 caller는 shouldCapture, action, reason, qualityScore, event_id 및 선택적인 memory_id를 확인할 수 있습니다.

const scope = 'memory-os';
const sessionId = crypto.randomUUID();

await client.recallContext('current task and recent decisions', { scope, preferWorking: true });
await client.taskStart('Implement production adapter hook', { source: 'codex', sessionId, scope });
await client.recordDecision('Use the hosted MCP transport', { source: 'codex', sessionId, scope });
await client.taskEnd('Production adapter hook implemented', { source: 'codex', sessionId, scope });

Authentication error handling

MemoryOSClient는 REST request에 X-API-Key를 보냅니다. private request method는 모든 non-2xx response에서 plain Error를 throw하며 exact prefix `Memory OS request failed: <status> ` 뒤에 response body를 붙입니다. 401과 403을 처리할 때 key나 민감한 data를 포함할 수 있는 response content를 log하지 않습니다. 별도로 export된 MemoryOSHttpError는 이 MemoryOSClient workflow method가 아니라 MemoryOSHttpClient에 속합니다.

try {
  await client.recallContext('connection check', { maxItems: 1 });
} catch (error) {
  if (error instanceof Error) {
    // The message starts: Memory OS request failed: <status> <response body>
    console.error('XMemo request failed; re-check XMEMO_KEY and required scope');
  }
}

Capture policy result

captureEvent는 event를 normalize하고 deterministic capture policy를 적용한 뒤에만 write합니다. low-signal event는 write 없이 shouldCapture: false를 반환하고 token-like text는 capture 전에 redact됩니다. helper가 memory를 썼다고 가정하지 말고 CaptureResult를 확인합니다.

const result = await client.recordDecision('Remote agents should use network MCP, not SSH stdio', { source: 'codex' });
if (result.shouldCapture) {
  console.log(result.event_id, result.memory_id);
} else {
  console.log(result.reason, result.action);
}

출처: SDK workflow helpers