openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
287 lines (286 loc) • 9.17 kB
JavaScript
import "./src-H3RMXyFL.mjs";
import { t as stableStringify } from "./stable-stringify-vqde_3tT.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { n as normalizeAgentId, t as isValidAgentId } from "./agent-id-CQjtp2ft.mjs";
import "./session-key-CqAyZeVk.mjs";
import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs";
import { f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs";
import { Am as validateMigrationsMemoryPlanParams, km as validateMigrationsMemoryApplyParams } from "./src-BX8OAe1J.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs";
import { p as errorShape } from "./error-codes-BzF7aRQ0.mjs";
import { n as defineValidatedGatewayHandler } from "./validation-DwNk6A-B.mjs";
import { v as summarizeMigrationItems } from "./migration-C73lp9ea.mjs";
import { i as withMemoryMigrationProviders, n as planProviderMemoryImport, t as applyProviderMemoryImport } from "./memory-import-DbJNP7hq.mjs";
//#region src/gateway/server-methods/migrations.ts
const MEMORY_APPLY_DEDUPE_PREFIX = "migrations.memory.apply:";
const activeApplies = /* @__PURE__ */ new Set();
const inFlightMemoryApplies = /* @__PURE__ */ new WeakMap();
function memoryApplyInflightMap(e) {
let t = inFlightMemoryApplies.get(e);
if (!t) {
t = /* @__PURE__ */ new Map();
inFlightMemoryApplies.set(e, t);
}
return t;
}
function isCachedMemoryApply(e) {
if (!e || typeof e !== "object") return false;
const t = e;
return typeof t.requestFingerprint === "string" && t.outcome !== void 0;
}
function respondMemoryApply(e, t, n = false) {
const r = n ? { cached: true } : void 0;
if (e.ok) t(true, JSON.parse(e.resultJson), void 0, r);
else t(false, void 0, e.error, r);
}
function toWireItem(e) {
return {
id: e.id,
status: e.status,
...e.source ? { source: e.source } : {},
...e.target ? { target: e.target } : {},
...e.message !== void 0 ? { message: e.message } : {},
...e.reason !== void 0 ? { reason: e.reason } : {},
...e.details !== void 0 ? { details: e.details } : {}
};
}
function fingerprintMemoryPlan(e) {
return sha256Hex(stableStringify({
version: 3,
agentId: e.agentId,
workspace: e.workspace,
providerId: e.providerId,
overwrite: e.overwrite === true,
plan: e.plan
}));
}
function targetAgentOrRespond(e, t, n) {
if (!isValidAgentId(e)) {
n(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "invalid agent id"));
return;
}
const r = normalizeAgentId(e);
if (!listAgentIds(t).includes(r)) {
n(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "unknown agent id"));
return;
}
return r;
}
async function planMemoryProvider(e) {
const t = {
providerId: e.provider.id,
label: e.provider.label,
...e.provider.description ? { description: e.provider.description } : {}
};
try {
const { detection: n, plan: r } = await planProviderMemoryImport(e);
if (n && !n.found) return {
...t,
found: false,
...n.source ? { source: n.source } : {},
...n.confidence ? { confidence: n.confidence } : {},
...n.message ? { message: n.message } : {},
summary: summarizeMigrationItems([]),
items: []
};
const i = r.items.length > 0;
const a = resolveAgentWorkspaceDir(e.config, e.agentId);
return {
...t,
found: i,
planFingerprint: fingerprintMemoryPlan({
agentId: e.agentId,
workspace: a,
providerId: e.provider.id,
overwrite: e.overwrite,
plan: r
}),
source: r.source,
...r.target ? { target: r.target } : {},
...n?.confidence ? { confidence: n.confidence } : {},
...n?.message ? { message: n.message } : {},
summary: r.summary,
items: r.items.map(toWireItem),
...r.warnings?.length ? { warnings: r.warnings } : {}
};
} catch (e) {
return {
...t,
found: false,
error: formatErrorMessage(e),
summary: summarizeMigrationItems([]),
items: []
};
}
}
const migrationsHandlers = {
"migrations.memory.plan": defineValidatedGatewayHandler("migrations.memory.plan", validateMigrationsMemoryPlanParams, async ({ params: e, respond: t, context: n }) => {
const r = n.getRuntimeConfig();
const i = targetAgentOrRespond(e.agentId, r, t);
if (!i) return;
const a = await withMemoryMigrationProviders(r, async (t) => {
const n = t.map(async (t) => await planMemoryProvider({
provider: t,
config: r,
agentId: i,
overwrite: e.overwrite
}));
let a;
try {
a = await Promise.all(n);
} catch (e) {
await Promise.allSettled(n);
throw e;
}
const o = {
agentId: i,
workspace: resolveAgentWorkspaceDir(r, i),
providers: a
};
return JSON.stringify(o);
});
t(true, JSON.parse(a), void 0);
}),
"migrations.memory.apply": defineValidatedGatewayHandler("migrations.memory.apply", validateMigrationsMemoryApplyParams, async ({ params: e, respond: t, context: n }) => {
const r = n.getRuntimeConfig();
const i = targetAgentOrRespond(e.agentId, r, t);
if (!i) return;
const a = stableStringify({
agentId: i,
providerId: e.providerId,
planFingerprint: e.planFingerprint,
itemIds: e.itemIds,
overwrite: e.overwrite === true
});
const o = `${MEMORY_APPLY_DEDUPE_PREFIX}${e.idempotencyKey}`;
const s = n.dedupe.get(o);
const c = s && isCachedMemoryApply(s.payload) ? s.payload : memoryApplyInflightMap(n.dedupe).get(o);
if (c) {
if (c.requestFingerprint !== a) {
t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "memory import idempotency key was reused"));
return;
}
respondMemoryApply("outcome" in c ? c.outcome : await c.completion, t, true);
return;
}
const l = memoryApplyInflightMap(n.dedupe);
const u = createDeferredCore();
l.set(o, {
requestFingerprint: a,
completion: u.promise
});
let d = false;
let f;
let p;
const runApply = async (t) => {
const n = t.find((t) => t.id === e.providerId);
if (!n) return {
ok: false,
error: errorShape(ErrorCodes.INVALID_REQUEST, "unknown memory migration provider")
};
const a = `${i}:${n.id}`;
if (activeApplies.has(a)) return {
ok: false,
error: errorShape(ErrorCodes.UNAVAILABLE, "memory import already running", {
retryable: true,
retryAfterMs: 1e3
})
};
activeApplies.add(a);
try {
const { plan: t } = await planProviderMemoryImport({
provider: n,
config: r,
agentId: i,
overwrite: e.overwrite
});
if (fingerprintMemoryPlan({
agentId: i,
workspace: resolveAgentWorkspaceDir(r, i),
providerId: n.id,
overwrite: e.overwrite,
plan: t
}) !== e.planFingerprint) return {
ok: false,
error: errorShape(ErrorCodes.INVALID_REQUEST, "memory migration plan changed; refresh the plan before importing")
};
const a = new Map(t.items.filter((e) => e.status === "planned" || e.status === "conflict").map((e) => [e.id, e]));
const o = e.itemIds.filter((e) => !a.has(e));
if (o.length > 0) return {
ok: false,
error: errorShape(ErrorCodes.INVALID_REQUEST, `memory migration items changed; refresh the plan (${o.join(", ")})`)
};
const s = e.itemIds.filter((e) => a.get(e)?.status === "conflict");
if (!e.overwrite && s.length > 0) return {
ok: false,
error: errorShape(ErrorCodes.INVALID_REQUEST, "selected memory was already imported; enable replacement and refresh the plan")
};
const c = await applyProviderMemoryImport({
provider: n,
config: r,
agentId: i,
itemIds: e.itemIds,
overwrite: e.overwrite,
preflightPlan: t,
onApplyCompleted: () => {
d = true;
}
});
const l = {
providerId: c.providerId,
source: c.source,
...c.target ? { target: c.target } : {},
summary: c.summary,
items: c.items.map(toWireItem),
...c.warnings?.length ? { warnings: c.warnings } : {},
...c.backupPath ? { backupPath: c.backupPath } : {},
...c.reportDir ? { reportDir: c.reportDir } : {}
};
return {
ok: true,
resultJson: JSON.stringify(l)
};
} finally {
activeApplies.delete(a);
}
};
try {
p = await withMemoryMigrationProviders(r, async (e) => {
try {
f = await runApply(e);
} catch (e) {
f = {
ok: false,
error: errorShape(ErrorCodes.UNAVAILABLE, d ? `Memory import apply completed, but its result could not be returned: ${formatErrorMessage(e)}. Inspect the migration report before starting another import.` : formatErrorMessage(e))
};
}
if (d) n.dedupe.set(o, {
ts: Date.now(),
ok: f.ok,
payload: {
requestFingerprint: a,
outcome: f
}
});
return f;
});
} catch (e) {
if (f) {
n.logGateway.warn(`Memory migration plugin cleanup failed: ${formatErrorMessage(e)}`);
p = f;
} else p = {
ok: false,
error: errorShape(ErrorCodes.UNAVAILABLE, formatErrorMessage(e))
};
} finally {
l.delete(o);
}
u.resolve(p);
respondMemoryApply(p, t);
})
};
//#endregion
export { migrationsHandlers };