openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
203 lines (202 loc) • 7.58 kB
JavaScript
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import "./session-key-CqAyZeVk.mjs";
import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs";
import { _ as resolveDefaultAgentId, t as AgentSelectionRequiredError } from "./agent-scope-config-DmXgFGKP.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { t as ADMIN_SCOPE } from "./operator-scopes-CULmYfyY.mjs";
import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs";
import { p as errorShape } from "./error-codes-BzF7aRQ0.mjs";
import { i as hasMultipleResidentSessionSharingIdentities } from "./user-profile-list-D7DDbqt5.mjs";
import { p as resolveOperatorRoleAgents } from "./operator-role-policy-DhcqVpmG.mjs";
import { r as isSyntheticGatewayCaller } from "./gateway-personal-caller-_qqOw6oy.mjs";
import { n as captureGatewayOperatorRunAuthority } from "./operator-run-authority-3Pm3MQDA.mjs";
import { a as getActiveMemoryProviderCore } from "./memory-runtime-C3z9zu-7.mjs";
//#region src/gateway/server-methods/memory-provider.ts
function requireNonEmptyStringIfPresent(e, t) {
if (e === void 0) return;
if (typeof e !== "string" || !e.trim()) throw new TypeError(`${t} must be a non-empty string`);
return e;
}
function requireNumberIfPresent(e, t, n = false) {
if (e === void 0) return;
if (typeof e !== "number" || !Number.isFinite(e) || n && (!Number.isInteger(e) || e < 1)) throw new TypeError(`${t} must be a ${n ? "positive integer" : "finite number"}`);
return e;
}
function requireSourcesIfPresent(e) {
if (e === void 0) return;
if (!Array.isArray(e) || e.length === 0) throw new TypeError("sources must be a non-empty array of memory or sessions");
return e.map((e) => {
if (e !== "memory" && e !== "sessions") throw new TypeError("sources must contain only memory or sessions");
return e;
});
}
function parseOperation(e, t) {
if (e === "memory.search") {
const e = requireNonEmptyStringIfPresent(t.query, "query")?.trim();
if (!e) throw new TypeError("query must be a non-empty string");
return {
kind: "search",
input: {
query: e,
maxResults: Math.min(50, requireNumberIfPresent(t.maxResults, "maxResults", true) ?? 20),
minScore: requireNumberIfPresent(t.minScore, "minScore"),
cursor: requireNonEmptyStringIfPresent(t.cursor, "cursor"),
sources: requireSourcesIfPresent(t.sources)
}
};
}
if (e === "memory.get") {
const e = t.reference;
if (!isRecord(e)) throw new TypeError("reference must be a provider-scoped memory reference");
const n = requireNonEmptyStringIfPresent(e.providerId, "reference.providerId");
const r = requireNonEmptyStringIfPresent(e.id, "reference.id");
if (!n || !r) throw new TypeError("reference.providerId and reference.id are required");
return {
kind: "get",
input: {
reference: {
providerId: n,
id: r,
revision: requireNonEmptyStringIfPresent(e.revision, "reference.revision"),
fragment: requireNonEmptyStringIfPresent(e.fragment, "reference.fragment")
},
from: requireNumberIfPresent(t.from, "from", true),
lines: requireNumberIfPresent(t.lines, "lines", true)
}
};
}
return { kind: "health" };
}
/**
* A connected operator reads with the scopes the dispatcher already authorized for
* this method, as `memory.search` v1 does. Synthetic, agent-tool, and agent-runtime
* callers act for an admitted run, so they keep that run's captured operator authority.
*/
async function captureMemoryReadAuthority(e, t) {
const { client: n, context: r, signal: i, hasCurrentClientAuthority: a } = e;
if (isSyntheticGatewayCaller(n) || n?.internal?.remoteIngressPrincipal) {
const e = await captureGatewayOperatorRunAuthority({
client: n,
context: r,
hasCurrentClientAuthority: a,
invocationAuthority: {
assertCurrent: t,
signal: i
}
});
if (!e) throw new Error("Memory provider reads require current operator authority");
return {
scopes: e.authority.scopes,
assertCurrent: () => {
t();
e.authority.assertCurrent();
},
release: e.release
};
}
if (n?.connect?.role !== "operator" || !n.connId) throw new Error("Memory provider reads require an authenticated operator connection");
return {
scopes: [...n.connect.scopes ?? []],
assertCurrent: t,
release: () => {}
};
}
/**
* Operator reads release an agent's private memory, which session turns reach
* only with the owner audience. A role's agent ceiling bounds every read; on a
* shared Gateway, content reads also need an administrator, matching the owner
* status that grants that audience to a turn.
*/
function assertOperatorMemoryAccess(e) {
const t = resolveOperatorRoleAgents(e.client, e.cfg);
if (t && !t.includes(e.agentId)) throw new Error(`Your operator role does not include agent "${e.agentId}".`);
if (e.operation.kind !== "health" && !e.scopes.includes("operator.admin") && hasMultipleResidentSessionSharingIdentities()) throw new Error("On a shared Gateway, reading an agent's private memory requires an administrator.");
}
/** Neutral reads deliberately do not use workspace RPCs or Memory Core artifacts. */
async function handleMemoryProviderRequest(e) {
const { params: t, req: n, respond: r, context: i, client: a, signal: o, hasCurrentClientAuthority: s } = e;
const c = i.getRuntimeConfig();
let l;
let u;
try {
u = parseOperation(n.method, t);
const e = requireNonEmptyStringIfPresent(t.agentId, "agentId");
if (e !== void 0) {
l = normalizeAgentId(e);
if (normalizeAgentId(`${e}a`) === "a" || !listAgentIds(c).includes(l)) throw new TypeError("unknown agentId");
} else l = resolveDefaultAgentId(c, {
surface: "memory provider",
hint: "Pass agentId to select a configured agent."
});
} catch (e) {
if (!(e instanceof TypeError || e instanceof AgentSelectionRequiredError)) throw e;
r(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, e.message));
return;
}
let d = true;
const assertRequestCurrent = () => {
o?.throwIfAborted();
a?.connectionSignal?.throwIfAborted();
if (!d || a?.invalidated || s?.() === false) throw new Error("Memory request authority is no longer active");
};
let f;
let p = null;
try {
assertRequestCurrent();
f = await captureMemoryReadAuthority(e, assertRequestCurrent);
const { scopes: t, assertCurrent: n } = f;
const assertCurrent = () => {
n();
assertOperatorMemoryAccess({
client: a,
cfg: i.getRuntimeConfig(),
agentId: l,
operation: u,
scopes: t
});
};
assertCurrent();
const s = await getActiveMemoryProviderCore({
cfg: c,
agentId: l,
purpose: "cli",
context: {
authority: {
kind: "operator",
scopes: f.scopes,
connId: a?.connId
},
assertCurrent,
signal: o
}
});
p = s.provider;
if (!p) throw new Error(s.error ?? "Memory provider unavailable");
const d = u.kind === "search" ? await p.search(u.input) : u.kind === "get" ? await p.get(u.input) : await p.health();
assertCurrent();
r(true, {
version: 2,
agentId: l,
providerId: s.providerId,
...d
}, void 0);
} catch (e) {
r(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, formatErrorMessage(e)));
} finally {
d = false;
try {
await p?.close();
} finally {
f?.release();
}
}
}
const memoryProviderHandlers = {
"memory.search": handleMemoryProviderRequest,
"memory.get": handleMemoryProviderRequest,
"memory.status": handleMemoryProviderRequest
};
//#endregion
export { memoryProviderHandlers };