openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
867 lines (866 loc) • 27.1 kB
JavaScript
import { i as normalizeBoundedOptionalString } from "../../string-coerce-CCIiB4H7.mjs";
import { s as asFiniteNumber } from "../../number-coercion-D6u-4YD8.mjs";
import { l as isRecord } from "../../record-coerce-CVPuDqcc.mjs";
import { r as truncateUtf16Safe } from "../../utf16-slice-CuDyEXgS.mjs";
import { t as pruneMapToMaxSize } from "../../map-size-BBr20tbc.mjs";
import { i as clampNumber } from "../../utils-C8YECn2Q.mjs";
import { o as racePromiseWithAbortSignal } from "../../src-BPmQBLJp.mjs";
import { o as getPluginRuntimeGatewayRequestScope } from "../../gateway-request-scope-BvvDhs5D.mjs";
import { w as resolveSessionAgentIdsStrict } from "../../agent-scope-config-DmXgFGKP.mjs";
import { g as ssrfPolicyFromHttpBaseUrlAllowedOrigin } from "../../ssrf-DHBNJw0c.mjs";
import { f as GuardedFetchRedirectError, r as fetchWithSsrFGuard } from "../../fetch-guard-BLMw2n18.mjs";
import { n as sendJsonNoStore } from "../../http-json-ddGJz5CA.mjs";
import "../../string-coerce-runtime-BwAZZDf5.mjs";
import "../../ssrf-runtime-B6q6NM4E.mjs";
import "../../text-utility-runtime-Ds8jsG0J.mjs";
import { s as createFixedWindowRateLimiter } from "../../webhook-ingress-pvI5xLbj.mjs";
import { a as createWebhookInFlightLimiter, i as beginWebhookRequestPipelineOrReject, s as readJsonWebhookBodyOrReject } from "../../webhook-request-guards-Br7AftEb.mjs";
import "../../time-runtime-DoAwjF0T.mjs";
import "../../agent-scope-runtime-CDpr-vor.mjs";
import { t as definePluginEntry } from "../../plugin-entry-CiJdaHtx.mjs";
import "../../plugin-runtime-z_iV2vts.mjs";
import { n as buildControlUiCatalogSharePath, r as isControlUiCatalogShareId, t as listActiveSessionCatalogs } from "../../session-catalog-runtime-DOaATvJ1.mjs";
import { createHash } from "node:crypto";
//#region extensions/beam/src/types.ts
const BEAM_HOST_ID = "gateway";
const BEAM_SESSION_SHARE_ROUTE = {
kind: "thread-id-prefix",
routeSegment: "beam",
hostId: BEAM_HOST_ID,
identifierAlphabet: "lowercase-hex",
fullLength: 32,
minPrefixLength: 12,
lookup: "catalog-list-search-by-thread-id-prefix",
ambiguity: "multiple-results-or-next-cursor"
};
const BEAM_MAX_BODY_BYTES = 57344;
const BEAM_RETENTION_MS = 6048e5;
const BEAM_MAX_ITEMS = 200;
const BEAM_MAX_ITEM_CHARS = 6e3;
const TOP_LEVEL_KEYS = /* @__PURE__ */ new Set([
"version",
"beamId",
"source",
"title",
"updatedAt",
"completed",
"truncated",
"hookEvent",
"sourceModel",
"items"
]);
const ITEM_KEYS = /* @__PURE__ */ new Set(["type", "text"]);
const SOURCE_MODEL_KEYS = /* @__PURE__ */ new Set(["provider", "model"]);
function hasOnlyKeys(e, t) {
return Object.keys(e).every((e) => t.has(e));
}
function isIsoTimestamp(e) {
const t = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:Z|([+-])(\d{2}):(\d{2}))$/.exec(e);
if (!t || !Number.isFinite(Date.parse(e))) return false;
return (/* @__PURE__ */ new Date(`${t[1]}-${t[2]}-${t[3]}T00:00:00Z`)).getUTCDate() === Number(t[3]) && Number(t[4]) < 24 && Number(t[5]) < 60 && Number(t[6]) < 60 && Number(t[8] ?? 0) < 24 && Number(t[9] ?? 0) < 60;
}
function parseBeamUpload(e) {
if (!isRecord(e) || !hasOnlyKeys(e, TOP_LEVEL_KEYS)) return {
ok: false,
error: "request body must be a closed Beam object"
};
if (e.version !== 1) return {
ok: false,
error: "version must be 1"
};
const t = normalizeBoundedOptionalString(e.beamId, 64);
if (!t || !/^[a-f0-9]{32}$/i.test(t)) return {
ok: false,
error: "beamId must be a 32-character hex id"
};
const n = normalizeBoundedOptionalString(e.source, 32);
if (!n || !/^[a-z0-9._-]+$/i.test(n)) return {
ok: false,
error: "source must be a short identifier"
};
const r = normalizeBoundedOptionalString(e.title, 160);
if (!r) return {
ok: false,
error: "title must be a non-empty string"
};
const i = normalizeBoundedOptionalString(e.updatedAt, 64);
if (!i || !isIsoTimestamp(i)) return {
ok: false,
error: "updatedAt must be an ISO timestamp"
};
if (typeof e.completed !== "boolean") return {
ok: false,
error: "completed must be a boolean"
};
if (e.truncated !== void 0 && typeof e.truncated !== "boolean") return {
ok: false,
error: "truncated must be a boolean"
};
const a = e.hookEvent === void 0 ? void 0 : normalizeBoundedOptionalString(e.hookEvent, 64);
if (e.hookEvent !== void 0 && !a) return {
ok: false,
error: "hookEvent must be a short string"
};
let o;
if (e.sourceModel !== void 0) {
if (!isRecord(e.sourceModel) || !hasOnlyKeys(e.sourceModel, SOURCE_MODEL_KEYS)) return {
ok: false,
error: "sourceModel must be a closed object"
};
const t = normalizeBoundedOptionalString(e.sourceModel.provider, 64);
const n = normalizeBoundedOptionalString(e.sourceModel.model, 256);
if (!t || !/^[a-z0-9._-]+$/i.test(t) || !n || !/^\S+$/u.test(n)) return {
ok: false,
error: "sourceModel must contain a provider and model"
};
o = {
provider: t.toLowerCase(),
model: n
};
}
if (!Array.isArray(e.items) || e.items.length === 0 || e.items.length > 200) return {
ok: false,
error: `items must contain 1-${200} entries`
};
const s = [];
for (const t of e.items) {
if (!isRecord(t) || !hasOnlyKeys(t, ITEM_KEYS)) return {
ok: false,
error: "each transcript item must be a closed object"
};
if (t.type !== "userMessage" && t.type !== "agentMessage" && t.type !== "other") return {
ok: false,
error: "transcript item type is invalid"
};
const e = normalizeBoundedOptionalString(t.text, BEAM_MAX_ITEM_CHARS);
if (!e) return {
ok: false,
error: `transcript item text must be 1-${BEAM_MAX_ITEM_CHARS} characters`
};
s.push({
type: t.type,
text: e
});
}
return {
ok: true,
value: {
version: 1,
beamId: t.toLowerCase(),
source: n.toLowerCase(),
title: r,
updatedAt: i,
completed: e.completed,
...e.truncated === true ? { truncated: true } : {},
...a ? { hookEvent: a } : {},
...o ? { sourceModel: o } : {},
items: s
}
};
}
//#endregion
//#region extensions/beam/src/http.ts
function currentRequestClient(e) {
const t = getPluginRuntimeGatewayRequestScope()?.client;
return {
clientIp: t?.clientIp ?? e.socket.remoteAddress ?? "unknown",
scopes: t?.connect?.scopes ?? [],
profileId: t?.authenticatedUserProfile?.profileId
};
}
function canPublish(e) {
return e.includes("operator.write") || e.includes("operator.admin");
}
function createBeamRequestHandler(e) {
const t = createFixedWindowRateLimiter({
windowMs: 6e4,
maxRequests: 60,
maxTrackedKeys: 2048
});
const n = createWebhookInFlightLimiter({
maxInFlightPerKey: 2,
maxTrackedKeys: 2048
});
return async (r, i) => {
const a = e.resolveClient?.(r) ?? currentRequestClient(r);
if (!canPublish(a.scopes)) {
sendJsonNoStore(i, 403, {
ok: false,
error: "operator.write is required"
});
return true;
}
const o = beginWebhookRequestPipelineOrReject({
req: r,
res: i,
allowMethods: ["POST"],
requireJsonContentType: true,
rateLimiter: t,
rateLimitKey: a.clientIp,
inFlightLimiter: n,
inFlightKey: a.clientIp
});
if (!o.ok) return true;
try {
const t = await readJsonWebhookBodyOrReject({
req: r,
res: i,
maxBytes: BEAM_MAX_BODY_BYTES,
timeoutMs: 1e4,
emptyObjectOnEmpty: false,
invalidJsonMessage: "invalid Beam request body"
});
if (!t.ok) return true;
const n = parseBeamUpload(t.value);
if (!n.ok) {
sendJsonNoStore(i, 400, {
ok: false,
error: n.error
});
return true;
}
const o = getPluginRuntimeGatewayRequestScope()?.revalidate;
await o?.();
const s = e.now?.() ?? Date.now();
await e.store.upload(n.value, {
receivedAt: s,
uploaderProfileId: a.profileId,
revalidatePublisher: o
});
sendJsonNoStore(i, 200, {
ok: true,
beamId: n.value.beamId,
url: buildControlUiCatalogSharePath({
shareRoute: BEAM_SESSION_SHARE_ROUTE,
threadId: n.value.beamId,
displayName: n.value.title,
basePath: e.resolveControlUiBasePath()
})
});
return true;
} finally {
o.release();
}
};
}
//#endregion
//#region extensions/beam/src/mirror.ts
const MIRROR_CONFIG_PATH = "plugins.entries.beam.config.mirror";
const MIRROR_TOKEN_PATH = `${MIRROR_CONFIG_PATH}.token`;
const DEFAULT_POLL_SECONDS = 30;
const DEFAULT_ACTIVE_WINDOW_MINUTES = 180;
const MIRROR_LIST_LIMIT = 100;
const MIRROR_READ_LIMIT = 50;
const MIRROR_MAX_SESSIONS = 32;
const MIRROR_RETRY_CAP = 2 * 500;
const MIRROR_BODY_BUDGET_BYTES = BEAM_MAX_BODY_BYTES - 2048;
const MIRROR_WARN_INTERVAL_MS = 3e5;
const MIRROR_UPLOAD_TIMEOUT_MS = 15e3;
function isLoopbackHostname(e) {
const t = e.replace(/^\[|\]$/g, "");
return t === "localhost" || t === "127.0.0.1" || t === "::1";
}
const MIRROR_KEYS = /* @__PURE__ */ new Set([
"endpoint",
"token",
"catalogs",
"pollSeconds",
"activeWindowMinutes"
]);
/** Returns the mirror config, undefined when mirroring is not configured, or an error string. */
function parseBeamMirrorConfig(e) {
const t = e.plugins?.entries?.beam?.config?.mirror;
if (t === void 0) return;
if (!isRecord(t) || !Object.keys(t).every((e) => MIRROR_KEYS.has(e))) return `${MIRROR_CONFIG_PATH} must be a closed object with endpoint/token/catalogs/pollSeconds/activeWindowMinutes`;
const n = typeof t.endpoint === "string" ? t.endpoint.trim() : "";
const r = URL.parse(n);
if (!r) return `${MIRROR_CONFIG_PATH}.endpoint must be an absolute URL`;
if (r.protocol === "http:") {
if (!isLoopbackHostname(r.hostname)) return `${MIRROR_CONFIG_PATH}.endpoint must use https for non-loopback hosts`;
} else if (r.protocol !== "https:") return `${MIRROR_CONFIG_PATH}.endpoint must use http(s)`;
if (!Array.isArray(t.catalogs) || t.catalogs.length === 0 || !t.catalogs.every((e) => typeof e === "string" && e.trim().length > 0)) return `${MIRROR_CONFIG_PATH}.catalogs must explicitly list the catalog ids to mirror`;
return {
endpoint: n,
token: t.token === void 0 ? void 0 : typeof t.token === "string" && t.token.trim() ? t.token.trim() : null,
catalogs: t.catalogs.map((e) => e.trim().toLowerCase()),
pollSeconds: clampNumber(asFiniteNumber(t.pollSeconds) ?? DEFAULT_POLL_SECONDS, 10, 3600),
activeWindowMinutes: clampNumber(asFiniteNumber(t.activeWindowMinutes) ?? DEFAULT_ACTIVE_WINDOW_MINUTES, 1, 10080)
};
}
function beamMirrorId(e, t, n) {
return createHash("sha256").update(`${e}\0${t}\0${n}`).digest("hex").slice(0, 32);
}
/**
* Reduce newest-first catalog items to chronological Beam uploads. Only user/agent
* message text crosses the wire; reasoning, tool calls, tool results, and raw
* payloads collapse into compact counts.
*/
function buildBeamMirrorItems(e) {
const t = [];
const n = /* @__PURE__ */ new Map();
let r = e.some((e) => e.truncated);
const flush = () => {
if (n.size > 0) {
const e = [...n].map(([e, t]) => `${t} ${e}`).join(", ");
t.push({
type: "other",
text: `${e}; raw content dropped`
});
n.clear();
}
};
const i = {
toolCall: "tool calls",
toolResult: "tool results",
reasoning: "reasoning items"
};
for (const a of e.toReversed()) {
const e = a.text?.trim();
if ((a.type === "userMessage" || a.type === "agentMessage") && e) {
flush();
const n = truncateUtf16Safe(e, BEAM_MAX_ITEM_CHARS);
r ||= n.length < e.length;
t.push({
type: a.type,
text: n
});
continue;
}
const o = i[a.type] ?? "other entries";
n.set(o, (n.get(o) ?? 0) + 1);
}
flush();
return {
items: t,
truncated: r
};
}
/** Drop oldest items until the payload fits the receiver's item and byte caps. */
function fitBeamMirrorUpload(e) {
const t = e.items.slice(-200);
const n = {
...e,
items: t
};
let r = Buffer.byteLength(JSON.stringify(n), "utf8");
if (t.length < e.items.length || r > MIRROR_BODY_BUDGET_BYTES) {
n.truncated = true;
r = Buffer.byteLength(JSON.stringify(n), "utf8");
}
let i = 0;
while (i + 1 < t.length && r > MIRROR_BODY_BUDGET_BYTES) r -= Buffer.byteLength(JSON.stringify(t[i++]), "utf8") + 1;
return {
...n,
items: t.slice(i)
};
}
function sourceModelForMirror(e, t) {
const n = e?.trim().toLowerCase();
const r = t.find((e) => e.type === "agentMessage" && e.model?.trim())?.model;
if (!n || !/^[a-z0-9._-]+$/i.test(n) || !r) return;
const i = r.trim();
const a = truncateUtf16Safe(i.startsWith(`${n}/`) ? i.slice(n.length + 1) : i, 256).trim();
return a && /^\S+$/u.test(a) ? {
provider: n,
model: a
} : void 0;
}
function mirrorCandidateKey(e) {
return `${e.catalogId}\0${e.hostId}\0${e.threadId}`;
}
function createBeamMirrorRunner(e) {
const t = e.now ?? Date.now;
const n = /* @__PURE__ */ new Map();
const { signal: r } = e;
let i = 0;
let a = false;
let o = "";
let s = false;
const c = /* @__PURE__ */ new Error("Beam mirror stopped");
const raceCatalog = (e) => racePromiseWithAbortSignal(e, r, () => c);
const trackSuccessfulUpload = (e, r, i) => {
n.delete(e);
n.set(e, {
candidate: r,
fingerprint: i,
expiresAt: t() + BEAM_RETENTION_MS
});
pruneMapToMaxSize(n, MIRROR_RETRY_CAP);
};
const warnThrottled = (n) => {
if (t() - i >= MIRROR_WARN_INTERVAL_MS) {
i = t();
e.logger.warn(n);
}
};
const upload = async (t) => {
if (r.aborted || s) return false;
const n = parseBeamMirrorConfig(e.runtime.config.current());
if (!n || typeof n === "string" || n.token === null || n.endpoint !== o) return false;
const i = n.token;
let a;
try {
a = await fetchWithSsrFGuard({
url: o,
timeoutMs: MIRROR_UPLOAD_TIMEOUT_MS,
signal: r,
policy: ssrfPolicyFromHttpBaseUrlAllowedOrigin(o),
auditContext: "beam.mirror_upload",
maxRedirects: 0,
init: {
method: "POST",
headers: {
"Content-Type": "application/json",
...i ? { Authorization: `Bearer ${i}` } : {}
},
body: JSON.stringify(t)
}
});
} catch (n) {
r.throwIfAborted();
if (n instanceof GuardedFetchRedirectError) {
s = true;
e.logger.warn(`beam mirror upload blocked for ${t.source}: receiver returned redirect (${n.status}); redirects are not followed; configure the final endpoint`);
return false;
}
throw n;
}
const { response: c, release: l } = a;
try {
r.throwIfAborted();
if (!c.ok) warnThrottled(`beam mirror upload failed (${c.status}) for ${t.source}`);
return c.ok;
} finally {
await c.body?.cancel().catch(() => void 0);
await l();
}
};
const buildUpload = async (e, n, i, a) => {
const o = await raceCatalog(n.read({
agentId: e,
hostId: i.hostId,
threadId: i.threadId,
limit: MIRROR_READ_LIMIT
}));
r.throwIfAborted();
const s = buildBeamMirrorItems(o.items);
const c = sourceModelForMirror(i.modelProvider, o.items);
const l = s.items.length ? s.items : [{
type: "other",
text: "no shareable messages yet"
}];
return fitBeamMirrorUpload({
version: 1,
beamId: beamMirrorId(i.catalogId, i.hostId, i.threadId),
source: i.catalogId,
title: truncateUtf16Safe(i.title, 160),
updatedAt: new Date(i.recencyAt || t()).toISOString(),
completed: a,
...c ? { sourceModel: c } : {},
...s.truncated || o.nextCursor ? { truncated: true } : {},
items: l
});
};
const mirrorFingerprint = ({ updatedAt: e, ...t }) => createHash("sha256").update(JSON.stringify(t)).digest("hex");
const scan = async () => {
try {
r.throwIfAborted();
const i = e.runtime.config.current();
const c = parseBeamMirrorConfig(i);
if (c === void 0) return;
if (typeof c === "string") {
warnThrottled(`beam mirror disabled: ${c}`);
return;
}
if (o !== c.endpoint) {
o = c.endpoint;
n.clear();
s = false;
}
let l;
try {
l = resolveSessionAgentIdsStrict({ config: i }).defaultAgentId;
} catch (e) {
warnThrottled(`beam mirror disabled: ${String(e)}`);
return;
}
if (c.token === null) {
warnThrottled(`beam mirror paused: ${MIRROR_TOKEN_PATH} credential unavailable; restore it and run openclaw secrets reload`);
return;
}
const u = t() - c.activeWindowMinutes * 6e4;
const d = listActiveSessionCatalogs().filter((e) => e.id !== "beam" && c.catalogs.includes(e.id));
if (!a && d.some((e) => !e.processHomeFallbackAllowed)) {
a = true;
e.logger.warn("beam mirror process-HOME fallback disabled: isolated state; only explicit catalog roots can be mirrored");
}
const f = new Map(d.map((e) => [e.id, e]));
const p = /* @__PURE__ */ new Map();
const m = /* @__PURE__ */ new Set();
for (const e of d) {
r.throwIfAborted();
try {
const t = await raceCatalog(e.list({
agentId: l,
limitPerHost: MIRROR_LIST_LIMIT
}));
r.throwIfAborted();
for (const n of t) {
if (n.kind !== "gateway" || !n.connected || n.error) continue;
if (n.nextCursor === void 0) m.add(`${e.id}\0${n.hostId}`);
for (const t of n.sessions) {
const r = {
catalogId: e.id,
hostId: n.hostId,
modelProvider: t.modelProvider,
threadId: t.threadId,
title: t.name?.trim() || `${e.id} session`,
recencyAt: t.recencyAt ?? t.updatedAt ?? 0
};
p.set(mirrorCandidateKey(r), r);
}
}
} catch (t) {
r.throwIfAborted();
warnThrottled(`beam mirror list failed for ${e.id}: ${String(t)}`);
}
}
const h = [...p.values()].filter((e) => e.recencyAt >= u).toSorted((e, t) => t.recencyAt - e.recencyAt).slice(0, MIRROR_MAX_SESSIONS);
for (const e of h) {
r.throwIfAborted();
const t = mirrorCandidateKey(e);
const i = f.get(e.catalogId);
if (!i) continue;
try {
const a = await buildUpload(l, i, e, false);
r.throwIfAborted();
const o = mirrorFingerprint(a);
if (n.get(t)?.fingerprint === o) continue;
const s = await upload(a);
r.throwIfAborted();
if (s) trackSuccessfulUpload(t, e, o);
} catch (t) {
r.throwIfAborted();
warnThrottled(`beam mirror upload failed for ${e.catalogId}: ${String(t)}`);
}
}
const g = t();
const _ = [];
for (const [e, t] of n) {
r.throwIfAborted();
const i = p.get(e);
if (!(i ? i.recencyAt < u : m.has(`${t.candidate.catalogId}\0${t.candidate.hostId}`))) continue;
if (t.expiresAt <= g) n.delete(e);
else if (_.length < MIRROR_MAX_SESSIONS) _.push([e, i ? {
...t,
candidate: i
} : t]);
}
for (const [e, t] of _) {
r.throwIfAborted();
let i = false;
const a = f.get(t.candidate.catalogId);
if (a) try {
const e = await buildUpload(l, a, t.candidate, true);
r.throwIfAborted();
i = await upload(e);
r.throwIfAborted();
} catch {
r.throwIfAborted();
}
n.delete(e);
if (!i) n.set(e, t);
}
} catch (e) {
if (!r.aborted) throw e;
}
};
return { tick: scan };
}
function createBeamMirrorService(e) {
return {
id: "beam-mirror",
apiVersion: 2,
start(t) {
const n = parseBeamMirrorConfig(e.runtime.config.current());
if (n === void 0) return;
if (typeof n === "string") {
t.logger.warn(`beam mirror disabled: ${n}`);
return;
}
const r = createBeamMirrorRunner({
runtime: e.runtime,
logger: t.logger,
signal: t.scheduler.signal
});
t.scheduler.schedule({
id: "mirror",
delayMs: 0,
everyMs: n.pollSeconds * 1e3,
run: () => r.tick()
});
if (n.token === null) t.logger.warn(`beam mirror paused: ${MIRROR_TOKEN_PATH} credential unavailable; restore it and run openclaw secrets reload`);
else t.logger.info(`beam mirror active: ${n.catalogs.join(", ")} -> ${new URL(n.endpoint).origin}`);
}
};
}
//#endregion
//#region extensions/beam/src/session-catalog.ts
const DEFAULT_LIMIT = 50;
const MAX_LIMIT = 100;
function boundedLimit(e) {
return Math.min(MAX_LIMIT, Math.max(1, e ?? DEFAULT_LIMIT));
}
function cursorOffset(e) {
if (!e || !/^\d+$/.test(e)) return 0;
const t = Number(e);
return Number.isSafeInteger(t) && t >= 0 ? t : 0;
}
function transcriptRevision(e) {
return createHash("sha256").update(JSON.stringify(e.items)).digest("base64url");
}
function encodeTranscriptCursor(e) {
return Buffer.from(JSON.stringify(e), "utf8").toString("base64url");
}
function decodeTranscriptCursor(e) {
try {
const t = JSON.parse(Buffer.from(e, "base64url").toString("utf8"));
if (isRecord(t) && typeof t.revision === "string" && /^[A-Za-z0-9_-]{43}$/.test(t.revision) && typeof t.end === "number" && Number.isSafeInteger(t.end) && t.end >= 0) return {
revision: t.revision,
end: t.end
};
} catch {}
throw new Error("invalid Beam transcript cursor");
}
function createBeamSessionCatalog(e) {
async function requireSession(t, n) {
if (t !== "gateway") throw new Error(`unknown Beam host: ${t}`);
const r = await e.get(n);
if (!r) throw new Error(`unknown Beam session: ${n}`);
return r;
}
return {
id: "beam",
label: "Beam",
audience: "gateway-operators",
shareRoute: BEAM_SESSION_SHARE_ROUTE,
supportsProcessHomeIsolation: true,
async list(t) {
const n = t.search?.trim().toLowerCase().normalize("NFC");
const r = n && isControlUiCatalogShareId(BEAM_SESSION_SHARE_ROUTE, n) ? n : void 0;
const i = (await e.list()).filter((e) => !n || (r ? e.beamId.startsWith(r) : `${e.title}\n${e.source}`.toLowerCase().normalize("NFC").includes(n))).toSorted((e, t) => t.receivedAt - e.receivedAt || e.beamId.localeCompare(t.beamId));
const a = cursorOffset(t.cursors?.[BEAM_HOST_ID]);
const o = boundedLimit(t.limitPerHost);
const s = i.slice(a, a + o);
return [{
hostId: BEAM_HOST_ID,
label: "Beamed sessions",
kind: "gateway",
connected: true,
sessions: s.map((e) => ({
threadId: e.beamId,
name: e.title,
status: e.completed ? "completed" : "live",
createdAt: e.createdAt,
updatedAt: e.receivedAt,
recencyAt: e.receivedAt,
source: e.source,
archived: false,
canContinue: true,
canArchive: true
})),
...a + s.length < i.length ? { nextCursor: String(a + s.length) } : {}
}];
},
async read(e) {
const t = await requireSession(e.hostId, e.threadId);
const n = e.cursor === void 0 ? void 0 : decodeTranscriptCursor(e.cursor);
const r = Math.min(t.items.length, n?.end ?? t.items.length);
const i = Math.max(0, r - boundedLimit(e.limit));
let a;
if (n || i > 0) {
const e = transcriptRevision(t);
if (n && n.revision !== e) throw new Error("stale Beam transcript cursor");
if (i > 0) a = encodeTranscriptCursor({
revision: e,
end: i
});
}
return {
hostId: BEAM_HOST_ID,
label: t.title,
threadId: t.beamId,
items: t.items.slice(i, r).map((e, n) => ({
id: `${t.beamId}:${i + n}`,
type: e.type,
text: e.text,
timestamp: t.updatedAt,
sender: e.type === "userMessage" && t.uploaderProfileId ? { identity: {
type: "profile",
id: t.uploaderProfileId
} } : void 0
})).toReversed(),
...a ? { nextCursor: a } : {}
};
},
async archive(t) {
if (t.hostId !== "gateway") throw new Error(`unknown Beam host: ${t.hostId}`);
if (!await e.delete(t.threadId)) throw new Error(`unknown Beam session: ${t.threadId}`);
return { ok: true };
},
async copyToGatewaySession(e) {
const t = await requireSession(e.hostId, e.threadId);
return {
displayName: t.title,
...t.sourceModel ? { preferredModel: `${t.sourceModel.provider}/${t.sourceModel.model}` } : {}
};
}
};
}
//#endregion
//#region extensions/beam/src/store.ts
function beamTimestampEpochNanoseconds(e) {
const t = /\.(\d{1,9})(?=Z|[+-]\d{2}:\d{2}$)/.exec(e);
const n = (t?.[1] ?? "").padEnd(9, "0");
const r = t ? `${e.slice(0, t.index)}.${n.slice(0, 3)}${e.slice(t.index + t[0].length)}` : e;
return BigInt(Date.parse(r)) * 1000000n + BigInt(n.slice(3));
}
function compareBeamTimestamps(e, t) {
const n = beamTimestampEpochNanoseconds(e);
const r = beamTimestampEpochNanoseconds(t);
return n < r ? -1 : n > r ? 1 : 0;
}
function decideBeamUpload(e, t) {
const n = e ? compareBeamTimestamps(t.updatedAt, e.updatedAt) : 1;
if (n < 0 || n === 0 && e?.completed && !t.completed) return;
return {
...t,
createdAt: e?.createdAt ?? t.receivedAt
};
}
function createBeamStore(e) {
const t = e.state.openKeyedStoreV2({
namespace: "sessions",
maxEntries: 500,
overflowPolicy: "evict-oldest",
defaultTtlMs: BEAM_RETENTION_MS
});
let n;
let r;
let i;
const invalidate = () => {
n = void 0;
};
const refresh = () => {
if (i?.aborted) return Promise.reject(/* @__PURE__ */ new Error("Beam catalog inventory is stopped"));
r ??= (async () => {
const e = await t.entries();
if (i?.aborted) return;
n = e.map(({ value: e, expiresAt: t }) => ({
value: {
beamId: e.beamId,
title: e.title,
source: e.source,
completed: e.completed,
createdAt: e.createdAt,
receivedAt: e.receivedAt
},
expiresAt: t
}));
})().finally(() => {
r = void 0;
});
return r;
};
return {
catalogService: {
id: "beam-catalog",
apiVersion: 2,
async start(e) {
i = e.scheduler.signal;
const update = () => refresh().catch((t) => {
invalidate();
e.logger.warn(`beam catalog inventory refresh failed: ${String(t)}`);
});
e.scheduler.schedule({
id: "inventory",
delayMs: 3e4,
everyMs: 3e4,
run: update
});
await update();
},
async stop() {
invalidate();
await r?.catch(() => {});
}
},
async upload(e, { receivedAt: n, uploaderProfileId: r, revalidatePublisher: i }) {
const a = {
...e,
...r ? { uploaderProfileId: r } : {},
receivedAt: n
};
try {
let e = await t.observe(a.beamId);
for (;;) {
const n = decideBeamUpload(e.value, a);
await i?.();
const r = await t.compareAndApply(a.beamId, e.comparison, n ? {
operation: "update",
action: "set",
value: n
} : {
operation: "update",
action: "keep"
});
if (r.status !== "conflict") return r.status === "applied";
e = r.current;
}
} finally {
invalidate();
}
},
get: (e) => t.lookup(e),
async delete(e) {
try {
return await t.delete(e);
} finally {
invalidate();
}
},
async list() {
for (;;) {
if (n) {
const e = Date.now();
return n.filter((t) => t.expiresAt === void 0 || t.expiresAt > e).map(({ value: e }) => e);
}
await refresh();
}
}
};
}
//#endregion
//#region extensions/beam/index.ts
var beam_default = definePluginEntry({
id: "beam",
name: "Beam",
description: "Receive redacted coding-session snapshots for review or Team continuation",
register(e) {
const t = createBeamStore(e.runtime);
e.registerSessionCatalog(createBeamSessionCatalog(t));
e.registerService(t.catalogService);
e.registerHttpRoute({
path: "/api/v1/beam/sessions",
auth: "gateway",
match: "exact",
handler: createBeamRequestHandler({
store: t,
resolveControlUiBasePath: () => e.runtime.config.current().gateway?.controlUi?.basePath
})
});
e.registerService(createBeamMirrorService({ runtime: e.runtime }));
}
});
//#endregion
export { beam_default as default };