154 lines
14 KiB
JavaScript
154 lines
14 KiB
JavaScript
import { createHash } from 'node:crypto';
|
|
|
|
export const MNEMO_PROTOCOL = 'mnemo.project-memory.v1';
|
|
class ProjectBridgeError extends Error {
|
|
constructor(code, message, status) { super(message); this.code = code; this.status = status; }
|
|
}
|
|
export const bridgeError = (code, message, status = 409) => new ProjectBridgeError(code, message, status);
|
|
export const digest = value => createHash('sha256').update(JSON.stringify(value), 'utf8').digest('hex');
|
|
const uuid = value => typeof value === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
|
|
const id = value => typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9:_.-]{0,99}$/.test(value);
|
|
const sha = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
|
|
const time = value => typeof value === 'string' && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z$/.test(value) && Number.isFinite(Date.parse(value));
|
|
const positive = value => Number.isSafeInteger(value) && value > 0;
|
|
const states = ['current', 'candidate', 'unverified', 'expired', 'archived', 'withdrawn', 'deleted'];
|
|
function assert(ok, message = '项目记忆响应的结构、来源或摘要不符。') { if (!ok) throw bridgeError('PROJECT_RESPONSE_INVALID', message); }
|
|
export function strict(value, keys, required = keys) {
|
|
assert(value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).every(key => keys.includes(key)) && required.every(key => Object.hasOwn(value, key)));
|
|
return value;
|
|
}
|
|
export function sourcePayload(source, memory) {
|
|
return { source: { id: source.id, sequence: source.sequence, version: source.version, state: source.state,
|
|
fingerprint: source.fingerprint ?? null, expiresAt: source.expiresAt ?? null,
|
|
confirmation: source.confirmation ? { by: source.confirmation.by, at: source.confirmation.at } : null },
|
|
memory: memory ? { title: memory.title, content: memory.content, kind: memory.kind } : null };
|
|
}
|
|
export const sourceDigest = (source, memory) => digest(sourcePayload(source, memory));
|
|
export const eventDigest = input => digest({ protocol: input.protocol, bindingId: input.bindingId, requestKey: input.requestKey, ...sourcePayload(input.source, input.memory) });
|
|
export const manifestDigest = manifest => digest({ projectId: manifest.projectId, projectFingerprint: manifest.projectFingerprint, complete: manifest.complete,
|
|
sources: [...manifest.sources].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0).map(s => ({ id: s.id, sequence: s.sequence, digest: s.digest })) });
|
|
export const contextDigest = entries => digest(entries.map(e => ({ origin: e.origin, bindingId: e.bindingId, projectId: e.projectId, memoryId: e.memoryId,
|
|
revision: e.revision, source: sourcePayload(e.source, null).source, sourceDigest: e.sourceDigest, title: e.title, content: e.content, kind: e.kind, visibility: e.visibility })));
|
|
export const entryRef = e => ({ sourceId: e.source.id, sequence: e.source.sequence, sourceDigest: e.sourceDigest, memoryId: e.memoryId, revision: e.revision });
|
|
export function checkSource(s) {
|
|
strict(s, ['id', 'sequence', 'version', 'state', 'fingerprint', 'expiresAt', 'confirmation']);
|
|
assert(id(s.id) && positive(s.sequence) && id(s.version) && states.includes(s.state) && (s.fingerprint === null || sha(s.fingerprint)) && (s.expiresAt === null || time(s.expiresAt)));
|
|
if (s.confirmation !== null) { strict(s.confirmation, ['by', 'at']); assert(s.confirmation.by === 'user' && time(s.confirmation.at)); }
|
|
assert(s.state === 'current' ? s.fingerprint && s.confirmation : s.confirmation === null);
|
|
}
|
|
export function checkMemory(m) {
|
|
strict(m, ['title', 'content', 'kind']);
|
|
assert(typeof m.title === 'string' && m.title.length >= 1 && m.title.length <= 100 && typeof m.content === 'string' && m.content.length >= 1 && m.content.length <= 12000
|
|
&& ['decision', 'preference', 'fact', 'experience'].includes(m.kind), '材料超出可选记忆桥格式;本地原文保持。');
|
|
}
|
|
export function checkSync(input) {
|
|
strict(input, ['protocol', 'bindingId', 'requestKey', 'source', 'memory']);
|
|
assert(input.protocol === MNEMO_PROTOCOL && uuid(input.bindingId) && uuid(input.requestKey)); checkSource(input.source);
|
|
assert(['current', 'candidate'].includes(input.source.state) === (input.memory !== null)); if (input.memory) checkMemory(input.memory);
|
|
assert(Buffer.byteLength(JSON.stringify(input)) <= 128 * 1024, '材料超过可选记忆桥128KB请求上限;本地原文保持。'); return input;
|
|
}
|
|
export function checkManifest(m, now = Date.now()) {
|
|
strict(m, ['projectId', 'projectFingerprint', 'checkedAt', 'complete', 'sources']);
|
|
assert(id(m.projectId) && sha(m.projectFingerprint) && time(m.checkedAt) && m.complete === true && Array.isArray(m.sources) && m.sources.length <= 500
|
|
&& now - Date.parse(m.checkedAt) <= 30000 && Date.parse(m.checkedAt) - now <= 5000, '本次来源清单不完整或已到期,不能使用远端记忆。');
|
|
for (const s of m.sources) { strict(s, ['id', 'sequence', 'digest']); assert(id(s.id) && positive(s.sequence) && sha(s.digest)); }
|
|
assert(new Set(m.sources.map(s => s.id)).size === m.sources.length); return m;
|
|
}
|
|
function checkSnapshot(s) {
|
|
strict(s, ['id', 'bindingId', 'grantId', 'manifestDigest', 'contextDigest', 'issuedAt', 'expiresAt', 'refs']);
|
|
assert(uuid(s.id) && uuid(s.bindingId) && uuid(s.grantId) && sha(s.manifestDigest) && sha(s.contextDigest) && time(s.issuedAt) && time(s.expiresAt) && Array.isArray(s.refs) && s.refs.length <= 50);
|
|
for (const r of s.refs) { strict(r, ['sourceId', 'sequence', 'sourceDigest', 'memoryId', 'revision']); assert(id(r.sourceId) && positive(r.sequence) && sha(r.sourceDigest) && uuid(r.memoryId) && positive(r.revision)); }
|
|
}
|
|
export function checkRecall(result, bindingId, manifest) {
|
|
strict(result, ['protocol', 'entries', 'snapshot']); const { entries, snapshot } = result; checkManifest(manifest); checkSnapshot(snapshot);
|
|
assert(result.protocol === MNEMO_PROTOCOL && Array.isArray(entries) && entries.length <= 50 && snapshot.bindingId === bindingId
|
|
&& snapshot.manifestDigest === manifestDigest(manifest) && Date.parse(snapshot.expiresAt) > Date.now()
|
|
&& Date.parse(snapshot.issuedAt) <= Date.now() + 5000 && Date.parse(snapshot.expiresAt) <= Date.parse(manifest.checkedAt) + 30000);
|
|
for (const e of entries) {
|
|
strict(e, ['origin', 'bindingId', 'projectId', 'memoryId', 'revision', 'source', 'sourceDigest', 'title', 'content', 'kind', 'visibility']);
|
|
checkSource(e.source); checkMemory({ title: e.title, content: e.content, kind: e.kind });
|
|
assert(e.origin === 'authorized_project_mirror' && e.bindingId === bindingId && e.projectId === manifest.projectId && uuid(e.memoryId) && positive(e.revision)
|
|
&& e.visibility === 'private' && e.source.state === 'current' && sourceDigest(e.source, e) === e.sourceDigest
|
|
&& manifest.sources.some(s => s.id === e.source.id && s.sequence === e.source.sequence && s.digest === e.sourceDigest)
|
|
&& (!e.source.expiresAt || Date.parse(snapshot.expiresAt) <= Date.parse(e.source.expiresAt)));
|
|
}
|
|
assert(new Set(entries.map(e => e.source.id)).size === entries.length && contextDigest(entries) === snapshot.contextDigest && digest(entries.map(entryRef)) === digest(snapshot.refs));
|
|
return result;
|
|
}
|
|
function checkReceipt(r, input, expected = null) {
|
|
strict(r, ['protocol', 'bindingId', 'requestKey', 'receiptId', 'sourceId', 'sequence', 'sourceDigest', 'eventDigest', 'state', 'memoryId', 'revision', 'committedAt', 'replayed', 'currentState', 'requiresFreshManifest']);
|
|
assert(r.protocol === MNEMO_PROTOCOL && r.bindingId === input.bindingId && r.requestKey === input.requestKey && uuid(r.receiptId) && r.sourceId === input.source.id
|
|
&& r.sequence === input.source.sequence && r.sourceDigest === (expected?.sourceDigest ?? sourceDigest(input.source, input.memory)) && r.eventDigest === (expected?.eventDigest ?? eventDigest(input)) && r.state === input.source.state
|
|
&& (r.memoryId === null || uuid(r.memoryId)) && (r.revision === null || positive(r.revision)) && time(r.committedAt) && typeof r.replayed === 'boolean'
|
|
&& [...states, 'locally_deleted'].includes(r.currentState) && r.requiresFreshManifest === true);
|
|
assert(r.state !== 'current' || r.memoryId && r.revision); return r;
|
|
}
|
|
export function bridgeOrigin(baseUrl) {
|
|
let u; try { u = new URL(baseUrl); } catch { throw bridgeError('PROJECT_ENDPOINT_INVALID', '请填写HTTPS或本机HTTP根地址。', 400); }
|
|
const local = ['127.0.0.1', 'localhost', '[::1]'].includes(u.hostname);
|
|
if (!(u.protocol === 'https:' || local && u.protocol === 'http:') || u.username || u.password || u.search || u.hash || u.pathname !== '/') throw bridgeError('PROJECT_ENDPOINT_INVALID', '请填写无凭据、路径和查询的HTTPS或本机HTTP根地址。', 400);
|
|
return u.origin;
|
|
}
|
|
|
|
/** Bridge-specific protocol bounds never change model input, history or budgets. */
|
|
export class MnemoClient {
|
|
constructor({ enabled = false, baseUrl, bindingId, token, producerId, projectId, timeoutMs = 10000, fetch: transport = globalThis.fetch, observe = () => {} }) {
|
|
this.origin = bridgeOrigin(baseUrl); assert(uuid(bindingId) && uuid(producerId) && id(projectId));
|
|
Object.assign(this, { enabled, bindingId, token, producerId, projectId, timeoutMs, transport, observe });
|
|
}
|
|
async request(route, body) {
|
|
if (!this.enabled || !this.token) throw bridgeError('PROJECT_BRIDGE_DISABLED', '桥默认关闭;需要显式启用并填写本次项目凭据。');
|
|
const request = body === undefined ? null : structuredClone(body), startedAt = new Date().toISOString();
|
|
let response, raw = '', result;
|
|
try {
|
|
response = await this.transport(this.origin + '/api/service/project-memory/v1/' + route, { method: body === undefined ? 'GET' : 'POST', redirect: 'error',
|
|
headers: { Authorization: 'Bearer ' + this.token, ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) },
|
|
...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(this.timeoutMs) });
|
|
if (response.status >= 300 && response.status < 400) throw new Error('Redirect refused');
|
|
const chunks = []; let bytes = 0;
|
|
for await (const chunk of response.body ?? []) { bytes += chunk.length; if (bytes > 2 * 1024 * 1024) throw new Error('Bridge response too large'); chunks.push(chunk); }
|
|
raw = Buffer.concat(chunks).toString('utf8');
|
|
try { result = JSON.parse(raw); } catch { throw bridgeError('PROJECT_RESPONSE_INVALID', '桥返回不完整JSON,未使用远端记忆。'); }
|
|
if (!response.ok) throw bridgeError(typeof result?.code === 'string' ? result.code : 'PROJECT_HTTP_ERROR', '项目记忆服务拒绝本次操作(HTTP ' + response.status + ')。', response.status);
|
|
return result;
|
|
} catch (cause) {
|
|
// Upstream codes use their own namespace. A received HTTP rejection is
|
|
// distinct from a transport failure, regardless of the code's spelling.
|
|
throw cause instanceof ProjectBridgeError ? cause : bridgeError('PROJECT_TRANSPORT_UNAVAILABLE', '项目记忆暂不可用;不使用旧远端缓存。', 0);
|
|
} finally {
|
|
this.observe({ route, startedAt, finishedAt: new Date().toISOString(), request, httpStatus: response?.status ?? null, responseText: raw.split(this.token).join('[PROJECT_TOKEN]'),
|
|
response: result === undefined ? null : JSON.parse(JSON.stringify(result).split(this.token).join('[PROJECT_TOKEN]')) });
|
|
}
|
|
}
|
|
async capabilities() {
|
|
const r = await this.request('capabilities?bindingId=' + encodeURIComponent(this.bindingId));
|
|
strict(r, ['protocol', 'bindingId', 'producerId', 'projectId', 'grantId', 'available', 'manifestLifetimeMs', 'executionAuthorized', 'privateOnly']);
|
|
assert(r.protocol === MNEMO_PROTOCOL && r.bindingId === this.bindingId && r.producerId === this.producerId && r.projectId === this.projectId && uuid(r.grantId)
|
|
&& r.available === true && r.manifestLifetimeMs === 30000 && r.executionAuthorized === false && r.privateOnly === true); return r;
|
|
}
|
|
async sync(input) {
|
|
checkSync(input);
|
|
try { return checkReceipt(await this.request('sync', input), input); }
|
|
catch (cause) {
|
|
if (cause.status >= 400 && cause.status < 500 && cause.code !== 'PROJECT_RESPONSE_INVALID') throw cause;
|
|
throw bridgeError('PROJECT_SYNC_UNKNOWN', '同步结果未知;保留原包原键,只查询原回执。');
|
|
}
|
|
}
|
|
async lookup(input, expected = null) {
|
|
const r = await this.request('lookup', { protocol: MNEMO_PROTOCOL, bindingId: this.bindingId, requestKey: input.requestKey });
|
|
strict(r, ['found', 'receipt']); assert(typeof r.found === 'boolean');
|
|
if (r.found) checkReceipt(r.receipt, input, expected); else assert(r.receipt === null); return r;
|
|
}
|
|
async recall(query, manifest, limit = 20) {
|
|
checkManifest(manifest); assert(typeof query === 'string' && query.trim().length > 0 && query.trim().length <= 4000 && Number.isInteger(limit) && limit >= 1 && limit <= 50);
|
|
return checkRecall(await this.request('recall', { protocol: MNEMO_PROTOCOL, bindingId: this.bindingId, query: query.trim(), manifest, limit }), this.bindingId, manifest);
|
|
}
|
|
async validate(snapshot, manifest) {
|
|
checkManifest(manifest); checkSnapshot(snapshot);
|
|
assert(snapshot.bindingId === this.bindingId && snapshot.manifestDigest === manifestDigest(manifest) && Date.parse(snapshot.expiresAt) > Date.now());
|
|
const r = await this.request('validate', { protocol: MNEMO_PROTOCOL, bindingId: this.bindingId, snapshot, manifest });
|
|
strict(r, ['protocol', 'valid', 'bindingId', 'snapshotId', 'contextDigest', 'executionAuthorized']);
|
|
assert(r.protocol === MNEMO_PROTOCOL && r.valid === true && r.bindingId === this.bindingId && r.snapshotId === snapshot.id && r.contextDigest === snapshot.contextDigest && r.executionAuthorized === false); return r;
|
|
}
|
|
}
|