# TypeScript SDK

使用 TypeScript SDK 的 workflow helpers 和 capture policy，不在 UI 中重复实现 memory semantics。

- Canonical: https://docs.xmemo.dev/zh/docs/sdk/typescript
- Locale: zh-CN
- Content-Locale: zh-CN
- Canonical-Content-Digest: 653aac1dcb59382f7266c99c91cd6e028767760475df9ae3b36a903b2283d333
- Edition-Digest: 3132988cf018dfa5586a39175cbc6c0f7b33db44018681f2d06b70c953e4b3ed
- Source-Revision: sha256:b831c81b583cfb5aec737b2369ccaa15a57a7f4f2f846d89d9f40fc118b9f4bb

## 安装

注意：程序化 TypeScript SDK（MemoryOSClient）尚未在 npm 上发布。npm 上的官方 @xmemo/client 包仅为命令行编排工具（用于账户配置、诊断以及 xmemo-mcp 本地 stdio 代理）。在程序化 SDK 发布之前，请通过 REST API (/docs/api/authentication) 或 Model Context Protocol (/docs/mcp/overview) 集成应用。

安装官方 @xmemo/client CLI package，用于账户配置、诊断以及本地 MCP server 管理：

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

## 构造 client（预览参考）

预览参考：以下客户端构造代码展示了即将发布的程序化 TypeScript SDK 接口。注意：MemoryOSClient 尚未包含在已发布的 @xmemo/client npm 包中；下方导入语句展示了 SDK 发布后的未来用法。将 API key 放在环境中，绝不要内联到 source 或 public configuration。可选的 agentId 和 agentInstanceId 是 attribution fields，不是 credentials。

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

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

## Client option types（预览参考）

预览参考：这些 option types 代表即将发布的 SDK 客户端接口。Workflow methods 接受 AgentWorkflowOptions，而 recallContext 接受 RecallContextOptions。

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

```ts
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 helpers 使用完全相同的 signature 和 return type。recordDecision 和 recordBugFix 默认将 captured memory type 设为 semantic；event type 标识记录的是哪一种 lifecycle fact。

```ts
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 返回形状

taskStart、taskEnd、recordDecision、recordBugFix、recordCorrection、captureEvent 和 recordEvent 都解析为 CaptureResult。policy 在跳过低信号 event 时可能返回没有 memory_id 的 decision；不要假设每次调用都会写入。

```ts
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 options 映射为 REST fields max_items、max_tokens；默认值是 memory_type auto、status active、threshold 0.5 和 prefer_working true。

```ts
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 返回形状

TypeScript return type 有意设为 Record<string, unknown>，因为 REST response 可以增加 additive fields。当前 server 生成的核心 shape 是包含以下 fields 的 structured context object；items 和 budget 的值取决于数据。

```json
{
  "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

两者使用相同的 bounded recall-context semantics 和底层 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；带下划线的 MCP tool name 只在 MCP surface 使用。

- SDK caller：调用 client.recallContext(query, options) 的 TypeScript code。
- MCP caller：使用 MCP arguments 调用 recall_context 的 MCP client。
- SDK result：包含 version、retrieval_plan、budget、items、context_text 和 answer_status 核心字段的 Record<string, unknown>。
- MCP result：包含 Reference、Type、Location 行和 Context section 的 public text；不会暴露 retrieval internals。

## Workflow sequence

production hook 可以 recall 已有 context、capture task lifecycle events，然后结束 task。每个 workflow helper 仍返回 CaptureResult，因此 caller 可以检查 shouldCapture、action、reason、qualityScore、event_id 和可选的 memory_id。

```ts
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 requests 中发送 X-API-Key。它的 private request method 对每个 non-2xx response 抛出 plain Error，使用精确前缀 `Memory OS request failed: <status> `，后面接 response body。处理 401 和 403 时，不要记录 key 或可能包含敏感数据的 response content。另行 export 的 MemoryOSHttpError 属于 MemoryOSHttpClient，不属于这些 MemoryOSClient workflow methods。

```ts
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 会先 normalize event、应用 deterministic capture policy，之后才写入。低信号 event 会在不写入的情况下返回 shouldCapture: false，而 token-like text 会在 capture 前被 redact。请检查 CaptureResult，不要假设 helper 已写入 memory。

```ts
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);
}
```

