UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

683 lines (682 loc) • 22.2 kB
import { t as pruneMapToMaxSize } from "./map-size-BBr20tbc.mjs"; import { t as AgentSelectionRequiredError } from "./agent-scope-config-DmXgFGKP.mjs"; import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs"; import { Fr as validateArtifactsListParams, Nr as validateArtifactsDownloadParams, Pr as validateArtifactsGetParams } from "./src-BX8OAe1J.mjs"; import { c as readSessionTranscriptUpdateVersion } from "./transcript-events-BHwlF03q.mjs"; import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs"; import { p as errorShape } from "./error-codes-BzF7aRQ0.mjs"; import { n as resolveSessionTranscriptReadFence } from "./session-transcript-read-fence-Bl-ZY3_t.mjs"; import { r as isSessionTranscriptProjectionUnavailableError } from "./session-transcript-projection-error-D8lfGKCW.mjs"; import { t as MAX_PAYLOAD_BYTES } from "./payload-limits-ChDi8AHf.mjs"; import { r as resolveRequestedSessionAgentId, s as tryResolveSessionCompatibilityOwnerAgentId } from "./session-request-agent-tfwWH53J.mjs"; import { a as resolveSessionStoreIdentity } from "./session-store-key-CEwU3noi.mjs"; import "./session-accessor.sqlite-active-events-hAlJWczq.mjs"; import { n as getSessionRowProjection } from "./session-row-projection-access-CjLImwLs.mjs"; import { t as SessionMutationFactsUnavailableError } from "./session-sharing-incognito-DCw8veq-.mjs"; import { l as hasSessionReadAccessChanged, n as authorizeIncognitoSessionTarget } from "./session-sharing-policy-3TAaxC-R.mjs"; import "./session-sharing-preparation-vuYznHON.mjs"; import { t as getOrCreateWeakOwnerMap } from "./weak-owner-map-BGsaUABm.mjs"; import { r as createSessionListEntryFilter } from "./session-sharing-read-BqjuH16A.mjs"; import "./session-sharing-BIP3raq1.mjs"; import { n as prepareSessionSharingRead } from "./session-sharing-target-read-Gmjqaux8.mjs"; import { t as assertValidParams } from "./validation-DwNk6A-B.mjs"; import { a as readGatewayRequestMutationAuthority, s as retainGatewayRequestMutationAuthority } from "./session-mutation-guards-Bjnk_O0z.mjs"; import { a as createManagedArtifactDownload, i as createArtifactDownload, n as canCreateArtifactDownload } from "./artifact-download-grants-D5a8V4KO.mjs"; import { t as parseTranscriptImageArtifactId } from "./transcript-image-artifacts-CcmdOg97.mjs"; import { i as readSessionArtifacts } from "./session-transcript-readers-D1WqgwbF.mjs"; import { i as resolveChatAttachmentFrameBudgetBytes } from "./chat-attachment-policy-7g-oMINW.mjs"; import { n as normalizeChatImageRenditionWidth } from "./chat-image-renditions-swq0mtjT.mjs"; import { d as resolveManagedOutgoingMediaArtifactDownload, f as resolveManagedOutgoingMediaUrlDownload } from "./managed-image-attachments-DSFNBym_.mjs"; import { r as resolveManagedImageThumbnail, t as encodeImageThumbnail } from "./managed-image-thumbnail-cache-B4-EHveZ.mjs"; import { o as parseManagedOutgoingArtifactId } from "./managed-outgoing-artifact-id-CdPx-kme.mjs"; import { i as sessionFilesError } from "./session-files-errors-4OQSCO6W.mjs"; import { i as toArtifactSummary } from "./artifacts-content-BcrVrp_t.mjs"; import { t as resolveSessionForRun } from "./server-session-key-hkL-QKIp.mjs"; import { createHash, randomUUID } from "node:crypto"; //#region src/gateway/server-methods/artifacts-session-resolution.ts /** RPCs and HTTP readers release their facts unless a download grant adopts them. */ function createArtifactSessionAccess(e) { const t = /* @__PURE__ */ new Set(); return { ...e, retain(e) { t.add(e); }, detach(e) { t.delete(e); }, [Symbol.dispose]() { for (const e of t) e(); t.clear(); } }; } function resolveQuerySession(e, t, n) { const r = !e.sessionKey && e.runId ? resolveSessionForRun(e.runId, { ...e.agentId ? { agentId: e.agentId } : {}, ...n ? { projection: n } : {} }) : void 0; const i = e.sessionKey ?? r?.sessionKey; if (!i) return; let a = e.agentId ?? r?.agentId; if (e.sessionKey) { const e = resolveRequestedSessionAgentId(t, i, a); if (!e.ok) throw new ArtifactSessionResolutionError(e.error); a = e.agentId; } const o = resolveSessionStoreIdentity({ cfg: t, sessionKey: i, agentId: a, preserveQualifiedAddress: !e.sessionKey }); return { sessionKey: o.canonicalKey, agentId: o.agentId }; } var ArtifactSessionResolutionError = class extends Error { constructor(e = errorShape(ErrorCodes.UNAVAILABLE, "session changed while reading artifact; reload the conversation", { retryable: true })) { super(e.message); this.shape = e; } }; function throwArtifactSessionReadError(e) { if (e instanceof SessionMutationFactsUnavailableError) throw new ArtifactSessionResolutionError(); throw e; } function artifactResponseIsCurrent(e, t) { try { e.assertCurrent?.(); return true; } catch (e) { if (!(e instanceof ArtifactSessionResolutionError)) throw e; t(false, void 0, e.shape); return false; } } async function prepareArtifactSessionResolution(e, t) { const n = { ...e }; if (!n.sessionKey && n.runId && t?.sharingRevision === void 0) await t?.ensureMaterialized(); return async (e) => { try { const { client: r } = e; const resolveSession = (e) => resolveQuerySession(n, e, t); const i = e.getRuntimeConfig(); const a = resolveSession(i); if (!a) return; const o = await prepareSessionSharingRead({ cfg: i, sessionKey: a.sessionKey, agentId: a.agentId, preserveQualifiedAddress: !n.sessionKey, projection: t }); e.retain(o.release); const s = o.readCurrent(i).target; const c = s?.readSource && structuredClone(s.entry); const readCurrent = () => { try { const t = e.getRuntimeConfig(); const i = resolveSession(t); if (i?.sessionKey !== a.sessionKey || i.agentId !== a.agentId) throw new SessionMutationFactsUnavailableError(); const s = o.readCurrent(t); if (c && (!s.target || hasSessionReadAccessChanged(c, s.target.entry))) throw new SessionMutationFactsUnavailableError(); const { target: l } = s; const u = authorizeIncognitoSessionTarget({ client: r, sessionKey: n.sessionKey ?? a.sessionKey, target: l }); const d = Boolean(l && createSessionListEntryFilter({ client: r, cfg: t, membership: s.membership })?.(l.storeKey, l.entry) === false); if (!u && !d) return s; throw new ArtifactSessionResolutionError(n.sessionKey && u ? u : errorShape(ErrorCodes.INVALID_REQUEST, "no session found for artifact query", { details: { type: "artifact_scope_not_found" } })); } catch (e) { return throwArtifactSessionReadError(e); } }; return { sessionKey: o.storageTarget.canonicalKey, agentId: o.storageTarget.agentId, ...readCurrent(), readCurrent, release: o.release }; } catch (e) { return throwArtifactSessionReadError(e); } }; } //#endregion //#region src/gateway/server-methods/artifacts-session-read.ts /** Authorization and transcript reads retain the same selected physical target. */ async function prepareArtifactSessionRead(e, t) { const n = await (await prepareArtifactSessionResolution(e, t.projection))(t); if (!n) return; const { sessionKey: r, release: i } = n; const a = n.readCurrent(); const { target: o } = a; const s = o?.entry; const c = s?.sessionId; const l = a.sourcePath ?? o?.storePath; const u = s?.lifecycleRevision; const assertCurrent = () => { const e = n.readCurrent(); if ((e.sourcePath ?? e.target?.storePath) !== l || e.target?.entry.sessionId !== c || e.target?.entry.lifecycleRevision !== u) throw new ArtifactSessionResolutionError(); }; if (!c || !l) return { sessionKey: r, assertCurrent, release: i }; return { sessionKey: r, scope: { agentId: a.sourceAgentId ?? n.agentId, sessionEntry: s, sessionId: c, sessionKey: r, storePath: l }, assertCurrent, release: i }; } //#endregion //#region src/gateway/server-methods/artifacts-transcript-images.ts /** Recover only the referenced persisted bitmap; transcript bytes remain in their existing owner. */ async function findTranscriptImageArtifact(e, t, n) { const r = await prepareArtifactSessionRead(e, t); if (!r?.scope) return { sessionKey: r?.sessionKey }; const { artifact: i } = await readSessionArtifacts(r.scope, { kind: "image", sessionKey: r.sessionKey, artifactId: e.artifactId, includeData: n, runId: e.runId, messageRole: e.messageRole }); r.assertCurrent(); return { sessionKey: r.sessionKey, assertCurrent: r.assertCurrent, artifact: i }; } //#endregion //#region src/gateway/server-methods/artifacts.ts const CURSOR_TTL_MS = 9e5; const cursors = /* @__PURE__ */ new WeakMap(); const internalCaller = {}; function invalidImageCursor(e) { return new ArtifactSessionResolutionError(errorShape(ErrorCodes.INVALID_REQUEST, e, { details: { type: "artifact_cursor_invalid" } })); } const queuedArtifactDownloads = /* @__PURE__ */ new Map(); function createArtifactRequestAccess(e, t = readGatewayRequestMutationAuthority(e)) { const { assertCurrent: n } = t; const { context: r, respond: i } = e; const a = createArtifactSessionAccess({ client: e.client, projection: getSessionRowProjection(r), getRuntimeConfig: () => { n(); return r.getRuntimeConfig(); } }); if (t.release) a.retain(t.release); try { n(); } catch (e) { a[Symbol.dispose](); throw e; } return Object.assign(a, { assertCurrent: n, respond: (...e) => { n(); i(...e); } }); } async function loadArtifacts(e, t, n) { const r = await prepareArtifactSessionRead(e, t); if (!r?.scope) return { sessionKey: r?.sessionKey, artifacts: [] }; const { sessionKey: i, scope: a, assertCurrent: o } = r; const { storePath: s, sessionId: c, sessionEntry: l } = a; if (e.type === "image") { const n = JSON.stringify([ i, a.agentId, c, e.runId, e.messageRole ]); const r = getOrCreateWeakOwnerMap(cursors, t.client ?? internalCaller); const s = Date.now(); for (const [e, t] of r) if (t.expiresAt <= s) r.delete(e); const l = e.cursor ? r.get(e.cursor) : void 0; if (e.cursor && (!l || l.binding !== n)) throw invalidImageCursor("Image cursor expired or belongs to another session; restart artifacts.list"); const u = await readSessionArtifacts(a, { kind: "image-page", sessionKey: i, runId: e.runId, messageRole: e.messageRole, limit: e.limit ?? 4, beforeSeq: l?.beforeSeq, imageOffset: l?.imageOffset, readWindow: l?.readWindow }).catch((e) => { if (l && isSessionTranscriptProjectionUnavailableError(e)) throw invalidImageCursor("Transcript changed; restart artifacts.list"); throw e; }); let d; if (u.next) { d = randomUUID(); r.set(d, { ...u.next, binding: n, expiresAt: s + CURSOR_TTL_MS }); pruneMapToMaxSize(r, 128); } o(); return { artifacts: u.artifacts, ...d ? { nextCursor: d } : {}, ...u.omittedOversized ? { omittedOversized: true } : {}, sessionKey: i, assertCurrent: o }; } const u = n.downloadArtifactId ? /* @__PURE__ */ new Set([n.downloadArtifactId]) : void 0; const d = u && !resolveSessionTranscriptReadFence(a) ? JSON.stringify([ s, a.agentId, i, c, l?.lifecycleRevision, e.runId, e.messageRole, readSessionTranscriptUpdateVersion() ]) : void 0; const f = d ? queuedArtifactDownloads.get(d) : void 0; if (f && n.downloadArtifactId) { f.ids.add(n.downloadArtifactId); const e = await f.result; o(); return { ...e, assertCurrent: o }; } const collect = async () => { if (d) queuedArtifactDownloads.delete(d); const { artifacts: t } = await readSessionArtifacts(a, { kind: "list", sessionKey: i, runId: e.runId, messageRole: e.messageRole, includeDownloadData: n.includeDownloadData, downloadArtifactIds: u ? [...u] : void 0 }); return { sessionKey: i, artifacts: t }; }; const p = d && u ? Promise.resolve().then(collect) : collect(); if (d && u) queuedArtifactDownloads.set(d, { ids: u, result: p }); const m = await p; o(); return { ...m, assertCurrent: o }; } function requireQueryable(e, t) { if (e.sessionKey || e.runId) return true; t(false, void 0, sessionFilesError("artifact_query_unsupported", "artifacts require sessionKey or runId")); return false; } function respondArtifactNotFound(e, t) { e(false, void 0, sessionFilesError("artifact_not_found", "artifact not found", { artifactId: t })); } async function runArtifactSessionOperation(e, t) { try { return { ok: true, value: await t() }; } catch (t) { if (t instanceof ArtifactSessionResolutionError) { e(false, void 0, t.shape); return { ok: false }; } if (t instanceof AgentSelectionRequiredError) { e(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, t.message)); return { ok: false }; } throw t; } } async function findArtifact(e, t, n) { if (parseTranscriptImageArtifactId(e.artifactId)) return findTranscriptImageArtifact(e, t, n.includeDownloadData !== false); const r = await loadArtifacts(e, t, n); return { sessionKey: r.sessionKey, artifact: r.artifacts.find((t) => t.id === e.artifactId), assertCurrent: r.assertCurrent }; } async function prepareDownload(e, t) { const n = await prepareArtifactSessionRead(e, t); if (!n?.scope) return { sessionKey: n?.sessionKey }; const { selection: r } = await readSessionArtifacts(n.scope, { ...e, kind: "download-grant", sessionKey: n.sessionKey }); n.assertCurrent(); const i = { sessionKey: n.sessionKey, assertCurrent: n.assertCurrent, release: n.release }; return r?.kind === "prepared" ? { ...i, artifact: r.download.artifact, download: r.download } : { ...i, artifact: r?.artifact }; } async function respondManagedArtifactDownload(e, t, n, r) { try { var i = _usingCtx(); const a = retainGatewayRequestMutationAuthority(t); const o = i.u(createArtifactRequestAccess(t, a)); await runArtifactSessionOperation(n, async () => { const t = await prepareArtifactSessionRead(e, o); const i = t?.scope; const s = o.getRuntimeConfig(); const c = t ? tryResolveSessionCompatibilityOwnerAgentId(s, t.sessionKey) : void 0; const l = t && i && (!r || r.sessionKey === t.sessionKey) ? await resolveManagedOutgoingMediaArtifactDownload({ sessionKey: t.sessionKey, ...i.agentId ? { agentId: i.agentId } : {}, ...c ? { defaultAgentId: c } : {}, artifactId: e.artifactId }) : null; t?.assertCurrent(); if (!l || !t) { respondArtifactNotFound(n, e.artifactId); return; } const u = createManagedArtifactDownload({ client: o.client, path: l.url, assertCurrent: t.assertCurrent, release: () => { t.release(); a.release(); } }); o.detach(t.release); o.detach(a.release); n(true, { artifact: { id: l.artifactId, type: l.type, title: l.title, ...l.mimeType ? { mimeType: l.mimeType } : {}, ...l.sizeBytes !== void 0 ? { sizeBytes: l.sizeBytes } : {}, sessionKey: l.sessionKey, ...r?.runId ? { runId: r.runId } : {}, ...r?.messageSeq !== void 0 ? { messageSeq: r.messageSeq } : {}, source: "session-transcript", download: { mode: "url" } }, ...u }); }); } catch (e) { i.e = e; } finally { i.d(); } } const artifactsHandlers = { "artifacts.list": async (e) => { try { var t = _usingCtx(); const { params: n } = e; const r = t.u(createArtifactRequestAccess(e)); const { respond: i } = r; if (!assertValidParams(n, validateArtifactsListParams, "artifacts.list", i)) return; if (!requireQueryable(n, i)) return; if (n.type !== "image" && (n.limit !== void 0 || n.cursor !== void 0)) { i(false, void 0, sessionFilesError("artifact_query_unsupported", "limit and cursor require type image")); return; } const a = { ...n }; const o = await runArtifactSessionOperation(i, () => loadArtifacts(a, r, { includeDownloadData: false })); if (!o.ok) return; const { artifacts: s, sessionKey: c, nextCursor: l, omittedOversized: u } = o.value; if (!c && a.runId) { i(false, void 0, sessionFilesError("artifact_scope_not_found", "no session found for artifact query")); return; } if (artifactResponseIsCurrent(o.value, i)) i(true, { artifacts: s, ...l ? { nextCursor: l } : {}, ...u ? { omittedOversized: true } : {} }); } catch (e) { t.e = e; } finally { t.d(); } }, "artifacts.get": async (e) => { try { var t = _usingCtx(); const { params: n } = e; const r = t.u(createArtifactRequestAccess(e)); const { respond: i } = r; if (!assertValidParams(n, validateArtifactsGetParams, "artifacts.get", i)) return; if (!requireQueryable(n, i)) return; const a = { ...n }; const o = await runArtifactSessionOperation(i, () => findArtifact(a, r, { includeDownloadData: false })); if (!o.ok) return; const { artifact: s } = o.value; if (!s) { respondArtifactNotFound(i, a.artifactId); return; } if (artifactResponseIsCurrent(o.value, i)) i(true, { artifact: toArtifactSummary(s) }); } catch (e) { t.e = e; } finally { t.d(); } }, "artifacts.download": async (e) => { try { var t = _usingCtx(); const { params: r, client: i } = e; const a = t.u(createArtifactRequestAccess(e)); const { respond: o, assertCurrent: s } = a; if (!assertValidParams(r, validateArtifactsDownloadParams, "artifacts.download", o)) return; if (!requireQueryable(r, o)) return; const c = { ...r }; if (c.sessionKey && !c.runId && !c.messageRole && parseManagedOutgoingArtifactId(c.artifactId)) { await respondManagedArtifactDownload(c, e, o); return; } let l = await runArtifactSessionOperation(o, () => c.transport === "http" && canCreateArtifactDownload(i) ? prepareDownload(c, a) : findArtifact(c, a, { downloadArtifactId: c.artifactId })); s(); if (l.ok && l.value.download && !canCreateArtifactDownload(i)) { l = await runArtifactSessionOperation(o, () => findArtifact(c, a, { downloadArtifactId: c.artifactId })); s(); } if (!l.ok) return; let { artifact: u } = l.value; if (!u) { respondArtifactNotFound(o, c.artifactId); return; } if (parseManagedOutgoingArtifactId(u.id)) { await respondManagedArtifactDownload(c, e, o, u); return; } if (u.download.mode === "unsupported") { o(false, void 0, sessionFilesError("artifact_download_unsupported", "artifact download is unsupported", { artifactId: u.id })); return; } if (l.value.download) { const e = l.value.assertCurrent; const t = createArtifactDownload({ client: i, prepared: l.value.download, release: l.value.release, assertCurrent: () => { s(); e?.(); }, read: async (e) => { try { var t = _usingCtx(); const n = t.u(createArtifactSessionAccess({ getRuntimeConfig: a.getRuntimeConfig, client: i, projection: a.projection })); const r = await prepareArtifactSessionRead(c, n); if (!r?.scope) return; const o = await readSessionArtifacts(r.scope, { ...c, kind: "download-response", sessionKey: r.sessionKey, response: e }); r.assertCurrent(); return o.response; } catch (e) { t.e = e; } finally { t.d(); } } }); a.detach(l.value.release); o(true, { artifact: { ...toArtifactSummary(u), download: { mode: "url" } }, ...t }); return; } const d = u.download.mode === "url" && u.url && u.sessionKey ? await resolveManagedOutgoingMediaUrlDownload({ sessionKey: u.sessionKey, url: u.url }) : null; if (!artifactResponseIsCurrent(l.value, o)) return; let f; if (d) try { var n = _usingCtx(); const t = retainGatewayRequestMutationAuthority(e); const r = n.u(createArtifactRequestAccess(e, t)); const a = await runArtifactSessionOperation(o, () => prepareArtifactSessionRead(c, r)); if (!a.ok) return; if (!a.value || a.value.sessionKey !== d.sessionKey) { respondArtifactNotFound(o, c.artifactId); return; } const s = a.value; f = createManagedArtifactDownload({ client: i, path: d.url, assertCurrent: s.assertCurrent, release: () => { s.release(); t.release(); } }); r.detach(s.release); r.detach(t.release); } catch (e) { n.e = e; } finally { n.d(); } if (c.previewWidth !== void 0 && !f) { let e; if (u.type === "image" && u.download.mode === "bytes" && u.data !== void 0) { const t = Buffer.from(u.data, "base64"); const n = normalizeChatImageRenditionWidth(c.previewWidth); const r = `${createHash("sha256").update(t).digest("hex")}\0${n}`; e = await resolveManagedImageThumbnail(r, () => encodeImageThumbnail(t, n)).catch(() => void 0); } s(); if (!artifactResponseIsCurrent(l.value, o)) return; if (!e) { o(false, void 0, sessionFilesError("artifact_preview_unavailable", "artifact image preview is unavailable", { artifactId: u.id })); return; } u = { ...u, image: void 0, mimeType: "image/webp", sizeBytes: e.byteLength, data: e.toString("base64") }; } const p = { artifact: toArtifactSummary(u), ...u.download.mode === "bytes" ? { encoding: "base64", data: u.data } : {}, ...u.download.mode === "url" ? { url: f?.url ?? u.url, ...f ? { expiresAt: f.expiresAt } : {} } : {} }; if (u.download.mode === "bytes") { const t = 4 * Math.floor(resolveChatAttachmentFrameBudgetBytes(MAX_PAYLOAD_BYTES) / 3); const n = Buffer.byteLength(JSON.stringify({ type: "res", id: e.req.id, ok: true, payload: { ...p, data: "" } })); if ((u.data?.length ?? 0) > Math.min(t, 26214400 - n)) { o(false, void 0, sessionFilesError("artifact_download_unsupported", "artifact is too large for inline transfer; request transport: \"http\"", { artifactId: u.id })); return; } } o(true, p); } catch (e) { t.e = e; } finally { t.d(); } } }; //#endregion export { artifactsHandlers };