インストール
注意:プログラム用 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 のインターフェースを示しています。注意:公開されている @xmemo/client npm パッケージには MemoryOSClient はまだ含まれていません。以下のインポート文はリリース後の将来の使用方法を示しています。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はcaptureする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されます。low-signal eventをskipする場合、policyはmemory_idなしのdecisionを返すことがあるため、毎回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へmappingします。既定値は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が生成するcore 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
両者は同じ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をrenderします。underscore付きの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のcore fieldを持つRecord<string, unknown>。
- MCP result: Reference、Type、Locationの行と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の結果
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);
}