@mebular/mcp 0.2.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4734 @@
1
+ // MCP Memory Capability API(0.3.0 contract v2 §7.1 / capability-api §1–§6)
2
+ //
3
+ // 内部接口:`/internal/memory/v1`,运行在 MCP daemon 内,只允许本机 memory-runtime
4
+ // sidecar 调用。不是公共 MCP 工具面(29 工具不变)。
5
+ //
6
+ // 端点:
7
+ // GET /version
8
+ // GET /status
9
+ // GET /namespaces
10
+ // POST /query /search /history /profile /skills /graph
11
+ // POST /write /update /delete /archive /internal-object /detail
12
+ // GET/POST /sync
13
+ //
14
+ // 约束:
15
+ // - 只调用 MemoryService / Mebular 公共方法;不直接打开 GraphStore 文件、不 append
16
+ // 事件、不新增事件类型或同步协议。普通 MemoryRecord 的读写只经 MemoryService;
17
+ // 只有 internal-object(compact/self_record/context_checkpoint)与 detail
18
+ // (detail_record)允许受控的内部对象写入,且都经统一图/事件/同步。
19
+ // - 读取(query/search/history/profile/skills/graph)、状态/域统计与同步状态都由
20
+ // MemoryService 统一执行;capability 只负责授权域、owner/provenance 投影与响应信封。
21
+ // - 内部对象(metadata.internal / __*)默认不返回;graph 不遍历内部对象。
22
+ // - capability token 不进入日志、status、错误详情;响应使用统一信封。
23
+ // - 本模块不 import @mebular/memory-runtime 的业务实现。
24
+
25
+ import { createHash, randomUUID } from 'node:crypto';
26
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
27
+ import { join } from 'node:path';
28
+ import { domainOfNamespace, semanticKindOf } from '@mebular/core';
29
+ import {
30
+ DEFAULT_DETAIL_QUOTA_LIMITS,
31
+ DETAIL_DELETE_REASONS,
32
+ DETAIL_KINDS,
33
+ DETAIL_RETENTION_CLASSES,
34
+ DETAIL_RETENTION_DAYS,
35
+ MAX_DETAIL_BATCH_ITEMS,
36
+ MAX_DETAIL_DOMAINS,
37
+ MAX_DETAIL_GET_BYTES,
38
+ MAX_DETAIL_LIST_LIMIT,
39
+ MAX_DETAIL_RECORD_IDS,
40
+ MAX_DETAIL_TEXT_BYTES,
41
+ detailContentHash,
42
+ detailTextBytes,
43
+ isDetailDeleteReason,
44
+ isDetailKind,
45
+ isDetailMime,
46
+ isDetailRetentionClass,
47
+ isDetailRole,
48
+ resolveDetailExpiresAt,
49
+ } from '@mebular/core';
50
+ import {
51
+ ensureCapabilityToken,
52
+ removeCapabilityToken,
53
+ verifyCapabilityToken,
54
+ } from './memory-runtime-token.mjs';
55
+ import { APP_VERSION } from './version.mjs';
56
+
57
+ export { domainOfNamespace };
58
+
59
+ export const CAPABILITY_API_PREFIX = '/internal/memory/v1';
60
+ export const CAPABILITY_API_VERSION = 1;
61
+ export const CAPABILITY_SCHEMA_VERSION = 1;
62
+
63
+ const MAX_BODY_BYTES = 2 * 1024 * 1024;
64
+ const MAX_QUERY_BYTES = 8 * 1024;
65
+ const MAX_DOMAINS = 16;
66
+ const MAX_LIMIT = 50;
67
+ const MAX_DEPTH = 5;
68
+ const DEFAULT_LIMIT = 10;
69
+ const MAX_TAGS = 32;
70
+ const MAX_TAG_CHARS = 128;
71
+ const MAX_BATCH_ITEMS = 100;
72
+ const MAX_CONTENT_BYTES = 256 * 1024;
73
+ const MAX_PROVENANCE_BYTES = 8 * 1024;
74
+ const MAX_COMPACT_SUMMARY_BYTES = 64 * 1024;
75
+ const MAX_CHECKPOINT_STATE_BYTES = 256 * 1024;
76
+ const MAX_COMPACT_SOURCES = 200;
77
+ const MAX_CHECKPOINT_GOAL_BYTES = 2 * 1024;
78
+ const MAX_CHECKPOINT_CONSTRAINTS = 32;
79
+ const MAX_CHECKPOINT_DECISIONS = 50;
80
+ const MAX_CHECKPOINT_PROGRESS = 50;
81
+ const MAX_CHECKPOINT_NEXT_STEPS = 32;
82
+ const MAX_CHECKPOINT_FILES = 100;
83
+ const MAX_CHECKPOINT_QUESTIONS = 32;
84
+ const MAX_CHECKPOINT_REFERENCES = 200;
85
+ const MAX_CHECKPOINT_URLS = 64;
86
+ const MAX_CHECKPOINT_ITEM_BYTES = 1024;
87
+ const MAX_CHECKPOINT_FILE_BYTES = 512;
88
+ const MAX_CHECKPOINT_DECISION_BYTES = 2 * 1024;
89
+ const MAX_CHECKPOINT_ID_CHARS = 128;
90
+ const MAX_CHECKPOINT_URL_BYTES = 2 * 1024;
91
+ const DEFAULT_CHECKPOINT_LEASE_MS = 60_000;
92
+ const MAX_RELATED = 32;
93
+ const MAX_SUPERSEDES = 16;
94
+ const MAX_MESSAGE_IDS = 64;
95
+ const MAX_JSON_FIELD_BYTES = 16 * 1024;
96
+ const OPEN_VALID_TO = 9999999999999;
97
+ const IDEMPOTENCY_TTL_MS = 24 * 60 * 60 * 1000;
98
+ const IDEMPOTENCY_MAX_ENTRIES = 5000;
99
+ const IDEMPOTENCY_LEDGER_VERSION = 1;
100
+ const IDEMPOTENCY_LEDGER_FILE = 'capability-idempotency.json';
101
+ const MAX_SYNC_WAIT_MS = 30_000;
102
+
103
+ const AGENT_ID_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
104
+ const THREAD_ID_RE = /^[A-Za-z0-9._:-]{1,128}$/;
105
+ const REQUEST_ID_RE = /^[A-Za-z0-9._:-]{1,128}$/;
106
+ const IDEMPOTENCY_KEY_RE = /^[A-Za-z0-9._:-]{1,200}$/;
107
+ const CLIENT_ITEM_ID_RE = /^[A-Za-z0-9._:-]{1,128}$/;
108
+
109
+ const RESERVED_DOMAINS = new Set(['user', 'default', 'shared', 'system']);
110
+ const ALLOWED_TYPES = new Set(['fact', 'preference', 'episode', 'observation', 'skill', 'entity', 'meta']);
111
+ const DEFAULT_TYPES = ['fact', 'preference', 'episode', 'observation', 'skill', 'entity'];
112
+ const WRITE_ENDPOINTS = new Set(['write', 'update', 'delete', 'archive', 'internal-object', 'sync']);
113
+ const INTERNAL_OBJECT_KINDS = ['compact', 'self_record', 'context_checkpoint'];
114
+ const WRITE_KINDS = new Set(['fact', 'preference', 'episode', 'observation', 'skill', 'entity']);
115
+ const EPISODE_KINDS = new Set(['conversation', 'task', 'decision', 'error', 'observation', 'other']);
116
+ const ENTITY_KINDS = new Set(['user', 'project', 'tool', 'concept', 'organization', 'location', 'other']);
117
+ const SOURCE_VALUES = new Set(['mcp', 'runtime', 'host', 'import', 'legacy']);
118
+ const EXTRACTOR_VALUES = new Set(['user', 'heuristic', 'local', 'host', 'api']);
119
+ const CONFIRMATION_VALUES = new Set(['explicit', 'policy', 'none']);
120
+ const PROTECTED_METADATA_KEYS = new Set([
121
+ 'internal',
122
+ 'internalObject',
123
+ 'provenance',
124
+ 'owner',
125
+ 'ownerType',
126
+ 'ownerId',
127
+ 'archivedAt',
128
+ 'domain',
129
+ 'namespace',
130
+ 'kind',
131
+ 'contentHash',
132
+ 'contentHashValidFrom',
133
+ 'clientItemId',
134
+ 'updatedBy',
135
+ 'supersededBy',
136
+ 'supersededAt',
137
+ ]);
138
+ const PATCH_KEYS = new Set(['content', 'tags', 'validFrom', 'validTo', 'metadata']);
139
+
140
+ export const CAPABILITY_LIMITS = Object.freeze({
141
+ maxBodyBytes: MAX_BODY_BYTES,
142
+ maxBatchItems: MAX_BATCH_ITEMS,
143
+ maxContentBytes: MAX_CONTENT_BYTES,
144
+ maxProvenanceBytes: MAX_PROVENANCE_BYTES,
145
+ maxDomains: MAX_DOMAINS,
146
+ maxLimit: MAX_LIMIT,
147
+ maxGraphDepth: MAX_DEPTH,
148
+ maxCheckpointStateBytes: MAX_CHECKPOINT_STATE_BYTES,
149
+ maxCheckpointGoalBytes: MAX_CHECKPOINT_GOAL_BYTES,
150
+ maxCheckpointConstraints: MAX_CHECKPOINT_CONSTRAINTS,
151
+ maxCheckpointDecisions: MAX_CHECKPOINT_DECISIONS,
152
+ maxCheckpointProgress: MAX_CHECKPOINT_PROGRESS,
153
+ maxCheckpointNextSteps: MAX_CHECKPOINT_NEXT_STEPS,
154
+ maxCheckpointFiles: MAX_CHECKPOINT_FILES,
155
+ maxCheckpointQuestions: MAX_CHECKPOINT_QUESTIONS,
156
+ maxCheckpointReferences: MAX_CHECKPOINT_REFERENCES,
157
+ maxCheckpointUrls: MAX_CHECKPOINT_URLS,
158
+ maxCompactSummaryBytes: MAX_COMPACT_SUMMARY_BYTES,
159
+ maxCompactSources: MAX_COMPACT_SOURCES,
160
+ maxDetailTextBytes: MAX_DETAIL_TEXT_BYTES,
161
+ maxDetailBatchItems: MAX_DETAIL_BATCH_ITEMS,
162
+ maxDetailGetBytes: MAX_DETAIL_GET_BYTES,
163
+ maxDetailListLimit: MAX_DETAIL_LIST_LIMIT,
164
+ maxDetailDomains: MAX_DETAIL_DOMAINS,
165
+ maxSupersedes: MAX_SUPERSEDES,
166
+ detailDomainQuotaBytes: DEFAULT_DETAIL_QUOTA_LIMITS.domainBytes,
167
+ detailCloudQuotaBytes: DEFAULT_DETAIL_QUOTA_LIMITS.cloudBytes,
168
+ detailThreadQuotaBytes: DEFAULT_DETAIL_QUOTA_LIMITS.threadBytes,
169
+ idempotencyTtlMs: IDEMPOTENCY_TTL_MS,
170
+ });
171
+
172
+ class CapabilityError extends Error {
173
+ constructor(status, code, message, details, retryable = false) {
174
+ super(message);
175
+ this.status = status;
176
+ this.code = code;
177
+ this.details = details;
178
+ this.retryable = retryable;
179
+ }
180
+ }
181
+
182
+ function isObject(value) {
183
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
184
+ }
185
+
186
+ function hasValue(value) {
187
+ return value !== undefined && value !== null;
188
+ }
189
+
190
+ /** 仅当 MCP 配置 `memoryRuntime.enabled=true` 时挂载能力端点。 */
191
+ export function isMemoryRuntimeEnabled(config) {
192
+ return config?.memoryRuntime?.enabled === true;
193
+ }
194
+
195
+ export function isMemoryCapabilityPath(path) {
196
+ return typeof path === 'string'
197
+ && (path === CAPABILITY_API_PREFIX || path.startsWith(`${CAPABILITY_API_PREFIX}/`));
198
+ }
199
+
200
+ /** 服务端只接受这三个 loopback 地址(含 IPv4-mapped IPv6)。 */
201
+ export function isLoopbackRemoteAddress(address) {
202
+ return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1';
203
+ }
204
+
205
+ export function isLoopbackHostname(hostname) {
206
+ let normalized = String(hostname ?? '').toLowerCase();
207
+ if (normalized.startsWith('[') && normalized.endsWith(']')) normalized = normalized.slice(1, -1);
208
+ return normalized === '127.0.0.1' || normalized === 'localhost' || normalized === '::1';
209
+ }
210
+
211
+ /** 解析 Host 头;IPv6 用 `[::1]:port`。 */
212
+ export function parseHostHeader(header) {
213
+ if (typeof header !== 'string' || header.length === 0) return null;
214
+ const value = header.trim();
215
+ if (value.startsWith('[')) {
216
+ const end = value.indexOf(']');
217
+ if (end === -1) return null;
218
+ const hostname = value.slice(1, end);
219
+ const rest = value.slice(end + 1);
220
+ if (rest === '') return { hostname, port: null };
221
+ if (!rest.startsWith(':')) return null;
222
+ return { hostname, port: rest.slice(1) };
223
+ }
224
+ const colon = value.lastIndexOf(':');
225
+ if (colon === -1) return { hostname: value, port: null };
226
+ // 裸 IPv6(无方括号)不是合法 Host;这里只在恰好一个冒号时按 host:port 解析。
227
+ if (value.indexOf(':') !== colon) return null;
228
+ return { hostname: value.slice(0, colon), port: value.slice(colon + 1) };
229
+ }
230
+
231
+ function portMatches(port, localPort) {
232
+ if (!hasValue(localPort)) return true;
233
+ if (port === null || port === '') return false;
234
+ return String(port) === String(localPort);
235
+ }
236
+
237
+ export function hostHeaderAllowed(header, localPort) {
238
+ const parsed = parseHostHeader(header);
239
+ if (!parsed || !isLoopbackHostname(parsed.hostname)) return false;
240
+ return portMatches(parsed.port, localPort);
241
+ }
242
+
243
+ export function originAllowed(origin, localPort) {
244
+ if (!hasValue(origin) || origin === '') return true;
245
+ if (typeof origin !== 'string') return false;
246
+ let parsed;
247
+ try {
248
+ parsed = new URL(origin);
249
+ } catch {
250
+ return false;
251
+ }
252
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false;
253
+ if (parsed.username !== '' || parsed.password !== '') return false;
254
+ if (!isLoopbackHostname(parsed.hostname)) return false;
255
+ const port = parsed.port || (parsed.protocol === 'https:' ? '443' : '80');
256
+ return portMatches(port, localPort);
257
+ }
258
+
259
+ /** agentId 语法(contract v2 §4.2)。 */
260
+ export function isValidAgentId(agentId) {
261
+ return typeof agentId === 'string' && AGENT_ID_RE.test(agentId);
262
+ }
263
+
264
+ /** 记忆域语法;非法返回 null。 */
265
+ export function normalizeDomain(value) {
266
+ if (typeof value !== 'string') return null;
267
+ const domain = value.trim();
268
+ if (domain.length === 0 || domain.length > 128) return null;
269
+ // `__policy__` 与所有 `__*` 保留域不是记忆域。
270
+ if (domain.startsWith('__')) return null;
271
+ if (RESERVED_DOMAINS.has(domain)) return domain;
272
+ if (domain.startsWith('agent:')) {
273
+ return isValidAgentId(domain.slice('agent:'.length)) ? domain : null;
274
+ }
275
+ if (domain.startsWith('task:')) {
276
+ return THREAD_ID_RE.test(domain.slice('task:'.length)) ? domain : null;
277
+ }
278
+ // 0.2 任意 namespace = Other 显式域;保留原值,不迁移、不改名。
279
+ if (/[\u0000-\u001f\u007f/\\]/.test(domain)) return null;
280
+ return domain;
281
+ }
282
+
283
+ /** 域 → 归属(服务端推导,客户端不能伪造)。 */
284
+ export function deriveOwner(domain, { userId = 'user' } = {}) {
285
+ if (domain === 'user') return { ownerType: 'user', ownerId: userId };
286
+ if (domain.startsWith('agent:')) return { ownerType: 'agent', ownerId: domain.slice('agent:'.length) };
287
+ return { ownerType: 'other', ownerId: domain };
288
+ }
289
+
290
+ /** core 的通用内部可见性约定(contract v2 §5.3 / §9.2)。 */
291
+ export function isInternalNode(node) {
292
+ if (!node) return false;
293
+ if (node.metadata?.internal === true) return true;
294
+ const namespace = node.namespace;
295
+ return typeof namespace === 'string' && namespace.startsWith('__') && namespace !== '__policy__';
296
+ }
297
+
298
+ function isArchivedNode(node) {
299
+ return typeof node?.metadata?.archivedAt === 'number';
300
+ }
301
+
302
+ // ---------- 写路径通用工具(W2b) ----------
303
+
304
+ function canonicalize(value) {
305
+ if (value === null || typeof value !== 'object') return value;
306
+ if (Array.isArray(value)) return value.map((entry) => canonicalize(entry));
307
+ const out = {};
308
+ for (const key of Object.keys(value).sort()) {
309
+ if (value[key] !== undefined) out[key] = canonicalize(value[key]);
310
+ }
311
+ return out;
312
+ }
313
+
314
+ function canonicalJson(value) {
315
+ return JSON.stringify(canonicalize(value));
316
+ }
317
+
318
+ function sha256Hex(value) {
319
+ return createHash('sha256').update(value).digest('hex');
320
+ }
321
+
322
+ function byteSize(value) {
323
+ return Buffer.byteLength(typeof value === 'string' ? value : canonicalJson(value), 'utf-8');
324
+ }
325
+
326
+ function jsonClone(value) {
327
+ return value === undefined ? undefined : JSON.parse(JSON.stringify(value));
328
+ }
329
+
330
+ function validationError(index, field, message, extra) {
331
+ return new CapabilityError(422, 'validation_failed', message, {
332
+ ...(Number.isInteger(index) ? { index } : {}),
333
+ field,
334
+ ...(extra ?? {}),
335
+ });
336
+ }
337
+
338
+ function nonEmptyString(value, field, index) {
339
+ if (typeof value !== 'string' || value.trim() === '') {
340
+ throw validationError(index, field, `${field} 必须是非空字符串`);
341
+ }
342
+ return value;
343
+ }
344
+
345
+ function optionalString(value, field, index, maxChars = 4096) {
346
+ if (value === undefined || value === null) return undefined;
347
+ if (typeof value !== 'string' || value.length > maxChars) {
348
+ throw validationError(index, field, `${field} 必须是字符串且不超过 ${maxChars} 字符`);
349
+ }
350
+ return value;
351
+ }
352
+
353
+ function optionalNumber(value, field, index) {
354
+ if (value === undefined || value === null) return undefined;
355
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
356
+ throw validationError(index, field, `${field} 必须是有限数字`);
357
+ }
358
+ return value;
359
+ }
360
+
361
+ function optionalConfidence(value, field, index) {
362
+ if (value === undefined || value === null) return undefined;
363
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) {
364
+ throw validationError(index, field, `${field} 必须在 [0,1] 区间`);
365
+ }
366
+ return value;
367
+ }
368
+
369
+ function stringArray(value, field, index, { maxItems = MAX_TAGS, maxChars = MAX_TAG_CHARS } = {}) {
370
+ if (value === undefined || value === null) return undefined;
371
+ if (!Array.isArray(value)) throw validationError(index, field, `${field} 必须是字符串数组`);
372
+ if (value.length > maxItems) throw validationError(index, field, `${field} 最多 ${maxItems} 项`);
373
+ const out = [];
374
+ for (const entry of value) {
375
+ if (typeof entry !== 'string' || entry.length === 0 || entry.length > maxChars) {
376
+ throw validationError(index, field, `${field} 每项需为 1–${maxChars} 字符`);
377
+ }
378
+ if (!out.includes(entry)) out.push(entry);
379
+ }
380
+ return out;
381
+ }
382
+
383
+ function normalizeTags(value, index) {
384
+ const tags = stringArray(value, 'tags', index) ?? [];
385
+ for (const tag of tags) {
386
+ if (tag.startsWith('mebular:runtime:')) {
387
+ throw validationError(index, 'tags', '不得使用 mebular:runtime:* 保留标签', { tag });
388
+ }
389
+ }
390
+ return tags;
391
+ }
392
+
393
+ function normalizeRelatedTo(value, index) {
394
+ const related = stringArray(value, 'relatedTo', index, { maxItems: MAX_RELATED, maxChars: 128 }) ?? [];
395
+ return related;
396
+ }
397
+
398
+ function normalizeSupersedes(value, index) {
399
+ if (value === undefined || value === null) return [];
400
+ const ids = stringArray(value, 'supersedes', index, { maxItems: MAX_SUPERSEDES, maxChars: 128 }) ?? [];
401
+ return ids;
402
+ }
403
+
404
+ /** fact/preference 内容 → 同键判定用三元组(preference 兼容 entity/preferenceType/value)。 */
405
+ function factTriple(content) {
406
+ if (!isObject(content)) return null;
407
+ const subject = typeof content.subject === 'string'
408
+ ? content.subject
409
+ : typeof content.entity === 'string' ? content.entity : null;
410
+ const predicate = typeof content.predicate === 'string'
411
+ ? content.predicate
412
+ : typeof content.preferenceType === 'string' ? content.preferenceType : null;
413
+ const object = typeof content.object === 'string'
414
+ ? content.object
415
+ : typeof content.value === 'string' ? content.value : null;
416
+ if (subject === null || predicate === null || object === null) return null;
417
+ return { subject, predicate, object };
418
+ }
419
+
420
+ function normalizeMessageIds(value, field, index) {
421
+ return stringArray(value, field, index, { maxItems: MAX_MESSAGE_IDS, maxChars: 256 }) ?? [];
422
+ }
423
+
424
+ function parseProvenanceInput(value, index) {
425
+ if (value === undefined || value === null) return {};
426
+ if (!isObject(value)) throw validationError(index, 'provenance', 'provenance 必须是对象');
427
+ const out = {};
428
+ if (value.source !== undefined) {
429
+ if (!SOURCE_VALUES.has(value.source)) throw validationError(index, 'provenance.source', 'provenance.source 非法');
430
+ out.source = value.source;
431
+ }
432
+ if (value.extractor !== undefined) {
433
+ if (!EXTRACTOR_VALUES.has(value.extractor)) {
434
+ throw validationError(index, 'provenance.extractor', 'provenance.extractor 非法');
435
+ }
436
+ out.extractor = value.extractor;
437
+ }
438
+ if (value.model !== undefined && value.model !== null) {
439
+ if (typeof value.model !== 'string' || value.model.length > 128) {
440
+ throw validationError(index, 'provenance.model', 'provenance.model 必须是字符串或 null');
441
+ }
442
+ out.model = value.model;
443
+ } else {
444
+ out.model = null;
445
+ }
446
+ if (value.threadId !== undefined && value.threadId !== null) {
447
+ if (typeof value.threadId !== 'string' || !THREAD_ID_RE.test(value.threadId)) {
448
+ throw validationError(index, 'provenance.threadId', 'threadId 格式非法');
449
+ }
450
+ out.threadId = value.threadId;
451
+ }
452
+ if (value.confirmation !== undefined) {
453
+ if (!CONFIRMATION_VALUES.has(value.confirmation)) {
454
+ throw validationError(index, 'provenance.confirmation', 'provenance.confirmation 非法');
455
+ }
456
+ out.confirmation = value.confirmation;
457
+ }
458
+ if (value.agentName !== undefined && value.agentName !== null) {
459
+ if (typeof value.agentName !== 'string' || value.agentName.length > 128) {
460
+ throw validationError(index, 'provenance.agentName', 'provenance.agentName 必须是字符串');
461
+ }
462
+ out.agentName = value.agentName;
463
+ }
464
+ out.messageIds = normalizeMessageIds(value.messageIds, 'provenance.messageIds', index);
465
+ out.rawChunkIds = normalizeMessageIds(value.rawChunkIds, 'provenance.rawChunkIds', index);
466
+ return out;
467
+ }
468
+
469
+ function buildWriteProvenance({
470
+ input,
471
+ actor,
472
+ identity,
473
+ hostId,
474
+ now,
475
+ threadId = null,
476
+ confirmation = 'none',
477
+ }) {
478
+ const writerId = actor.type === 'agent'
479
+ ? actor.agentId
480
+ : actor.type === 'user'
481
+ ? (actor.userId ?? identity.userId ?? 'user')
482
+ : 'system';
483
+ return {
484
+ source: input.source ?? 'runtime',
485
+ writerType: actor.type,
486
+ writerId,
487
+ extractor: input.extractor ?? (actor.type === 'agent' ? 'heuristic' : 'user'),
488
+ model: input.model ?? null,
489
+ version: APP_VERSION,
490
+ deviceId: identity.deviceId ?? null,
491
+ hostId,
492
+ threadId: input.threadId ?? threadId ?? null,
493
+ agentId: actor.type === 'agent' ? actor.agentId : null,
494
+ agentName: actor.displayName ?? input.agentName ?? null,
495
+ messageIds: [...(input.messageIds ?? [])],
496
+ rawChunkIds: [...(input.rawChunkIds ?? [])],
497
+ confirmation,
498
+ at: now,
499
+ };
500
+ }
501
+
502
+ function domainWriteForbidden(message, details) {
503
+ return new CapabilityError(403, 'domain_write_forbidden', message, details);
504
+ }
505
+
506
+ /**
507
+ * 写权限矩阵(contract v2 §6.2 / capability-api §5.2)。
508
+ * actor/domain 由服务端推导 owner;客户端只能在 item 里回传校验。
509
+ */
510
+ function assertDomainWrite(actor, domain, provenanceInput, requestThreadId = null) {
511
+ if (actor.type === 'system') return;
512
+ if (actor.type === 'user') {
513
+ // capability token 具备 memory.admin,user/system 可按治理矩阵写入。
514
+ return;
515
+ }
516
+ if (domain === 'user') {
517
+ if (provenanceInput?.confirmation !== 'explicit' || typeof provenanceInput?.source !== 'string'
518
+ || provenanceInput.source.length === 0) {
519
+ throw domainWriteForbidden('Agent 写入 user 域需要用户明确确认', {
520
+ domain,
521
+ actor: actor.agentId,
522
+ allowedDomain: `agent:${actor.agentId}`,
523
+ });
524
+ }
525
+ return;
526
+ }
527
+ if (domain === 'system') {
528
+ throw domainWriteForbidden('Agent 不能写入 system 域', { domain, actor: actor.agentId });
529
+ }
530
+ if (domain.startsWith('agent:')) {
531
+ if (domain !== `agent:${actor.agentId}`) {
532
+ throw domainWriteForbidden('Agent 不能写入其他 Agent 的记忆域', {
533
+ domain,
534
+ actor: actor.agentId,
535
+ allowedDomain: `agent:${actor.agentId}`,
536
+ });
537
+ }
538
+ return;
539
+ }
540
+ if (domain.startsWith('task:')) {
541
+ const threadId = domain.slice('task:'.length);
542
+ const claimed = provenanceInput?.threadId ?? requestThreadId;
543
+ if (claimed !== threadId) {
544
+ throw domainWriteForbidden('Agent 只能写入自己参与且 threadId 匹配的任务域', {
545
+ domain,
546
+ actor: actor.agentId,
547
+ threadId: claimed ?? null,
548
+ });
549
+ }
550
+ }
551
+ }
552
+
553
+ /** 治理动作:user/system 全部;agent 只能治理自己域内、自己写入的记录。 */
554
+ function canGovernNode(actor, node) {
555
+ if (actor.type === 'user' || actor.type === 'system') return true;
556
+ if (actor.type !== 'agent') return false;
557
+ const domain = domainOfNamespace(node?.namespace);
558
+ if (domain !== `agent:${actor.agentId}`) return false;
559
+ const provenance = isObject(node?.metadata?.provenance) ? node.metadata.provenance : {};
560
+ return provenance.writerId === actor.agentId;
561
+ }
562
+
563
+ /** 更新:agent 只能更新自己域内、自己写入的记录。 */
564
+ function canUpdateNode(actor, node) {
565
+ return canGovernNode(actor, node);
566
+ }
567
+
568
+ /**
569
+ * 修正/替代权限:常规更新权限之外,Agent 可替代自己在可写域(如 user/default)
570
+ * 写入的旧事实;不能替代其他 Agent 或 user/system 写入的记录。
571
+ */
572
+ function canSupersedeNode(actor, node, domain) {
573
+ if (canUpdateNode(actor, node)) return true;
574
+ if (actor.type !== 'agent' || domain === 'system') return false;
575
+ const provenance = isObject(node?.metadata?.provenance) ? node.metadata.provenance : {};
576
+ if (provenance.writerType !== 'agent' || provenance.writerId !== actor.agentId) return false;
577
+ if (domain === 'user' && provenance.confirmation !== 'explicit') return false;
578
+ return true;
579
+ }
580
+
581
+ function factExtras(raw, index) {
582
+ const confidence = optionalConfidence(raw.confidence, 'content.confidence', index);
583
+ const source = optionalString(raw.source, 'content.source', index);
584
+ return {
585
+ ...(confidence !== undefined ? { confidence } : {}),
586
+ ...(source !== undefined ? { source } : {}),
587
+ };
588
+ }
589
+
590
+ function normalizeWriteContent(kind, raw, index) {
591
+ if (!isObject(raw)) throw validationError(index, 'content', 'content 必须是非空对象');
592
+ if (byteSize(raw) > MAX_CONTENT_BYTES) {
593
+ throw new CapabilityError(413, 'payload_too_large', `content 超过 ${MAX_CONTENT_BYTES} 字节`, { index });
594
+ }
595
+ switch (kind) {
596
+ case 'fact':
597
+ return {
598
+ nodeType: 'fact',
599
+ content: {
600
+ subject: nonEmptyString(raw.subject, 'content.subject', index),
601
+ predicate: nonEmptyString(raw.predicate, 'content.predicate', index),
602
+ object: nonEmptyString(raw.object, 'content.object', index),
603
+ ...factExtras(raw, index),
604
+ },
605
+ tags: [],
606
+ };
607
+ case 'preference':
608
+ return {
609
+ nodeType: 'fact',
610
+ content: {
611
+ subject: nonEmptyString(raw.entity, 'content.entity', index),
612
+ predicate: nonEmptyString(raw.preferenceType, 'content.preferenceType', index),
613
+ object: nonEmptyString(raw.value, 'content.value', index),
614
+ ...factExtras(raw, index),
615
+ },
616
+ tags: ['preference'],
617
+ };
618
+ case 'observation':
619
+ // 与公共 memory_write 一致:observation 是 episode(episodeType=observation),不是 fact。
620
+ return {
621
+ nodeType: 'episode',
622
+ content: {
623
+ episodeType: 'observation',
624
+ content: nonEmptyString(raw.content, 'content.content', index),
625
+ },
626
+ tags: [],
627
+ };
628
+ case 'episode': {
629
+ const episodeType = nonEmptyString(raw.episodeType, 'content.episodeType', index);
630
+ if (!EPISODE_KINDS.has(episodeType)) {
631
+ throw validationError(index, 'content.episodeType', 'episodeType 非法');
632
+ }
633
+ const content = {
634
+ episodeType,
635
+ content: nonEmptyString(raw.content, 'content.content', index),
636
+ };
637
+ const title = optionalString(raw.title, 'content.title', index, 512);
638
+ if (title !== undefined) content.title = title;
639
+ const startTime = optionalNumber(raw.startTime, 'content.startTime', index);
640
+ const endTime = optionalNumber(raw.endTime, 'content.endTime', index);
641
+ if (startTime !== undefined) content.startTime = startTime;
642
+ if (endTime !== undefined) content.endTime = endTime;
643
+ const context = optionalString(raw.context, 'content.context', index, 512);
644
+ if (context !== undefined) content.context = context;
645
+ return { nodeType: 'episode', content, tags: [] };
646
+ }
647
+ case 'skill': {
648
+ const content = {
649
+ name: nonEmptyString(raw.name, 'content.name', index),
650
+ description: nonEmptyString(raw.description, 'content.description', index),
651
+ category: nonEmptyString(raw.category, 'content.category', index),
652
+ };
653
+ for (const field of ['steps', 'commands', 'toolReferences', 'prerequisites', 'relatedEntities']) {
654
+ const value = stringArray(raw[field], `content.${field}`, index, { maxItems: 64, maxChars: 1024 });
655
+ if (value !== undefined) content[field] = value;
656
+ }
657
+ return { nodeType: 'skill', content, tags: [] };
658
+ }
659
+ case 'entity': {
660
+ const entityType = nonEmptyString(raw.entityType, 'content.entityType', index);
661
+ if (!ENTITY_KINDS.has(entityType)) throw validationError(index, 'content.entityType', 'entityType 非法');
662
+ const content = {
663
+ entityType,
664
+ name: nonEmptyString(raw.name, 'content.name', index),
665
+ };
666
+ const description = optionalString(raw.description, 'content.description', index, 4096);
667
+ if (description !== undefined) content.description = description;
668
+ if (raw.properties !== undefined && raw.properties !== null) {
669
+ if (!isObject(raw.properties)) throw validationError(index, 'content.properties', 'properties 必须是对象');
670
+ if (byteSize(raw.properties) > MAX_JSON_FIELD_BYTES) {
671
+ throw validationError(index, 'content.properties', `properties 超过 ${MAX_JSON_FIELD_BYTES} 字节`);
672
+ }
673
+ content.properties = jsonClone(raw.properties);
674
+ }
675
+ return { nodeType: 'entity', content, tags: [] };
676
+ }
677
+ default:
678
+ throw validationError(index, 'kind', 'kind 非法');
679
+ }
680
+ }
681
+
682
+ /** 更新时对合并后的节点内容重新按 kind 校验(只保留已知字段)。 */
683
+ function normalizeNodeContent(kind, nodeType, raw, index) {
684
+ if (!isObject(raw)) throw validationError(index, 'patch.content', 'content 必须是对象');
685
+ if (byteSize(raw) > MAX_CONTENT_BYTES) {
686
+ throw new CapabilityError(413, 'payload_too_large', `content 超过 ${MAX_CONTENT_BYTES} 字节`, { index });
687
+ }
688
+ if (kind === 'observation' && nodeType === 'episode') {
689
+ const episodeType = nonEmptyString(raw.episodeType ?? 'observation', 'content.episodeType', index);
690
+ if (!EPISODE_KINDS.has(episodeType)) throw validationError(index, 'content.episodeType', 'episodeType 非法');
691
+ return {
692
+ episodeType,
693
+ content: nonEmptyString(raw.content, 'content.content', index),
694
+ ...(optionalString(raw.title, 'content.title', index, 512) !== undefined
695
+ ? { title: optionalString(raw.title, 'content.title', index, 512) }
696
+ : {}),
697
+ ...(optionalNumber(raw.startTime, 'content.startTime', index) !== undefined
698
+ ? { startTime: optionalNumber(raw.startTime, 'content.startTime', index) }
699
+ : {}),
700
+ ...(optionalNumber(raw.endTime, 'content.endTime', index) !== undefined
701
+ ? { endTime: optionalNumber(raw.endTime, 'content.endTime', index) }
702
+ : {}),
703
+ ...(optionalString(raw.context, 'content.context', index, 512) !== undefined
704
+ ? { context: optionalString(raw.context, 'content.context', index, 512) }
705
+ : {}),
706
+ };
707
+ }
708
+ if (kind === 'observation') {
709
+ return { content: nonEmptyString(raw.content, 'content.content', index) };
710
+ }
711
+ if (kind === 'fact' || kind === 'preference') {
712
+ return {
713
+ subject: nonEmptyString(raw.subject, 'content.subject', index),
714
+ predicate: nonEmptyString(raw.predicate, 'content.predicate', index),
715
+ object: nonEmptyString(raw.object, 'content.object', index),
716
+ ...factExtras(raw, index),
717
+ };
718
+ }
719
+ if (kind === 'episode') {
720
+ const episodeType = nonEmptyString(raw.episodeType, 'content.episodeType', index);
721
+ if (!EPISODE_KINDS.has(episodeType)) throw validationError(index, 'content.episodeType', 'episodeType 非法');
722
+ return {
723
+ episodeType,
724
+ content: nonEmptyString(raw.content, 'content.content', index),
725
+ ...(optionalString(raw.title, 'content.title', index, 512) !== undefined
726
+ ? { title: optionalString(raw.title, 'content.title', index, 512) }
727
+ : {}),
728
+ ...(optionalNumber(raw.startTime, 'content.startTime', index) !== undefined
729
+ ? { startTime: optionalNumber(raw.startTime, 'content.startTime', index) }
730
+ : {}),
731
+ ...(optionalNumber(raw.endTime, 'content.endTime', index) !== undefined
732
+ ? { endTime: optionalNumber(raw.endTime, 'content.endTime', index) }
733
+ : {}),
734
+ ...(optionalString(raw.context, 'content.context', index, 512) !== undefined
735
+ ? { context: optionalString(raw.context, 'content.context', index, 512) }
736
+ : {}),
737
+ };
738
+ }
739
+ if (kind === 'skill') {
740
+ const content = {
741
+ name: nonEmptyString(raw.name, 'content.name', index),
742
+ description: nonEmptyString(raw.description, 'content.description', index),
743
+ category: nonEmptyString(raw.category, 'content.category', index),
744
+ };
745
+ for (const field of ['steps', 'commands', 'toolReferences', 'prerequisites', 'relatedEntities']) {
746
+ const value = stringArray(raw[field], `content.${field}`, index, { maxItems: 64, maxChars: 1024 });
747
+ if (value !== undefined) content[field] = value;
748
+ }
749
+ return content;
750
+ }
751
+ if (kind === 'entity') {
752
+ const entityType = nonEmptyString(raw.entityType, 'content.entityType', index);
753
+ if (!ENTITY_KINDS.has(entityType)) throw validationError(index, 'content.entityType', 'entityType 非法');
754
+ const content = {
755
+ entityType,
756
+ name: nonEmptyString(raw.name, 'content.name', index),
757
+ };
758
+ const description = optionalString(raw.description, 'content.description', index, 4096);
759
+ if (description !== undefined) content.description = description;
760
+ if (raw.properties !== undefined && raw.properties !== null) {
761
+ if (!isObject(raw.properties)) throw validationError(index, 'content.properties', 'properties 必须是对象');
762
+ if (byteSize(raw.properties) > MAX_JSON_FIELD_BYTES) {
763
+ throw validationError(index, 'content.properties', `properties 超过 ${MAX_JSON_FIELD_BYTES} 字节`);
764
+ }
765
+ content.properties = jsonClone(raw.properties);
766
+ }
767
+ return content;
768
+ }
769
+ throw validationError(index, 'kind', '节点类型不支持更新');
770
+ }
771
+
772
+ function ownerMismatchError(index, domain, expected, actual) {
773
+ return new CapabilityError(400, 'owner_mismatch', '客户端 owner 与服务端推导不一致', {
774
+ index,
775
+ domain,
776
+ expected,
777
+ actual,
778
+ });
779
+ }
780
+
781
+ function contentHashFor(kind, content, validFrom) {
782
+ // observation 的节点正文已从 fact {content} 迁到 episode {episodeType, content};
783
+ // hash 仍只取语义正文,保证升级前后同一 observation 仍按内容去重。
784
+ const hashContent = kind === 'observation' && isObject(content)
785
+ ? { content: content.content }
786
+ : content;
787
+ return `sha256:${sha256Hex(canonicalJson({
788
+ kind,
789
+ content: hashContent,
790
+ ...(validFrom !== undefined ? { validFrom } : {}),
791
+ }))}`;
792
+ }
793
+
794
+ function dedupeKey(prefix, domain, value) {
795
+ return `${prefix}\u0000${domain}\u0000${value}`;
796
+ }
797
+
798
+ async function buildDedupeIndex(app) {
799
+ const index = { client: new Map(), hash: new Map() };
800
+ for (const node of await listAllNodes(app)) {
801
+ // 墓碑不参与去重;归档仍视为已存在(避免重复创建后又出现两条)。
802
+ if (!node || node.deletedAt || isInternalNode(node)) continue;
803
+ const metadata = isObject(node.metadata) ? node.metadata : {};
804
+ const domain = domainOfNamespace(node.namespace);
805
+ if (typeof metadata.clientItemId === 'string') {
806
+ index.client.set(dedupeKey('client', domain, metadata.clientItemId), node);
807
+ }
808
+ if (typeof metadata.contentHash === 'string') {
809
+ index.hash.set(dedupeKey('hash', domain, metadata.contentHash), node);
810
+ }
811
+ }
812
+ return index;
813
+ }
814
+
815
+ function recordWriteResult(status, node, item, owner, superseded = []) {
816
+ return {
817
+ ...(item.clientItemId !== undefined ? { clientItemId: item.clientItemId } : {}),
818
+ status,
819
+ id: node.id,
820
+ type: node.type,
821
+ kind: item.kind,
822
+ domain: item.domain,
823
+ ownerType: owner.ownerType,
824
+ ownerId: owner.ownerId,
825
+ ...(status === 'duplicate' ? { duplicate: true } : {}),
826
+ ...(superseded.length > 0 ? { superseded } : {}),
827
+ };
828
+ }
829
+
830
+ async function listNodesOfType(app, type) {
831
+ try {
832
+ if (app?.graph && typeof app.graph.listNodes === 'function') {
833
+ return await app.graph.listNodes({ type });
834
+ }
835
+ } catch {
836
+ // fall through
837
+ }
838
+ return (await listAllNodes(app)).filter((node) => node?.type === type);
839
+ }
840
+
841
+ function internalObjectMetadata(node) {
842
+ return isObject(node?.metadata?.internalObject) ? node.metadata.internalObject : {};
843
+ }
844
+
845
+ function internalObjectRevision(node) {
846
+ const value = internalObjectMetadata(node).revision ?? (isObject(node?.content) ? node.content.revision : undefined);
847
+ return typeof value === 'number' && Number.isFinite(value) ? value : 0;
848
+ }
849
+
850
+ function compareInternalObjectNodes(a, b) {
851
+ if (internalObjectRevision(a) !== internalObjectRevision(b)) {
852
+ return internalObjectRevision(b) - internalObjectRevision(a);
853
+ }
854
+ if ((b.updatedAt ?? 0) !== (a.updatedAt ?? 0)) return (b.updatedAt ?? 0) - (a.updatedAt ?? 0);
855
+ return String(b.id).localeCompare(String(a.id));
856
+ }
857
+
858
+ function checkpointState(node) {
859
+ const content = isObject(node?.content) ? node.content : {};
860
+ return isObject(content.state) ? content.state : {};
861
+ }
862
+
863
+ function checkpointSchema(node) {
864
+ const state = checkpointState(node);
865
+ return state.schema === 2 ? 2 : 1;
866
+ }
867
+
868
+ function isV2CheckpointNode(node) {
869
+ const domain = domainOfNamespace(node?.namespace);
870
+ return node?.type === 'context_checkpoint'
871
+ && isInternalNode(node)
872
+ && (domain === 'default' || (domain.startsWith('task:') && !domain.startsWith('__')));
873
+ }
874
+
875
+ function checkpointAgentId(node) {
876
+ const content = isObject(node?.content) ? node.content : {};
877
+ const internalObject = internalObjectMetadata(node);
878
+ if (typeof content.agentId === 'string') return content.agentId;
879
+ if (typeof internalObject.agentId === 'string') return internalObject.agentId;
880
+ return null;
881
+ }
882
+
883
+ function checkpointThreadId(node) {
884
+ const content = isObject(node?.content) ? node.content : {};
885
+ const internalObject = internalObjectMetadata(node);
886
+ const state = checkpointState(node);
887
+ if (typeof content.threadId === 'string') return content.threadId;
888
+ if (isObject(state.task) && typeof state.task.threadId === 'string') return state.task.threadId;
889
+ if (typeof internalObject.threadId === 'string') return internalObject.threadId;
890
+ const domain = domainOfNamespace(node?.namespace);
891
+ return domain.startsWith('task:') ? domain.slice('task:'.length) : null;
892
+ }
893
+
894
+ function checkpointMatches(node, agentId, threadId, domain = null) {
895
+ if (!isV2CheckpointNode(node) || checkpointThreadId(node) !== threadId) return false;
896
+ const nodeDomain = domainOfNamespace(node?.namespace);
897
+ if (domain !== null && nodeDomain !== domain) return false;
898
+ if (nodeDomain.startsWith('task:')) return true;
899
+ return checkpointAgentId(node) === agentId;
900
+ }
901
+
902
+ async function currentSelfRecord(app, agentId) {
903
+ const nodes = await listNodesOfType(app, 'self_record');
904
+ return nodes
905
+ .filter((node) => !node.deletedAt
906
+ && isInternalNode(node)
907
+ && internalObjectKind(node) === 'self_record'
908
+ && domainOfNamespace(node.namespace) === `agent:${agentId}`)
909
+ .sort(compareInternalObjectNodes)[0] ?? null;
910
+ }
911
+
912
+ function checkpointRevisionKey(node) {
913
+ const domain = domainOfNamespace(node?.namespace);
914
+ if (domain.startsWith('task:')) return `task:${domain}`;
915
+ return `default:${checkpointAgentId(node) ?? ''}:${checkpointThreadId(node) ?? ''}`;
916
+ }
917
+
918
+ async function currentCheckpoint(app, { agentId, threadId, domain = null } = {}) {
919
+ const nodes = await listNodesOfType(app, 'context_checkpoint');
920
+ const matches = nodes
921
+ .filter((node) => !node.deletedAt && checkpointMatches(node, agentId, threadId, domain));
922
+ if (matches.length === 0) return null;
923
+ const keyed = new Map();
924
+ for (const node of matches) {
925
+ const key = checkpointRevisionKey(node);
926
+ const existing = keyed.get(key);
927
+ if (!existing || compareInternalObjectNodes(node, existing) < 0) keyed.set(key, node);
928
+ }
929
+ return [...keyed.values()].sort(compareInternalObjectNodes)[0] ?? null;
930
+ }
931
+
932
+ async function allCheckpoints(app, agentId, threadId = null) {
933
+ const nodes = await listNodesOfType(app, 'context_checkpoint');
934
+ return nodes.filter((node) => {
935
+ if (node.deletedAt || !isV2CheckpointNode(node)) return false;
936
+ const domain = domainOfNamespace(node.namespace);
937
+ if (domain.startsWith('task:')) {
938
+ if (threadId !== null && checkpointThreadId(node) !== threadId) return false;
939
+ return true;
940
+ }
941
+ if (checkpointAgentId(node) !== agentId) return false;
942
+ if (threadId !== null && checkpointThreadId(node) !== threadId) return false;
943
+ return checkpointThreadId(node) !== null;
944
+ });
945
+ }
946
+
947
+ function checkpointExpired(node, now = Date.now()) {
948
+ const content = isObject(node?.content) ? node.content : {};
949
+ return typeof content.expiresAt === 'number' && content.expiresAt > 0 && content.expiresAt < now;
950
+ }
951
+
952
+ async function isCompactStale(app, node) {
953
+ const content = isObject(node?.content) ? node.content : {};
954
+ const sourceIds = Array.isArray(content.sourceIds) ? content.sourceIds : [];
955
+ const sourceHashes = Array.isArray(content.sourceHashes) ? content.sourceHashes : [];
956
+ for (let index = 0; index < sourceIds.length; index += 1) {
957
+ const source = await app?.graph?.getNode?.(sourceIds[index]);
958
+ if (!source || source.deletedAt) return true;
959
+ const expected = sourceHashes[index];
960
+ if (typeof expected === 'string' && expected.length > 0) {
961
+ const actual = `sha256:${sha256Hex(canonicalJson(source.content ?? null))}`;
962
+ if (actual !== expected) return true;
963
+ } else if ((source.updatedAt ?? 0) > (node.createdAt ?? 0)) {
964
+ return true;
965
+ }
966
+ }
967
+ return false;
968
+ }
969
+
970
+ export function requestIdOf(req) {
971
+ const incoming = req?.headers?.['x-request-id'];
972
+ return typeof incoming === 'string' && REQUEST_ID_RE.test(incoming) ? incoming : `req_${randomUUID()}`;
973
+ }
974
+
975
+ export function hostIdForHome(home) {
976
+ return `h_${createHash('sha256').update(String(home ?? '')).digest('hex').slice(0, 16)}`;
977
+ }
978
+
979
+ function parseActor(value) {
980
+ if (!isObject(value)) {
981
+ throw new CapabilityError(400, 'invalid_request', '缺少 actor');
982
+ }
983
+ if (value.type === 'agent') {
984
+ const agentId = typeof value.agentId === 'string' ? value.agentId.trim() : '';
985
+ if (agentId === '') throw new CapabilityError(400, 'invalid_request', 'actor.type=agent 需要 agentId');
986
+ if (!isValidAgentId(agentId)) throw new CapabilityError(400, 'invalid_agent_id', 'agentId 格式非法');
987
+ return {
988
+ type: 'agent',
989
+ agentId,
990
+ ...(typeof value.displayName === 'string' && value.displayName.length > 0
991
+ ? { displayName: value.displayName.slice(0, 128) }
992
+ : {}),
993
+ };
994
+ }
995
+ if (value.type === 'user') {
996
+ return {
997
+ type: 'user',
998
+ ...(typeof value.userId === 'string' && /^u_[A-Za-z0-9._:-]{1,128}$/.test(value.userId)
999
+ ? { userId: value.userId }
1000
+ : {}),
1001
+ ...(typeof value.displayName === 'string' && value.displayName.length > 0
1002
+ ? { displayName: value.displayName.slice(0, 128) }
1003
+ : {}),
1004
+ };
1005
+ }
1006
+ if (value.type === 'system') return { type: 'system' };
1007
+ throw new CapabilityError(400, 'invalid_request', 'actor.type 必须是 agent | user | system');
1008
+ }
1009
+
1010
+ function actorFromQuery(url) {
1011
+ const raw = url?.searchParams?.get('actor');
1012
+ if (typeof raw === 'string' && raw.length > 0) {
1013
+ if (raw === 'user' || raw === 'system') return { type: raw };
1014
+ if (raw.startsWith('agent:')) return { type: 'agent', agentId: raw.slice('agent:'.length) };
1015
+ try {
1016
+ return JSON.parse(raw);
1017
+ } catch {
1018
+ throw new CapabilityError(400, 'invalid_request', 'actor 必须是 JSON 对象或 agentId');
1019
+ }
1020
+ }
1021
+ const agentId = url?.searchParams?.get('agentId');
1022
+ if (typeof agentId === 'string' && agentId.length > 0) return { type: 'agent', agentId };
1023
+ throw new CapabilityError(400, 'invalid_request', '缺少 actor');
1024
+ }
1025
+
1026
+ function parseThreadId(value) {
1027
+ if (!hasValue(value)) return null;
1028
+ if (typeof value !== 'string' || !THREAD_ID_RE.test(value)) {
1029
+ throw new CapabilityError(400, 'invalid_thread_id', 'threadId 格式非法');
1030
+ }
1031
+ return value;
1032
+ }
1033
+
1034
+ function parseTypes(value) {
1035
+ if (!hasValue(value)) return [...DEFAULT_TYPES];
1036
+ if (!Array.isArray(value) || value.length === 0) {
1037
+ throw new CapabilityError(400, 'invalid_request', 'types 必须是非空数组');
1038
+ }
1039
+ const out = [];
1040
+ for (const type of value) {
1041
+ if (typeof type !== 'string' || !ALLOWED_TYPES.has(type)) {
1042
+ throw new CapabilityError(400, 'invalid_request', 'types 含未知类型');
1043
+ }
1044
+ if (!out.includes(type)) out.push(type);
1045
+ }
1046
+ return out;
1047
+ }
1048
+
1049
+ function parseFilters(value) {
1050
+ if (!hasValue(value)) return undefined;
1051
+ if (!isObject(value)) throw new CapabilityError(400, 'invalid_request', 'filters 必须是对象');
1052
+ const out = {};
1053
+ if (Array.isArray(value.tags)) {
1054
+ if (value.tags.length > MAX_TAGS) {
1055
+ throw new CapabilityError(400, 'invalid_request', `tags 最多 ${MAX_TAGS} 个`);
1056
+ }
1057
+ if (value.tags.some((tag) => typeof tag !== 'string' || tag.length === 0 || tag.length > MAX_TAG_CHARS)) {
1058
+ throw new CapabilityError(400, 'invalid_request', `每个 tag 需为 1–${MAX_TAG_CHARS} 字符`);
1059
+ }
1060
+ if (value.tags.length > 0) out.tags = [...value.tags];
1061
+ }
1062
+ if (typeof value.createdAfter === 'number' && Number.isFinite(value.createdAfter)) out.createdAfter = value.createdAfter;
1063
+ if (typeof value.createdBefore === 'number' && Number.isFinite(value.createdBefore)) out.createdBefore = value.createdBefore;
1064
+ if (typeof value.entity === 'string' && value.entity.length > 0) out.entity = value.entity;
1065
+ if (typeof value.minConfidence === 'number' && Number.isFinite(value.minConfidence)) {
1066
+ out.minConfidence = Math.min(Math.max(value.minConfidence, 0), 1);
1067
+ }
1068
+ // 显式 domains 是唯一域入口;忽略 filters.namespace,避免绕过域过滤。
1069
+ return Object.keys(out).length > 0 ? out : undefined;
1070
+ }
1071
+
1072
+ function clampLimit(value, fallback = DEFAULT_LIMIT) {
1073
+ const n = typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : fallback;
1074
+ return Math.min(Math.max(n, 1), MAX_LIMIT);
1075
+ }
1076
+
1077
+ function clampOffset(value) {
1078
+ const n = typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : 0;
1079
+ return Math.max(n, 0);
1080
+ }
1081
+
1082
+ function clampDepth(value) {
1083
+ const n = typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : 2;
1084
+ return Math.min(Math.max(n, 0), MAX_DEPTH);
1085
+ }
1086
+
1087
+ function subscriptionView(config) {
1088
+ const raw = Array.isArray(config?.sync?.namespaces)
1089
+ ? config.sync.namespaces.filter((ns) => typeof ns === 'string' && ns.length > 0 && ns !== '__policy__')
1090
+ : [];
1091
+ const namespaces = [...new Set(raw)];
1092
+ return { mode: namespaces.length === 0 ? 'all' : 'list', namespaces };
1093
+ }
1094
+
1095
+ function defaultDomainsFor(endpoint, actor, threadId) {
1096
+ const domains = ['user'];
1097
+ if (actor.type === 'agent') domains.push(`agent:${actor.agentId}`);
1098
+ domains.push('default');
1099
+ if (endpoint === 'skills') {
1100
+ domains.push('shared');
1101
+ } else if (threadId) {
1102
+ domains.push(`task:${threadId}`);
1103
+ }
1104
+ return domains;
1105
+ }
1106
+
1107
+ async function listAllNodes(app) {
1108
+ try {
1109
+ const storage = app?.storage;
1110
+ if (storage && typeof storage.listNodes === 'function') {
1111
+ return await storage.listNodes();
1112
+ }
1113
+ } catch {
1114
+ // fall through
1115
+ }
1116
+ try {
1117
+ if (app?.graph && typeof app.graph.listNodes === 'function') {
1118
+ return await app.graph.listNodes({});
1119
+ }
1120
+ } catch {
1121
+ // fall through
1122
+ }
1123
+ return [];
1124
+ }
1125
+
1126
+ async function knownDomainsFor(app, _config, actor, threadId, currentService = null) {
1127
+ const known = new Set(['user', 'default', 'shared', 'system']);
1128
+ if (actor?.type === 'agent') known.add(`agent:${actor.agentId}`);
1129
+ if (threadId) known.add(`task:${threadId}`);
1130
+ try {
1131
+ if (app && typeof app.getNamespaceDirectory === 'function') {
1132
+ for (const ns of await app.getNamespaceDirectory()) {
1133
+ const domain = normalizeDomain(ns);
1134
+ if (domain) known.add(domain);
1135
+ }
1136
+ return known;
1137
+ }
1138
+ } catch {
1139
+ // fall through to unified stats
1140
+ }
1141
+ try {
1142
+ if (currentService && typeof currentService.stats === 'function') {
1143
+ const stats = await currentService.stats();
1144
+ for (const entry of Array.isArray(stats?.domains) ? stats.domains : []) {
1145
+ const domain = normalizeDomain(entry?.domain);
1146
+ if (domain) known.add(domain);
1147
+ }
1148
+ }
1149
+ } catch {
1150
+ // 统计不可用时只保留内建域;不另造第二套扫描。
1151
+ }
1152
+ return known;
1153
+ }
1154
+
1155
+ function isBuiltinDomain(domain, actor, threadId) {
1156
+ if (RESERVED_DOMAINS.has(domain)) return true;
1157
+ if (actor?.type === 'agent' && domain === `agent:${actor.agentId}`) return true;
1158
+ if (threadId && domain === `task:${threadId}`) return true;
1159
+ return false;
1160
+ }
1161
+
1162
+ async function resolveDomains({
1163
+ requested,
1164
+ endpoint,
1165
+ actor,
1166
+ threadId,
1167
+ strictDomains,
1168
+ app,
1169
+ config,
1170
+ service,
1171
+ }) {
1172
+ if (hasValue(requested) && !Array.isArray(requested)) {
1173
+ throw new CapabilityError(400, 'invalid_request', 'domains 必须是字符串数组');
1174
+ }
1175
+ const explicit = Array.isArray(requested) && requested.length > 0;
1176
+ if (explicit && requested.length > MAX_DOMAINS) {
1177
+ throw new CapabilityError(400, 'invalid_request', `domains 最多 ${MAX_DOMAINS} 个`);
1178
+ }
1179
+
1180
+ const candidates = explicit
1181
+ ? requested.map((value) => {
1182
+ if (typeof value !== 'string') throw new CapabilityError(400, 'domain_invalid', 'domains 含非字符串');
1183
+ const domain = normalizeDomain(value);
1184
+ if (!domain) throw new CapabilityError(400, 'domain_invalid', 'domains 含非法域', { domain: value });
1185
+ return domain;
1186
+ })
1187
+ : defaultDomainsFor(endpoint, actor, threadId);
1188
+
1189
+ const known = explicit
1190
+ ? await knownDomainsFor(app, config, actor, threadId, service)
1191
+ : null;
1192
+ const allowed = [];
1193
+ const warnings = [];
1194
+ for (const domain of candidates) {
1195
+ if (allowed.includes(domain)) continue;
1196
+ const available = known === null || known.has(domain) || isBuiltinDomain(domain, actor, threadId);
1197
+ if (!available) {
1198
+ if (strictDomains) {
1199
+ throw new CapabilityError(403, 'domain_read_forbidden', '域在本机不可用', { domain });
1200
+ }
1201
+ warnings.push({ code: 'domain_unavailable', domain, message: `域 ${domain} 本机不可用,已跳过` });
1202
+ continue;
1203
+ }
1204
+ allowed.push(domain);
1205
+ }
1206
+ return { domains: allowed, warnings, explicit };
1207
+ }
1208
+
1209
+ function buildProvenance(metadata, domain, owner, node) {
1210
+ const stored = isObject(metadata?.provenance) ? metadata.provenance : {};
1211
+ const agentIdFromDomain = domain.startsWith('agent:') ? domain.slice('agent:'.length) : null;
1212
+ const threadIdFromDomain = domain.startsWith('task:') ? domain.slice('task:'.length) : null;
1213
+ const writerType = typeof stored.writerType === 'string'
1214
+ ? stored.writerType
1215
+ : owner.ownerType === 'agent'
1216
+ ? 'agent'
1217
+ : owner.ownerType === 'user'
1218
+ ? 'user'
1219
+ : 'system';
1220
+ return {
1221
+ source: typeof stored.source === 'string' ? stored.source : 'legacy',
1222
+ writerType,
1223
+ writerId: typeof stored.writerId === 'string' ? stored.writerId : owner.ownerId,
1224
+ extractor: typeof stored.extractor === 'string' ? stored.extractor : null,
1225
+ model: typeof stored.model === 'string' ? stored.model : null,
1226
+ version: typeof stored.version === 'string' ? stored.version : null,
1227
+ deviceId: typeof stored.deviceId === 'string'
1228
+ ? stored.deviceId
1229
+ : typeof metadata?.deviceId === 'string'
1230
+ ? metadata.deviceId
1231
+ : node?.createdBy ?? null,
1232
+ hostId: typeof stored.hostId === 'string'
1233
+ ? stored.hostId
1234
+ : typeof metadata?.hostId === 'string'
1235
+ ? metadata.hostId
1236
+ : null,
1237
+ threadId: threadIdFromDomain ?? (typeof stored.threadId === 'string' ? stored.threadId : null),
1238
+ agentId: agentIdFromDomain ?? (typeof stored.agentId === 'string' ? stored.agentId : null),
1239
+ agentName: typeof stored.agentName === 'string'
1240
+ ? stored.agentName
1241
+ : typeof metadata?.agentName === 'string'
1242
+ ? metadata.agentName
1243
+ : null,
1244
+ messageIds: Array.isArray(stored.messageIds)
1245
+ ? stored.messageIds.filter((id) => typeof id === 'string').slice(0, 64)
1246
+ : [],
1247
+ rawChunkIds: Array.isArray(stored.rawChunkIds)
1248
+ ? stored.rawChunkIds.filter((id) => typeof id === 'string').slice(0, 64)
1249
+ : [],
1250
+ confirmation: typeof stored.confirmation === 'string' ? stored.confirmation : null,
1251
+ at: typeof stored.at === 'number' ? stored.at : node?.createdAt ?? null,
1252
+ };
1253
+ }
1254
+
1255
+ function normalizeValidTo(value) {
1256
+ return typeof value === 'number' && value !== 9999999999999 ? value : null;
1257
+ }
1258
+
1259
+ function kindOf(node, memory) {
1260
+ if (node) return semanticKindOf(node);
1261
+ return semanticKindOf({
1262
+ type: memory?.type ?? 'unknown',
1263
+ content: {},
1264
+ tags: Array.isArray(memory?.metadata?.tags) ? memory.metadata.tags : [],
1265
+ metadata: {},
1266
+ });
1267
+ }
1268
+
1269
+ function renderNodeText(node) {
1270
+ const content = node?.content;
1271
+ if (typeof content === 'string') return content;
1272
+ if (!isObject(content)) return '';
1273
+ if (node?.type === 'fact') {
1274
+ const { subject, predicate, object } = content;
1275
+ if (typeof subject === 'string' && typeof predicate === 'string' && typeof object === 'string') {
1276
+ return `${subject} ${predicate} ${object}`;
1277
+ }
1278
+ }
1279
+ if (typeof content.content === 'string') return content.content;
1280
+ if (typeof content.name === 'string') return content.name;
1281
+ if (typeof content.title === 'string') return content.title;
1282
+ if (typeof content.summary === 'string') return content.summary;
1283
+ try {
1284
+ return JSON.stringify(content);
1285
+ } catch {
1286
+ return '';
1287
+ }
1288
+ }
1289
+
1290
+ function recordView(memory, node, { userId = 'user', withScore = false, detailAvailability = null } = {}) {
1291
+ const domain = domainOfNamespace(node?.namespace ?? memory?.metadata?.namespace);
1292
+ const owner = deriveOwner(domain, { userId });
1293
+ const metadata = isObject(node?.metadata) ? node.metadata : {};
1294
+ const id = memory?.id ?? node?.id;
1295
+ const text = typeof memory?.content === 'string' ? memory.content : renderNodeText(node);
1296
+ const content = isObject(node?.content) ? node.content : { content: text };
1297
+ const tags = Array.isArray(node?.tags)
1298
+ ? node.tags
1299
+ : Array.isArray(memory?.metadata?.tags)
1300
+ ? memory.metadata.tags
1301
+ : [];
1302
+ const view = {
1303
+ id,
1304
+ type: node?.type ?? memory?.type ?? 'unknown',
1305
+ kind: kindOf(node, memory),
1306
+ domain,
1307
+ namespace: domain,
1308
+ ownerType: owner.ownerType,
1309
+ ownerId: owner.ownerId,
1310
+ provenance: buildProvenance(metadata, domain, owner, node),
1311
+ content,
1312
+ text,
1313
+ tags,
1314
+ validFrom: node?.validFrom ?? memory?.metadata?.validFrom ?? null,
1315
+ validTo: normalizeValidTo(node?.validTo ?? memory?.metadata?.validTo),
1316
+ ...(typeof metadata.supersededBy === 'string' ? { supersededBy: metadata.supersededBy } : {}),
1317
+ ...(typeof metadata.supersededAt === 'number' ? { supersededAt: metadata.supersededAt } : {}),
1318
+ createdAt: node?.createdAt ?? memory?.metadata?.createdAt ?? null,
1319
+ updatedAt: node?.updatedAt ?? node?.createdAt ?? memory?.metadata?.createdAt ?? null,
1320
+ // 详情是否存在是派生状态:新运行时批量查 DetailRecord;旧运行时保留 metadata 兼容。
1321
+ detailAvailable: detailAvailability !== null
1322
+ ? detailAvailability.get(id) === true
1323
+ : metadata.detailAvailable !== false,
1324
+ legacy: !isObject(metadata.provenance),
1325
+ };
1326
+ if (withScore && typeof memory?.relevance === 'number') {
1327
+ view.score = memory.relevance;
1328
+ view.why = 'vector+keyword';
1329
+ } else if (withScore) {
1330
+ view.why = 'keyword';
1331
+ }
1332
+ return view;
1333
+ }
1334
+
1335
+ function nodeView(node, { userId = 'user', detailAvailability = null } = {}) {
1336
+ return recordView(null, node, { userId, detailAvailability });
1337
+ }
1338
+
1339
+ /**
1340
+ * 批量派生记录/节点的 `detailAvailable`。
1341
+ *
1342
+ * 新 MemoryService 一次扫描详情并返回 Map;旧运行时返回 null,
1343
+ * 由 recordView 回退到 metadata(不产生 N+1 查询)。
1344
+ */
1345
+ async function detailAvailabilityFor(currentService, ids, { now = Date.now() } = {}) {
1346
+ if (!currentService || typeof currentService.detailAvailabilityForRecords !== 'function') return null;
1347
+ const unique = [...new Set((Array.isArray(ids) ? ids : [])
1348
+ .filter((id) => typeof id === 'string' && id.length > 0))];
1349
+ if (unique.length === 0) return new Map();
1350
+ return currentService.detailAvailabilityForRecords(unique, { now });
1351
+ }
1352
+
1353
+ async function loadNode(app, id, cache) {
1354
+ if (!cache) return null;
1355
+ if (cache.has(id)) return cache.get(id);
1356
+ let node = null;
1357
+ try {
1358
+ if (app?.graph && typeof app.graph.getNode === 'function') {
1359
+ node = await app.graph.getNode(id);
1360
+ }
1361
+ } catch {
1362
+ node = null;
1363
+ }
1364
+ cache.set(id, node);
1365
+ return node;
1366
+ }
1367
+
1368
+ function internalObjectKind(node) {
1369
+ const metadata = isObject(node?.metadata) ? node.metadata : {};
1370
+ const internalObject = isObject(metadata.internalObject) ? metadata.internalObject : {};
1371
+ if (typeof internalObject.kind === 'string') return internalObject.kind;
1372
+ return node?.type ?? null;
1373
+ }
1374
+
1375
+ // ---------- 内部对象视图(compact / self_record / context_checkpoint) ----------
1376
+
1377
+ function internalProvenance(node, domain, userId) {
1378
+ const metadata = isObject(node?.metadata) ? node.metadata : {};
1379
+ const owner = deriveOwner(domain, { userId });
1380
+ return buildProvenance(metadata, domain, owner, node);
1381
+ }
1382
+
1383
+ function compactObjectView(node, { userId = 'user', stale = false } = {}) {
1384
+ const domain = domainOfNamespace(node?.namespace);
1385
+ const content = isObject(node?.content) ? node.content : {};
1386
+ const owner = deriveOwner(domain, { userId });
1387
+ return {
1388
+ id: node.id,
1389
+ type: 'compact',
1390
+ kind: 'compact',
1391
+ domain,
1392
+ namespace: domain,
1393
+ ownerType: owner.ownerType,
1394
+ ownerId: owner.ownerId,
1395
+ internal: true,
1396
+ provenance: internalProvenance(node, domain, userId),
1397
+ summary: typeof content.summary === 'string' ? content.summary : '',
1398
+ sourceIds: Array.isArray(content.sourceIds) ? content.sourceIds : [],
1399
+ sourceHashes: Array.isArray(content.sourceHashes) ? content.sourceHashes : [],
1400
+ strategy: typeof content.strategy === 'string' ? content.strategy : 'summary',
1401
+ tokenCount: typeof content.tokenCount === 'number' ? content.tokenCount : null,
1402
+ ...(isObject(content.model) ? { model: content.model } : {}),
1403
+ stale,
1404
+ createdAt: node.createdAt ?? null,
1405
+ updatedAt: node.updatedAt ?? node.createdAt ?? null,
1406
+ };
1407
+ }
1408
+
1409
+ function selfRecordView(node, { userId = 'user' } = {}) {
1410
+ const domain = domainOfNamespace(node?.namespace);
1411
+ const content = isObject(node?.content) ? node.content : {};
1412
+ const owner = deriveOwner(domain, { userId });
1413
+ const record = isObject(content.record)
1414
+ ? content.record
1415
+ : Object.fromEntries(Object.entries(content).filter(([key]) => key !== 'agentId' && key !== 'revision'));
1416
+ const internalObject = internalObjectMetadata(node);
1417
+ return {
1418
+ id: node.id,
1419
+ type: 'self_record',
1420
+ kind: 'self_record',
1421
+ domain,
1422
+ namespace: domain,
1423
+ ownerType: owner.ownerType,
1424
+ ownerId: owner.ownerId,
1425
+ internal: true,
1426
+ agentId: typeof content.agentId === 'string'
1427
+ ? content.agentId
1428
+ : typeof internalObject.agentId === 'string'
1429
+ ? internalObject.agentId
1430
+ : domain.startsWith('agent:') ? domain.slice('agent:'.length) : null,
1431
+ revision: internalObjectRevision(node),
1432
+ content: record,
1433
+ provenance: internalProvenance(node, domain, userId),
1434
+ createdAt: node.createdAt ?? null,
1435
+ updatedAt: node.updatedAt ?? node.createdAt ?? null,
1436
+ };
1437
+ }
1438
+
1439
+ function checkpointObjectView(node, { userId = 'user' } = {}) {
1440
+ const domain = domainOfNamespace(node?.namespace);
1441
+ const content = isObject(node?.content) ? node.content : {};
1442
+ const owner = deriveOwner(domain, { userId });
1443
+ const internalObject = internalObjectMetadata(node);
1444
+ const threadId = typeof content.threadId === 'string'
1445
+ ? content.threadId
1446
+ : isObject(checkpointState(node).task) && typeof checkpointState(node).task.threadId === 'string'
1447
+ ? checkpointState(node).task.threadId
1448
+ : typeof internalObject.threadId === 'string'
1449
+ ? internalObject.threadId
1450
+ : domain.startsWith('task:') ? domain.slice('task:'.length) : null;
1451
+ const state = checkpointState(node);
1452
+ const schema = checkpointSchema(node);
1453
+ const contentMode = schema === 2
1454
+ ? (state.contentMode === 'summary_only' ? 'summary_only' : 'structured')
1455
+ : null;
1456
+ const structured = schema === 2 && contentMode === 'structured';
1457
+ const summary = typeof content.summary === 'string' ? content.summary : null;
1458
+ const summaryOnly = contentMode === 'summary_only';
1459
+ const legacy = schema !== 2;
1460
+ return {
1461
+ id: node.id,
1462
+ type: 'context_checkpoint',
1463
+ kind: 'context_checkpoint',
1464
+ domain,
1465
+ namespace: domain,
1466
+ ownerType: owner.ownerType,
1467
+ ownerId: owner.ownerId,
1468
+ internal: true,
1469
+ agentId: typeof content.agentId === 'string'
1470
+ ? content.agentId
1471
+ : typeof internalObject.agentId === 'string'
1472
+ ? internalObject.agentId
1473
+ : null,
1474
+ threadId,
1475
+ revision: internalObjectRevision(node),
1476
+ schema,
1477
+ state,
1478
+ contentMode,
1479
+ structured,
1480
+ legacy,
1481
+ degraded: summaryOnly || legacy,
1482
+ summary,
1483
+ recordIds: Array.isArray(content.recordIds) ? content.recordIds : [],
1484
+ detailIds: Array.isArray(content.detailIds) ? content.detailIds : [],
1485
+ lease: isObject(content.lease) ? content.lease : null,
1486
+ updatedBy: isObject(content.updatedBy) ? content.updatedBy : null,
1487
+ expiresAt: typeof content.expiresAt === 'number' ? content.expiresAt : 0,
1488
+ provenance: internalProvenance(node, domain, userId),
1489
+ createdAt: node.createdAt ?? null,
1490
+ updatedAt: node.updatedAt ?? node.createdAt ?? null,
1491
+ };
1492
+ }
1493
+
1494
+ function checkpointWarnings(view) {
1495
+ const warnings = [];
1496
+ if (view?.contentMode === 'summary_only' && view?.summary === null) warnings.push('summary_unavailable');
1497
+ if (view?.contentMode === 'summary_only') warnings.push('checkpoint_summary_only');
1498
+ if (view?.legacy) warnings.push('checkpoint_legacy');
1499
+ return warnings;
1500
+ }
1501
+
1502
+ function checkpointDegraded(view) {
1503
+ return view?.contentMode === 'summary_only' || view?.legacy === true;
1504
+ }
1505
+
1506
+ function normalizeSelfRecord(value, index) {
1507
+ if (!isObject(value)) throw validationError(index, 'record', 'record 必须是对象');
1508
+ const record = {};
1509
+ const displayName = optionalString(value.displayName, 'record.displayName', index, 128);
1510
+ if (displayName !== undefined) record.displayName = displayName;
1511
+ for (const field of ['goals', 'traits', 'capabilities', 'boundaries']) {
1512
+ const list = stringArray(value[field], `record.${field}`, index, { maxItems: 64, maxChars: 1024 });
1513
+ if (list !== undefined) record[field] = list;
1514
+ }
1515
+ if (value.preferences !== undefined && value.preferences !== null) {
1516
+ if (!isObject(value.preferences)) throw validationError(index, 'record.preferences', 'preferences 必须是对象');
1517
+ if (byteSize(value.preferences) > MAX_JSON_FIELD_BYTES) {
1518
+ throw validationError(index, 'record.preferences', `preferences 超过 ${MAX_JSON_FIELD_BYTES} 字节`);
1519
+ }
1520
+ record.preferences = jsonClone(value.preferences);
1521
+ }
1522
+ if (byteSize(record) > MAX_CONTENT_BYTES) {
1523
+ throw new CapabilityError(413, 'payload_too_large', 'SelfRecord 超过大小限制', { index });
1524
+ }
1525
+ return record;
1526
+ }
1527
+
1528
+ function checkpointFieldString(value, field, index, { maxBytes = MAX_CHECKPOINT_ITEM_BYTES, allowNull = false } = {}) {
1529
+ if (value === undefined || value === null) {
1530
+ if (allowNull) return null;
1531
+ throw validationError(index, field, `${field} 必须是非空字符串`);
1532
+ }
1533
+ if (typeof value !== 'string') throw validationError(index, field, `${field} 必须是字符串`);
1534
+ if (value.trim() === '') {
1535
+ if (allowNull) return null;
1536
+ throw validationError(index, field, `${field} 必须是非空字符串`);
1537
+ }
1538
+ if (Buffer.byteLength(value, 'utf-8') > maxBytes) {
1539
+ throw new CapabilityError(413, 'payload_too_large', `${field} 超过 ${maxBytes} 字节`, { index, field });
1540
+ }
1541
+ return value;
1542
+ }
1543
+
1544
+ function checkpointOptionalId(value, field, index) {
1545
+ if (value === undefined || value === null) return null;
1546
+ if (typeof value !== 'string' || value.length === 0 || value.length > MAX_CHECKPOINT_ID_CHARS) {
1547
+ throw validationError(index, field, `${field} 需为 1–${MAX_CHECKPOINT_ID_CHARS} 字符`);
1548
+ }
1549
+ return value;
1550
+ }
1551
+
1552
+ function checkpointStringList(value, field, index, { maxItems = MAX_CHECKPOINT_REFERENCES, maxChars = 128 } = {}) {
1553
+ if (value === undefined || value === null) return [];
1554
+ if (!Array.isArray(value)) throw validationError(index, field, `${field} 必须是字符串数组`);
1555
+ if (value.length > maxItems) throw validationError(index, field, `${field} 最多 ${maxItems} 项`);
1556
+ const out = [];
1557
+ for (const entry of value) {
1558
+ if (typeof entry !== 'string' || entry.length === 0 || entry.length > maxChars) {
1559
+ throw validationError(index, field, `${field} 每项需为 1–${maxChars} 字符`);
1560
+ }
1561
+ if (!out.includes(entry)) out.push(entry);
1562
+ }
1563
+ return out;
1564
+ }
1565
+
1566
+ function checkpointItems(value, field, index, { maxItems, normalize }) {
1567
+ if (value === undefined || value === null) return [];
1568
+ if (!Array.isArray(value)) throw validationError(index, field, `${field} 必须是数组`);
1569
+ if (value.length > maxItems) throw validationError(index, field, `${field} 最多 ${maxItems} 项`);
1570
+ return value.map((entry, itemIndex) => normalize(entry, `${field}[${itemIndex}]`));
1571
+ }
1572
+
1573
+ function checkpointTextItem(value, field, index, { maxBytes = MAX_CHECKPOINT_ITEM_BYTES } = {}) {
1574
+ if (!isObject(value)) throw validationError(index, field, `${field} 必须是对象`);
1575
+ const item = {
1576
+ id: checkpointOptionalId(value.id, `${field}.id`, index),
1577
+ text: checkpointFieldString(value.text, `${field}.text`, index, { maxBytes }),
1578
+ };
1579
+ return item;
1580
+ }
1581
+
1582
+ function normalizeCheckpointReferences(value, index) {
1583
+ if (value === undefined || value === null) {
1584
+ return { recordIds: [], detailIds: [], messageIds: [], fleetTaskId: null, urls: [] };
1585
+ }
1586
+ if (!isObject(value)) throw validationError(index, 'state.references', 'references 必须是对象');
1587
+ return {
1588
+ recordIds: checkpointStringList(value.recordIds, 'state.references.recordIds', index),
1589
+ detailIds: checkpointStringList(value.detailIds, 'state.references.detailIds', index),
1590
+ messageIds: checkpointStringList(value.messageIds, 'state.references.messageIds', index, { maxChars: 256 }),
1591
+ fleetTaskId: value.fleetTaskId === undefined || value.fleetTaskId === null
1592
+ ? null
1593
+ : checkpointFieldString(value.fleetTaskId, 'state.references.fleetTaskId', index, { maxBytes: 128 }),
1594
+ urls: checkpointStringList(value.urls, 'state.references.urls', index, {
1595
+ maxItems: MAX_CHECKPOINT_URLS,
1596
+ maxChars: MAX_CHECKPOINT_URL_BYTES,
1597
+ }),
1598
+ };
1599
+ }
1600
+
1601
+ function normalizeCheckpointState(value, index) {
1602
+ if (value === undefined || value === null || !isObject(value)) {
1603
+ throw validationError(index, 'state', 'state 必须是 schema 2 对象');
1604
+ }
1605
+ if (value.schema !== 2) {
1606
+ throw validationError(index, 'state.schema', '新写入 checkpoint 必须使用 state.schema=2');
1607
+ }
1608
+ if (byteSize(value) > MAX_CHECKPOINT_STATE_BYTES) {
1609
+ throw new CapabilityError(413, 'payload_too_large', `state 超过 ${MAX_CHECKPOINT_STATE_BYTES} 字节`, { index });
1610
+ }
1611
+ const contentMode = value.contentMode === 'summary_only' ? 'summary_only' : value.contentMode === 'structured' ? 'structured' : null;
1612
+ if (contentMode === null) {
1613
+ throw validationError(index, 'state.contentMode', 'contentMode 必须是 structured | summary_only');
1614
+ }
1615
+ if (!isObject(value.task)) throw validationError(index, 'state.task', 'task 必须是对象');
1616
+ const task = {
1617
+ ...jsonClone(value.task),
1618
+ key: checkpointFieldString(value.task.key, 'state.task.key', index, { maxBytes: 128 }),
1619
+ threadId: checkpointFieldString(value.task.threadId, 'state.task.threadId', index, { maxBytes: 128 }),
1620
+ fleetTaskId: value.task.fleetTaskId === undefined || value.task.fleetTaskId === null
1621
+ ? null
1622
+ : checkpointFieldString(value.task.fleetTaskId, 'state.task.fleetTaskId', index, { maxBytes: 128 }),
1623
+ };
1624
+ const state = {
1625
+ ...jsonClone(value),
1626
+ schema: 2,
1627
+ contentMode,
1628
+ task,
1629
+ goal: value.goal === undefined || value.goal === null || value.goal === ''
1630
+ ? null
1631
+ : checkpointFieldString(value.goal, 'state.goal', index, { maxBytes: MAX_CHECKPOINT_GOAL_BYTES }),
1632
+ constraints: checkpointItems(value.constraints, 'state.constraints', index, {
1633
+ maxItems: MAX_CHECKPOINT_CONSTRAINTS,
1634
+ maxBytes: MAX_CHECKPOINT_ITEM_BYTES,
1635
+ normalize: (entry, field) => {
1636
+ if (!isObject(entry)) throw validationError(index, field, `${field} 必须是对象`);
1637
+ return {
1638
+ ...jsonClone(entry),
1639
+ ...checkpointTextItem(entry, field, index),
1640
+ ...(entry.source === undefined || entry.source === null
1641
+ ? {}
1642
+ : { source: checkpointFieldString(entry.source, `${field}.source`, index, { maxBytes: 128 }) }),
1643
+ };
1644
+ },
1645
+ }),
1646
+ decisions: checkpointItems(value.decisions, 'state.decisions', index, {
1647
+ maxItems: MAX_CHECKPOINT_DECISIONS,
1648
+ maxBytes: MAX_CHECKPOINT_DECISION_BYTES,
1649
+ normalize: (entry, field) => {
1650
+ if (!isObject(entry)) throw validationError(index, field, `${field} 必须是对象`);
1651
+ const at = entry.at === undefined || entry.at === null ? undefined : optionalNumber(entry.at, `${field}.at`, index);
1652
+ return {
1653
+ ...jsonClone(entry),
1654
+ ...checkpointTextItem(entry, field, index, { maxBytes: MAX_CHECKPOINT_DECISION_BYTES }),
1655
+ ...(entry.reason === undefined || entry.reason === null
1656
+ ? {}
1657
+ : { reason: checkpointFieldString(entry.reason, `${field}.reason`, index, { maxBytes: MAX_CHECKPOINT_DECISION_BYTES }) }),
1658
+ ...(at === undefined ? {} : { at }),
1659
+ recordIds: checkpointStringList(entry.recordIds, `${field}.recordIds`, index, { maxItems: MAX_CHECKPOINT_REFERENCES }),
1660
+ };
1661
+ },
1662
+ }),
1663
+ progress: (() => {
1664
+ const progress = value.progress === undefined || value.progress === null || !isObject(value.progress)
1665
+ ? {}
1666
+ : value.progress;
1667
+ if (value.progress !== undefined && value.progress !== null && !isObject(value.progress)) {
1668
+ throw validationError(index, 'state.progress', 'progress 必须是对象');
1669
+ }
1670
+ const normalizeProgress = (entries, key, { allowReason = false } = {}) => checkpointItems(entries, `state.progress.${key}`, index, {
1671
+ maxItems: MAX_CHECKPOINT_PROGRESS,
1672
+ maxBytes: MAX_CHECKPOINT_ITEM_BYTES,
1673
+ normalize: (entry, field) => {
1674
+ if (!isObject(entry)) throw validationError(index, field, `${field} 必须是对象`);
1675
+ return {
1676
+ ...jsonClone(entry),
1677
+ ...checkpointTextItem(entry, field, index),
1678
+ ...(allowReason && entry.reason !== undefined && entry.reason !== null
1679
+ ? { reason: checkpointFieldString(entry.reason, `${field}.reason`, index) }
1680
+ : {}),
1681
+ recordIds: checkpointStringList(entry.recordIds, `${field}.recordIds`, index, { maxItems: MAX_CHECKPOINT_REFERENCES }),
1682
+ };
1683
+ },
1684
+ });
1685
+ return {
1686
+ done: normalizeProgress(progress.done, 'done'),
1687
+ doing: normalizeProgress(progress.doing, 'doing'),
1688
+ blocked: normalizeProgress(progress.blocked, 'blocked', { allowReason: true }),
1689
+ };
1690
+ })(),
1691
+ nextSteps: checkpointItems(value.nextSteps, 'state.nextSteps', index, {
1692
+ maxItems: MAX_CHECKPOINT_NEXT_STEPS,
1693
+ maxBytes: MAX_CHECKPOINT_ITEM_BYTES,
1694
+ normalize: (entry, field) => {
1695
+ if (!isObject(entry)) throw validationError(index, field, `${field} 必须是对象`);
1696
+ return {
1697
+ ...jsonClone(entry),
1698
+ ...checkpointTextItem(entry, field, index),
1699
+ ...(entry.owner === undefined || entry.owner === null
1700
+ ? {}
1701
+ : { owner: checkpointFieldString(entry.owner, `${field}.owner`, index, { maxBytes: 128 }) }),
1702
+ };
1703
+ },
1704
+ }),
1705
+ files: checkpointItems(value.files, 'state.files', index, {
1706
+ maxItems: MAX_CHECKPOINT_FILES,
1707
+ maxBytes: MAX_CHECKPOINT_FILE_BYTES,
1708
+ normalize: (entry, field) => {
1709
+ if (!isObject(entry)) throw validationError(index, field, `${field} 必须是对象`);
1710
+ return {
1711
+ ...jsonClone(entry),
1712
+ path: checkpointFieldString(entry.path, `${field}.path`, index, { maxBytes: MAX_CHECKPOINT_FILE_BYTES }),
1713
+ ...(entry.role === undefined || entry.role === null
1714
+ ? {}
1715
+ : { role: checkpointFieldString(entry.role, `${field}.role`, index, { maxBytes: 128 }) }),
1716
+ ...(entry.status === undefined || entry.status === null
1717
+ ? {}
1718
+ : { status: checkpointFieldString(entry.status, `${field}.status`, index, { maxBytes: 128 }) }),
1719
+ };
1720
+ },
1721
+ }),
1722
+ openQuestions: checkpointItems(value.openQuestions, 'state.openQuestions', index, {
1723
+ maxItems: MAX_CHECKPOINT_QUESTIONS,
1724
+ maxBytes: MAX_CHECKPOINT_ITEM_BYTES,
1725
+ normalize: (entry, field) => {
1726
+ if (!isObject(entry)) throw validationError(index, field, `${field} 必须是对象`);
1727
+ return {
1728
+ ...jsonClone(entry),
1729
+ ...checkpointTextItem(entry, field, index),
1730
+ blocking: entry.blocking === true,
1731
+ };
1732
+ },
1733
+ }),
1734
+ references: normalizeCheckpointReferences(value.references, index),
1735
+ };
1736
+ if (contentMode === 'summary_only') {
1737
+ const structuredFields = [
1738
+ state.goal,
1739
+ state.constraints.length,
1740
+ state.decisions.length,
1741
+ state.progress.done.length,
1742
+ state.progress.doing.length,
1743
+ state.progress.blocked.length,
1744
+ state.nextSteps.length,
1745
+ state.files.length,
1746
+ state.openQuestions.length,
1747
+ ];
1748
+ if (structuredFields.some((entry) => (Array.isArray(entry) ? entry.length > 0 : Boolean(entry)))) {
1749
+ throw validationError(index, 'state.contentMode', 'summary_only checkpoint 不得包含结构化字段');
1750
+ }
1751
+ }
1752
+ if (byteSize(state) > MAX_CHECKPOINT_STATE_BYTES) {
1753
+ throw new CapabilityError(413, 'payload_too_large', `state 超过 ${MAX_CHECKPOINT_STATE_BYTES} 字节`, { index });
1754
+ }
1755
+ return state;
1756
+ }
1757
+
1758
+ function timeoutAfter(promise, ms, message) {
1759
+ let timer;
1760
+ const timeout = new Promise((_, reject) => {
1761
+ timer = setTimeout(() => reject(new CapabilityError(503, 'sync_unavailable', message, { reason: 'timeout' }, true)), ms);
1762
+ if (typeof timer.unref === 'function') timer.unref();
1763
+ });
1764
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
1765
+ }
1766
+
1767
+ function versionPayload() {
1768
+ return {
1769
+ capabilityApiVersion: CAPABILITY_API_VERSION,
1770
+ schemaVersion: CAPABILITY_SCHEMA_VERSION,
1771
+ mcpVersion: APP_VERSION,
1772
+ coreVersion: APP_VERSION,
1773
+ features: {
1774
+ domains: true,
1775
+ owner: true,
1776
+ provenance: true,
1777
+ batchWrite: true,
1778
+ idempotency: true,
1779
+ supersedes: true,
1780
+ temporalUpdates: ['validTo'],
1781
+ internalObjects: [...INTERNAL_OBJECT_KINDS],
1782
+ details: true,
1783
+ detailKinds: [...DETAIL_KINDS],
1784
+ detailRetentionClasses: [...DETAIL_RETENTION_CLASSES],
1785
+ detailDeleteReasons: [...DETAIL_DELETE_REASONS],
1786
+ sync: true,
1787
+ graph: true,
1788
+ readOnly: false,
1789
+ readEndpoints: [
1790
+ 'version',
1791
+ 'status',
1792
+ 'namespaces',
1793
+ 'query',
1794
+ 'search',
1795
+ 'history',
1796
+ 'profile',
1797
+ 'skills',
1798
+ 'graph',
1799
+ 'detail',
1800
+ 'sync',
1801
+ ],
1802
+ writeEndpoints: ['write', 'update', 'delete', 'archive', 'internal-object', 'detail', 'sync'],
1803
+ },
1804
+ limits: { ...CAPABILITY_LIMITS },
1805
+ domains: {
1806
+ reserved: ['user', 'default', 'shared', 'system'],
1807
+ agentPrefix: 'agent:',
1808
+ taskPrefix: 'task:',
1809
+ policyDomain: '__policy__',
1810
+ },
1811
+ };
1812
+ }
1813
+
1814
+ /**
1815
+ * 创建 capability HTTP handler。
1816
+ *
1817
+ * @param {{
1818
+ * home: string,
1819
+ * getConfig?: () => object,
1820
+ * getService?: () => object|null,
1821
+ * getApp?: () => object|null,
1822
+ * getIdentity?: () => {cloudId?: string|null, profileId?: string|null, userId?: string|null},
1823
+ * env?: NodeJS.ProcessEnv,
1824
+ * now?: () => number,
1825
+ * ttlMs?: number,
1826
+ * }} options
1827
+ */
1828
+ export function createMemoryCapabilityHandler({
1829
+ home,
1830
+ getConfig = () => ({}),
1831
+ getService = () => null,
1832
+ getApp = () => null,
1833
+ getIdentity = () => ({}),
1834
+ env = process.env,
1835
+ now = () => Date.now(),
1836
+ ttlMs,
1837
+ } = {}) {
1838
+ let tokenRecord = null;
1839
+ let tokenPromise = null;
1840
+ let tokenError = null;
1841
+ let disposed = false;
1842
+ const hostId = hostIdForHome(home);
1843
+
1844
+ async function ensureToken() {
1845
+ const current = tokenRecord;
1846
+ if (current && !(typeof current.expiresAt === 'number' && current.expiresAt > 0 && now() >= current.expiresAt)) {
1847
+ return current;
1848
+ }
1849
+ if (!tokenPromise) {
1850
+ tokenPromise = ensureCapabilityToken({
1851
+ home,
1852
+ env,
1853
+ now: now(),
1854
+ mcpPid: process.pid,
1855
+ ...(ttlMs !== undefined ? { ttlMs } : {}),
1856
+ })
1857
+ .then((record) => {
1858
+ tokenRecord = record;
1859
+ tokenError = null;
1860
+ return record;
1861
+ })
1862
+ .catch((error) => {
1863
+ tokenError = error;
1864
+ tokenRecord = null;
1865
+ throw error;
1866
+ })
1867
+ .finally(() => {
1868
+ tokenPromise = null;
1869
+ });
1870
+ }
1871
+ return tokenPromise;
1872
+ }
1873
+
1874
+ /** daemon 启动时调用(仅 enabled):提前生成 token 文件,sidecar 才能发现。 */
1875
+ async function prepare() {
1876
+ if (!isMemoryRuntimeEnabled(getConfig())) return { enabled: false, tokenId: null };
1877
+ try {
1878
+ const record = await ensureToken();
1879
+ return { enabled: true, tokenId: record.tokenId };
1880
+ } catch {
1881
+ return { enabled: true, tokenId: null };
1882
+ }
1883
+ }
1884
+
1885
+ /** 停用/关闭:撤销进程内 token 并删除 token 文件(旧 sidecar 下一次请求 401)。 */
1886
+ async function revoke() {
1887
+ tokenRecord = null;
1888
+ tokenError = null;
1889
+ await removeCapabilityToken({ home });
1890
+ }
1891
+
1892
+ async function dispose() {
1893
+ disposed = true;
1894
+ await revoke();
1895
+ }
1896
+
1897
+ function identitySnapshot() {
1898
+ let identity = {};
1899
+ try {
1900
+ identity = getIdentity?.() ?? {};
1901
+ } catch {
1902
+ identity = {};
1903
+ }
1904
+ return {
1905
+ cloudId: identity?.cloudId ?? null,
1906
+ cloudTrustId: identity?.cloudTrustId ?? null,
1907
+ userId: identity?.userId ?? 'user',
1908
+ profileId: identity?.profileId ?? null,
1909
+ deviceId: identity?.deviceId ?? null,
1910
+ hostId,
1911
+ };
1912
+ }
1913
+
1914
+ const handle = async function handleMemoryCapabilityRequest({ req, res, url, body }) {
1915
+ const path = url?.pathname ?? '';
1916
+ if (!isMemoryCapabilityPath(path)) return false;
1917
+
1918
+ const requestId = requestIdOf(req);
1919
+ res.setHeader('x-request-id', requestId);
1920
+ res.setHeader('x-mebular-capability-version', String(CAPABILITY_API_VERSION));
1921
+ res.setHeader('x-mebular-degraded', 'false');
1922
+
1923
+ const sendOk = (data, warnings = [], status = 200, degraded = false) => {
1924
+ res.setHeader('x-mebular-degraded', String(degraded));
1925
+ res.statusCode = status;
1926
+ res.setHeader('content-type', 'application/json; charset=utf-8');
1927
+ res.setHeader('cache-control', 'no-store');
1928
+ res.end(JSON.stringify({
1929
+ ok: true,
1930
+ requestId,
1931
+ capabilityVersion: CAPABILITY_API_VERSION,
1932
+ data,
1933
+ warnings,
1934
+ degraded,
1935
+ }));
1936
+ return true;
1937
+ };
1938
+
1939
+ const sendError = (status, code, message, details, retryable = false) => {
1940
+ res.statusCode = status;
1941
+ if (status === 503 && retryable) res.setHeader('retry-after', '1');
1942
+ res.setHeader('content-type', 'application/json; charset=utf-8');
1943
+ res.setHeader('cache-control', 'no-store');
1944
+ res.end(JSON.stringify({
1945
+ ok: false,
1946
+ requestId,
1947
+ capabilityVersion: CAPABILITY_API_VERSION,
1948
+ error: {
1949
+ code,
1950
+ message,
1951
+ retryable,
1952
+ ...(details !== undefined ? { details } : {}),
1953
+ },
1954
+ }));
1955
+ return true;
1956
+ };
1957
+
1958
+ const service = () => {
1959
+ const value = getService?.() ?? null;
1960
+ if (!value) {
1961
+ throw new CapabilityError(503, 'capability_unavailable', '记忆服务尚未初始化', undefined, true);
1962
+ }
1963
+ return value;
1964
+ };
1965
+
1966
+ const app = () => getApp?.() ?? null;
1967
+
1968
+ /**
1969
+ * 状态/域统计唯一来源:MemoryService.stats()。
1970
+ * 兼容测试/旧运行时没有 stats 的情况时只回落到 status 计数,绝不扫描图另造统计。
1971
+ */
1972
+ async function statsFor(currentService) {
1973
+ if (currentService && typeof currentService.stats === 'function') {
1974
+ return await currentService.stats();
1975
+ }
1976
+ const status = currentService && typeof currentService.status === 'function'
1977
+ ? await currentService.status()
1978
+ : null;
1979
+ const nodes = typeof status?.nodeCount === 'number' ? status.nodeCount : 0;
1980
+ return {
1981
+ nodeCount: nodes,
1982
+ edgeCount: typeof status?.edgeCount === 'number' ? status.edgeCount : 0,
1983
+ counts: {
1984
+ nodes,
1985
+ memoryRecords: 0,
1986
+ compacts: 0,
1987
+ checkpoints: 0,
1988
+ selfRecords: 0,
1989
+ },
1990
+ domains: [],
1991
+ };
1992
+ }
1993
+
1994
+ /**
1995
+ * 同步状态唯一来源:MemoryService.syncStatus()。
1996
+ * 兼容旧运行时只回落到 status 的同一组字段,不读 app.sync 另造一份。
1997
+ */
1998
+ async function syncStatusFor(currentService) {
1999
+ if (currentService && typeof currentService.syncStatus === 'function') {
2000
+ return await currentService.syncStatus();
2001
+ }
2002
+ const status = currentService && typeof currentService.status === 'function'
2003
+ ? await currentService.status()
2004
+ : null;
2005
+ return {
2006
+ running: status?.running === true,
2007
+ pendingEventCount: typeof status?.pendingEventCount === 'number' ? status.pendingEventCount : 0,
2008
+ lastSyncAt: typeof status?.lastSyncAt === 'number' ? status.lastSyncAt : null,
2009
+ isSyncing: status?.isSyncing === true,
2010
+ };
2011
+ }
2012
+
2013
+ const requireObjectBody = () => {
2014
+ if (!body || body.length === 0) {
2015
+ throw new CapabilityError(400, 'invalid_request', '请求体必须是 JSON 对象');
2016
+ }
2017
+ let parsed;
2018
+ try {
2019
+ parsed = JSON.parse(body.toString('utf-8'));
2020
+ } catch {
2021
+ throw new CapabilityError(400, 'invalid_request', '请求体不是合法 JSON');
2022
+ }
2023
+ if (!isObject(parsed)) {
2024
+ throw new CapabilityError(400, 'invalid_request', '请求体必须是 JSON 对象');
2025
+ }
2026
+ return parsed;
2027
+ };
2028
+
2029
+ // ---------- 写路径:幂等账本(24h,本地过渡数据,不进入图/同步) ----------
2030
+
2031
+ const ledgerDir = typeof home === 'string' && home.length > 0 ? join(home, 'memory-runtime') : null;
2032
+ const ledgerFile = ledgerDir ? join(ledgerDir, IDEMPOTENCY_LEDGER_FILE) : null;
2033
+ let ledger = null;
2034
+ let ledgerLoading = null;
2035
+
2036
+ async function ledgerState() {
2037
+ if (ledger) return ledger;
2038
+ if (!ledgerFile) {
2039
+ ledger = new Map();
2040
+ return ledger;
2041
+ }
2042
+ if (!ledgerLoading) {
2043
+ ledgerLoading = (async () => {
2044
+ const state = new Map();
2045
+ try {
2046
+ const raw = JSON.parse(await readFile(ledgerFile, 'utf-8'));
2047
+ if (raw?.version === IDEMPOTENCY_LEDGER_VERSION && Array.isArray(raw.entries)) {
2048
+ const cutoff = now() - IDEMPOTENCY_TTL_MS;
2049
+ for (const entry of raw.entries) {
2050
+ if (!isObject(entry) || typeof entry.key !== 'string' || !isObject(entry.data)) continue;
2051
+ if (typeof entry.at !== 'number' || entry.at < cutoff) continue;
2052
+ state.set(entry.key, entry);
2053
+ }
2054
+ }
2055
+ } catch {
2056
+ // 账本损坏/不存在:按空处理;clientItemId 与内容 hash 仍可防重。
2057
+ }
2058
+ ledger = state;
2059
+ return state;
2060
+ })().finally(() => {
2061
+ ledgerLoading = null;
2062
+ });
2063
+ }
2064
+ return ledgerLoading;
2065
+ }
2066
+
2067
+ async function saveLedger(state) {
2068
+ if (!ledgerFile || !ledgerDir) return;
2069
+ const cutoff = now() - IDEMPOTENCY_TTL_MS;
2070
+ const entries = [...state.values()].filter((entry) => entry.at >= cutoff);
2071
+ while (entries.length > IDEMPOTENCY_MAX_ENTRIES) {
2072
+ const oldest = entries.shift();
2073
+ if (oldest) state.delete(oldest.key);
2074
+ }
2075
+ // 重新过滤:淘汰后 entries 与 state 保持一致。
2076
+ const payload = {
2077
+ version: IDEMPOTENCY_LEDGER_VERSION,
2078
+ entries: entries.filter((entry) => state.has(entry.key)),
2079
+ };
2080
+ await mkdir(ledgerDir, { recursive: true, mode: 0o700 });
2081
+ await chmod(ledgerDir, 0o700);
2082
+ const tmp = `${ledgerFile}.tmp-${process.pid}-${randomUUID()}`;
2083
+ try {
2084
+ await writeFile(tmp, JSON.stringify(payload), { encoding: 'utf-8', mode: 0o600 });
2085
+ await chmod(tmp, 0o600);
2086
+ await rename(tmp, ledgerFile);
2087
+ await chmod(ledgerFile, 0o600);
2088
+ } catch (error) {
2089
+ await rm(tmp, { force: true }).catch(() => undefined);
2090
+ throw error;
2091
+ }
2092
+ }
2093
+
2094
+ function idempotencyKeyOf(req, payload) {
2095
+ const header = req?.headers?.['idempotency-key'];
2096
+ if (hasValue(header) && header !== '') {
2097
+ if (typeof header !== 'string' || !IDEMPOTENCY_KEY_RE.test(header)) {
2098
+ throw new CapabilityError(400, 'invalid_request', 'Idempotency-Key 格式非法', { field: 'Idempotency-Key' });
2099
+ }
2100
+ return header;
2101
+ }
2102
+ if (hasValue(payload?.requestId)) {
2103
+ if (typeof payload.requestId !== 'string' || !IDEMPOTENCY_KEY_RE.test(payload.requestId)) {
2104
+ throw new CapabilityError(400, 'invalid_request', 'requestId 格式非法', { field: 'requestId' });
2105
+ }
2106
+ return payload.requestId;
2107
+ }
2108
+ return null;
2109
+ }
2110
+
2111
+ async function withIdempotency(route, payload, tokenId, execute) {
2112
+ const key = idempotencyKeyOf(req, payload);
2113
+ if (key === null) return execute();
2114
+ const state = await ledgerState();
2115
+ const composite = `${tokenId ?? 'none'}\u0000${route}\u0000${key}`;
2116
+ const requestHash = sha256Hex(canonicalJson(payload));
2117
+ const existing = state.get(composite);
2118
+ if (existing) {
2119
+ if (existing.requestHash !== requestHash) {
2120
+ throw new CapabilityError(409, 'idempotency_conflict', '同一幂等键对应了不同请求体', {
2121
+ key,
2122
+ route,
2123
+ });
2124
+ }
2125
+ return {
2126
+ data: { ...jsonClone(existing.data), replayed: true },
2127
+ warnings: jsonClone(existing.warnings ?? []),
2128
+ degraded: existing.degraded === true,
2129
+ };
2130
+ }
2131
+ const result = await execute();
2132
+ // 详情批量部分失败不缓存:同一 outbox 键重放时应重新尝试失败项;
2133
+ // 已成功项仍由 clientItemId/contentHash 去重,不会重复写。
2134
+ if (route === 'detail:write' && result?.data?.partial === true) {
2135
+ return result;
2136
+ }
2137
+ const entry = {
2138
+ key: composite,
2139
+ requestHash,
2140
+ at: now(),
2141
+ data: jsonClone({ ...(result.data ?? {}), replayed: false }),
2142
+ warnings: jsonClone(result.warnings ?? []),
2143
+ degraded: result.degraded === true,
2144
+ };
2145
+ // LRU:同键刷新到队尾。
2146
+ state.delete(composite);
2147
+ state.set(composite, entry);
2148
+ const cutoff = now() - IDEMPOTENCY_TTL_MS;
2149
+ for (const [entryKey, value] of state) {
2150
+ if (typeof value.at !== 'number' || value.at < cutoff) state.delete(entryKey);
2151
+ }
2152
+ while (state.size > IDEMPOTENCY_MAX_ENTRIES) {
2153
+ const oldest = state.keys().next().value;
2154
+ if (oldest === undefined) break;
2155
+ state.delete(oldest);
2156
+ }
2157
+ try {
2158
+ await saveLedger(state);
2159
+ } catch {
2160
+ result.warnings = [
2161
+ ...(result.warnings ?? []),
2162
+ { code: 'idempotency_ledger_unavailable', message: '幂等账本写入失败;仍可依赖内容 hash 防重' },
2163
+ ];
2164
+ }
2165
+ return result;
2166
+ }
2167
+
2168
+ // ---------- /write ----------
2169
+
2170
+ /**
2171
+ * 校验记录级修正:旧事实必须同域、同 subject/predicate、不同 object、非内部对象,
2172
+ * 且当前 actor 对旧记录有更新权限。已删除的旧记录跳过(幂等重放不阻塞新值)。
2173
+ */
2174
+ async function validateSupersedes({
2175
+ ids,
2176
+ appValue,
2177
+ actor,
2178
+ domain,
2179
+ kind,
2180
+ content,
2181
+ validFrom,
2182
+ index,
2183
+ }) {
2184
+ if (ids.length === 0) return { ids: [], warnings: [] };
2185
+ if (kind !== 'fact' && kind !== 'preference') {
2186
+ throw validationError(index, 'supersedes', 'supersedes 仅适用于 fact/preference');
2187
+ }
2188
+ const incoming = factTriple(content);
2189
+ if (!incoming) throw validationError(index, 'supersedes', '新记录缺少 subject/predicate/object');
2190
+ const effective = [];
2191
+ const warnings = [];
2192
+ for (const id of ids) {
2193
+ const node = await appValue.graph.getNode(id);
2194
+ if (!node) {
2195
+ throw validationError(index, 'supersedes', 'supersedes 指向的记录不存在', {
2196
+ id,
2197
+ supersedesCode: 'not_found',
2198
+ });
2199
+ }
2200
+ if (node.deletedAt) {
2201
+ warnings.push({
2202
+ code: 'supersedes_skipped_deleted',
2203
+ id,
2204
+ message: '旧记录已删除,跳过替代',
2205
+ });
2206
+ continue;
2207
+ }
2208
+ if (isInternalNode(node)) {
2209
+ throw validationError(index, 'supersedes', '不能 supersede 内部对象', {
2210
+ id,
2211
+ supersedesCode: 'internal_object',
2212
+ });
2213
+ }
2214
+ if (domainOfNamespace(node.namespace) !== domain) {
2215
+ throw validationError(index, 'supersedes', 'supersedes 必须与新记录同域', {
2216
+ id,
2217
+ domain,
2218
+ recordDomain: domainOfNamespace(node.namespace),
2219
+ supersedesCode: 'domain_mismatch',
2220
+ });
2221
+ }
2222
+ if (node.type !== 'fact') {
2223
+ throw validationError(index, 'supersedes', '只能 supersede fact 记录', {
2224
+ id,
2225
+ type: node.type,
2226
+ supersedesCode: 'kind_mismatch',
2227
+ });
2228
+ }
2229
+ const previous = factTriple(node.content);
2230
+ if (!previous || previous.subject !== incoming.subject || previous.predicate !== incoming.predicate) {
2231
+ throw validationError(index, 'supersedes', 'supersedes 必须同 subject/predicate', {
2232
+ id,
2233
+ supersedesCode: 'key_mismatch',
2234
+ });
2235
+ }
2236
+ if (previous.object === incoming.object) {
2237
+ throw validationError(index, 'supersedes', '新旧记录 object 相同,无需替代', {
2238
+ id,
2239
+ supersedesCode: 'same_object',
2240
+ });
2241
+ }
2242
+ if (!canSupersedeNode(actor, node, domain)) {
2243
+ throw new CapabilityError(403, 'forbidden_scope', '当前 actor 不能替代该记录', {
2244
+ index,
2245
+ id,
2246
+ domain,
2247
+ supersedesCode: 'forbidden',
2248
+ });
2249
+ }
2250
+ if (typeof node.validFrom === 'number' && node.validFrom > validFrom) {
2251
+ throw validationError(index, 'supersedes', '旧记录 validFrom 晚于新记录', {
2252
+ id,
2253
+ validFrom,
2254
+ recordValidFrom: node.validFrom,
2255
+ supersedesCode: 'valid_from_mismatch',
2256
+ });
2257
+ }
2258
+ effective.push(id);
2259
+ }
2260
+ return { ids: effective, warnings };
2261
+ }
2262
+
2263
+ async function validateWriteItem(raw, index, requestThreadId, actor, appValue) {
2264
+ if (!isObject(raw)) throw validationError(index, 'item', 'item 必须是对象');
2265
+ if (!hasValue(raw.domain) || (typeof raw.domain === 'string' && raw.domain.trim() === '')) {
2266
+ throw validationError(index, 'domain', 'item.domain 必填');
2267
+ }
2268
+ const domain = normalizeDomain(raw.domain);
2269
+ if (!domain) {
2270
+ throw new CapabilityError(400, 'domain_invalid', 'item.domain 非法', {
2271
+ index,
2272
+ ...(typeof raw.domain === 'string' ? { domain: raw.domain } : {}),
2273
+ });
2274
+ }
2275
+ if (typeof raw.kind !== 'string' || !WRITE_KINDS.has(raw.kind)) {
2276
+ throw validationError(index, 'kind', 'kind 非法');
2277
+ }
2278
+ let clientItemId;
2279
+ if (hasValue(raw.clientItemId)) {
2280
+ if (typeof raw.clientItemId !== 'string' || !CLIENT_ITEM_ID_RE.test(raw.clientItemId)) {
2281
+ throw validationError(index, 'clientItemId', 'clientItemId 格式非法');
2282
+ }
2283
+ clientItemId = raw.clientItemId;
2284
+ }
2285
+ const normalized = normalizeWriteContent(raw.kind, raw.content, index);
2286
+ let tags = [...new Set([...normalized.tags, ...normalizeTags(raw.tags, index)])];
2287
+ // `preference` 是 preference 的保留语义标签;其他 kind 不得借它冒充偏好。
2288
+ if (raw.kind !== 'preference') tags = tags.filter((tag) => tag !== 'preference');
2289
+ const relatedTo = normalizeRelatedTo(raw.relatedTo, index);
2290
+ const supersedes = normalizeSupersedes(raw.supersedes, index);
2291
+ const validFrom = raw.validFrom === undefined || raw.validFrom === null
2292
+ ? now()
2293
+ : optionalNumber(raw.validFrom, 'validFrom', index);
2294
+ const validTo = raw.validTo === undefined || raw.validTo === null
2295
+ ? OPEN_VALID_TO
2296
+ : optionalNumber(raw.validTo, 'validTo', index);
2297
+ if (validTo < validFrom) throw validationError(index, 'validTo', 'validTo 必须不早于 validFrom');
2298
+
2299
+ const provenanceInput = parseProvenanceInput(raw.provenance, index);
2300
+ assertDomainWrite(actor, domain, provenanceInput, requestThreadId);
2301
+ const supersedeCheck = await validateSupersedes({
2302
+ ids: supersedes,
2303
+ appValue,
2304
+ actor,
2305
+ domain,
2306
+ kind: raw.kind,
2307
+ content: normalized.content,
2308
+ validFrom,
2309
+ index,
2310
+ });
2311
+ const identity = identitySnapshot();
2312
+ const provenance = buildWriteProvenance({
2313
+ input: provenanceInput,
2314
+ actor,
2315
+ identity,
2316
+ hostId,
2317
+ now: now(),
2318
+ threadId: provenanceInput.threadId ?? requestThreadId ?? null,
2319
+ confirmation: provenanceInput.confirmation ?? 'none',
2320
+ });
2321
+ if (byteSize(provenance) > MAX_PROVENANCE_BYTES) {
2322
+ throw new CapabilityError(413, 'payload_too_large', `provenance 超过 ${MAX_PROVENANCE_BYTES} 字节`, { index });
2323
+ }
2324
+ const owner = deriveOwner(domain, { userId: identity.userId });
2325
+ if (hasValue(raw.ownerType) && raw.ownerType !== owner.ownerType) {
2326
+ throw ownerMismatchError(index, domain, owner, {
2327
+ ownerType: raw.ownerType,
2328
+ ownerId: raw.ownerId ?? null,
2329
+ });
2330
+ }
2331
+ if (hasValue(raw.ownerId) && raw.ownerId !== owner.ownerId) {
2332
+ throw ownerMismatchError(index, domain, owner, {
2333
+ ownerType: raw.ownerType ?? owner.ownerType,
2334
+ ownerId: raw.ownerId,
2335
+ });
2336
+ }
2337
+ const explicitValidFrom = raw.validFrom !== undefined && raw.validFrom !== null;
2338
+ const contentHash = contentHashFor(
2339
+ raw.kind,
2340
+ normalized.content,
2341
+ explicitValidFrom ? validFrom : undefined,
2342
+ );
2343
+ return {
2344
+ index,
2345
+ domain,
2346
+ owner,
2347
+ kind: raw.kind,
2348
+ nodeType: normalized.nodeType,
2349
+ content: normalized.content,
2350
+ tags,
2351
+ relatedTo,
2352
+ validFrom,
2353
+ validTo,
2354
+ ...(supersedeCheck.ids.length > 0 ? { supersedes: supersedeCheck.ids } : {}),
2355
+ supersedeWarnings: supersedeCheck.warnings,
2356
+ provenance,
2357
+ ...(clientItemId !== undefined ? { clientItemId } : {}),
2358
+ contentHash,
2359
+ contentHashIncludesValidFrom: explicitValidFrom,
2360
+ };
2361
+ }
2362
+
2363
+ async function performWriteItem(appValue, item) {
2364
+ if (!appValue?.graph?.getNode) {
2365
+ throw new CapabilityError(503, 'capability_unavailable', '图存储不可用', undefined, true);
2366
+ }
2367
+ const currentService = service();
2368
+ if (typeof currentService.writeRecords !== 'function') {
2369
+ throw new CapabilityError(503, 'capability_unavailable', '记忆服务不支持统一写入', undefined, true);
2370
+ }
2371
+ const metadata = {
2372
+ kind: item.kind,
2373
+ provenance: item.provenance,
2374
+ contentHash: item.contentHash,
2375
+ ...(item.contentHashIncludesValidFrom ? { contentHashValidFrom: item.validFrom } : {}),
2376
+ ...(item.clientItemId !== undefined ? { clientItemId: item.clientItemId } : {}),
2377
+ };
2378
+ const [stored] = await currentService.writeRecords([{
2379
+ kind: item.kind,
2380
+ content: item.content,
2381
+ namespace: item.domain,
2382
+ tags: item.tags,
2383
+ validFrom: item.validFrom,
2384
+ validTo: item.validTo,
2385
+ relatedTo: item.relatedTo,
2386
+ metadata,
2387
+ }], { tolerateVectorIndexFailure: true });
2388
+ if (!stored?.node) {
2389
+ throw new CapabilityError(503, 'capability_unavailable', '节点写入后读取失败', undefined, true);
2390
+ }
2391
+ const warnings = [];
2392
+ if (!stored.vectorIndexed) {
2393
+ warnings.push({ code: 'vector_index_unavailable', message: '向量索引更新失败;图数据已写入' });
2394
+ }
2395
+ for (const targetId of stored.skippedRelatedTo ?? []) {
2396
+ warnings.push({
2397
+ code: 'related_to_skipped',
2398
+ id: targetId,
2399
+ message: 'relatedTo 目标不存在、已删除或为内部对象,已跳过',
2400
+ });
2401
+ }
2402
+ return { node: stored.node, warnings };
2403
+ }
2404
+
2405
+ async function applyWriteSupersedes(item, newNode) {
2406
+ if (!Array.isArray(item.supersedes) || item.supersedes.length === 0) {
2407
+ return { superseded: [], skipped: [] };
2408
+ }
2409
+ const currentService = service();
2410
+ if (typeof currentService.supersedeRecords !== 'function') {
2411
+ throw new CapabilityError(503, 'capability_unavailable', '记忆服务不支持记录替代', undefined, true);
2412
+ }
2413
+ return currentService.supersedeRecords(item.supersedes, {
2414
+ validTo: typeof newNode.validFrom === 'number' ? newNode.validFrom : item.validFrom,
2415
+ supersededBy: newNode.id,
2416
+ now: now(),
2417
+ });
2418
+ }
2419
+
2420
+ async function handleWrite(payload, actor) {
2421
+ const items = payload.items;
2422
+ if (!Array.isArray(items) || items.length === 0) {
2423
+ throw new CapabilityError(400, 'invalid_request', 'items 必须是非空数组');
2424
+ }
2425
+ if (items.length > MAX_BATCH_ITEMS) {
2426
+ throw new CapabilityError(413, 'payload_too_large', `items 最多 ${MAX_BATCH_ITEMS} 条`, {
2427
+ maxBatchItems: MAX_BATCH_ITEMS,
2428
+ });
2429
+ }
2430
+ if (payload.sync !== undefined || payload['self.sync'] !== undefined || payload['checkpoint.sync'] !== undefined) {
2431
+ throw new CapabilityError(400, 'legacy_sync_unsupported', '不再支持 sync/self.sync/checkpoint.sync 字段');
2432
+ }
2433
+ const requestThreadId = parseThreadId(payload.threadId);
2434
+ const appValue = app();
2435
+ if (!appValue) throw new CapabilityError(503, 'capability_unavailable', '图存储尚未初始化', undefined, true);
2436
+ // 校验原子:先全部校验,再逐项落库。
2437
+ const validated = [];
2438
+ for (let index = 0; index < items.length; index += 1) {
2439
+ validated.push(await validateWriteItem(items[index], index, requestThreadId, actor, appValue));
2440
+ }
2441
+ const dedupe = await buildDedupeIndex(appValue);
2442
+ const results = [];
2443
+ const warnings = [];
2444
+ let created = 0;
2445
+ let duplicates = 0;
2446
+ let failed = 0;
2447
+ for (const item of validated) {
2448
+ warnings.push(...(item.supersedeWarnings ?? []));
2449
+ const existing = (item.clientItemId !== undefined
2450
+ ? dedupe.client.get(dedupeKey('client', item.domain, item.clientItemId))
2451
+ : undefined)
2452
+ ?? dedupe.hash.get(dedupeKey('hash', item.domain, item.contentHash));
2453
+ if (existing) {
2454
+ try {
2455
+ const replaced = await applyWriteSupersedes(item, existing);
2456
+ duplicates += 1;
2457
+ results.push(recordWriteResult('duplicate', existing, item, item.owner, replaced.superseded));
2458
+ for (const id of replaced.skipped) {
2459
+ warnings.push({
2460
+ code: 'supersedes_skipped',
2461
+ id,
2462
+ message: '旧记录已删除、非 fact 或与当前记录不匹配,已跳过替代',
2463
+ });
2464
+ }
2465
+ } catch (error) {
2466
+ failed += 1;
2467
+ results.push({
2468
+ ...(item.clientItemId !== undefined ? { clientItemId: item.clientItemId } : {}),
2469
+ status: 'failed',
2470
+ id: existing.id,
2471
+ kind: item.kind,
2472
+ domain: item.domain,
2473
+ code: error instanceof CapabilityError ? error.code : 'supersede_failed',
2474
+ retryable: true,
2475
+ });
2476
+ }
2477
+ continue;
2478
+ }
2479
+ try {
2480
+ const written = await performWriteItem(appValue, item);
2481
+ warnings.push(...written.warnings);
2482
+ const node = written.node;
2483
+ const replaced = await applyWriteSupersedes(item, node);
2484
+ for (const id of replaced.skipped) {
2485
+ warnings.push({
2486
+ code: 'supersedes_skipped',
2487
+ id,
2488
+ message: '旧记录已删除、非 fact 或与当前记录不匹配,已跳过替代',
2489
+ });
2490
+ }
2491
+ created += 1;
2492
+ results.push(recordWriteResult('created', node, item, item.owner, replaced.superseded));
2493
+ if (item.clientItemId !== undefined) {
2494
+ dedupe.client.set(dedupeKey('client', item.domain, item.clientItemId), node);
2495
+ }
2496
+ dedupe.hash.set(dedupeKey('hash', item.domain, item.contentHash), node);
2497
+ } catch (error) {
2498
+ failed += 1;
2499
+ results.push({
2500
+ ...(item.clientItemId !== undefined ? { clientItemId: item.clientItemId } : {}),
2501
+ status: 'failed',
2502
+ kind: item.kind,
2503
+ domain: item.domain,
2504
+ code: error instanceof CapabilityError ? error.code : 'internal',
2505
+ retryable: error instanceof CapabilityError ? error.retryable : true,
2506
+ });
2507
+ }
2508
+ }
2509
+ return {
2510
+ data: {
2511
+ results,
2512
+ created,
2513
+ duplicates,
2514
+ failed,
2515
+ partial: failed > 0,
2516
+ replayed: false,
2517
+ },
2518
+ warnings,
2519
+ degraded: false,
2520
+ };
2521
+ }
2522
+
2523
+ // ---------- /update ----------
2524
+
2525
+ function validateUpdateItem(raw, index) {
2526
+ if (!isObject(raw)) throw validationError(index, 'item', 'item 必须是对象');
2527
+ if (typeof raw.id !== 'string' || raw.id.length === 0 || raw.id.length > 128) {
2528
+ throw validationError(index, 'id', 'id 必须是节点 id');
2529
+ }
2530
+ if (!isObject(raw.patch)) throw validationError(index, 'patch', 'patch 必须是对象');
2531
+ for (const key of Object.keys(raw.patch)) {
2532
+ if (!PATCH_KEYS.has(key)) {
2533
+ throw validationError(index, key, `${key} 不是允许更新的字段`, { field: key });
2534
+ }
2535
+ }
2536
+ return raw;
2537
+ }
2538
+
2539
+ async function handleUpdate(payload, actor) {
2540
+ const items = payload.items;
2541
+ if (!Array.isArray(items) || items.length === 0) {
2542
+ throw new CapabilityError(400, 'invalid_request', 'items 必须是非空数组');
2543
+ }
2544
+ if (items.length > MAX_BATCH_ITEMS) {
2545
+ throw new CapabilityError(413, 'payload_too_large', `items 最多 ${MAX_BATCH_ITEMS} 条`, {
2546
+ maxBatchItems: MAX_BATCH_ITEMS,
2547
+ });
2548
+ }
2549
+ if (payload.sync !== undefined || payload['self.sync'] !== undefined || payload['checkpoint.sync'] !== undefined) {
2550
+ throw new CapabilityError(400, 'legacy_sync_unsupported', '不再支持 sync/self.sync/checkpoint.sync 字段');
2551
+ }
2552
+ const appValue = app();
2553
+ if (!appValue) throw new CapabilityError(503, 'capability_unavailable', '图存储尚未初始化', undefined, true);
2554
+ const identity = identitySnapshot();
2555
+ const plans = [];
2556
+ // 校验原子:保护字段、权限、版本、合并后的 content 全部通过后才写。
2557
+ for (let index = 0; index < items.length; index += 1) {
2558
+ const raw = validateUpdateItem(items[index], index);
2559
+ const node = await appValue.graph.getNode(raw.id);
2560
+ if (!node || node.deletedAt) {
2561
+ throw new CapabilityError(404, 'not_found', '节点不存在', { index, id: raw.id });
2562
+ }
2563
+ if (isInternalNode(node)) {
2564
+ throw new CapabilityError(404, 'internal_object', '内部对象必须通过 /internal-object 更新', { index, id: raw.id });
2565
+ }
2566
+ if (!canUpdateNode(actor, node)) {
2567
+ throw new CapabilityError(403, 'forbidden_scope', '当前 actor 不能更新该记录', {
2568
+ index,
2569
+ id: raw.id,
2570
+ domain: domainOfNamespace(node.namespace),
2571
+ });
2572
+ }
2573
+ if (hasValue(raw.expectedUpdatedAt)) {
2574
+ if (typeof raw.expectedUpdatedAt !== 'number' || !Number.isFinite(raw.expectedUpdatedAt)) {
2575
+ throw validationError(index, 'expectedUpdatedAt', 'expectedUpdatedAt 必须是数字');
2576
+ }
2577
+ if (node.updatedAt !== raw.expectedUpdatedAt) {
2578
+ throw new CapabilityError(409, 'update_conflict', '记录已被其他写入方更新', {
2579
+ index,
2580
+ id: raw.id,
2581
+ currentUpdatedAt: node.updatedAt,
2582
+ }, true);
2583
+ }
2584
+ }
2585
+ const patch = raw.patch;
2586
+ const kind = kindOf(node);
2587
+ let content;
2588
+ if (patch.content !== undefined) {
2589
+ if (!isObject(patch.content)) throw validationError(index, 'patch.content', 'patch.content 必须是对象');
2590
+ // preference 的写入形状是 entity/preferenceType/value;更新时兼容映射到 fact 三元组。
2591
+ const contentPatch = kind === 'preference' ? { ...patch.content } : patch.content;
2592
+ if (kind === 'preference') {
2593
+ if (contentPatch.subject === undefined && contentPatch.entity !== undefined) contentPatch.subject = contentPatch.entity;
2594
+ if (contentPatch.predicate === undefined && contentPatch.preferenceType !== undefined) {
2595
+ contentPatch.predicate = contentPatch.preferenceType;
2596
+ }
2597
+ if (contentPatch.object === undefined && contentPatch.value !== undefined) contentPatch.object = contentPatch.value;
2598
+ }
2599
+ const merged = { ...(isObject(node.content) ? node.content : {}) };
2600
+ for (const [key, value] of Object.entries(contentPatch)) {
2601
+ if (value === null) delete merged[key];
2602
+ else merged[key] = value;
2603
+ }
2604
+ content = normalizeNodeContent(kind, node.type, merged, index);
2605
+ }
2606
+ let tags;
2607
+ if (patch.tags !== undefined) {
2608
+ tags = normalizeTags(patch.tags, index);
2609
+ if (kind === 'preference' && !tags.includes('preference')) tags.push('preference');
2610
+ if (kind !== 'preference') tags = tags.filter((tag) => tag !== 'preference');
2611
+ }
2612
+ let contentHash;
2613
+ if (content !== undefined) {
2614
+ const metadataForHash = isObject(node.metadata) ? node.metadata : {};
2615
+ contentHash = contentHashFor(
2616
+ kind,
2617
+ content,
2618
+ typeof metadataForHash.contentHashValidFrom === 'number'
2619
+ ? metadataForHash.contentHashValidFrom
2620
+ : undefined,
2621
+ );
2622
+ }
2623
+ let metadata;
2624
+ if (patch.metadata !== undefined) {
2625
+ if (!isObject(patch.metadata)) throw validationError(index, 'patch.metadata', 'patch.metadata 必须是对象');
2626
+ for (const key of Object.keys(patch.metadata)) {
2627
+ if (PROTECTED_METADATA_KEYS.has(key)) {
2628
+ throw validationError(index, `patch.metadata.${key}`, 'metadata 含受保护字段', { field: key });
2629
+ }
2630
+ }
2631
+ metadata = { ...(isObject(node.metadata) ? node.metadata : {}), ...jsonClone(patch.metadata) };
2632
+ }
2633
+ // validFrom 仍不可变;validTo 仅允许受控缩短/结束 fact 的有效窗口(修正/替代路径)。
2634
+ if (patch.validFrom !== undefined && patch.validFrom !== node.validFrom) {
2635
+ throw validationError(index, 'patch.validFrom', 'validFrom 暂不支持更新', {
2636
+ code: 'temporal_update_unsupported',
2637
+ });
2638
+ }
2639
+ let validTo;
2640
+ if (patch.validTo !== undefined) {
2641
+ if (typeof patch.validTo !== 'number' || !Number.isFinite(patch.validTo)) {
2642
+ throw validationError(index, 'patch.validTo', 'validTo 必须是有限数字');
2643
+ }
2644
+ if (node.type !== 'fact') {
2645
+ throw validationError(index, 'patch.validTo', 'validTo 仅适用于 fact 记录', {
2646
+ code: 'temporal_update_unsupported',
2647
+ });
2648
+ }
2649
+ if (patch.validTo < (node.validFrom ?? 0)) {
2650
+ throw validationError(index, 'patch.validTo', 'validTo 必须不早于 validFrom');
2651
+ }
2652
+ const currentValidTo = node.validTo ?? OPEN_VALID_TO;
2653
+ if (currentValidTo <= now() && patch.validTo > currentValidTo) {
2654
+ throw new CapabilityError(409, 'temporal_conflict', '已结束的事实不能重新打开', {
2655
+ index,
2656
+ id: raw.id,
2657
+ currentValidTo,
2658
+ });
2659
+ }
2660
+ // 相同值也按幂等 no-op 接受;Service 会跳过实际写入。
2661
+ validTo = patch.validTo;
2662
+ }
2663
+ if (content === undefined && tags === undefined && metadata === undefined && validTo === undefined) {
2664
+ throw validationError(index, 'patch', 'patch 没有可更新字段');
2665
+ }
2666
+ plans.push({
2667
+ index,
2668
+ id: raw.id,
2669
+ node,
2670
+ content,
2671
+ tags,
2672
+ metadata,
2673
+ contentHash,
2674
+ ...(validTo !== undefined ? { validTo } : {}),
2675
+ actorId: actor.type === 'agent' ? actor.agentId : actor.type === 'user' ? identity.userId : 'system',
2676
+ });
2677
+ }
2678
+
2679
+ const results = [];
2680
+ const warnings = [];
2681
+ let updated = 0;
2682
+ let failed = 0;
2683
+ for (const plan of plans) {
2684
+ try {
2685
+ const currentService = service();
2686
+ if (typeof currentService.updateRecord !== 'function') {
2687
+ throw new CapabilityError(503, 'capability_unavailable', '记忆服务不支持统一更新', undefined, true);
2688
+ }
2689
+ const metadata = {
2690
+ ...(plan.metadata ?? (isObject(plan.node.metadata) ? plan.node.metadata : {})),
2691
+ ...(plan.contentHash !== undefined ? { contentHash: plan.contentHash } : {}),
2692
+ updatedBy: { actorType: actor.type, actorId: plan.actorId, at: now() },
2693
+ };
2694
+ const updatedRecord = await currentService.updateRecord({
2695
+ id: plan.id,
2696
+ ...(plan.content !== undefined ? { content: plan.content } : {}),
2697
+ ...(plan.tags !== undefined ? { tags: plan.tags } : {}),
2698
+ metadata,
2699
+ ...(plan.validTo !== undefined ? { validTo: plan.validTo } : {}),
2700
+ }, { tolerateVectorIndexFailure: true });
2701
+ if (!updatedRecord?.node) {
2702
+ throw new CapabilityError(404, 'not_found', '节点不存在', { id: plan.id });
2703
+ }
2704
+ const node = updatedRecord.node;
2705
+ if (!updatedRecord.vectorIndexed) {
2706
+ warnings.push({ code: 'vector_index_unavailable', message: '向量索引更新失败;图数据已更新' });
2707
+ }
2708
+ updated += 1;
2709
+ const domain = domainOfNamespace(node.namespace);
2710
+ const owner = deriveOwner(domain, { userId: identity.userId });
2711
+ results.push({
2712
+ id: plan.id,
2713
+ status: 'updated',
2714
+ domain,
2715
+ ownerType: owner.ownerType,
2716
+ ownerId: owner.ownerId,
2717
+ updatedAt: node.updatedAt,
2718
+ validTo: normalizeValidTo(node.validTo),
2719
+ });
2720
+ } catch (error) {
2721
+ failed += 1;
2722
+ results.push({
2723
+ id: plan.id,
2724
+ status: 'failed',
2725
+ code: error instanceof CapabilityError ? error.code : 'internal',
2726
+ retryable: error instanceof CapabilityError ? error.retryable : true,
2727
+ });
2728
+ }
2729
+ }
2730
+ return {
2731
+ data: { results, updated, failed, partial: failed > 0, replayed: false },
2732
+ warnings,
2733
+ degraded: false,
2734
+ };
2735
+ }
2736
+
2737
+ // ---------- /delete /archive ----------
2738
+
2739
+ function parseIdList(payload) {
2740
+ const ids = payload.ids;
2741
+ if (!Array.isArray(ids) || ids.length === 0) {
2742
+ throw new CapabilityError(400, 'invalid_request', 'ids 必须是非空数组');
2743
+ }
2744
+ if (ids.length > MAX_BATCH_ITEMS) {
2745
+ throw new CapabilityError(413, 'payload_too_large', `ids 最多 ${MAX_BATCH_ITEMS} 个`, {
2746
+ maxBatchItems: MAX_BATCH_ITEMS,
2747
+ });
2748
+ }
2749
+ for (const id of ids) {
2750
+ if (typeof id !== 'string' || id.length === 0 || id.length > 128) {
2751
+ throw new CapabilityError(422, 'validation_failed', 'ids 含非法节点 id', { field: 'ids' });
2752
+ }
2753
+ }
2754
+ return [...new Set(ids)];
2755
+ }
2756
+
2757
+ async function classifyGovernanceTargets(ids, actor) {
2758
+ const appValue = app();
2759
+ if (!appValue) throw new CapabilityError(503, 'capability_unavailable', '图存储尚未初始化', undefined, true);
2760
+ const allowed = [];
2761
+ const notFound = [];
2762
+ const forbidden = [];
2763
+ const internal = [];
2764
+ const nodes = new Map();
2765
+ for (const id of ids) {
2766
+ const node = await appValue.graph.getNode(id);
2767
+ if (!node) {
2768
+ notFound.push(id);
2769
+ continue;
2770
+ }
2771
+ nodes.set(id, node);
2772
+ if (isInternalNode(node)) {
2773
+ internal.push(id);
2774
+ continue;
2775
+ }
2776
+ if (!canGovernNode(actor, node)) {
2777
+ forbidden.push(id);
2778
+ continue;
2779
+ }
2780
+ allowed.push(id);
2781
+ }
2782
+ return { appValue, nodes, allowed, notFound, forbidden, internal };
2783
+ }
2784
+
2785
+ async function handleDelete(payload, actor) {
2786
+ if (payload.sync !== undefined) {
2787
+ throw new CapabilityError(400, 'legacy_sync_unsupported', '不再支持 sync 字段');
2788
+ }
2789
+ const ids = parseIdList(payload);
2790
+ const classified = await classifyGovernanceTargets(ids, actor);
2791
+ const deleted = [];
2792
+ let detailsDeleted = [];
2793
+ if (classified.allowed.length > 0) {
2794
+ const result = await service().delete(classified.allowed);
2795
+ deleted.push(...(result?.deleted ?? []));
2796
+ detailsDeleted = Array.isArray(result?.detailsDeleted) ? result.detailsDeleted : [];
2797
+ classified.notFound.push(...(result?.notFound ?? []));
2798
+ classified.internal.push(...(result?.internal ?? []));
2799
+ }
2800
+ return {
2801
+ data: {
2802
+ deleted,
2803
+ ...(detailsDeleted.length > 0 ? { detailsDeleted } : {}),
2804
+ notFound: classified.notFound,
2805
+ forbidden: classified.forbidden,
2806
+ internal: classified.internal,
2807
+ partial: classified.notFound.length > 0
2808
+ || classified.forbidden.length > 0
2809
+ || classified.internal.length > 0,
2810
+ replayed: false,
2811
+ },
2812
+ warnings: [],
2813
+ degraded: false,
2814
+ };
2815
+ }
2816
+
2817
+ async function handleArchive(payload, actor) {
2818
+ if (payload.sync !== undefined) {
2819
+ throw new CapabilityError(400, 'legacy_sync_unsupported', '不再支持 sync 字段');
2820
+ }
2821
+ if (payload.archived !== undefined && typeof payload.archived !== 'boolean') {
2822
+ throw new CapabilityError(400, 'invalid_request', 'archived 必须是布尔值');
2823
+ }
2824
+ const archived = payload.archived !== false;
2825
+ const ids = parseIdList(payload);
2826
+ const classified = await classifyGovernanceTargets(ids, actor);
2827
+ const skipped = [];
2828
+ const allowed = [];
2829
+ for (const id of classified.allowed) {
2830
+ const node = classified.nodes.get(id);
2831
+ if (node?.deletedAt) skipped.push(id);
2832
+ else allowed.push(id);
2833
+ }
2834
+ let archivedIds = [];
2835
+ let unarchivedIds = [];
2836
+ if (allowed.length > 0) {
2837
+ const result = await service().archive(allowed, archived);
2838
+ archivedIds = result?.archived ?? [];
2839
+ unarchivedIds = result?.unarchived ?? [];
2840
+ classified.notFound.push(...(result?.notFound ?? []));
2841
+ skipped.push(...(result?.skipped ?? []));
2842
+ classified.internal.push(...(result?.internal ?? []));
2843
+ }
2844
+ return {
2845
+ data: {
2846
+ archived: archivedIds,
2847
+ unarchived: unarchivedIds,
2848
+ notFound: classified.notFound,
2849
+ skipped,
2850
+ forbidden: classified.forbidden,
2851
+ internal: classified.internal,
2852
+ partial: classified.notFound.length > 0
2853
+ || classified.forbidden.length > 0
2854
+ || classified.internal.length > 0,
2855
+ replayed: false,
2856
+ },
2857
+ warnings: [],
2858
+ degraded: false,
2859
+ };
2860
+ }
2861
+
2862
+ // ---------- /internal-object ----------
2863
+
2864
+ function assertInternalObjectActor(actor, agentId) {
2865
+ if (actor.type === 'user' || actor.type === 'system') return;
2866
+ if (actor.type === 'agent' && actor.agentId === agentId) return;
2867
+ throw new CapabilityError(403, 'forbidden_scope', '当前 actor 不能读写该 Agent 的内部对象', {
2868
+ actor: actor.type === 'agent' ? actor.agentId : actor.type,
2869
+ agentId,
2870
+ });
2871
+ }
2872
+
2873
+ function parseInternalDomain(value, { required = true } = {}) {
2874
+ if (value === undefined || value === null) {
2875
+ if (required) throw new CapabilityError(400, 'domain_invalid', '缺少 domain');
2876
+ return null;
2877
+ }
2878
+ const domain = normalizeDomain(value);
2879
+ if (!domain) throw new CapabilityError(400, 'domain_invalid', 'domain 非法', { domain: value });
2880
+ return domain;
2881
+ }
2882
+
2883
+ async function findCompactByIdentity(appValue, domain, identityKey) {
2884
+ const nodes = await listNodesOfType(appValue, 'compact');
2885
+ return nodes.find((node) => !node.deletedAt
2886
+ && isInternalNode(node)
2887
+ && internalObjectKind(node) === 'compact'
2888
+ && domainOfNamespace(node.namespace) === domain
2889
+ && internalObjectMetadata(node).identityKey === identityKey) ?? null;
2890
+ }
2891
+
2892
+ // [internal-object-write] 内部对象允许直接 GraphStore 写入;普通 MemoryRecord 禁止。
2893
+ async function handleCompactObject(payload, actor) { const op = payload.op;
2894
+ if (!['upsert', 'get', 'list', 'delete'].includes(op)) {
2895
+ throw new CapabilityError(400, 'internal_kind_invalid', 'compact op 必须是 upsert/get/list/delete');
2896
+ }
2897
+ const appValue = app();
2898
+ if (!appValue) throw new CapabilityError(503, 'capability_unavailable', '图存储尚未初始化', undefined, true);
2899
+ const identity = identitySnapshot();
2900
+
2901
+ if (op === 'upsert') {
2902
+ const domain = parseInternalDomain(payload.domain);
2903
+ const strategy = payload.strategy === 'dedupe' ? 'dedupe' : 'summary';
2904
+ if (payload.strategy !== undefined && !['summary', 'dedupe'].includes(payload.strategy)) {
2905
+ throw new CapabilityError(400, 'invalid_request', 'strategy 必须是 summary | dedupe');
2906
+ }
2907
+ const sourceIds = (() => {
2908
+ if (Array.isArray(payload.sourceIds) && payload.sourceIds.length > MAX_COMPACT_SOURCES) {
2909
+ throw new CapabilityError(413, 'payload_too_large', `sourceIds 最多 ${MAX_COMPACT_SOURCES} 个`, {
2910
+ maxCompactSources: MAX_COMPACT_SOURCES,
2911
+ });
2912
+ }
2913
+ return stringArray(payload.sourceIds, 'sourceIds', 0, {
2914
+ maxItems: MAX_COMPACT_SOURCES,
2915
+ maxChars: 128,
2916
+ }) ?? [];
2917
+ })();
2918
+ if (sourceIds.length === 0) {
2919
+ throw new CapabilityError(400, 'invalid_request', 'sourceIds 不能为空');
2920
+ }
2921
+ if (new Set(sourceIds).size !== sourceIds.length) {
2922
+ throw new CapabilityError(400, 'invalid_request', 'sourceIds 不得重复');
2923
+ }
2924
+ const sourceHashes = stringArray(payload.sourceHashes, 'sourceHashes', 0, {
2925
+ maxItems: MAX_COMPACT_SOURCES,
2926
+ maxChars: 128,
2927
+ }) ?? [];
2928
+ if (sourceHashes.length > 0 && sourceHashes.length !== sourceIds.length) {
2929
+ throw new CapabilityError(400, 'invalid_request', 'sourceHashes 必须与 sourceIds 等长');
2930
+ }
2931
+ const provenanceInput = parseProvenanceInput(payload.provenance, 0);
2932
+ assertDomainWrite(actor, domain, provenanceInput, payload.threadId);
2933
+ const summary = nonEmptyString(payload.summary, 'summary', 0);
2934
+ if (Buffer.byteLength(summary, 'utf-8') > MAX_COMPACT_SUMMARY_BYTES) {
2935
+ throw new CapabilityError(413, 'payload_too_large', 'summary 超过 64 KiB');
2936
+ }
2937
+ const tokenCount = optionalNumber(payload.tokenCount, 'tokenCount', 0);
2938
+ if (tokenCount !== undefined && tokenCount < 0) {
2939
+ throw validationError(0, 'tokenCount', 'tokenCount 不能为负数');
2940
+ }
2941
+ const model = isObject(payload.model) ? jsonClone(payload.model) : undefined;
2942
+ if (model && byteSize(model) > MAX_JSON_FIELD_BYTES) {
2943
+ throw new CapabilityError(413, 'payload_too_large', 'model 超过大小限制');
2944
+ }
2945
+ const sourceNodes = [];
2946
+ for (const sourceId of sourceIds) {
2947
+ const source = await appValue.graph.getNode(sourceId);
2948
+ if (!source || source.deletedAt) {
2949
+ throw new CapabilityError(404, 'not_found', 'compact source 不存在', { id: sourceId });
2950
+ }
2951
+ if (isInternalNode(source)) {
2952
+ throw new CapabilityError(400, 'domain_mismatch', 'compact source 不能是内部对象', { id: sourceId });
2953
+ }
2954
+ const sourceDomain = domainOfNamespace(source.namespace);
2955
+ if (sourceDomain !== domain) {
2956
+ throw new CapabilityError(400, 'domain_mismatch', 'compact 与 source 必须同域', {
2957
+ domain,
2958
+ sourceId,
2959
+ sourceDomain,
2960
+ });
2961
+ }
2962
+ sourceNodes.push(source);
2963
+ }
2964
+ const effectiveSourceHashes = sourceHashes.length > 0
2965
+ ? [...sourceHashes]
2966
+ : sourceNodes.map((source) => `sha256:${sha256Hex(canonicalJson(source.content ?? null))}`);
2967
+ const identityKey = sha256Hex(canonicalJson({
2968
+ domain,
2969
+ strategy,
2970
+ sourceIds: [...sourceIds].sort(),
2971
+ sourceHashes: effectiveSourceHashes,
2972
+ }));
2973
+ const existing = await findCompactByIdentity(appValue, domain, identityKey);
2974
+ if (existing) {
2975
+ return {
2976
+ data: {
2977
+ object: compactObjectView(existing, {
2978
+ userId: identity.userId,
2979
+ stale: await isCompactStale(appValue, existing),
2980
+ }),
2981
+ replayed: false,
2982
+ },
2983
+ warnings: [],
2984
+ degraded: false,
2985
+ };
2986
+ }
2987
+ const provenance = buildWriteProvenance({
2988
+ input: provenanceInput,
2989
+ actor,
2990
+ identity,
2991
+ hostId,
2992
+ now: now(),
2993
+ threadId: provenanceInput.threadId ?? payload.threadId ?? null,
2994
+ });
2995
+ const content = {
2996
+ summary,
2997
+ sourceIds: [...sourceIds],
2998
+ sourceHashes: effectiveSourceHashes,
2999
+ strategy,
3000
+ ...(tokenCount !== undefined ? { tokenCount } : {}),
3001
+ ...(model !== undefined ? { model } : {}),
3002
+ };
3003
+ const created = await appValue.graph.createNode('compact', content, undefined, { namespace: domain });
3004
+ const node = await appValue.graph.updateNode(created.id, {
3005
+ metadata: {
3006
+ internal: true,
3007
+ internalObject: {
3008
+ schema: 1,
3009
+ kind: 'compact',
3010
+ strategy,
3011
+ identityKey,
3012
+ sourceIds: [...sourceIds],
3013
+ sourceHashes: effectiveSourceHashes,
3014
+ },
3015
+ provenance,
3016
+ },
3017
+ });
3018
+ if (!node) throw new CapabilityError(503, 'capability_unavailable', 'compact 写入后读取失败', undefined, true);
3019
+ return {
3020
+ data: {
3021
+ object: compactObjectView(node, { userId: identity.userId, stale: false }),
3022
+ replayed: false,
3023
+ },
3024
+ warnings: [],
3025
+ degraded: false,
3026
+ };
3027
+ }
3028
+
3029
+ if (op === 'get') {
3030
+ if (typeof payload.id !== 'string' || payload.id.length === 0) {
3031
+ throw new CapabilityError(400, 'invalid_request', 'compact get 需要 id');
3032
+ }
3033
+ const node = await appValue.graph.getNode(payload.id);
3034
+ if (!node || node.deletedAt || !isInternalNode(node) || internalObjectKind(node) !== 'compact') {
3035
+ throw new CapabilityError(404, 'not_found', 'compact 不存在', { id: payload.id });
3036
+ }
3037
+ return {
3038
+ data: {
3039
+ object: compactObjectView(node, {
3040
+ userId: identity.userId,
3041
+ stale: await isCompactStale(appValue, node),
3042
+ }),
3043
+ replayed: false,
3044
+ },
3045
+ warnings: [],
3046
+ degraded: false,
3047
+ };
3048
+ }
3049
+
3050
+ if (op === 'list') {
3051
+ let domains = null;
3052
+ if (payload.domains !== undefined) {
3053
+ if (!Array.isArray(payload.domains) || payload.domains.length > MAX_DOMAINS) {
3054
+ throw new CapabilityError(400, 'invalid_request', `domains 最多 ${MAX_DOMAINS} 个`);
3055
+ }
3056
+ domains = payload.domains.map((value) => {
3057
+ const domain = normalizeDomain(value);
3058
+ if (!domain) throw new CapabilityError(400, 'domain_invalid', 'domains 含非法域', { domain: value });
3059
+ return domain;
3060
+ });
3061
+ }
3062
+ const limit = clampLimit(payload.limit, 20);
3063
+ const staleOnly = payload.stale === true;
3064
+ const nodes = (await listNodesOfType(appValue, 'compact'))
3065
+ .filter((node) => !node.deletedAt && isInternalNode(node) && internalObjectKind(node) === 'compact')
3066
+ .filter((node) => domains === null || domains.includes(domainOfNamespace(node.namespace)))
3067
+ .sort((a, b) => (b.updatedAt ?? 0) - (a.updatedAt ?? 0));
3068
+ const objects = [];
3069
+ for (const node of nodes) {
3070
+ const stale = await isCompactStale(appValue, node);
3071
+ if (staleOnly && !stale) continue;
3072
+ objects.push(compactObjectView(node, { userId: identity.userId, stale }));
3073
+ }
3074
+ return {
3075
+ data: { objects: objects.slice(0, limit), total: objects.length, replayed: false },
3076
+ warnings: [],
3077
+ degraded: false,
3078
+ };
3079
+ }
3080
+
3081
+ // delete
3082
+ if (actor.type !== 'user' && actor.type !== 'system') {
3083
+ throw new CapabilityError(403, 'forbidden_scope', '删除 compact 需要 user/system 权限');
3084
+ }
3085
+ if (typeof payload.id !== 'string' || payload.id.length === 0) {
3086
+ throw new CapabilityError(400, 'invalid_request', 'compact delete 需要 id');
3087
+ }
3088
+ const node = await appValue.graph.getNode(payload.id);
3089
+ if (!node || node.deletedAt || !isInternalNode(node) || internalObjectKind(node) !== 'compact') {
3090
+ throw new CapabilityError(404, 'not_found', 'compact 不存在', { id: payload.id });
3091
+ }
3092
+ await appValue.graph.deleteNode(payload.id);
3093
+ return {
3094
+ data: { deleted: true, id: payload.id, replayed: false },
3095
+ warnings: [],
3096
+ degraded: false,
3097
+ };
3098
+ }
3099
+
3100
+ async function handleSelfRecordObject(payload, actor) {
3101
+ const op = payload.op;
3102
+ if (!['upsert', 'get'].includes(op)) {
3103
+ throw new CapabilityError(400, 'internal_kind_invalid', 'self_record op 必须是 upsert/get');
3104
+ }
3105
+ if (!isValidAgentId(payload.agentId)) {
3106
+ throw new CapabilityError(400, 'invalid_agent_id', 'agentId 格式非法');
3107
+ }
3108
+ const agentId = payload.agentId;
3109
+ assertInternalObjectActor(actor, agentId);
3110
+ const domain = `agent:${agentId}`;
3111
+ if (payload.domain !== undefined && payload.domain !== domain) {
3112
+ throw new CapabilityError(400, 'domain_mismatch', 'SelfRecord 必须位于 agent:<agentId> 域', {
3113
+ domain: payload.domain,
3114
+ expected: domain,
3115
+ });
3116
+ }
3117
+ if (payload.sync !== undefined || payload['self.sync'] !== undefined) {
3118
+ throw new CapabilityError(400, 'legacy_sync_unsupported', '不再支持 sync/self.sync 字段');
3119
+ }
3120
+ const appValue = app();
3121
+ if (!appValue) throw new CapabilityError(503, 'capability_unavailable', '图存储尚未初始化', undefined, true);
3122
+ const identity = identitySnapshot();
3123
+ const current = await currentSelfRecord(appValue, agentId);
3124
+ if (op === 'get') {
3125
+ return {
3126
+ data: {
3127
+ object: current ? selfRecordView(current, { userId: identity.userId }) : null,
3128
+ replayed: false,
3129
+ },
3130
+ warnings: [],
3131
+ degraded: false,
3132
+ };
3133
+ }
3134
+ const currentRevision = current ? internalObjectRevision(current) : 0;
3135
+ if (hasValue(payload.expectedRevision)) {
3136
+ if (typeof payload.expectedRevision !== 'number' || !Number.isInteger(payload.expectedRevision) || payload.expectedRevision < 0) {
3137
+ throw new CapabilityError(400, 'invalid_request', 'expectedRevision 必须是非负整数');
3138
+ }
3139
+ if (payload.expectedRevision !== currentRevision) {
3140
+ throw new CapabilityError(409, 'revision_mismatch', 'SelfRecord revision 冲突', {
3141
+ agentId,
3142
+ currentRevision,
3143
+ expectedRevision: payload.expectedRevision,
3144
+ }, true);
3145
+ }
3146
+ }
3147
+ const record = normalizeSelfRecord(payload.record, 0);
3148
+ const provenanceInput = parseProvenanceInput(payload.provenance, 0);
3149
+ assertDomainWrite(actor, domain, provenanceInput, null);
3150
+ const provenance = buildWriteProvenance({
3151
+ input: provenanceInput,
3152
+ actor,
3153
+ identity,
3154
+ hostId,
3155
+ now: now(),
3156
+ });
3157
+ const revision = currentRevision + 1;
3158
+ const created = await appValue.graph.createNode('self_record', {
3159
+ agentId,
3160
+ revision,
3161
+ record,
3162
+ }, undefined, { namespace: domain });
3163
+ const node = await appValue.graph.updateNode(created.id, {
3164
+ metadata: {
3165
+ internal: true,
3166
+ internalObject: { schema: 1, kind: 'self_record', agentId, revision },
3167
+ provenance,
3168
+ },
3169
+ });
3170
+ if (!node) throw new CapabilityError(503, 'capability_unavailable', 'SelfRecord 写入后读取失败', undefined, true);
3171
+ return {
3172
+ data: { object: selfRecordView(node, { userId: identity.userId }), conflict: null, replayed: false },
3173
+ warnings: [],
3174
+ degraded: false,
3175
+ };
3176
+ }
3177
+
3178
+ async function handleCheckpointObject(payload, actor) {
3179
+ const op = payload.op;
3180
+ if (!['upsert', 'get', 'list', 'delete'].includes(op)) {
3181
+ throw new CapabilityError(400, 'internal_kind_invalid', 'context_checkpoint op 必须是 upsert/get/list/delete');
3182
+ }
3183
+ if (!isValidAgentId(payload.agentId)) {
3184
+ throw new CapabilityError(400, 'invalid_agent_id', 'agentId 格式非法');
3185
+ }
3186
+ const agentId = payload.agentId;
3187
+ if (payload.sync !== undefined || payload['checkpoint.sync'] !== undefined) {
3188
+ throw new CapabilityError(400, 'legacy_sync_unsupported', '不再支持 sync/checkpoint.sync 字段');
3189
+ }
3190
+ const appValue = app();
3191
+ if (!appValue) throw new CapabilityError(503, 'capability_unavailable', '图存储尚未初始化', undefined, true);
3192
+ const identity = identitySnapshot();
3193
+
3194
+ const readDomain = (() => {
3195
+ if (payload.domain === undefined || payload.domain === null) return null;
3196
+ const domain = parseInternalDomain(payload.domain);
3197
+ if (domain !== 'default' && !domain.startsWith('task:')) {
3198
+ throw new CapabilityError(400, 'domain_mismatch', 'Checkpoint 只能位于 task:<key> 或 default 域', {
3199
+ domain,
3200
+ });
3201
+ }
3202
+ return domain;
3203
+ })();
3204
+ const assertCheckpointRead = (domain) => {
3205
+ if (domain.startsWith('task:')) return;
3206
+ assertInternalObjectActor(actor, agentId);
3207
+ };
3208
+
3209
+ if (op === 'get') {
3210
+ if (payload.id !== undefined) {
3211
+ if (typeof payload.id !== 'string' || payload.id.length === 0) {
3212
+ throw new CapabilityError(400, 'invalid_request', 'id 非法');
3213
+ }
3214
+ const byId = await appValue.graph.getNode(payload.id);
3215
+ if (!byId || byId.deletedAt || !isV2CheckpointNode(byId) || internalObjectKind(byId) !== 'context_checkpoint') {
3216
+ return { data: { object: null, replayed: false }, warnings: [], degraded: false };
3217
+ }
3218
+ const visible = !checkpointExpired(byId, now()) ? byId : null;
3219
+ const view = visible ? checkpointObjectView(visible, { userId: identity.userId }) : null;
3220
+ if (view) assertCheckpointRead(view.domain);
3221
+ return {
3222
+ data: { object: view, replayed: false },
3223
+ warnings: checkpointWarnings(view),
3224
+ degraded: checkpointDegraded(view),
3225
+ };
3226
+ }
3227
+ const threadId = parseThreadId(payload.threadId);
3228
+ if (!threadId) throw new CapabilityError(400, 'invalid_thread_id', 'checkpoint get 需要 threadId');
3229
+ const requestedTaskId = typeof payload.fleetTaskId === 'string' && payload.fleetTaskId.length > 0
3230
+ ? payload.fleetTaskId
3231
+ : (typeof payload.taskId === 'string' && payload.taskId.length > 0 ? payload.taskId : null);
3232
+ const candidates = readDomain
3233
+ ? [readDomain]
3234
+ : [...new Set([
3235
+ ...(requestedTaskId ? [`task:${requestedTaskId}`] : []),
3236
+ `task:${threadId}`,
3237
+ 'default',
3238
+ ])];
3239
+ let visible = null;
3240
+ for (const domain of candidates) {
3241
+ const node = await currentCheckpoint(appValue, { agentId, threadId, domain });
3242
+ if (!node || checkpointExpired(node, now())) continue;
3243
+ visible = node;
3244
+ break;
3245
+ }
3246
+ const view = visible ? checkpointObjectView(visible, { userId: identity.userId }) : null;
3247
+ if (view) assertCheckpointRead(view.domain);
3248
+ return {
3249
+ data: {
3250
+ object: view,
3251
+ replayed: false,
3252
+ },
3253
+ warnings: checkpointWarnings(view),
3254
+ degraded: checkpointDegraded(view),
3255
+ };
3256
+ }
3257
+
3258
+ if (op === 'list') {
3259
+ const threadId = payload.threadId === undefined ? null : parseThreadId(payload.threadId);
3260
+ const limit = clampLimit(payload.limit, 20);
3261
+ if (!readDomain?.startsWith('task:')) assertInternalObjectActor(actor, agentId);
3262
+ const nodes = (await allCheckpoints(appValue, agentId, threadId))
3263
+ .filter((node) => (readDomain ? domainOfNamespace(node.namespace) === readDomain : true))
3264
+ .filter((node) => !checkpointExpired(node, now()))
3265
+ .sort(compareInternalObjectNodes);
3266
+ const latestByKey = new Map();
3267
+ for (const node of nodes) {
3268
+ const key = checkpointRevisionKey(node);
3269
+ if (!latestByKey.has(key)) latestByKey.set(key, node);
3270
+ }
3271
+ const views = [...latestByKey.values()].map((node) => checkpointObjectView(node, { userId: identity.userId }));
3272
+ return {
3273
+ data: { objects: views.slice(0, limit), total: views.length, replayed: false },
3274
+ warnings: [...new Set(views.flatMap((view) => checkpointWarnings(view)))],
3275
+ degraded: views.some((view) => checkpointDegraded(view)),
3276
+ };
3277
+ }
3278
+
3279
+ if (op === 'delete') {
3280
+ if (actor.type !== 'user' && actor.type !== 'system') {
3281
+ throw new CapabilityError(403, 'forbidden_scope', '删除 checkpoint 需要 user/system 权限');
3282
+ }
3283
+ if (payload.id !== undefined) {
3284
+ if (typeof payload.id !== 'string' || payload.id.length === 0) {
3285
+ throw new CapabilityError(400, 'invalid_request', 'id 非法');
3286
+ }
3287
+ const node = await appValue.graph.getNode(payload.id);
3288
+ if (!node || node.deletedAt || !isV2CheckpointNode(node) || internalObjectKind(node) !== 'context_checkpoint') {
3289
+ throw new CapabilityError(404, 'not_found', 'checkpoint 不存在', { id: payload.id });
3290
+ }
3291
+ const revisionAgentId = checkpointAgentId(node);
3292
+ const revisionThreadId = checkpointThreadId(node);
3293
+ const revisions = revisionAgentId && revisionThreadId
3294
+ ? await allCheckpoints(appValue, revisionAgentId, revisionThreadId)
3295
+ : [node];
3296
+ for (const revision of revisions) {
3297
+ await appValue.graph.deleteNode(revision.id);
3298
+ }
3299
+ return {
3300
+ data: { deleted: true, id: payload.id, count: revisions.length, replayed: false },
3301
+ warnings: [],
3302
+ degraded: false,
3303
+ };
3304
+ }
3305
+ const threadId = parseThreadId(payload.threadId);
3306
+ if (!threadId) throw new CapabilityError(400, 'invalid_thread_id', 'checkpoint delete 需要 id 或 threadId');
3307
+ const nodes = (await allCheckpoints(appValue, agentId, threadId))
3308
+ .filter((node) => (readDomain ? domainOfNamespace(node.namespace) === readDomain : true));
3309
+ for (const node of nodes) {
3310
+ await appValue.graph.deleteNode(node.id);
3311
+ }
3312
+ return {
3313
+ data: { deleted: nodes.length > 0, count: nodes.length, replayed: false },
3314
+ warnings: [],
3315
+ degraded: false,
3316
+ };
3317
+ }
3318
+
3319
+ // upsert
3320
+ const threadId = parseThreadId(payload.threadId);
3321
+ if (!threadId) throw new CapabilityError(400, 'invalid_thread_id', 'checkpoint 需要 threadId');
3322
+ assertInternalObjectActor(actor, agentId);
3323
+ if (payload.force === true && actor.type === 'agent') {
3324
+ throw new CapabilityError(403, 'forbidden_scope', 'force=true 仅允许 user/system');
3325
+ }
3326
+ const state = normalizeCheckpointState(payload.state, 0);
3327
+ let summary = null;
3328
+ if (payload.summary !== undefined && payload.summary !== null) {
3329
+ if (typeof payload.summary !== 'string') throw validationError(0, 'summary', 'summary 必须是字符串');
3330
+ if (Buffer.byteLength(payload.summary, 'utf-8') > MAX_COMPACT_SUMMARY_BYTES) {
3331
+ throw new CapabilityError(413, 'payload_too_large', 'summary 超过 64 KiB');
3332
+ }
3333
+ summary = payload.summary;
3334
+ }
3335
+ const warnings = [];
3336
+ if (state.contentMode === 'summary_only' && summary === null) warnings.push('summary_unavailable');
3337
+ const incomingWarnings = Array.isArray(payload.warnings)
3338
+ ? payload.warnings
3339
+ : (typeof payload.warning === 'string' ? [payload.warning] : []);
3340
+ for (const warning of incomingWarnings) {
3341
+ if (typeof warning === 'string' && warning.length > 0 && !warnings.includes(warning)) warnings.push(warning);
3342
+ }
3343
+ let domain = 'default';
3344
+ if (payload.domain !== undefined && payload.domain !== null) {
3345
+ domain = parseInternalDomain(payload.domain);
3346
+ } else if (state.task.key.startsWith('task:')) {
3347
+ domain = parseInternalDomain(state.task.key);
3348
+ } else if (state.task.key !== 'default') {
3349
+ throw new CapabilityError(400, 'domain_mismatch', 'Checkpoint 只能位于 task:<key> 或 default 域', {
3350
+ domain: state.task.key,
3351
+ threadId,
3352
+ });
3353
+ }
3354
+ if (state.task.key !== domain) {
3355
+ throw new CapabilityError(400, 'domain_mismatch', 'state.task.key 必须等于 domain', {
3356
+ domain,
3357
+ taskKey: state.task.key,
3358
+ });
3359
+ }
3360
+ if (state.task.threadId !== threadId) {
3361
+ throw new CapabilityError(400, 'domain_mismatch', 'state.task.threadId 必须等于路径 threadId', {
3362
+ threadId,
3363
+ taskThreadId: state.task.threadId,
3364
+ });
3365
+ }
3366
+ if (domain !== 'default') {
3367
+ const validTaskDomain = domain.startsWith('task:')
3368
+ && (domain.slice('task:'.length) === threadId
3369
+ || domain.slice('task:'.length) === state.task.fleetTaskId
3370
+ || domain.slice('task:'.length) === payload.fleetTaskId
3371
+ || domain.slice('task:'.length) === payload.taskId);
3372
+ if (!validTaskDomain) {
3373
+ throw new CapabilityError(400, 'domain_mismatch', 'Checkpoint 只能位于 task:<threadId|taskId> 或 default 域', {
3374
+ domain,
3375
+ threadId,
3376
+ fleetTaskId: state.task.fleetTaskId,
3377
+ });
3378
+ }
3379
+ }
3380
+ const current = await currentCheckpoint(appValue, { agentId, threadId, domain });
3381
+ const currentRevision = current ? internalObjectRevision(current) : 0;
3382
+ if (hasValue(payload.expectedRevision)) {
3383
+ if (typeof payload.expectedRevision !== 'number' || !Number.isInteger(payload.expectedRevision) || payload.expectedRevision < 0) {
3384
+ throw new CapabilityError(400, 'invalid_request', 'expectedRevision 必须是非负整数');
3385
+ }
3386
+ if (payload.expectedRevision !== currentRevision) {
3387
+ throw new CapabilityError(409, 'revision_mismatch', 'checkpoint revision 冲突', {
3388
+ agentId,
3389
+ threadId,
3390
+ domain,
3391
+ currentRevision,
3392
+ expectedRevision: payload.expectedRevision,
3393
+ }, true);
3394
+ }
3395
+ }
3396
+ const currentContent = isObject(current?.content) ? current.content : {};
3397
+ const currentLease = isObject(currentContent.lease) ? currentContent.lease : null;
3398
+ if (currentLease && typeof currentLease.until === 'number' && currentLease.until > now()
3399
+ && currentLease.hostId !== hostId) {
3400
+ if (payload.force !== true) {
3401
+ throw new CapabilityError(409, 'checkpoint_lease_held', 'checkpoint 租约被其他 host 持有', {
3402
+ hostId: currentLease.hostId,
3403
+ until: currentLease.until,
3404
+ }, true);
3405
+ }
3406
+ if (actor.type !== 'user' && actor.type !== 'system') {
3407
+ throw new CapabilityError(403, 'forbidden_scope', '只有 user/system 可以抢占租约');
3408
+ }
3409
+ }
3410
+ const recordIds = stringArray(payload.recordIds, 'recordIds', 0, {
3411
+ maxItems: MAX_COMPACT_SOURCES,
3412
+ maxChars: 128,
3413
+ }) ?? [];
3414
+ const detailIds = stringArray(payload.detailIds, 'detailIds', 0, {
3415
+ maxItems: MAX_COMPACT_SOURCES,
3416
+ maxChars: 128,
3417
+ }) ?? state.references.detailIds;
3418
+ const expiresAt = payload.expiresAt === undefined || payload.expiresAt === null
3419
+ ? 0
3420
+ : optionalNumber(payload.expiresAt, 'expiresAt', 0);
3421
+ if (expiresAt < 0) throw validationError(0, 'expiresAt', 'expiresAt 不能为负数');
3422
+ let leaseMs = DEFAULT_CHECKPOINT_LEASE_MS;
3423
+ if (payload.leaseMs !== undefined && payload.leaseMs !== null) {
3424
+ if (typeof payload.leaseMs !== 'number' || !Number.isFinite(payload.leaseMs) || payload.leaseMs <= 0) {
3425
+ throw validationError(0, 'leaseMs', 'leaseMs 必须是正数');
3426
+ }
3427
+ leaseMs = Math.min(payload.leaseMs, 3_600_000);
3428
+ }
3429
+ const lease = { hostId, until: now() + leaseMs };
3430
+ const provenanceInput = parseProvenanceInput(payload.provenance, 0);
3431
+ assertDomainWrite(actor, domain.startsWith('task:') ? `task:${threadId}` : domain, {
3432
+ ...provenanceInput,
3433
+ threadId: provenanceInput.threadId ?? threadId,
3434
+ }, threadId);
3435
+ const provenance = buildWriteProvenance({
3436
+ input: provenanceInput,
3437
+ actor,
3438
+ identity,
3439
+ hostId,
3440
+ now: now(),
3441
+ threadId: provenanceInput.threadId ?? threadId,
3442
+ });
3443
+ const revision = currentRevision + 1;
3444
+ const updatedBy = {
3445
+ agentId: actor.type === 'agent' ? actor.agentId : null,
3446
+ actorType: actor.type,
3447
+ hostId,
3448
+ at: now(),
3449
+ };
3450
+ const content = {
3451
+ agentId,
3452
+ threadId,
3453
+ revision,
3454
+ state,
3455
+ contentMode: state.contentMode,
3456
+ structured: state.contentMode === 'structured',
3457
+ summary,
3458
+ recordIds,
3459
+ detailIds,
3460
+ lease,
3461
+ updatedBy,
3462
+ expiresAt,
3463
+ };
3464
+ const created = await appValue.graph.createNode('context_checkpoint', content, undefined, { namespace: domain });
3465
+ const node = await appValue.graph.updateNode(created.id, {
3466
+ metadata: {
3467
+ internal: true,
3468
+ internalObject: {
3469
+ schema: 2,
3470
+ kind: 'context_checkpoint',
3471
+ agentId,
3472
+ threadId,
3473
+ revision,
3474
+ lease,
3475
+ taskKey: domain,
3476
+ contentMode: state.contentMode,
3477
+ structured: state.contentMode === 'structured',
3478
+ cloudId: identity.cloudId ?? null,
3479
+ },
3480
+ provenance,
3481
+ },
3482
+ });
3483
+ if (!node) {
3484
+ throw new CapabilityError(503, 'capability_unavailable', 'checkpoint 写入后读取失败', undefined, true);
3485
+ }
3486
+ const view = checkpointObjectView(node, { userId: identity.userId });
3487
+ return {
3488
+ data: { object: view, conflict: null, replayed: false },
3489
+ warnings: [...new Set([...warnings, ...checkpointWarnings(view)])],
3490
+ degraded: checkpointDegraded(view),
3491
+ };
3492
+ }
3493
+
3494
+ // [/internal-object-write]
3495
+ async function handleInternalObject(payload, actor) {
3496
+ if (payload.sync !== undefined || payload['self.sync'] !== undefined || payload['checkpoint.sync'] !== undefined) {
3497
+ throw new CapabilityError(400, 'legacy_sync_unsupported', '不再支持 sync/self.sync/checkpoint.sync 字段');
3498
+ }
3499
+ const kind = payload.kind;
3500
+ if (!INTERNAL_OBJECT_KINDS.includes(kind)) {
3501
+ throw new CapabilityError(400, 'internal_kind_invalid', 'kind 必须是 compact | self_record | context_checkpoint');
3502
+ }
3503
+ if (kind === 'compact') return handleCompactObject(payload, actor);
3504
+ if (kind === 'self_record') return handleSelfRecordObject(payload, actor);
3505
+ return handleCheckpointObject(payload, actor);
3506
+ }
3507
+
3508
+ // ---------- /detail ----------
3509
+
3510
+ /**
3511
+ * 详情配额可被本机 admin 配置收紧(`memoryRuntime.detailLimits`);
3512
+ * 默认值仍是契约的 256 MiB/域、1 GiB/云、64 MiB/thread。
3513
+ * 该配置只在 capability 进程内使用,不进入公共 MCP 工具面。
3514
+ */
3515
+ function detailLimitsForConfig() {
3516
+ const raw = getConfig()?.memoryRuntime?.detailLimits;
3517
+ const limits = { ...DEFAULT_DETAIL_QUOTA_LIMITS };
3518
+ if (isObject(raw)) {
3519
+ for (const key of ['domainBytes', 'cloudBytes', 'threadBytes']) {
3520
+ const value = raw[key];
3521
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
3522
+ // 契约只允许在默认配额内收紧,不允许配置放大。
3523
+ limits[key] = Math.min(limits[key], Math.trunc(value));
3524
+ }
3525
+ }
3526
+ }
3527
+ return limits;
3528
+ }
3529
+
3530
+ function detailCoreError(error, index) {
3531
+ if (error instanceof CapabilityError) return error;
3532
+ if (error?.code === 'DETAIL_QUOTA_EXCEEDED') {
3533
+ return new CapabilityError(413, 'detail_quota_exceeded', '详情配额超限且无法淘汰', {
3534
+ ...(Number.isInteger(index) ? { index } : {}),
3535
+ ...(isObject(error.details) ? error.details : {}),
3536
+ });
3537
+ }
3538
+ if (error?.name === 'ValidationError' || error?.code === 'VALIDATION_INVALID_NODE') {
3539
+ return new CapabilityError(422, 'validation_failed', error.message ?? '详情字段非法', {
3540
+ ...(Number.isInteger(index) ? { index } : {}),
3541
+ ...(isObject(error.details) ? error.details : {}),
3542
+ });
3543
+ }
3544
+ return new CapabilityError(500, 'internal', '能力接口内部错误', undefined, true);
3545
+ }
3546
+
3547
+ function parseDetailKinds(value) {
3548
+ if (value === undefined || value === null) return undefined;
3549
+ if (!Array.isArray(value) || value.length === 0) {
3550
+ throw new CapabilityError(400, 'invalid_request', 'detailKinds 必须是非空数组');
3551
+ }
3552
+ const kinds = [];
3553
+ for (const kind of value) {
3554
+ if (!isDetailKind(kind)) {
3555
+ throw new CapabilityError(400, 'invalid_request', 'detailKinds 含未知类型', { detailKind: kind });
3556
+ }
3557
+ if (!kinds.includes(kind)) kinds.push(kind);
3558
+ }
3559
+ return kinds;
3560
+ }
3561
+
3562
+ function assertDetailGovernance(actor, includeExpired, includeDeleted) {
3563
+ if (!includeExpired && !includeDeleted) return;
3564
+ if (actor.type === 'user' || actor.type === 'system') return;
3565
+ throw new CapabilityError(403, 'forbidden_scope', 'includeExpired/includeDeleted 仅允许 user/system 治理读取');
3566
+ }
3567
+
3568
+ function validateDetailItem(raw, index, requestThreadId, actor) {
3569
+ if (!isObject(raw)) throw validationError(index, 'item', 'item 必须是对象');
3570
+ for (const key of ['internal', 'internalObject', 'owner']) {
3571
+ if (hasValue(raw[key])) {
3572
+ throw validationError(index, key, `${key} 是服务端受保护字段`);
3573
+ }
3574
+ }
3575
+ if (hasValue(raw.type) && raw.type !== 'detail_record') {
3576
+ throw validationError(index, 'type', 'type 固定为 detail_record');
3577
+ }
3578
+ if (hasValue(raw.kind) && raw.kind !== 'detail_record') {
3579
+ throw validationError(index, 'kind', 'kind 固定为 detail_record');
3580
+ }
3581
+ if (!hasValue(raw.domain) || (typeof raw.domain === 'string' && raw.domain.trim() === '')) {
3582
+ throw validationError(index, 'domain', 'item.domain 必填');
3583
+ }
3584
+ const domain = normalizeDomain(raw.domain);
3585
+ if (!domain) {
3586
+ throw new CapabilityError(400, 'domain_invalid', 'item.domain 非法', {
3587
+ index,
3588
+ ...(typeof raw.domain === 'string' ? { domain: raw.domain } : {}),
3589
+ });
3590
+ }
3591
+ if (hasValue(raw.namespace) && raw.namespace !== domain) {
3592
+ throw ownerMismatchError(index, domain, { ownerType: 'namespace', ownerId: domain }, {
3593
+ ownerType: 'namespace',
3594
+ ownerId: raw.namespace,
3595
+ });
3596
+ }
3597
+ if (!isDetailKind(raw.detailKind)) {
3598
+ throw validationError(index, 'detailKind', 'detailKind 非法');
3599
+ }
3600
+ if (typeof raw.text !== 'string' || raw.text.trim() === '') {
3601
+ throw validationError(index, 'text', 'text 必须是非空字符串');
3602
+ }
3603
+ if (detailTextBytes(raw.text) > MAX_DETAIL_TEXT_BYTES) {
3604
+ throw new CapabilityError(413, 'payload_too_large', `text 超过 ${MAX_DETAIL_TEXT_BYTES} 字节`, {
3605
+ index,
3606
+ maxBytes: MAX_DETAIL_TEXT_BYTES,
3607
+ });
3608
+ }
3609
+ const contentHash = detailContentHash(raw.text);
3610
+ if (hasValue(raw.contentHash) && raw.contentHash !== contentHash) {
3611
+ throw validationError(index, 'contentHash', 'contentHash 必须等于 sha256(text)', {
3612
+ expected: contentHash,
3613
+ });
3614
+ }
3615
+ if (hasValue(raw.mime) && !isDetailMime(raw.mime)) {
3616
+ throw validationError(index, 'mime', 'mime 非法');
3617
+ }
3618
+ if (hasValue(raw.role) && !isDetailRole(raw.role)) {
3619
+ throw validationError(index, 'role', 'role 非法');
3620
+ }
3621
+ if (raw.detailKind === 'raw_chunk' && !hasValue(raw.role)) {
3622
+ throw validationError(index, 'role', 'raw_chunk 需要 role');
3623
+ }
3624
+ if (hasValue(raw.messageId)
3625
+ && (typeof raw.messageId !== 'string' || raw.messageId.length > 256)) {
3626
+ throw validationError(index, 'messageId', 'messageId 需为 1–256 字符');
3627
+ }
3628
+ if (hasValue(raw.chunkIndex)
3629
+ && (typeof raw.chunkIndex !== 'number' || !Number.isInteger(raw.chunkIndex) || raw.chunkIndex < 0)) {
3630
+ throw validationError(index, 'chunkIndex', 'chunkIndex 必须是非负整数');
3631
+ }
3632
+ if (hasValue(raw.turn)
3633
+ && (typeof raw.turn !== 'number' || !Number.isInteger(raw.turn) || raw.turn < 0)) {
3634
+ throw validationError(index, 'turn', 'turn 必须是非负整数');
3635
+ }
3636
+ if (hasValue(raw.retentionClass) && !isDetailRetentionClass(raw.retentionClass)) {
3637
+ throw validationError(index, 'retentionClass', 'retentionClass 非法');
3638
+ }
3639
+ const retentionClass = hasValue(raw.retentionClass) ? raw.retentionClass : 'conversation';
3640
+ if (hasValue(raw.expiresAt)
3641
+ && (typeof raw.expiresAt !== 'number' || !Number.isFinite(raw.expiresAt) || raw.expiresAt < 0)) {
3642
+ throw validationError(index, 'expiresAt', 'expiresAt 必须是非负数字');
3643
+ }
3644
+ try {
3645
+ resolveDetailExpiresAt(retentionClass, hasValue(raw.expiresAt) ? raw.expiresAt : undefined, now());
3646
+ } catch (error) {
3647
+ throw validationError(index, 'expiresAt', error.message);
3648
+ }
3649
+ if (hasValue(raw.redaction)) {
3650
+ if (!isObject(raw.redaction)) throw validationError(index, 'redaction', 'redaction 必须是对象');
3651
+ if (raw.redaction.applied !== undefined && typeof raw.redaction.applied !== 'boolean') {
3652
+ throw validationError(index, 'redaction.applied', 'redaction.applied 必须是布尔值');
3653
+ }
3654
+ if (raw.redaction.rules !== undefined
3655
+ && (!Array.isArray(raw.redaction.rules)
3656
+ || raw.redaction.rules.some((rule) => typeof rule !== 'string' || rule.length === 0 || rule.length > 256)
3657
+ || raw.redaction.rules.length > 64)) {
3658
+ throw validationError(index, 'redaction.rules', 'redaction.rules 非法');
3659
+ }
3660
+ }
3661
+ if (hasValue(raw.clientItemId)
3662
+ && (typeof raw.clientItemId !== 'string' || !CLIENT_ITEM_ID_RE.test(raw.clientItemId))) {
3663
+ throw validationError(index, 'clientItemId', 'clientItemId 格式非法');
3664
+ }
3665
+ const safeMetadata = {};
3666
+ if (hasValue(raw.metadata)) {
3667
+ if (!isObject(raw.metadata)) throw validationError(index, 'metadata', 'metadata 必须是对象');
3668
+ for (const [key, value] of Object.entries(raw.metadata)) {
3669
+ if (PROTECTED_METADATA_KEYS.has(key)
3670
+ || ['expiresAt', 'detailKind', 'recordIds', 'deletedReason', 'detailAvailable'].includes(key)) {
3671
+ throw validationError(index, `metadata.${key}`, 'metadata 含受保护字段', { field: key });
3672
+ }
3673
+ safeMetadata[key] = value;
3674
+ }
3675
+ }
3676
+ if (hasValue(raw.recordIds)) {
3677
+ if (!Array.isArray(raw.recordIds) || raw.recordIds.length === 0) {
3678
+ throw validationError(index, 'recordIds', 'recordIds 必须是非空数组');
3679
+ }
3680
+ if (raw.recordIds.length > MAX_DETAIL_RECORD_IDS) {
3681
+ throw validationError(index, 'recordIds', `recordIds 最多 ${MAX_DETAIL_RECORD_IDS} 项`);
3682
+ }
3683
+ if (raw.recordIds.some((id) => typeof id !== 'string' || id.length === 0 || id.length > 128)) {
3684
+ throw validationError(index, 'recordIds', 'recordIds 含非法节点 id');
3685
+ }
3686
+ }
3687
+ const provenanceInput = parseProvenanceInput(raw.provenance, index);
3688
+ let detailThreadId = hasValue(raw.threadId) ? raw.threadId : null;
3689
+ if (hasValue(raw.threadId) && (typeof raw.threadId !== 'string' || !THREAD_ID_RE.test(raw.threadId))) {
3690
+ throw new CapabilityError(400, 'invalid_thread_id', 'threadId 格式非法', { index });
3691
+ }
3692
+ if (detailThreadId === null && typeof provenanceInput.threadId === 'string') {
3693
+ detailThreadId = provenanceInput.threadId;
3694
+ }
3695
+ if (detailThreadId === null && requestThreadId !== null) {
3696
+ detailThreadId = requestThreadId;
3697
+ }
3698
+ if (typeof provenanceInput.threadId === 'string'
3699
+ && detailThreadId !== null
3700
+ && provenanceInput.threadId !== detailThreadId) {
3701
+ throw validationError(index, 'provenance.threadId', 'provenance.threadId 与详情 threadId 不一致');
3702
+ }
3703
+ if (domain.startsWith('task:')) {
3704
+ const expected = domain.slice('task:'.length);
3705
+ if (detailThreadId !== null && detailThreadId !== expected) {
3706
+ if (actor.type === 'agent') {
3707
+ throw domainWriteForbidden('Agent 只能写入自己参与且 threadId 匹配的任务域', {
3708
+ domain,
3709
+ actor: actor.agentId,
3710
+ threadId: detailThreadId,
3711
+ });
3712
+ }
3713
+ throw validationError(index, 'threadId', 'task 域详情 threadId 必须与域一致', {
3714
+ domain,
3715
+ expected,
3716
+ });
3717
+ }
3718
+ detailThreadId = expected;
3719
+ }
3720
+ if (detailThreadId !== null) provenanceInput.threadId = detailThreadId;
3721
+ assertDomainWrite(actor, domain, provenanceInput, requestThreadId);
3722
+ const identity = identitySnapshot();
3723
+ const provenance = buildWriteProvenance({
3724
+ input: provenanceInput,
3725
+ actor,
3726
+ identity,
3727
+ hostId,
3728
+ now: now(),
3729
+ threadId: detailThreadId,
3730
+ confirmation: provenanceInput.confirmation ?? 'none',
3731
+ });
3732
+ if (byteSize(provenance) > MAX_PROVENANCE_BYTES) {
3733
+ throw new CapabilityError(413, 'payload_too_large', `provenance 超过 ${MAX_PROVENANCE_BYTES} 字节`, { index });
3734
+ }
3735
+ const owner = deriveOwner(domain, { userId: identity.userId });
3736
+ if (hasValue(raw.ownerType) && raw.ownerType !== owner.ownerType) {
3737
+ throw ownerMismatchError(index, domain, owner, {
3738
+ ownerType: raw.ownerType,
3739
+ ownerId: raw.ownerId ?? null,
3740
+ });
3741
+ }
3742
+ if (hasValue(raw.ownerId) && raw.ownerId !== owner.ownerId) {
3743
+ throw ownerMismatchError(index, domain, owner, {
3744
+ ownerType: raw.ownerType ?? owner.ownerType,
3745
+ ownerId: raw.ownerId,
3746
+ });
3747
+ }
3748
+ return {
3749
+ domain,
3750
+ detailKind: raw.detailKind,
3751
+ text: raw.text,
3752
+ ...(hasValue(raw.mime) ? { mime: raw.mime } : {}),
3753
+ ...(hasValue(raw.role) ? { role: raw.role } : {}),
3754
+ ...(hasValue(raw.messageId) ? { messageId: raw.messageId } : {}),
3755
+ ...(hasValue(raw.chunkIndex) ? { chunkIndex: raw.chunkIndex } : {}),
3756
+ ...(hasValue(raw.turn) ? { turn: raw.turn } : {}),
3757
+ ...(detailThreadId !== null ? { threadId: detailThreadId } : {}),
3758
+ recordIds: [...raw.recordIds],
3759
+ contentHash,
3760
+ ...(hasValue(raw.redaction) ? { redaction: jsonClone(raw.redaction) } : {}),
3761
+ retentionClass,
3762
+ ...(hasValue(raw.expiresAt) ? { expiresAt: raw.expiresAt } : {}),
3763
+ ...(hasValue(raw.clientItemId) ? { clientItemId: raw.clientItemId } : {}),
3764
+ provenance,
3765
+ ...(Object.keys(safeMetadata).length > 0 ? { metadata: safeMetadata } : {}),
3766
+ ownerType: owner.ownerType,
3767
+ ownerId: owner.ownerId,
3768
+ };
3769
+ }
3770
+
3771
+ async function handleDetailWrite(payload, actor) {
3772
+ const items = payload.items;
3773
+ if (!Array.isArray(items) || items.length === 0) {
3774
+ throw new CapabilityError(400, 'invalid_request', 'items 必须是非空数组');
3775
+ }
3776
+ if (items.length > MAX_DETAIL_BATCH_ITEMS) {
3777
+ throw new CapabilityError(413, 'payload_too_large', `items 最多 ${MAX_DETAIL_BATCH_ITEMS} 条`, {
3778
+ maxBatchItems: MAX_DETAIL_BATCH_ITEMS,
3779
+ });
3780
+ }
3781
+ const requestThreadId = parseThreadId(payload.threadId);
3782
+ // 校验原子:所有 item 先通过域/owner/recordIds/retention 校验,再逐项落库。
3783
+ const validated = items.map((raw, index) => validateDetailItem(raw, index, requestThreadId, actor));
3784
+ const currentService = service();
3785
+ if (typeof currentService.writeDetails !== 'function') {
3786
+ throw new CapabilityError(503, 'capability_unavailable', '记忆服务不支持详情写入', undefined, true);
3787
+ }
3788
+ let result;
3789
+ try {
3790
+ result = await currentService.writeDetails(validated, {
3791
+ userId: identitySnapshot().userId,
3792
+ detailLimits: detailLimitsForConfig(),
3793
+ });
3794
+ } catch (error) {
3795
+ throw detailCoreError(error);
3796
+ }
3797
+ const first = result.results[0];
3798
+ if (items.length === 1 && result.failed === 1 && first?.code === 'detail_quota_exceeded') {
3799
+ throw new CapabilityError(413, 'detail_quota_exceeded', first.message ?? '详情配额超限', {
3800
+ ...(isObject(first.details) ? first.details : {}),
3801
+ result: first,
3802
+ });
3803
+ }
3804
+ const warnings = [];
3805
+ if (Array.isArray(result.evicted) && result.evicted.length > 0) {
3806
+ warnings.push({
3807
+ code: 'detail_quota_evicted',
3808
+ ids: [...result.evicted],
3809
+ message: '详情配额淘汰了最旧 tool_output/conversation;记录保留',
3810
+ });
3811
+ }
3812
+ return {
3813
+ data: {
3814
+ results: result.results,
3815
+ created: result.created,
3816
+ duplicates: result.duplicates,
3817
+ failed: result.failed,
3818
+ partial: result.partial,
3819
+ replayed: false,
3820
+ },
3821
+ warnings,
3822
+ degraded: false,
3823
+ };
3824
+ }
3825
+
3826
+ async function handleDetailGet(payload, actor) {
3827
+ if (typeof payload.id !== 'string' || payload.id.length === 0 || payload.id.length > 128) {
3828
+ throw new CapabilityError(400, 'invalid_request', 'get 需要合法 id');
3829
+ }
3830
+ const includeText = payload.includeText !== false;
3831
+ const includeExpired = payload.includeExpired === true;
3832
+ const includeDeleted = payload.includeDeleted === true;
3833
+ assertDetailGovernance(actor, includeExpired, includeDeleted);
3834
+ const maxBytes = hasValue(payload.maxBytes)
3835
+ ? Math.min(Math.max(1, Math.trunc(optionalNumber(payload.maxBytes, 'maxBytes', 0) ?? MAX_DETAIL_GET_BYTES)), MAX_DETAIL_GET_BYTES)
3836
+ : MAX_DETAIL_GET_BYTES;
3837
+ const currentService = service();
3838
+ let detail;
3839
+ try {
3840
+ detail = await currentService.getDetail(payload.id, {
3841
+ includeText,
3842
+ maxBytes,
3843
+ includeExpired,
3844
+ includeDeleted,
3845
+ userId: identitySnapshot().userId,
3846
+ });
3847
+ } catch (error) {
3848
+ throw detailCoreError(error);
3849
+ }
3850
+ if (!detail) throw new CapabilityError(404, 'not_found', '详情不存在', { id: payload.id });
3851
+ const threadId = parseThreadId(payload.threadId);
3852
+ const readable = await detailDomainReadable(payload, actor, detail.domain, threadId);
3853
+ if (!readable) {
3854
+ throw new CapabilityError(403, 'domain_read_forbidden', '当前 actor 不能读取该域详情', {
3855
+ domain: detail.domain,
3856
+ });
3857
+ }
3858
+ if (detail.deletedAt !== null && !includeDeleted) {
3859
+ throw new CapabilityError(410, 'detail_deleted', '详情已删除', {
3860
+ id: detail.id,
3861
+ reason: detail.deletedReason,
3862
+ availability: detail.availability,
3863
+ });
3864
+ }
3865
+ if (detail.deletedAt === null && detail.availability[0] === 'expired' && !includeExpired) {
3866
+ throw new CapabilityError(410, 'detail_expired', '详情已过期', {
3867
+ id: detail.id,
3868
+ expiresAt: detail.expiresAt,
3869
+ availability: detail.availability,
3870
+ });
3871
+ }
3872
+ return {
3873
+ data: { detail },
3874
+ warnings: [],
3875
+ degraded: false,
3876
+ };
3877
+ }
3878
+
3879
+ async function handleDetailList(payload, actor) {
3880
+ const includeExpired = payload.includeExpired === true;
3881
+ const includeDeleted = payload.includeDeleted === true;
3882
+ assertDetailGovernance(actor, includeExpired, includeDeleted);
3883
+ const threadId = parseThreadId(payload.threadId);
3884
+ const detailKinds = parseDetailKinds(payload.detailKinds);
3885
+ let recordIds;
3886
+ if (hasValue(payload.recordIds)) {
3887
+ if (!Array.isArray(payload.recordIds) || payload.recordIds.length === 0) {
3888
+ throw new CapabilityError(400, 'invalid_request', 'recordIds 必须是非空数组');
3889
+ }
3890
+ if (payload.recordIds.length > MAX_DETAIL_RECORD_IDS) {
3891
+ throw new CapabilityError(400, 'invalid_request', `recordIds 最多 ${MAX_DETAIL_RECORD_IDS} 项`);
3892
+ }
3893
+ recordIds = payload.recordIds.filter((id) => typeof id === 'string' && id.length > 0);
3894
+ if (recordIds.length !== payload.recordIds.length) {
3895
+ throw new CapabilityError(422, 'validation_failed', 'recordIds 含非法节点 id', { field: 'recordIds' });
3896
+ }
3897
+ }
3898
+ const currentService = service();
3899
+ const resolved = await resolveDomains({
3900
+ requested: payload.domains,
3901
+ endpoint: 'detail',
3902
+ actor,
3903
+ threadId,
3904
+ strictDomains: payload.strictDomains === true,
3905
+ app: app(),
3906
+ config: getConfig(),
3907
+ service: currentService,
3908
+ });
3909
+ const limit = hasValue(payload.limit)
3910
+ ? Math.min(Math.max(1, Math.trunc(optionalNumber(payload.limit, 'limit', 0) ?? 20)), MAX_DETAIL_LIST_LIMIT)
3911
+ : 20;
3912
+ const offset = clampOffset(payload.offset);
3913
+ if (resolved.domains.length === 0) {
3914
+ return {
3915
+ data: {
3916
+ details: [],
3917
+ total: 0,
3918
+ offset,
3919
+ limit,
3920
+ hasMore: false,
3921
+ },
3922
+ warnings: resolved.warnings,
3923
+ degraded: false,
3924
+ };
3925
+ }
3926
+ let result;
3927
+ try {
3928
+ result = await currentService.listDetails({
3929
+ domains: resolved.domains,
3930
+ ...(threadId !== null ? { threadId } : {}),
3931
+ ...(recordIds !== undefined ? { recordIds } : {}),
3932
+ ...(detailKinds !== undefined ? { detailKinds } : {}),
3933
+ limit,
3934
+ offset,
3935
+ includeExpired,
3936
+ includeDeleted,
3937
+ userId: identitySnapshot().userId,
3938
+ });
3939
+ } catch (error) {
3940
+ throw detailCoreError(error);
3941
+ }
3942
+ return { data: result, warnings: resolved.warnings, degraded: false };
3943
+ }
3944
+
3945
+ async function handleDetailDelete(payload, actor) {
3946
+ const ids = parseIdList(payload);
3947
+ const reason = payload.reason === undefined ? 'user_requested' : payload.reason;
3948
+ if (!isDetailDeleteReason(reason)) {
3949
+ throw new CapabilityError(422, 'validation_failed', 'reason 非法', { field: 'reason', reason });
3950
+ }
3951
+ const currentService = service();
3952
+ let result;
3953
+ try {
3954
+ result = await currentService.deleteDetails(ids, {
3955
+ reason,
3956
+ actorType: actor.type,
3957
+ ...(actor.type === 'agent' ? { agentId: actor.agentId } : {}),
3958
+ userId: identitySnapshot().userId,
3959
+ });
3960
+ } catch (error) {
3961
+ throw detailCoreError(error);
3962
+ }
3963
+ return {
3964
+ data: {
3965
+ deleted: result.deleted,
3966
+ notFound: result.notFound,
3967
+ forbidden: result.forbidden,
3968
+ partial: result.partial,
3969
+ replayed: false,
3970
+ },
3971
+ warnings: [],
3972
+ degraded: false,
3973
+ };
3974
+ }
3975
+
3976
+ async function detailDomainReadable(payload, actor, domain, threadId) {
3977
+ if (actor.type === 'user' || actor.type === 'system') return true;
3978
+ if (hasValue(payload.domains)) {
3979
+ const resolved = await resolveDomains({
3980
+ requested: payload.domains,
3981
+ endpoint: 'detail',
3982
+ actor,
3983
+ threadId,
3984
+ strictDomains: payload.strictDomains === true,
3985
+ app: app(),
3986
+ config: getConfig(),
3987
+ service: service(),
3988
+ });
3989
+ return resolved.domains.includes(domain);
3990
+ }
3991
+ // task 域是协作域:sidecar 已用 recall trace 证明 fragment 来源;
3992
+ // 这里按 id 读取不开放 list 枚举,但允许参与者域。
3993
+ if (domain.startsWith('task:')) return true;
3994
+ const defaults = defaultDomainsFor('detail', actor, threadId);
3995
+ return defaults.includes(domain);
3996
+ }
3997
+
3998
+ async function handleDetail(payload, actor) {
3999
+ const op = payload.op;
4000
+ if (!['write', 'get', 'list', 'delete'].includes(op)) {
4001
+ throw new CapabilityError(400, 'invalid_request', 'detail op 必须是 write/get/list/delete');
4002
+ }
4003
+ if (payload.sync !== undefined || payload['self.sync'] !== undefined || payload['checkpoint.sync'] !== undefined) {
4004
+ throw new CapabilityError(400, 'legacy_sync_unsupported', '不再支持 sync/self.sync/checkpoint.sync 字段');
4005
+ }
4006
+ if (op === 'write') return handleDetailWrite(payload, actor);
4007
+ if (op === 'get') return handleDetailGet(payload, actor);
4008
+ if (op === 'list') return handleDetailList(payload, actor);
4009
+ return handleDetailDelete(payload, actor);
4010
+ }
4011
+
4012
+ // ---------- /sync ----------
4013
+
4014
+ async function syncStatusData() {
4015
+ const currentService = service();
4016
+ const syncStatus = await syncStatusFor(currentService);
4017
+ const running = syncStatus.running === true;
4018
+ return {
4019
+ running,
4020
+ pendingEvents: typeof syncStatus.pendingEventCount === 'number' ? syncStatus.pendingEventCount : 0,
4021
+ peers: [],
4022
+ subscriptions: subscriptionView(getConfig()),
4023
+ lastSyncAt: typeof syncStatus.lastSyncAt === 'number' ? syncStatus.lastSyncAt : null,
4024
+ isSyncing: syncStatus.isSyncing === true,
4025
+ degraded: !running,
4026
+ warnings: running
4027
+ ? []
4028
+ : [{ code: 'sync_unavailable', message: '同步网络未启用;本地图仍可读写' }],
4029
+ };
4030
+ }
4031
+
4032
+ async function handleSyncPost(payload) {
4033
+ if (payload.action !== 'now') {
4034
+ throw new CapabilityError(400, 'invalid_request', 'action 必须是 now');
4035
+ }
4036
+ let waitMs = MAX_SYNC_WAIT_MS;
4037
+ if (payload.waitMs !== undefined && payload.waitMs !== null) {
4038
+ if (typeof payload.waitMs !== 'number' || !Number.isFinite(payload.waitMs) || payload.waitMs < 0) {
4039
+ throw new CapabilityError(400, 'invalid_request', 'waitMs 必须是非负数字');
4040
+ }
4041
+ waitMs = Math.min(payload.waitMs, MAX_SYNC_WAIT_MS);
4042
+ }
4043
+ const currentService = service();
4044
+ if (typeof currentService.sync !== 'function') {
4045
+ throw new CapabilityError(503, 'sync_unavailable', '当前 MemoryService 不提供同步触发', undefined, true);
4046
+ }
4047
+ const syncStatus = await syncStatusFor(currentService);
4048
+ if (syncStatus.running !== true) {
4049
+ throw new CapabilityError(503, 'sync_unavailable', '同步网络未启用', { reason: 'network_not_running' }, true);
4050
+ }
4051
+ if (payload.peerId !== undefined && (typeof payload.peerId !== 'string' || payload.peerId.length === 0)) {
4052
+ throw new CapabilityError(400, 'invalid_request', 'peerId 必须是非空字符串');
4053
+ }
4054
+ if (payload.address !== undefined && typeof payload.address !== 'string') {
4055
+ throw new CapabilityError(400, 'invalid_request', 'address 必须是字符串');
4056
+ }
4057
+ if (typeof payload.peerId !== 'string' || payload.peerId.length === 0) {
4058
+ throw new CapabilityError(503, 'sync_unavailable', '需要显式 peerId 才能触发单次同步', {
4059
+ reason: 'peer_required',
4060
+ }, true);
4061
+ }
4062
+ const address = typeof payload.address === 'string' && payload.address.length > 0
4063
+ ? payload.address
4064
+ : undefined;
4065
+ let result;
4066
+ try {
4067
+ result = await timeoutAfter(
4068
+ currentService.sync(payload.peerId, address),
4069
+ Math.max(1, waitMs),
4070
+ '同步等待超时',
4071
+ );
4072
+ } catch (error) {
4073
+ if (error instanceof CapabilityError) throw error;
4074
+ throw new CapabilityError(503, 'sync_unavailable', '同步不可用', { reason: 'sync_failed' }, true);
4075
+ }
4076
+ return {
4077
+ data: {
4078
+ synced: true,
4079
+ peerId: typeof result?.peerDeviceId === 'string' ? result.peerDeviceId : payload.peerId,
4080
+ applied: typeof result?.receivedEvents === 'number' ? result.receivedEvents : 0,
4081
+ pushed: typeof result?.sentEvents === 'number' ? result.sentEvents : 0,
4082
+ duplicates: typeof result?.duplicates === 'number' ? result.duplicates : 0,
4083
+ conflicts: Array.isArray(result?.conflicts) ? result.conflicts.length : 0,
4084
+ tookMs: typeof result?.durationMs === 'number' ? result.durationMs : 0,
4085
+ replayed: false,
4086
+ },
4087
+ warnings: [],
4088
+ degraded: false,
4089
+ };
4090
+ }
4091
+
4092
+ try {
4093
+ if (disposed) throw new CapabilityError(503, 'capability_unavailable', '能力接口已关闭', undefined, true);
4094
+
4095
+ // 1) 挂载开关:轻量模式不创建目录/token/进程,直接 404。
4096
+ if (!isMemoryRuntimeEnabled(getConfig())) {
4097
+ await revoke().catch(() => undefined);
4098
+ throw new CapabilityError(404, 'capability_disabled', '记忆运行时能力接口未启用');
4099
+ }
4100
+
4101
+ // 2) loopback + Host/Origin;无 CORS、无 cookie。
4102
+ if (!isLoopbackRemoteAddress(req?.socket?.remoteAddress)) {
4103
+ throw new CapabilityError(403, 'loopback_required', '仅允许本机回环调用');
4104
+ }
4105
+ const localPort = req?.socket?.localPort;
4106
+ if (!hostHeaderAllowed(req?.headers?.host, localPort)) {
4107
+ throw new CapabilityError(403, 'loopback_required', 'Host 头必须是本机回环地址');
4108
+ }
4109
+ if (!originAllowed(req?.headers?.origin, localPort)) {
4110
+ throw new CapabilityError(403, 'loopback_required', 'Origin 必须是本机回环地址');
4111
+ }
4112
+
4113
+ // 3) 可选版本协商(major 不匹配拒绝)。
4114
+ const requestedVersion = req?.headers?.['x-mebular-capability-version'];
4115
+ if (hasValue(requestedVersion) && String(requestedVersion).trim() !== String(CAPABILITY_API_VERSION)) {
4116
+ throw new CapabilityError(409, 'capability_version_unsupported', '不支持的 capability major 版本');
4117
+ }
4118
+
4119
+ // 4) Bearer capability token。
4120
+ if (tokenError) throw new CapabilityError(503, 'capability_unavailable', '能力令牌不可用', undefined, true);
4121
+ const record = await ensureToken().catch(() => {
4122
+ throw new CapabilityError(503, 'capability_unavailable', '能力令牌不可用', undefined, true);
4123
+ });
4124
+ const authorization = req?.headers?.authorization;
4125
+ const presented = typeof authorization === 'string' && authorization.startsWith('Bearer ')
4126
+ ? authorization.slice('Bearer '.length).trim()
4127
+ : '';
4128
+ if (presented === '' || !verifyCapabilityToken(presented, record, { now: now() })) {
4129
+ res.setHeader('www-authenticate', 'Bearer');
4130
+ throw new CapabilityError(401, 'capability_token_invalid', '缺少或无效的 capability token');
4131
+ }
4132
+
4133
+ // 5) body 上限(contract §9.1)。
4134
+ if (body && body.length > MAX_BODY_BYTES) {
4135
+ throw new CapabilityError(413, 'payload_too_large', `请求体超过 ${MAX_BODY_BYTES} 字节`);
4136
+ }
4137
+
4138
+ const relative = path.slice(CAPABILITY_API_PREFIX.length) || '/';
4139
+ const route = relative === '/' ? '' : relative.replace(/^\/+/, '');
4140
+ const isGet = req?.method === 'GET' || req?.method === 'HEAD';
4141
+ const isPost = req?.method === 'POST';
4142
+
4143
+ // 6) 写端点:/sync(GET/POST)与 write/update/delete/archive/internal-object。
4144
+ if (route === 'sync') {
4145
+ if (isGet) {
4146
+ const data = await syncStatusData();
4147
+ return sendOk(data, data.warnings, 200, data.degraded);
4148
+ }
4149
+ if (!isPost) throw new CapabilityError(405, 'method_not_allowed', 'sync 仅接受 GET/POST');
4150
+ const payload = requireObjectBody();
4151
+ const result = await withIdempotency('sync', payload, record.tokenId, () => handleSyncPost(payload));
4152
+ return sendOk(result.data, result.warnings, 200, result.degraded);
4153
+ }
4154
+
4155
+ if (route === 'detail') {
4156
+ if (!isPost) throw new CapabilityError(405, 'method_not_allowed', 'detail 仅接受 POST');
4157
+ const payload = requireObjectBody();
4158
+ const actor = parseActor(payload.actor);
4159
+ const op = payload.op;
4160
+ const execute = () => handleDetail(payload, actor);
4161
+ const result = (op === 'write' || op === 'delete')
4162
+ ? await withIdempotency(`detail:${op}`, payload, record.tokenId, execute)
4163
+ : await execute();
4164
+ return sendOk(result.data, result.warnings, 200, result.degraded);
4165
+ }
4166
+
4167
+ if (WRITE_ENDPOINTS.has(route)) {
4168
+ if (!isPost) throw new CapabilityError(405, 'method_not_allowed', `${route} 仅接受 POST`);
4169
+ const payload = requireObjectBody();
4170
+ const actor = parseActor(payload.actor);
4171
+ let execute;
4172
+ if (route === 'write') execute = () => handleWrite(payload, actor);
4173
+ else if (route === 'update') execute = () => handleUpdate(payload, actor);
4174
+ else if (route === 'delete') execute = () => handleDelete(payload, actor);
4175
+ else if (route === 'archive') execute = () => handleArchive(payload, actor);
4176
+ else if (route === 'internal-object') execute = () => handleInternalObject(payload, actor);
4177
+ else throw new CapabilityError(404, 'not_found', '未知能力端点', { path: relative });
4178
+ const result = await withIdempotency(route, payload, record.tokenId, execute);
4179
+ return sendOk(result.data, result.warnings, 200, result.degraded);
4180
+ }
4181
+
4182
+ if (route === 'version') {
4183
+ if (!isGet) throw new CapabilityError(405, 'method_not_allowed', 'version 仅接受 GET');
4184
+ return sendOk(versionPayload());
4185
+ }
4186
+
4187
+ if (route === 'status') {
4188
+ if (!isGet) throw new CapabilityError(405, 'method_not_allowed', 'status 仅接受 GET');
4189
+ const actor = parseActor(actorFromQuery(url));
4190
+ const includeCounts = url?.searchParams?.get('includeCounts') !== 'false';
4191
+ const currentService = getService?.() ?? null;
4192
+ const stats = await statsFor(currentService);
4193
+ const syncStatus = await syncStatusFor(currentService);
4194
+ const identity = identitySnapshot();
4195
+ const data = {
4196
+ initialized: Boolean(currentService)
4197
+ && (typeof app()?.isInitialized === 'function' ? app().isInitialized() : Boolean(app())),
4198
+ identity: {
4199
+ ...identity,
4200
+ deviceId: identity.deviceId ?? app()?.deviceId ?? null,
4201
+ userId: identity.userId ?? 'user',
4202
+ },
4203
+ counts: includeCounts ? stats.counts : null,
4204
+ detailQuota: detailLimitsForConfig(),
4205
+ detailRetentionDays: { ...DETAIL_RETENTION_DAYS, pinned: 0 },
4206
+ domains: includeCounts
4207
+ ? stats.domains.map((entry) => ({
4208
+ domain: entry.domain,
4209
+ ownerType: deriveOwner(entry.domain, { userId: identity.userId }).ownerType,
4210
+ count: entry.count,
4211
+ }))
4212
+ : [],
4213
+ sync: {
4214
+ running: syncStatus.running === true,
4215
+ pendingEvents: typeof syncStatus.pendingEventCount === 'number' ? syncStatus.pendingEventCount : 0,
4216
+ subscriptions: subscriptionView(getConfig()),
4217
+ lastSyncAt: typeof syncStatus.lastSyncAt === 'number' ? syncStatus.lastSyncAt : null,
4218
+ },
4219
+ limits: {
4220
+ maxBodyBytes: CAPABILITY_LIMITS.maxBodyBytes,
4221
+ maxBatchItems: CAPABILITY_LIMITS.maxBatchItems,
4222
+ maxLimit: CAPABILITY_LIMITS.maxLimit,
4223
+ maxDetailTextBytes: CAPABILITY_LIMITS.maxDetailTextBytes,
4224
+ maxDetailBatchItems: CAPABILITY_LIMITS.maxDetailBatchItems,
4225
+ maxDetailGetBytes: CAPABILITY_LIMITS.maxDetailGetBytes,
4226
+ maxDetailListLimit: CAPABILITY_LIMITS.maxDetailListLimit,
4227
+ },
4228
+ actor: { type: actor.type, ...(actor.agentId ? { agentId: actor.agentId } : {}) },
4229
+ };
4230
+ return sendOk(data);
4231
+ }
4232
+
4233
+ if (route === 'namespaces') {
4234
+ if (!isGet) throw new CapabilityError(405, 'method_not_allowed', 'namespaces 仅接受 GET');
4235
+ const actor = parseActor(actorFromQuery(url));
4236
+ const includeCounts = url?.searchParams?.get('includeCounts') !== 'false';
4237
+ const currentService = getService?.() ?? null;
4238
+ const stats = await statsFor(currentService);
4239
+ const identity = identitySnapshot();
4240
+ const subscriptions = subscriptionView(getConfig());
4241
+ const domains = stats.domains.map((entry) => {
4242
+ const owner = deriveOwner(entry.domain, { userId: identity.userId });
4243
+ return {
4244
+ domain: entry.domain,
4245
+ ownerType: owner.ownerType,
4246
+ ownerId: owner.ownerId,
4247
+ namespace: entry.domain,
4248
+ ...(includeCounts
4249
+ ? {
4250
+ count: entry.count,
4251
+ memoryRecords: entry.memoryRecords,
4252
+ internalObjects: entry.internalObjects,
4253
+ detailBytes: entry.detailBytes ?? 0,
4254
+ }
4255
+ : {}),
4256
+ subscribed: subscriptions.mode === 'all' || subscriptions.namespaces.includes(entry.domain),
4257
+ lastUpdatedAt: entry.lastUpdatedAt,
4258
+ };
4259
+ });
4260
+ const legacyNamespaces = domains
4261
+ .map((entry) => entry.domain)
4262
+ .filter((domain) => !RESERVED_DOMAINS.has(domain)
4263
+ && !domain.startsWith('agent:')
4264
+ && !domain.startsWith('task:'));
4265
+ return sendOk({
4266
+ subscriptions,
4267
+ domains,
4268
+ legacyNamespaces,
4269
+ policyDomain: '__policy__',
4270
+ actor: { type: actor.type, ...(actor.agentId ? { agentId: actor.agentId } : {}) },
4271
+ });
4272
+ }
4273
+
4274
+ if (route === 'query') {
4275
+ if (!isPost) throw new CapabilityError(405, 'method_not_allowed', 'query 仅接受 POST');
4276
+ const payload = requireObjectBody();
4277
+ const actor = parseActor(payload.actor);
4278
+ const threadId = parseThreadId(payload.threadId);
4279
+ if (hasValue(payload.query) && typeof payload.query !== 'string') {
4280
+ throw new CapabilityError(400, 'invalid_request', 'query 必须是字符串');
4281
+ }
4282
+ if (typeof payload.query === 'string' && Buffer.byteLength(payload.query, 'utf-8') > MAX_QUERY_BYTES) {
4283
+ throw new CapabilityError(413, 'payload_too_large', 'query 文本超过 8 KiB');
4284
+ }
4285
+ const currentService = service();
4286
+ const resolved = await resolveDomains({
4287
+ requested: payload.domains,
4288
+ endpoint: 'query',
4289
+ actor,
4290
+ threadId,
4291
+ strictDomains: payload.strictDomains === true,
4292
+ app: app(),
4293
+ config: getConfig(),
4294
+ service: currentService,
4295
+ });
4296
+ const limit = clampLimit(payload.limit);
4297
+ const offset = clampOffset(payload.offset);
4298
+ const types = parseTypes(payload.types ?? undefined);
4299
+ if (resolved.domains.length === 0) {
4300
+ return sendOk({
4301
+ records: [],
4302
+ total: 0,
4303
+ offset,
4304
+ limit,
4305
+ hasMore: false,
4306
+ tookMs: 0,
4307
+ usedDomains: [],
4308
+ }, resolved.warnings);
4309
+ }
4310
+ const filters = parseFilters(payload.filters);
4311
+ const result = await currentService.query({
4312
+ ...(typeof payload.query === 'string' && payload.query.length > 0 ? { query: payload.query } : {}),
4313
+ types,
4314
+ limit,
4315
+ offset,
4316
+ ...(payload.includeHistory !== undefined ? { includeHistory: payload.includeHistory === true } : {}),
4317
+ ...(payload.includeArchived !== undefined ? { includeArchived: payload.includeArchived === true } : {}),
4318
+ filters: { ...(filters ?? {}), namespace: resolved.domains },
4319
+ });
4320
+ const cache = new Map();
4321
+ const loaded = await Promise.all((result?.memories ?? []).map(async (memory) => ({
4322
+ memory,
4323
+ node: await loadNode(app(), memory.id, cache),
4324
+ })));
4325
+ // 选择/过滤/分页已全部由 MemoryService 完成;这里只做 owner/provenance 投影。
4326
+ const detailAvailability = await detailAvailabilityFor(
4327
+ currentService,
4328
+ loaded.map(({ memory, node }) => memory?.id ?? node?.id),
4329
+ );
4330
+ const records = loaded.map(({ memory, node }) => recordView(memory, node, {
4331
+ userId: identitySnapshot().userId,
4332
+ withScore: true,
4333
+ detailAvailability,
4334
+ }));
4335
+ const total = typeof result?.totalMatches === 'number' ? result.totalMatches : records.length;
4336
+ return sendOk({
4337
+ records,
4338
+ total,
4339
+ offset,
4340
+ limit,
4341
+ hasMore: offset + records.length < total,
4342
+ tookMs: typeof result?.queryTimeMs === 'number' ? result.queryTimeMs : 0,
4343
+ usedDomains: resolved.domains,
4344
+ }, resolved.warnings);
4345
+ }
4346
+
4347
+ if (route === 'search') {
4348
+ if (!isPost) throw new CapabilityError(405, 'method_not_allowed', 'search 仅接受 POST');
4349
+ const payload = requireObjectBody();
4350
+ const actor = parseActor(payload.actor);
4351
+ const threadId = parseThreadId(payload.threadId);
4352
+ if (typeof payload.query !== 'string' || payload.query.trim() === '') {
4353
+ throw new CapabilityError(400, 'invalid_request', 'search 需要非空 query');
4354
+ }
4355
+ if (Buffer.byteLength(payload.query, 'utf-8') > MAX_QUERY_BYTES) {
4356
+ throw new CapabilityError(413, 'payload_too_large', 'query 文本超过 8 KiB');
4357
+ }
4358
+ const currentService = service();
4359
+ const resolved = await resolveDomains({
4360
+ requested: payload.domains,
4361
+ endpoint: 'search',
4362
+ actor,
4363
+ threadId,
4364
+ strictDomains: payload.strictDomains === true,
4365
+ app: app(),
4366
+ config: getConfig(),
4367
+ service: currentService,
4368
+ });
4369
+ const limit = clampLimit(payload.limit);
4370
+ const types = parseTypes(payload.types ?? undefined);
4371
+ if (resolved.domains.length === 0) {
4372
+ return sendOk({ records: [], relations: [], total: 0, tookMs: 0 }, resolved.warnings);
4373
+ }
4374
+ const filters = parseFilters(payload.filters);
4375
+ const result = await currentService.search({
4376
+ query: payload.query,
4377
+ types,
4378
+ limit,
4379
+ ...(payload.includeHistory !== undefined ? { includeHistory: payload.includeHistory === true } : {}),
4380
+ ...(payload.includeRelations !== undefined ? { includeRelations: payload.includeRelations === true } : {}),
4381
+ ...(payload.includeArchived !== undefined ? { includeArchived: payload.includeArchived === true } : {}),
4382
+ filters: { ...(filters ?? {}), namespace: resolved.domains },
4383
+ });
4384
+ const cache = new Map();
4385
+ const loaded = await Promise.all((result?.memories ?? []).map(async (memory) => ({
4386
+ memory,
4387
+ node: await loadNode(app(), memory.id, cache),
4388
+ })));
4389
+ // 选择/过滤/域关系过滤/分页已全部由 MemoryService 完成。
4390
+ const detailAvailability = await detailAvailabilityFor(
4391
+ currentService,
4392
+ loaded.map(({ memory, node }) => memory?.id ?? node?.id),
4393
+ );
4394
+ const records = loaded.map(({ memory, node }) => recordView(memory, node, {
4395
+ userId: identitySnapshot().userId,
4396
+ withScore: true,
4397
+ detailAvailability,
4398
+ }));
4399
+ const relations = payload.includeRelations === true
4400
+ ? (Array.isArray(result?.relations) ? result.relations : []).map((relation) => ({
4401
+ sourceId: relation.sourceId,
4402
+ targetId: relation.targetId,
4403
+ edgeType: relation.edgeType,
4404
+ ...(typeof relation.reason === 'string' ? { reason: relation.reason } : {}),
4405
+ }))
4406
+ : [];
4407
+ return sendOk({
4408
+ records,
4409
+ relations,
4410
+ total: records.length,
4411
+ tookMs: typeof result?.queryTimeMs === 'number' ? result.queryTimeMs : 0,
4412
+ usedDomains: resolved.domains,
4413
+ }, resolved.warnings);
4414
+ }
4415
+
4416
+ if (route === 'history') {
4417
+ if (!isPost) throw new CapabilityError(405, 'method_not_allowed', 'history 仅接受 POST');
4418
+ const payload = requireObjectBody();
4419
+ const actor = parseActor(payload.actor);
4420
+ const threadId = parseThreadId(payload.threadId);
4421
+ const currentService = service();
4422
+ const resolved = await resolveDomains({
4423
+ requested: payload.domains,
4424
+ endpoint: 'history',
4425
+ actor,
4426
+ threadId,
4427
+ strictDomains: payload.strictDomains === true,
4428
+ app: app(),
4429
+ config: getConfig(),
4430
+ service: currentService,
4431
+ });
4432
+ const limit = clampLimit(payload.limit);
4433
+ const offset = clampOffset(payload.offset);
4434
+ if (resolved.domains.length === 0) {
4435
+ return sendOk({ episodes: [], total: 0, offset, limit, hasMore: false }, resolved.warnings);
4436
+ }
4437
+ const result = await currentService.history({
4438
+ ...(Array.isArray(payload.sessionIds) ? { sessionIds: payload.sessionIds.filter((id) => typeof id === 'string') } : {}),
4439
+ ...(typeof payload.startTime === 'number' ? { startTime: payload.startTime } : {}),
4440
+ ...(typeof payload.endTime === 'number' ? { endTime: payload.endTime } : {}),
4441
+ ...(typeof payload.topic === 'string' && payload.topic.length > 0 ? { topic: payload.topic } : {}),
4442
+ ...(payload.includeArchived !== undefined ? { includeArchived: payload.includeArchived === true } : {}),
4443
+ domains: resolved.domains,
4444
+ limit,
4445
+ offset,
4446
+ });
4447
+ // 域过滤、会话/时间/主题过滤、排序与分页均由 MemoryService.history 统一执行。
4448
+ const detailAvailability = await detailAvailabilityFor(
4449
+ currentService,
4450
+ (result?.episodes ?? []).map((node) => node?.id),
4451
+ );
4452
+ const episodes = (result?.episodes ?? [])
4453
+ .map((node) => nodeView(node, { userId: identitySnapshot().userId, detailAvailability }));
4454
+ const total = typeof result?.totalCount === 'number' ? result.totalCount : episodes.length;
4455
+ return sendOk({
4456
+ episodes,
4457
+ total,
4458
+ offset,
4459
+ limit,
4460
+ hasMore: offset + episodes.length < total,
4461
+ }, resolved.warnings);
4462
+ }
4463
+
4464
+ if (route === 'skills') {
4465
+ if (!isPost) throw new CapabilityError(405, 'method_not_allowed', 'skills 仅接受 POST');
4466
+ const payload = requireObjectBody();
4467
+ const actor = parseActor(payload.actor);
4468
+ const currentService = service();
4469
+ const resolved = await resolveDomains({
4470
+ requested: payload.domains,
4471
+ endpoint: 'skills',
4472
+ actor,
4473
+ threadId: null,
4474
+ strictDomains: payload.strictDomains === true,
4475
+ app: app(),
4476
+ config: getConfig(),
4477
+ service: currentService,
4478
+ });
4479
+ const limit = clampLimit(payload.limit, MAX_LIMIT);
4480
+ if (resolved.domains.length === 0) {
4481
+ return sendOk({ skills: [], total: 0 }, resolved.warnings);
4482
+ }
4483
+ const skillFilter = {
4484
+ ...(typeof payload.category === 'string' && payload.category.length > 0 ? { category: payload.category } : {}),
4485
+ ...(typeof payload.search === 'string' && payload.search.length > 0 ? { search: payload.search } : {}),
4486
+ ...(Array.isArray(payload.tags) ? { tags: payload.tags.filter((tag) => typeof tag === 'string') } : {}),
4487
+ ...(payload.includeArchived !== undefined ? { includeArchived: payload.includeArchived === true } : {}),
4488
+ domains: resolved.domains,
4489
+ limit,
4490
+ };
4491
+ let page;
4492
+ if (typeof currentService.skillPage === 'function') {
4493
+ page = await currentService.skillPage(skillFilter);
4494
+ } else {
4495
+ // 兼容旧运行时:仍由 MemoryService 选技能;适配器只做分页兜底。
4496
+ const all = await currentService.skills(skillFilter);
4497
+ page = { skills: all.slice(0, limit), total: all.length };
4498
+ }
4499
+ const cache = new Map();
4500
+ const loadedSkills = [];
4501
+ for (const skill of Array.isArray(page?.skills) ? page.skills : []) {
4502
+ const node = await loadNode(app(), skill?.id, cache);
4503
+ if (!node) continue;
4504
+ loadedSkills.push({ skill, node });
4505
+ }
4506
+ const detailAvailability = await detailAvailabilityFor(
4507
+ currentService,
4508
+ loadedSkills.map(({ node }) => node?.id),
4509
+ );
4510
+ const skills = [];
4511
+ for (const { skill, node } of loadedSkills) {
4512
+ const domain = domainOfNamespace(node?.namespace);
4513
+ const owner = deriveOwner(domain, { userId: identitySnapshot().userId });
4514
+ const metadata = isObject(node?.metadata) ? node.metadata : {};
4515
+ skills.push({
4516
+ ...skill,
4517
+ kind: 'skill',
4518
+ domain,
4519
+ namespace: domain,
4520
+ ownerType: owner.ownerType,
4521
+ ownerId: owner.ownerId,
4522
+ provenance: buildProvenance(metadata, domain, owner, node),
4523
+ legacy: !isObject(metadata.provenance),
4524
+ detailAvailable: detailAvailability !== null
4525
+ ? detailAvailability.get(node?.id) === true
4526
+ : metadata.detailAvailable !== false,
4527
+ });
4528
+ }
4529
+ return sendOk({
4530
+ skills,
4531
+ total: typeof page?.total === 'number' ? page.total : skills.length,
4532
+ usedDomains: resolved.domains,
4533
+ }, resolved.warnings);
4534
+ }
4535
+
4536
+ if (route === 'profile') {
4537
+ if (!isPost) throw new CapabilityError(405, 'method_not_allowed', 'profile 仅接受 POST');
4538
+ const payload = requireObjectBody();
4539
+ const actor = parseActor(payload.actor);
4540
+ const currentService = service();
4541
+ const known = await knownDomainsFor(app(), getConfig(), actor, null, currentService);
4542
+ let allowedDomains;
4543
+ let profileWarnings = [];
4544
+ if (hasValue(payload.domains) && !Array.isArray(payload.domains)) {
4545
+ throw new CapabilityError(400, 'invalid_request', 'domains 必须是字符串数组');
4546
+ }
4547
+ if (Array.isArray(payload.domains) && payload.domains.length > 0) {
4548
+ const resolved = await resolveDomains({
4549
+ requested: payload.domains,
4550
+ endpoint: 'profile',
4551
+ actor,
4552
+ threadId: null,
4553
+ strictDomains: payload.strictDomains === true,
4554
+ app: app(),
4555
+ config: getConfig(),
4556
+ service: currentService,
4557
+ });
4558
+ allowedDomains = new Set(resolved.domains.filter((domain) => !domain.startsWith('agent:')
4559
+ && !domain.startsWith('task:')
4560
+ && domain !== 'system'));
4561
+ profileWarnings = resolved.warnings;
4562
+ if (allowedDomains.size === 0) {
4563
+ return sendOk({
4564
+ userId: identitySnapshot().userId,
4565
+ preferences: [],
4566
+ properties: {},
4567
+ legacyCount: 0,
4568
+ updatedAt: now(),
4569
+ }, resolved.warnings);
4570
+ }
4571
+ } else {
4572
+ allowedDomains = new Set([...known]
4573
+ .filter((domain) => !domain.startsWith('agent:')
4574
+ && !domain.startsWith('task:')
4575
+ && domain !== 'system'));
4576
+ }
4577
+ // 域过滤由 MemoryService.profile({domains}) 执行;这里只做 owner/provenance/legacy 投影。
4578
+ const profile = await currentService.profile({
4579
+ ...(payload.includeArchived !== undefined ? { includeArchived: payload.includeArchived === true } : {}),
4580
+ domains: [...allowedDomains],
4581
+ });
4582
+ const cache = new Map();
4583
+ const preferences = [];
4584
+ let legacyCount = 0;
4585
+ for (const preference of Array.isArray(profile?.preferences) ? profile.preferences : []) {
4586
+ const node = await loadNode(app(), preference?.id, cache);
4587
+ if (!node) continue;
4588
+ const domain = domainOfNamespace(node?.namespace);
4589
+ const metadata = isObject(node?.metadata) ? node.metadata : {};
4590
+ const legacy = !isObject(metadata.provenance);
4591
+ if (legacy) legacyCount += 1;
4592
+ preferences.push({
4593
+ ...preference,
4594
+ domain,
4595
+ namespace: domain,
4596
+ legacy,
4597
+ ownerType: deriveOwner(domain, { userId: identitySnapshot().userId }).ownerType,
4598
+ ownerId: deriveOwner(domain, { userId: identitySnapshot().userId }).ownerId,
4599
+ provenance: buildProvenance(metadata, domain, deriveOwner(domain, { userId: identitySnapshot().userId }), node),
4600
+ });
4601
+ }
4602
+ return sendOk({
4603
+ userId: profile?.userId ?? identitySnapshot().userId,
4604
+ preferences,
4605
+ properties: profile?.properties ?? {},
4606
+ legacyCount,
4607
+ updatedAt: typeof profile?.updatedAt === 'number' ? profile.updatedAt : now(),
4608
+ }, profileWarnings);
4609
+ }
4610
+
4611
+ if (route === 'graph') {
4612
+ if (!isPost) throw new CapabilityError(405, 'method_not_allowed', 'graph 仅接受 POST');
4613
+ const payload = requireObjectBody();
4614
+ const actor = parseActor(payload.actor);
4615
+ const threadId = parseThreadId(payload.threadId);
4616
+ if (typeof payload.startId !== 'string' || payload.startId.length === 0) {
4617
+ throw new CapabilityError(400, 'invalid_request', 'graph 需要 startId');
4618
+ }
4619
+ const startCache = new Map();
4620
+ const startNode = await loadNode(app(), payload.startId, startCache);
4621
+ if (!startNode || startNode.deletedAt) throw new CapabilityError(404, 'not_found', '起点不存在');
4622
+ if (isInternalNode(startNode)) throw new CapabilityError(404, 'internal_object', '内部对象不可通过记忆图访问');
4623
+ if (isArchivedNode(startNode) && payload.includeArchived !== true) {
4624
+ throw new CapabilityError(404, 'not_found', '起点不存在');
4625
+ }
4626
+ const startDomain = domainOfNamespace(startNode.namespace);
4627
+ if (startDomain.startsWith('__')) {
4628
+ // `__policy__` / 其他 `__*` 不是记忆域;capability 永不读写。
4629
+ throw new CapabilityError(404, 'internal_object', '内部对象不可通过记忆图访问');
4630
+ }
4631
+
4632
+ const currentService = service();
4633
+ let resolved;
4634
+ if (Array.isArray(payload.domains) && payload.domains.length > 0) {
4635
+ resolved = await resolveDomains({
4636
+ requested: payload.domains,
4637
+ endpoint: 'graph',
4638
+ actor,
4639
+ threadId,
4640
+ strictDomains: payload.strictDomains === true,
4641
+ app: app(),
4642
+ config: getConfig(),
4643
+ service: currentService,
4644
+ });
4645
+ } else {
4646
+ if (hasValue(payload.domains) && !Array.isArray(payload.domains)) {
4647
+ throw new CapabilityError(400, 'invalid_request', 'domains 必须是字符串数组');
4648
+ }
4649
+ resolved = await resolveDomains({
4650
+ requested: undefined,
4651
+ endpoint: 'graph',
4652
+ actor,
4653
+ threadId,
4654
+ strictDomains: payload.strictDomains === true,
4655
+ app: app(),
4656
+ config: getConfig(),
4657
+ service: currentService,
4658
+ });
4659
+ if (!resolved.domains.includes(startDomain)) resolved.domains.push(startDomain);
4660
+ }
4661
+ if (!resolved.domains.includes(startDomain)) {
4662
+ if (payload.strictDomains === true) {
4663
+ throw new CapabilityError(403, 'domain_read_forbidden', '起点域不可读', { domain: startDomain });
4664
+ }
4665
+ throw new CapabilityError(404, 'not_found', '起点不存在');
4666
+ }
4667
+
4668
+ let result;
4669
+ try {
4670
+ result = await currentService.graph(payload.startId, {
4671
+ direction: payload.direction === 'incoming' || payload.direction === 'outgoing' ? payload.direction : 'both',
4672
+ maxDepth: clampDepth(payload.maxDepth),
4673
+ ...(Array.isArray(payload.edgeTypes)
4674
+ ? { edgeTypes: payload.edgeTypes.filter((type) => typeof type === 'string') }
4675
+ : {}),
4676
+ ...(payload.includeArchived !== undefined ? { includeArchived: payload.includeArchived === true } : {}),
4677
+ domains: resolved.domains,
4678
+ });
4679
+ } catch (error) {
4680
+ if (error?.code === 'INTERNAL_OBJECT') {
4681
+ throw new CapabilityError(404, 'internal_object', '内部对象不可通过记忆图访问');
4682
+ }
4683
+ throw error;
4684
+ }
4685
+
4686
+ // 深度/方向/边类型、域、内部与归档过滤均已由 MemoryService.graph 执行。
4687
+ const visibleNodes = result?.visitedNodes ?? [];
4688
+ const detailAvailability = await detailAvailabilityFor(
4689
+ currentService,
4690
+ [startNode?.id, ...visibleNodes.map((node) => node?.id)],
4691
+ );
4692
+ const nodes = visibleNodes
4693
+ .filter((node) => node.id !== payload.startId)
4694
+ .map((node) => nodeView(node, {
4695
+ userId: identitySnapshot().userId,
4696
+ detailAvailability,
4697
+ }));
4698
+ const edges = (result?.visitedEdges ?? [])
4699
+ .map((edge) => ({
4700
+ id: edge.id,
4701
+ source: edge.source,
4702
+ target: edge.target,
4703
+ relation: edge.relation,
4704
+ domain: domainOfNamespace(edge.namespace),
4705
+ }));
4706
+ return sendOk({
4707
+ start: nodeView(startNode, {
4708
+ userId: identitySnapshot().userId,
4709
+ detailAvailability,
4710
+ }),
4711
+ nodes,
4712
+ edges,
4713
+ truncated: false,
4714
+ }, resolved.warnings);
4715
+ }
4716
+
4717
+ throw new CapabilityError(404, 'not_found', '未知能力端点', { path: relative });
4718
+ } catch (error) {
4719
+ if (error instanceof CapabilityError) {
4720
+ return sendError(error.status, error.code, error.message, error.details, error.retryable);
4721
+ }
4722
+ // 不把内部错误细节(含路径/内容)回给调用方;不记录 token。
4723
+ return sendError(500, 'internal', '能力接口内部错误', undefined, true);
4724
+ }
4725
+ };
4726
+
4727
+ return Object.assign(handle, {
4728
+ prepare,
4729
+ revoke,
4730
+ dispose,
4731
+ isEnabled: () => isMemoryRuntimeEnabled(getConfig()),
4732
+ tokenId: () => tokenRecord?.tokenId ?? null,
4733
+ });
4734
+ }