openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
757 lines (756 loc) • 26.8 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs";
import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs";
import { Cs as validateConversationSendParams, Ss as validateConversationListParams, Ts as validateConversationTurnParams, ws as validateConversationTurnCancelParams } from "./src-BX8OAe1J.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 { n as resolveConversationRouteFingerprint } from "./conversation-authority-B_Nl9_uN.mjs";
import { r as ConversationDeliveryInputError } from "./conversation-delivery-policy-XpNA31Ek.mjs";
import { t as buildConversationIdentity } from "./conversation-identity-phs9JhQi.mjs";
import { r as resolveRequestedSessionAgentId } from "./session-request-agent-tfwWH53J.mjs";
import { r as resolveChannelAccount } from "./account-resolution-D7u1J1M0.mjs";
import { t as formatForLog } from "./ws-log-CbOV6uhk.mjs";
import { t as respondError } from "./response-C7fEiIN1.mjs";
import { r as defineValidatedGatewayMethod } from "./validation-DwNk6A-B.mjs";
import { i as resolveMessageReceiptPrimaryId } from "./receipt-D4ZtbK66.mjs";
import { a as readConversation, i as prepareConversationRegistryScope, n as listConversations, o as registerConversationAddresses } from "./conversation-registry-DTUa0zh7.mjs";
import { c as markConversationDeliverySuppressed, r as getConversationDeliveryOperation, s as markConversationDeliverySent, t as beginConversationDeliveryOperation } from "./conversation-delivery-store-CwDySUK3.mjs";
import { t as captureConversationDeliveryTarget } from "./delivery-completion-DkLj6KUt.mjs";
import { r as registerPendingConversationTurn, t as cancelPendingConversationTurn } from "./conversation-turns-m-vBoIaV.mjs";
import { r as resolveOutboundChannelPlugin } from "./channel-resolution-DjtSMYUG.mjs";
import { a as resolveOutboundSessionRoute, i as prepareOutboundSessionBinding, n as captureOutboundSessionBinding, t as bindOutboundSessionEntry } from "./outbound-session-BGK8YYPT.mjs";
import { n as runMessageAction } from "./message-action-runner-CN0QRJoV.mjs";
import { i as withAuthorizedConversationDelivery, n as prepareConversationRouteEligibilitiesForAgent, o as ConversationInputError, r as resolveConversationRouteEligibilitiesForAgent, s as ConversationOperationConflictError, t as prepareConversationDeliveryRouteAuthorization } from "./conversation-route-ownership-Ce9HOylN.mjs";
import { n as resolveGatewayInflightRequest, r as runGatewayInflightWork, t as cacheGatewayDedupeResult } from "./inflight-BbR4qVzQ.mjs";
import crypto from "node:crypto";
//#region src/gateway/conversation-list.ts
const log = createSubsystemLogger("gateway/conversations");
/** Lists persisted and channel-directory addresses from the Gateway's live plugin runtime. */
async function runGatewayConversationList(e) {
const t = await prepareConversationRegistryScope(e);
const n = e.query?.trim() || void 0;
let r;
let i;
const a = /* @__PURE__ */ new Set();
if (e.channel) {
const o = resolveOutboundChannelPlugin({
channel: e.channel,
cfg: e.config
});
r = o?.directory ? o.id : e.channel.trim().toLowerCase();
if (o?.directory) {
const s = /* @__PURE__ */ new Map();
for (const t of new Set(o.config.listAccountIds(e.config).filter(Boolean))) {
const r = await resolveChannelAccount({
plugin: o,
cfg: e.config,
accountId: t
});
if (o.config.isEnabled?.(r, e.config) === false) continue;
if (o.config.isConfigured && !await o.config.isConfigured(r, e.config)) continue;
const i = {
cfg: e.config,
accountId: t,
...n ? { query: n } : {},
limit: e.limit,
runtime: defaultRuntime
};
const a = o.directory;
const c = a?.listPeersLive;
const l = a?.listGroupsLive;
const listLiveDirectoryEntries = async (e, n) => {
try {
return await n();
} catch (n) {
log.warn("live directory discovery failed; using configured entries", {
channel: o.id,
accountId: t,
kind: e,
error: formatErrorMessage(n)
});
return [];
}
};
const [u, d, f, p] = await Promise.all([
a?.listPeers?.(i) ?? [],
c ? listLiveDirectoryEntries("peers", () => c(i)) : [],
a?.listGroups?.(i) ?? [],
l ? listLiveDirectoryEntries("groups", () => l(i)) : []
]);
const m = /* @__PURE__ */ new Map();
for (const e of [
...u,
...d,
...f,
...p
]) m.set(`${e.kind}\u0000${e.id.trim()}`, e);
for (const n of m.values()) {
const r = n.id.trim();
if (!r) continue;
const i = n.name?.trim() || n.handle?.trim() || void 0;
const a = await resolveOutboundSessionRoute({
cfg: e.config,
channel: o.id,
plugin: o,
agentId: e.agentId,
accountId: t,
target: r,
resolvedTarget: {
to: r,
kind: n.kind,
...i ? { display: i } : {},
source: "directory",
resolutionSource: "directory"
}
});
if (!a) continue;
const c = buildConversationIdentity({
channel: o.id,
accountId: t,
kind: a.chatType,
peerId: a.from,
deliveryTarget: a.to,
...a.threadId !== void 0 ? { threadId: a.threadId } : {},
...a.peer.kind === "direct" ? { nativeDirectUserId: a.peer.id } : { nativeChannelId: a.peer.id },
...i ? { label: i } : {}
});
if (c) s.set(c.conversationRef, c);
}
}
const c = [...s.values()];
const l = e.readCurrentConfig?.() ?? e.config;
const u = await prepareConversationRouteEligibilitiesForAgent({
config: l,
agentId: e.agentId,
conversations: c.map((e) => ({
...e,
target: e.deliveryTarget
}))
});
const d = new Map(c.map((e, t) => [e.conversationRef, t]));
try {
i = await registerConversationAddresses(t, c, Date.now(), (t) => {
if ((e.readCurrentConfig?.() ?? e.config) !== l) return t.map(() => false);
const n = u.read();
const r = t.map((e) => n[d.get(e.conversationRef) ?? -1] ?? "denied");
if (r.includes("unavailable")) throw new Error("Conversation route ownership is temporarily unavailable");
return r.map((e) => e === "eligible");
}, { channel: r });
} finally {
u.dispose();
}
for (const e of c) a.add(e.conversationRef);
}
}
const o = i ?? await listConversations(t, r !== void 0 ? { channel: r } : {});
const s = e.readCurrentConfig?.() ?? e.config;
const c = n?.toLowerCase() ?? "";
const l = c.startsWith("@") && c.length > 1 ? c.slice(1).normalize("NFC") : c.normalize("NFC");
const u = o.filter((e) => !n || a.has(e.conversationRef) || [
e.conversationRef,
e.target,
e.label
].some((e) => e?.toLowerCase().normalize("NFC").includes(l)));
const d = await resolveConversationRouteEligibilitiesForAgent({
config: s,
agentId: e.agentId,
conversations: u
});
if (d.includes("unavailable")) throw new Error("Conversation route ownership is temporarily unavailable");
return { conversations: u.filter((e, t) => d[t] === "eligible").slice(0, e.limit).map((e) => {
const t = {
conversationRef: e.conversationRef,
channel: e.channel,
accountId: e.accountId,
kind: e.kind,
target: e.target
};
if (e.threadId) t.threadId = e.threadId;
if (e.label) t.label = e.label;
return Object.assign(t, {
firstSeenAt: e.firstSeenAt,
lastSeenAt: e.lastSeenAt
});
}) };
}
//#endregion
//#region src/infra/outbound/conversation-delivery.ts
/** Durable external-conversation delivery independent from local model sessions. */
var ConversationDeliveryRejectedError = class extends Error {
constructor(e) {
super(e);
this.name = "ConversationDeliveryRejectedError";
}
};
function buildConversationDeliveryIntentId(e, t) {
return `convq_${crypto.createHash("sha256").update(JSON.stringify([e, t])).digest("hex").slice(0, 32)}`;
}
function readMessageIdFromActionResult(e) {
const t = e.sendResult?.result;
if (t && "receipt" in t && t.receipt) {
const e = resolveMessageReceiptPrimaryId(t.receipt);
if (e) return e;
}
if (t && "messageId" in t && typeof t.messageId === "string") return t.messageId.trim() || void 0;
return normalizeOptionalString(asOptionalRecord(e.payload)?.messageId);
}
function resultFromExistingOperation(e) {
if (e.status === "created") return;
if (e.status === "rejected") throw new ConversationDeliveryRejectedError(e.rejectionError ?? "Conversation delivery was permanently rejected");
const t = e.status === "replied" ? "sent" : e.status;
const n = t === "sent" ? e.platformMessageId : void 0;
const r = t === "sent" || t === "queued" ? e.preparedMessageId : void 0;
return {
deliveryStatus: t,
operation: e,
...n || r ? { messageId: n ?? r } : {}
};
}
/**
* Sends one external message after a durable operation and queue intent exist.
* A retry with the same operation id observes prior state instead of re-sending.
*/
async function sendGatewayConversationMessage(e) {
const t = e.scope;
const n = captureConversationDeliveryTarget(t);
const r = e.operation ?? (await beginConversationDeliveryOperation(t, {
operationId: e.operationId,
operationKind: e.operationKind,
conversationRef: e.conversation.conversationRef,
...e.context.sourceSessionKey ? { sourceSessionKey: e.context.sourceSessionKey } : {},
message: e.message,
authority: e.authority,
...e.preparedMessageId ? { preparedMessageId: e.preparedMessageId } : {}
}, e.assertCurrent)).record;
e.assertCurrent();
const i = resultFromExistingOperation(r);
if (i) return i;
const readAuthoritativeOperation = async () => await getConversationDeliveryOperation(t, r.operationId) ?? r;
try {
const i = await runMessageAction({
cfg: e.context.config,
action: "send",
params: {
channel: e.conversation.channel,
to: e.conversation.target,
message: e.message,
...e.conversation.threadId ? { threadId: e.conversation.threadId } : {},
idempotencyKey: e.operationId
},
defaultAccountId: e.conversation.accountId,
agentId: e.context.agentId,
sessionKey: e.context.sourceSessionKey,
senderIsOwner: e.context.senderIsOwner,
forceCoreDelivery: true,
gatewayOwnedDelivery: true,
requireQueuePersistence: true,
deliveryIntentId: buildConversationDeliveryIntentId(e.context.agentId, r.operationId),
deliveryCompletion: {
kind: "conversation",
agentId: t.agentId,
operationId: r.operationId,
storePath: t.storePath,
routeFingerprint: e.routeFingerprint
},
conversationDeliveryTarget: n,
withDirectAdapterHandoff: e.withDirectAdapterHandoff,
...r.preparedMessageId ? { preparedMessageId: r.preparedMessageId } : {},
...e.signal ? { abortSignal: e.signal } : {}
});
if (i.kind !== "send") throw new Error(`Conversation delivery returned unexpected action: ${i.kind}`);
if (i.dryRun) throw new Error("Conversation delivery was only prepared; no message was sent");
if (i.handledBy !== "core" || !i.sendResult) throw new Error("Conversation delivery did not return a core platform send result");
const a = i.sendResult.deliveryStatus;
const o = a === "suppressed" ? await markConversationDeliverySuppressed(t, r.operationId) : a === "sent" ? await markConversationDeliverySent(t, r.operationId, readMessageIdFromActionResult(i)) : void 0;
const s = o ? resultFromExistingOperation(o) : void 0;
if (s) return s;
throw new Error(`Conversation delivery was not confirmed (${a ?? "unknown"})`);
} catch (e) {
const t = resultFromExistingOperation(await readAuthoritativeOperation());
if (t) return t;
throw e;
}
}
//#endregion
//#region src/gateway/conversation-send.ts
/** Performs one durable conversation send inside the Gateway channel owner. */
async function runGatewayConversationSend(e) {
const t = await prepareConversationRegistryScope(e);
e.signal?.throwIfAborted();
let n;
try {
const r = await getConversationDeliveryOperation(t, e.operationId, {
operationKind: "send",
conversationRef: e.conversationRef,
...e.sourceSessionKey ? { sourceSessionKey: e.sourceSessionKey } : {},
message: e.message
});
const i = await readConversation(t, e.conversationRef);
e.signal?.throwIfAborted();
if (!i) throw new ConversationInputError(`Conversation not found: ${e.conversationRef} (use conversations_list)`);
const a = e.readCurrentConfig?.() ?? e.config;
const o = resolveConversationRouteFingerprint(i);
const s = {
conversationRef: i.conversationRef,
expectedRouteFingerprint: o
};
n = await prepareConversationDeliveryRouteAuthorization({
...s,
config: a,
readCurrentConfig: e.readCurrentConfig,
agentId: e.agentId,
conversation: i
});
n.assertRequestEligible();
const c = r ? resultFromExistingOperation(r) : void 0;
const l = c ?? await sendGatewayConversationMessage({
scope: t,
context: {
agentId: e.agentId,
...e.sourceSessionKey ? { sourceSessionKey: e.sourceSessionKey } : {},
config: a,
senderIsOwner: e.senderIsOwner
},
conversation: i,
message: e.message,
operationId: e.operationId,
operationKind: "send",
routeFingerprint: o,
authority: s,
assertCurrent: () => {
e.signal?.throwIfAborted();
n.assertCurrent(i);
},
withDirectAdapterHandoff: (r) => withAuthorizedConversationDelivery({
...s,
config: a,
readCurrentConfig: e.readCurrentConfig,
agentId: e.agentId,
scope: t,
routeAuthority: n
}, () => {
e.signal?.throwIfAborted();
return r();
}),
...r ? { operation: r } : {},
...e.signal ? { signal: e.signal } : {}
});
const u = c ? c.operation : i;
return {
status: l.deliveryStatus,
conversationRef: u.conversationRef,
channel: u.channel,
...l.messageId ? { messageId: l.messageId } : {},
...l.operation.queueId ? { queueId: l.operation.queueId } : {}
};
} catch (e) {
if (e instanceof ConversationDeliveryInputError) throw new ConversationOperationConflictError(e.message);
if (e instanceof ConversationDeliveryRejectedError) throw new ConversationInputError(e.message);
throw e;
} finally {
n?.dispose();
}
}
//#endregion
//#region src/gateway/conversation-turn.ts
function hasConversationSessionBinding(e) {
return Boolean(e.sessionId && e.sessionKey);
}
const COMPLETED_TURN_MESSAGES = {
sent: "Message was already sent; no process-local reply waiter remains.",
queued: "Delivery is queued; a later reply will start an ordinary inbound turn.",
suppressed: "Delivery was suppressed before a message was sent.",
unknown: "Delivery could not be confirmed and will not be retried automatically.",
replied: "A reply was recorded, but its durable reply payload is incomplete."
};
function resultForCompletedOperation(e) {
const t = e.platformMessageId ?? e.preparedMessageId;
if (e.status === "replied" && e.reply && t) return {
status: "replied",
conversationRef: e.conversationRef,
channel: e.channel,
messageId: t,
correlationPersisted: true,
reply: {
conversationRef: e.conversationRef,
messageId: e.reply.messageId,
...e.reply.replyToId ? { replyToId: e.reply.replyToId } : {},
...e.reply.threadId ? { threadId: e.reply.threadId } : {},
text: e.reply.text,
timestamp: e.reply.timestamp
}
};
if (e.status === "created") return;
const n = {
conversationRef: e.conversationRef,
channel: e.channel,
...t ? { messageId: t } : {}
};
if (e.status === "rejected") throw new ConversationInputError(e.rejectionError ?? "Conversation delivery was permanently rejected");
return {
...n,
status: e.status === "replied" ? "sent" : e.status,
correlationPersisted: e.status === "sent" || e.status === "queued" || e.status === "replied",
error: COMPLETED_TURN_MESSAGES[e.status]
};
}
/** Owns correlation, delivery, and waiting inside the Gateway process that receives ingress. */
async function runGatewayConversationTurn(e) {
const t = await prepareConversationRegistryScope(e);
const n = captureOutboundSessionBinding({
cfg: e.config,
scope: t,
sourceSessionKey: e.sourceSessionKey
});
let r;
try {
const n = await getConversationDeliveryOperation(t, e.turnId, {
operationKind: "turn",
conversationRef: e.conversationRef,
...e.sourceSessionKey ? { sourceSessionKey: e.sourceSessionKey } : {},
message: e.message
});
r = n ? {
created: false,
record: n
} : void 0;
} catch (e) {
if (e instanceof ConversationDeliveryInputError) throw new ConversationOperationConflictError(e.message);
throw e;
}
const i = await readConversation(t, e.conversationRef);
if (!i) throw new ConversationInputError(`Conversation not found: ${e.conversationRef} (use conversations_list)`);
const a = e.readCurrentConfig ?? (() => e.config);
const o = a();
const s = resolveConversationRouteFingerprint(i);
const c = await prepareConversationDeliveryRouteAuthorization({
config: o,
readCurrentConfig: a,
agentId: e.agentId,
conversation: i,
conversationRef: i.conversationRef,
expectedRouteFingerprint: s
});
try {
c.assertRequestEligible();
if (r) {
const e = resultForCompletedOperation(r.record);
if (e) return e;
}
const l = resolveOutboundChannelPlugin({
channel: i.channel,
cfg: o
});
let u = r?.record.preparedMessageId;
if (!r) {
const t = l?.outbound?.prepareConversationTurnMessageId;
if (!t) throw new ConversationInputError(`Channel ${i.channel} does not support correlated conversation turns; use conversations_send`);
try {
u = t({
cfg: o,
to: i.target,
text: e.message,
accountId: i.accountId,
threadId: i.threadId
}).trim();
} catch (e) {
throw new ConversationInputError(e instanceof Error ? e.message : String(e));
}
if (!u) throw new ConversationInputError(`Channel ${i.channel} prepared an empty conversation-turn message id`);
}
if (!u) throw new ConversationInputError(`Conversation turn ${e.turnId} is missing its prepared message id`);
let d;
if (hasConversationSessionBinding(i)) d = i;
else {
const r = prepareOutboundSessionBinding(n);
const a = l?.id ?? i.channel;
const u = await resolveOutboundSessionRoute({
cfg: o,
channel: a,
...l ? { plugin: l } : {},
agentId: e.agentId,
accountId: i.accountId,
target: i.target,
...i.threadId ? { threadId: i.threadId } : {}
});
if (!u) throw new ConversationInputError(`Conversation ${i.conversationRef} no longer resolves to a channel route`);
await bindOutboundSessionEntry({
cfg: o,
channel: a,
accountId: i.accountId,
route: u,
sourceSessionKey: e.sourceSessionKey,
workerGuard: {
conversation: {
conversationRef: i.conversationRef,
expectedRouteFingerprint: s
},
assertCurrent: () => {
c.assertCurrent(i);
}
}
}, r);
const f = await readConversation(t, i.conversationRef);
if (!f || !hasConversationSessionBinding(f)) throw new Error(`Conversation ${i.conversationRef} could not create its local context binding`);
d = f;
}
const f = a();
c.assertCurrent(d);
const p = resolveConversationRouteFingerprint(d);
const m = {
conversationRef: d.conversationRef,
expectedRouteFingerprint: p,
expectedSessionId: d.sessionId,
expectedSessionKey: d.sessionKey
};
const assertCurrent = () => {
c.assertCurrent(d, m);
};
if (!r) {
try {
r = await beginConversationDeliveryOperation(t, {
operationId: e.turnId,
operationKind: "turn",
conversationRef: d.conversationRef,
...e.sourceSessionKey ? { sourceSessionKey: e.sourceSessionKey } : {},
message: e.message,
authority: m,
preparedMessageId: u
}, assertCurrent);
assertCurrent();
} catch (e) {
if (e instanceof ConversationDeliveryInputError) throw new ConversationOperationConflictError(e.message);
throw e;
}
const n = resultForCompletedOperation(r.record);
if (n) return n;
}
const h = r.record.preparedMessageId;
if (!h) throw new ConversationInputError(`Conversation turn ${e.turnId} is missing its prepared message id`);
const g = registerPendingConversationTurn({
agentId: e.agentId,
id: e.turnId,
conversationRef: d.conversationRef,
sessionId: d.sessionId,
...d.threadId ? { threadId: d.threadId } : {},
timeoutMs: e.timeoutMs
});
g.setOutboundMessageId(h);
try {
const n = await sendGatewayConversationMessage({
scope: t,
context: {
agentId: e.agentId,
...e.sourceSessionKey ? { sourceSessionKey: e.sourceSessionKey } : {},
config: f,
senderIsOwner: e.senderIsOwner
},
conversation: d,
message: e.message,
operationId: g.id,
operationKind: "turn",
operation: r.record,
preparedMessageId: h,
routeFingerprint: p,
authority: m,
assertCurrent,
withDirectAdapterHandoff: (n) => withAuthorizedConversationDelivery({
...m,
config: f,
readCurrentConfig: a,
agentId: e.agentId,
scope: t,
routeAuthority: c
}, n)
});
if (n.deliveryStatus !== "sent") {
g.cancel();
return resultForCompletedOperation(n.operation);
}
if (!(n.messageId === h)) {
g.cancel();
return {
status: "sent",
conversationRef: d.conversationRef,
channel: d.channel,
...n.messageId ? { messageId: n.messageId } : {},
correlationPersisted: true,
error: "Channel delivery did not preserve its prepared message id; reply correlation was disabled."
};
}
g.markReady();
const i = await g.wait();
const o = {
conversationRef: d.conversationRef,
channel: d.channel,
messageId: h,
correlationPersisted: true
};
return i ? {
status: "replied",
...o,
reply: i
} : {
status: "timeout",
...o
};
} catch (e) {
g.cancel();
if (e instanceof ConversationDeliveryRejectedError) throw new ConversationInputError(e.message);
throw e;
}
} finally {
c.dispose();
}
}
//#endregion
//#region src/gateway/server-methods/conversations.ts
async function handleConversationWrite({ context: e, client: t, respond: n }, r) {
const readCurrentConfig = () => e.getRuntimeConfig();
const i = readCurrentConfig();
if (r.sourceSessionKey) {
const e = parseAgentSessionKey(r.sourceSessionKey);
if (e) {
if (normalizeAgentId(e.agentId) !== normalizeAgentId(r.agentId)) {
respondError(n, ErrorCodes.INVALID_REQUEST, `agent "${r.agentId}" does not match session key agent "${e.agentId}"`);
return;
}
} else {
const e = resolveRequestedSessionAgentId(i, r.sourceSessionKey, r.agentId);
if (!e.ok) {
n(false, void 0, e.error);
return;
}
}
}
const a = `conversations.${r.method}:${JSON.stringify([r.agentId, r.operationId])}`;
const o = `${a}:identity`;
const s = sha256Hex(JSON.stringify([
r.agentId,
r.sourceSessionKey ?? null,
r.conversationRef,
r.message,
r.method === "turn" ? r.timeoutMs : null
]));
const c = e.dedupe.get(a);
const l = e.dedupe.get(o);
if (c && c.requestIdentity !== s || l && (!l.ok || l.requestIdentity !== s)) {
respondError(n, ErrorCodes.INVALID_REQUEST, `conversation ${r.method} ${r.operationId} was already used with different input`);
return;
}
e.dedupe.set(o, l ? {
...l,
ts: Date.now()
} : {
ts: Date.now(),
ok: true,
requestIdentity: s
});
const u = resolveGatewayInflightRequest({
context: e,
dedupeKey: a,
idempotencyKey: r.operationId,
respond: n
});
if (u.kind === "handled") {
await u.done;
return;
}
const { dedupeKey: d, inflightMap: f } = u;
let p = false;
const m = (async () => {
try {
const n = {
config: i,
readCurrentConfig,
agentId: r.agentId,
senderIsOwner: t?.connect?.scopes?.includes(ADMIN_SCOPE) === true,
...r.sourceSessionKey ? { sourceSessionKey: r.sourceSessionKey } : {},
conversationRef: r.conversationRef,
message: r.message
};
const a = await (r.method === "send" ? runGatewayConversationSend({
...n,
operationId: r.operationId
}) : runGatewayConversationTurn({
...n,
turnId: r.operationId,
timeoutMs: r.timeoutMs
}));
const o = {
ok: true,
payload: a,
meta: { channel: a.channel }
};
cacheGatewayDedupeResult({
context: e,
dedupeKey: d,
requestIdentity: s,
result: o
});
return o;
} catch (t) {
const n = t instanceof ConversationInputError;
const r = t instanceof ConversationOperationConflictError;
const i = {
ok: false,
error: errorShape(n ? ErrorCodes.INVALID_REQUEST : ErrorCodes.UNAVAILABLE, t instanceof Error ? t.message : String(t)),
meta: { error: formatForLog(t) }
};
if (r) p = true;
else if (n) cacheGatewayDedupeResult({
context: e,
dedupeKey: d,
requestIdentity: s,
result: i
});
return i;
}
})();
try {
await runGatewayInflightWork({
inflightMap: f,
dedupeKey: d,
work: m,
respond: n
});
} finally {
if (p && e.dedupe.get(o)?.requestIdentity === s) e.dedupe.delete(o);
}
}
const conversationHandlers = {
"conversations.list": defineValidatedGatewayMethod("conversations.list", validateConversationListParams, async ({ params: e, respond: t, context: n }) => {
const readCurrentConfig = () => n.getRuntimeConfig();
t(true, await runGatewayConversationList({
config: readCurrentConfig(),
readCurrentConfig,
agentId: e.agentId,
...e.channel ? { channel: e.channel } : {},
...e.query ? { query: e.query } : {},
limit: e.limit ?? 50
}), void 0);
}, (e) => errorShape(ErrorCodes.UNAVAILABLE, e instanceof Error ? e.message : String(e))),
"conversations.send": defineValidatedGatewayMethod("conversations.send", validateConversationSendParams, (e) => handleConversationWrite(e, {
...e.params,
method: "send"
})),
"conversations.turn.cancel": defineValidatedGatewayMethod("conversations.turn.cancel", validateConversationTurnCancelParams, ({ params: e, respond: t }) => {
t(true, { cancelled: cancelPendingConversationTurn({
agentId: e.agentId,
id: e.turnId
}) }, void 0);
}),
"conversations.turn": defineValidatedGatewayMethod("conversations.turn", validateConversationTurnParams, (e) => handleConversationWrite(e, {
...e.params,
operationId: e.params.turnId,
method: "turn"
}))
};
//#endregion
export { conversationHandlers };