openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
400 lines (399 loc) • 14.5 kB
JavaScript
import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs";
import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs";
import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs";
import { z as resolvePersistedSessionStoreOwnerForKey } from "./agent-scope-config-DmXgFGKP.mjs";
import { i as assertExistingDatabaseIdentity } from "./sqlite-worker-identity-BH8ZkJU9.mjs";
import { r as MAX_IMAGE_BYTES } from "./constants-ChkaB-HW.mjs";
import { d as extractCanvasFromRecord, f as extractCanvasShortcodes } from "./chat-display-projection.canvas-XAAIxHM8.mjs";
import { t as ASSISTANT_DISPLAY_CONTENT_FIELD } from "./assistant-display-content-CBuMU4m5.mjs";
import { n as sanitizeChatHistoryContentBlock } from "./chat-display-projection.sanitize-DYNE5Y5I.mjs";
import { n as isToolCallContentType, o as resolveToolBlockArgs } from "./tool-content-DG-uYHoo.mjs";
import { r as jsonUtf8Bytes } from "./json-utf8-bytes-DNwtq2cu.mjs";
import { c as findTranscriptEvent } from "./session-accessor-CizTbDQj.mjs";
import { l as resolveSessionPublicShare } from "./session-accessor.sqlite-entry-store-DmqxH0lm.mjs";
import { s as withReadySessionRows } from "./session-row-prepared-read-B4U_T7SO.mjs";
import { c as publicSessionMessageText, i as collectPublicSessionAttachments, l as readPublicWidgetReceipt, s as publicSessionMessageEntry } from "./control-ui-public-session-attachments-DauqtHb5.mjs";
import { s as unwrapToolCallForDisplay } from "./tool-display-BQXZgFy6.mjs";
import { d as readSessionMessagesPageWithStatsAsync, o as readSessionMessageByIdAsync } from "./session-transcript-readers-D1WqgwbF.mjs";
import { n as parseCanvasDocumentHttpPath } from "./documents-A82Go5Wp.mjs";
//#region src/gateway/control-ui-public-session-project.ts
function toolSummary(e) {
const t = asOptionalRecord(e);
const n = t ? [
"command",
"cmd",
"path",
"file_path",
"query",
"q",
"url"
].map((e) => t[e]).find((e) => typeof e === "string") : typeof e === "string" ? e : void 0;
return typeof n === "string" ? truncateUtf16Safe(n.replace(/\s+/gu, " ").trim(), 160) : "";
}
/** Public links leave the reader only on a click: absolute http(s), never embedded credentials. */
function publicSessionLinkHref(e) {
const t = e ? URL.parse(e) : null;
return t && (t.protocol === "https:" || t.protocol === "http:") && !t.username && !t.password ? t.href : void 0;
}
function hostedWidget(e) {
if (!e?.url) return;
const t = parseCanvasDocumentHttpPath(e.url);
if (!t || e.mcpApp || e.viewId && e.viewId !== t.documentId) return;
return {
kind: "widget",
docId: t.documentId,
title: e.title,
height: e.preferredHeight
};
}
/** Same visible-content boundary as chat: narration separates adjacent tool activity. */
function projectPublicSessionItems(e) {
const t = [];
const n = /* @__PURE__ */ new Map();
const r = e.map((e) => {
const t = publicSessionMessageEntry(e);
const r = hostedWidget(extractCanvasFromRecord(readPublicWidgetReceipt(e)));
if (r?.title) n.set(r.docId, r.title);
const i = t ? publicSessionMessageText(t) : "";
const a = extractCanvasShortcodes(t?.role === "assistant" ? i : void 0);
const o = a.previews.flatMap((e) => {
const t = hostedWidget(e);
const n = t ? void 0 : publicSessionLinkHref(e.url);
return t ? [t] : n ? [{
kind: "link",
href: n,
title: e.title
}] : [];
});
return {
message: e,
entry: t,
receipt: r,
text: t?.role === "assistant" ? a.text : i,
shortcodeEmbeds: o,
deferReceipt: false
};
});
const i = /* @__PURE__ */ new Set();
for (const e of r.toReversed()) {
if (e.entry?.role === "user") i.clear();
e.deferReceipt = Boolean(e.receipt && i.has(e.receipt.docId));
for (const t of e.shortcodeEmbeds) if (t.kind === "widget") i.add(t.docId);
}
const a = /* @__PURE__ */ new Set();
for (const [e, { message: i, entry: o, receipt: s, text: c, shortcodeEmbeds: l, deferReceipt: u }] of r.entries()) {
const r = [];
for (const e of [...l, ...s && !u ? [s] : []]) if (e.kind === "link") r.push(e);
else if (!a.has(e.docId)) {
a.add(e.docId);
r.push({
...e,
title: e.title ?? n.get(e.docId)
});
}
const d = o ? collectPublicSessionAttachments(o) : [];
if (c || d.length > 0 || r.length > 0) t.push({
kind: "message",
role: o?.role === "user" ? "user" : "assistant",
text: c,
message: i,
sourceIndex: e,
embeds: r
});
if (o?.role !== "assistant" || !Array.isArray(o.content)) continue;
for (const n of o.content) {
const r = asOptionalRecord(n);
if (!r || !isToolCallContentType(r.type)) continue;
const i = unwrapToolCallForDisplay({
name: typeof r.name === "string" ? r.name : "tool",
args: resolveToolBlockArgs(r)
});
const a = truncateUtf16Safe(i.name, 80);
const o = toolSummary(i.args);
const s = t.at(-1);
if (s?.kind === "tools") s.calls.push({
name: a,
summary: o
});
else t.push({
kind: "tools",
calls: [{
name: a,
summary: o
}],
sourceIndex: e
});
}
}
return t;
}
//#endregion
//#region src/gateway/control-ui-public-session-read.ts
const PUBLIC_SESSION_PAGE_ITEMS = 50;
const PUBLIC_SESSION_SCAN_ROWS = 2e3;
const PUBLIC_SESSION_READ_BYTES = 1048576;
const PUBLIC_SESSION_MEDIA_ENTRY_BYTES = Math.ceil(MAX_IMAGE_BYTES * 4 / 3) + PUBLIC_SESSION_READ_BYTES;
const PUBLIC_SESSION_MAX_MESSAGES = 100;
async function readPublicSessionOpening(e) {
let t = PUBLIC_SESSION_READ_BYTES;
let n = await readSessionMessagesPageWithStatsAsync(e, {
offset: 0,
beforeSeq: 2,
maxMessages: 1,
maxBytes: t,
allowResetArchiveFallback: false
});
let r = n.omittedOversized;
for (let i = 0; i < PUBLIC_SESSION_MAX_MESSAGES; i++) {
if (i > 0) {
n = await readSessionMessagesPageWithStatsAsync(e, {
offset: 0,
beforeSeq: i + 2,
maxMessages: 1,
maxBytes: t,
allowResetArchiveFallback: false
});
r ||= n.omittedOversized;
}
const a = n.messages[0];
const o = publicSessionMessageEntry(a);
if (o?.role === "user" && publicSessionMessageText(o)) return {
...n,
messages: [a],
olderOffset: void 0,
omittedOversized: r
};
if (a !== void 0) t -= Buffer.byteLength(JSON.stringify(a));
if (i + 1 >= n.totalMessages || t < 1024) break;
}
return {
...n,
messages: [],
olderOffset: void 0,
omittedOversized: r
};
}
function compactInlineImagePayloads(e) {
const t = asOptionalRecord(e);
if (!t) return;
const n = { ...t };
let r = false;
for (const e of ["content", ASSISTANT_DISPLAY_CONTENT_FIELD]) {
const i = t[e];
if (!Array.isArray(i)) continue;
n[e] = i.map((e) => {
const t = asOptionalRecord(e);
const n = asOptionalRecord(t?.source);
const i = asOptionalRecord(t?.image_url);
if (!t || ![
"image",
"image_url",
"input_image"
].includes(String(t.type)) || ![
t.data,
t.blob,
n?.data,
n?.blob
].some((e) => typeof e === "string" && e.length > 0) && ![
t.url,
t.image_url,
i?.url,
n?.url
].some((e) => typeof e === "string" && e.startsWith("data:image/"))) return e;
r = true;
const a = asOptionalRecord(sanitizeChatHistoryContentBlock(Object.assign({}, t, { type: "image" }), { maxChars: Number.MAX_SAFE_INTEGER }).block);
return Object.assign(a ?? {}, { type: t.type });
});
}
return r && jsonUtf8Bytes([n]) <= PUBLIC_SESSION_READ_BYTES ? n : void 0;
}
async function readVisiblePage(e, t) {
let n = [];
let r = 2;
let i = t;
let a = 0;
let o = false;
let s;
let c;
while (n.length < PUBLIC_SESSION_SCAN_ROWS && r <= 1047552) {
const l = await readSessionMessagesPageWithStatsAsync(e, {
offset: i,
maxMessages: Math.min(100, PUBLIC_SESSION_SCAN_ROWS - n.length),
maxBytes: PUBLIC_SESSION_READ_BYTES - r,
allowResetArchiveFallback: false,
...c ? {
beforeSeq: a + 1,
expectedReadWindow: c
} : { captureReadWindow: true }
});
if (l.windowReset) return null;
if (!c) {
a = l.totalMessages;
c = l.readWindow;
}
if (l.omittedOversized && n.length > 0) {
s = i;
break;
}
if (l.omittedOversized) {
const t = await readSessionMessagesPageWithStatsAsync(e, {
offset: i,
beforeSeq: a + 1,
expectedReadWindow: c,
maxMessages: 1,
maxBytes: PUBLIC_SESSION_MEDIA_ENTRY_BYTES,
allowResetArchiveFallback: false
});
if (t.windowReset) return null;
const r = t.messages.length === 1 ? compactInlineImagePayloads(t.messages[0]) : void 0;
if (r) {
n = [r];
s = l.olderOffset;
break;
}
}
n = [...l.messages, ...n];
r += jsonUtf8Bytes(l.messages);
s = l.olderOffset;
o ||= l.omittedOversized === true;
const u = projectPublicSessionItems(n);
if (u.length > PUBLIC_SESSION_PAGE_ITEMS) {
const e = u[u.length - PUBLIC_SESSION_PAGE_ITEMS].sourceIndex;
n = n.slice(e);
s = t + n.length;
break;
}
if (s === void 0 || l.messages.length < 100) break;
i = s;
}
o ||= s !== void 0 && projectPublicSessionItems(n).length < PUBLIC_SESSION_PAGE_ITEMS;
return {
messages: n,
totalMessages: a,
truncated: o,
olderOffset: s
};
}
function readAuthorizedTarget(e, t, n) {
const r = parseAgentSessionKey(t.sessionKey);
const i = resolvePersistedSessionStoreOwnerForKey(e, t.sessionKey);
if (t.sessionKey !== "global" && (!r || r.agentId !== t.agentId || t.sessionKey !== `agent:${r.agentId}:${r.rest}`) || i.kind === "retired" || i.kind === "configured" && i.agentId !== t.agentId || !listAgentIds(e).includes(t.agentId) || isIncognitoSessionKey(t.sessionKey) || n.sharingRevision === void 0 || n.state.cfg !== e) return;
const a = {
key: t.sessionKey,
agentId: t.agentId
};
const o = n.sharingTargetState(a);
if (o.status !== "ready") return;
const s = o.target;
const c = resolveSessionPublicShare(s.entry);
if (s.canonicalKey !== t.sessionKey || s.agentId !== t.agentId || c?.id !== t.shareId || c.sessionId !== t.sessionId) return;
const l = n.readSource({
...a,
storePath: s.storePath
});
if (!l || typeof l.databaseIdentity !== "string") return;
assertExistingDatabaseIdentity(l.path, `file:${l.databaseIdentity}`, l.databaseBirthtime);
return {
target: s,
source: l
};
}
/** The resident owner installs committed sharing facts before a response can consume them. */
function isPublicSessionShareActive(e, t, n) {
return Boolean(readAuthorizedTarget(e, t, n));
}
/** Only the exact published generation is readable; this grants no Gateway session authority. */
async function readPublicSessionShare(e, t, n) {
const { projection: r } = n;
if (isIncognitoSessionKey(t.sessionKey) || !listAgentIds(e).includes(t.agentId)) return null;
const queries = () => [{
key: t.sessionKey,
agentId: t.agentId
}];
const i = await withReadySessionRows(r, queries, () => readAuthorizedTarget(e, t, r));
if (!i) return null;
const a = {
agentId: i.source.agentId,
sessionKey: t.sessionKey,
sessionId: t.sessionId,
storePath: i.source.path,
sessionEntry: i.target.entry
};
const o = n.card ? await readPublicSessionOpening(a) : await readVisiblePage(a, n.offset ?? 0);
if (!o) return null;
const s = n.card ? (await import("./control-ui-public-session-card-facts-Dpp6guJK.mjs")).resolvePublicSessionCardFacts : void 0;
return withReadySessionRows(r, queries, (a) => {
const c = readAuthorizedTarget(e, t, r);
if (!c || c.source.path !== i.source.path || c.source.databaseIdentity !== i.source.databaseIdentity || c.source.databaseBirthtime !== i.source.databaseBirthtime) return null;
const l = (c.target.entry.label || c.target.entry.displayName || "Shared session").trim();
const u = n.card ? a.describe(queries()[0]) : void 0;
return {
title: l || "Shared session",
messages: o.messages,
totalMessages: o.totalMessages,
truncated: "truncated" in o ? o.truncated : o.omittedOversized === true,
...u && s ? { cardFacts: s({
cfg: e,
record: u,
rowContext: a.state.rowContext,
pullRequests: n.pullRequests
}) } : {},
...o.olderOffset !== void 0 ? { olderOffset: o.olderOffset } : {}
};
});
}
/** Media reads share the page's exact publication and physical-store authority. */
async function readPublicSessionMessage(e, t, n) {
const { projection: r } = n;
if (isIncognitoSessionKey(t.sessionKey) || !listAgentIds(e).includes(t.agentId)) return null;
const queries = () => [{
key: t.sessionKey,
agentId: t.agentId
}];
const i = await withReadySessionRows(r, queries, () => readAuthorizedTarget(e, t, r));
if (!i) return null;
const a = await readSessionMessageByIdAsync({
agentId: i.source.agentId,
sessionKey: t.sessionKey,
sessionId: t.sessionId,
storePath: i.source.path,
sessionEntry: i.target.entry
}, n.entryId, {
currentOnly: true,
maxBytes: PUBLIC_SESSION_MEDIA_ENTRY_BYTES,
allowResetArchiveFallback: false
});
return withReadySessionRows(r, queries, () => {
const n = readAuthorizedTarget(e, t, r);
return n && n.source.path === i.source.path && n.source.databaseIdentity === i.source.databaseIdentity && n.source.databaseBirthtime === i.source.databaseBirthtime && a.found && !a.oversized ? asOptionalRecord(a.message) ?? null : null;
});
}
/** A saved inline receipt grants document disclosure only for its published generation. */
async function readPublicSessionWidget(e, t, n) {
const { projection: r } = n;
if (isIncognitoSessionKey(t.sessionKey) || !listAgentIds(e).includes(t.agentId)) return false;
const queries = () => [{
key: t.sessionKey,
agentId: t.agentId
}];
const i = await withReadySessionRows(r, queries, () => readAuthorizedTarget(e, t, r));
if (!i) return false;
const a = await findTranscriptEvent({
agentId: i.source.agentId,
sessionKey: t.sessionKey,
sessionId: t.sessionId,
storePath: i.source.path,
sessionEntry: i.target.entry
}, {
kind: "canvas-widget",
docId: n.docId
});
return withReadySessionRows(r, queries, () => {
const n = readAuthorizedTarget(e, t, r);
return Boolean(a && readPublicWidgetReceipt(asOptionalRecord(a.event)?.message) && n && n.source.path === i.source.path && n.source.databaseIdentity === i.source.databaseIdentity && n.source.databaseBirthtime === i.source.databaseBirthtime);
});
}
//#endregion
export { projectPublicSessionItems as a, readPublicSessionWidget as i, readPublicSessionMessage as n, publicSessionLinkHref as o, readPublicSessionShare as r, isPublicSessionShareActive as t };