UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,027 lines (1,026 loc) • 30.1 kB
import { o as asRecord } from "./record-coerce-CVPuDqcc.mjs"; import { s as redactSensitiveText } from "./redact-Mj7pppxC.mjs"; import { d as sleepWithAbort } from "./src-BPmQBLJp.mjs"; import { n as createRuntimeConfigReader } from "./runtime-snapshot-WbwbY5b7.mjs"; import { i as isSilentReplyText } from "./tokens-CcE6ESvH.mjs"; import { N as createChannelIngressError, P as bindIngressLifecycleToReplyOptions, a as sendDurableMessageBatch } from "./channel-outbound-DQFse8vD.mjs"; import "./string-coerce-runtime-BwAZZDf5.mjs"; import "./runtime-config-snapshot-Dy0VFqWf.mjs"; import "./security-runtime-C-zE_Zy_.mjs"; import "./runtime-env-D-Pa5lD6.mjs"; import { r as resolveOutboundMediaAccessForConfig } from "./load-options-DWp5hboI.mjs"; import { n as getAgentScopedMediaLocalRoots } from "./local-roots-BTz6ULME.mjs"; import { o as resolveAgentRoute } from "./resolve-route-DBnTWpM6.mjs"; import "./routing-DmgGYTrU.mjs"; import "./reply-runtime-p4J3r0v7.mjs"; import { n as createChannelIngressMonitor } from "./ingress-monitor-CkIIn1aC.mjs"; import "./outbound-media-D5_eYDWs.mjs"; import "./media-local-roots-K_o_GELk.mjs"; import { i as resolveXAccount } from "./accounts-Bg4ihS1J.mjs"; import { i as openXAllowlist, t as XAllowlistChangedError } from "./allowlist-Cvibwhmj.mjs"; import { a as XBudgetExceededError, i as parseXPostEnvelope, n as getXTokenState, r as XApiError, s as xActivityCost, t as getXApi } from "./client-C7tbjMI4.mjs"; import { t as getXRuntime } from "./runtime-SL1x_YwB.mjs"; import { n as resolveXGuestSettings, t as formatXSenderLine } from "./guest-policy-BBy19wHq.mjs"; import { n as XGuestUsageUnavailableError, r as openXGuestUsage } from "./guest-usage-B1U2k5CF.mjs"; import { n as resolveXGuestContainmentError, t as getXGuestStatus } from "./guests-D-7yHbn6.mjs"; import { t as readXReplyOutcome } from "./outcome-BjLomHVm.mjs"; import { n as openXWorkOrigins, t as buildXWorkSessionContext } from "./work-origin-DDjO57e-.mjs"; import { a as resolveXRecipient, i as xMentionFacts, n as createXPublicationPreparation, r as resolveXIngress, t as sendXDelivery } from "./send-Bwry2Jbt.mjs"; import { nextTick } from "node:process"; //#region extensions/x/src/events.ts function laterId(e, t) { return !e || BigInt(t) > BigInt(e) ? t : e; } async function pollXMentions(e) { const t = await e.getCursor(); const n = t.sinceId; let r = t.backfill; if (r && r.sinceId !== n) { r = void 0; await e.setCursor({ sinceId: n }); } let i = r?.newestId ?? n; let a = r?.paginationToken; let o = false; let s = false; let c; const l = []; const u = new Set(a ? [a] : []); for (;;) { e.signal.throwIfAborted(); let t; try { t = await e.api.getMentions({ userId: e.userId, sinceId: n, paginationToken: a, signal: e.signal }); } catch (t) { e.signal.throwIfAborted(); if (a && t instanceof XApiError && t.status === 400 && !o) { await e.setCursor({ sinceId: n }); r = void 0; a = void 0; u.clear(); o = true; continue; } c = t instanceof Error ? t : new Error("X mentions request failed", { cause: t }); s = Boolean(a) && t instanceof XApiError && t.status === 400; break; } l.push(...t.data.map((e) => ({ post: e, users: t.includes.users }))); a = t.meta.next_token; if (a && u.has(a)) { c = /* @__PURE__ */ new Error("X mentions pagination repeated a token"); s = true; break; } if (a) u.add(a); else break; } if (s) { await e.setCursor({ sinceId: n }); a = void 0; } l.sort((e, t) => BigInt(e.post.id) < BigInt(t.post.id) ? -1 : BigInt(e.post.id) > BigInt(t.post.id) ? 1 : 0); for (const t of l) { e.signal.throwIfAborted(); await e.onPost(t); i = laterId(i, t.post.id); e.onStatus?.({ lastEventAt: Date.now() }); } if (c) { if (a) await e.setCursor({ sinceId: n, backfill: { sinceId: n, paginationToken: a, newestId: i } }); throw c; } if (r || i !== n) { await e.setCursor({ sinceId: i }); if (i) e.onStatus?.({ cursor: i }); } } async function waitForXBudgetReset(e, t) { while (Date.now() < e) await sleepWithAbort(e - Date.now(), t); t.throwIfAborted(); } function eventEnvelope(e) { const t = asRecord(asRecord(e).data); if (t.event_type !== "post.mention.create") return; return parseXPostEnvelope({ post: t.payload, users: asRecord(t.includes).users }); } async function receiveStream(e, t) { const n = new AbortController(); const r = AbortSignal.any([e.signal, n.signal]); let i = false; let a = false; let o = false; let s; let c; let l; let u; let d = false; let f; let p; let m; let h; let g = Promise.resolve(); const _ = 32; const v = 1048576; let y = 0; const b = []; const backlogFull = () => b.length >= _ || y >= v; const cancelOnAbort = () => { c?.cancel().catch(() => {}); }; const requestDrain = () => { a = true; p?.(); h?.(); }; const pause = (t) => { i = true; e.onBudgetPause(t); requestDrain(); }; const deferFailure = (e) => { f ??= e instanceof Error ? e : new Error("X activity stream failed", { cause: e }); requestDrain(); }; const fail = (e) => { deferFailure(e); n.abort(f); }; const checkBudget = async () => { const t = await e.api.spend.streamResumeAt(); if (!o && t !== void 0) pause(t); }; const x = e.api.spend.subscribe(() => { checkBudget().catch((e) => n.abort(e)); }); const disarmIdleTimer = () => { clearTimeout(s); s = void 0; }; const armIdleTimer = () => { disarmIdleTimer(); const e = setTimeout(() => { setImmediate(() => { if (s === e) n.abort(/* @__PURE__ */ new Error("X activity stream idle timeout")); }); }, 25e3); s = e; }; const receiveBatches = async (t) => { const r = new TextDecoder(); let i = ""; try { for (;;) { e.signal.throwIfAborted(); if (!a && !n.signal.aborted && backlogFull()) { await new Promise((t) => { const finish = () => { e.signal.removeEventListener("abort", finish); n.signal.removeEventListener("abort", finish); if (h === finish) h = void 0; t(); }; h = finish; e.signal.addEventListener("abort", finish, { once: true }); n.signal.addEventListener("abort", finish, { once: true }); }); continue; } const o = t.read(); let s = false; o.then(() => { s = true; }, () => { s = true; }); if (!a) { armIdleTimer(); try { await new Promise((e) => { p = e; o.then(() => e(), () => e()); }); } finally { p = void 0; disarmIdleTimer(); } } if (a && !s) { await new Promise((e) => { nextTick(e); }); if (!s) { n.abort(); e.onStatus?.({ streamConnected: false }); } } const c = await o; e.signal.throwIfAborted(); if (c.done) { if (a) return; throw new Error("X activity stream disconnected"); } i += r.decode(c.value, { stream: true }); if (i.length > 1048576) throw new Error("X activity stream event exceeded 1 MiB"); const l = []; let u = 0; let d; while ((d = i.indexOf("\n")) !== -1) { const e = i.slice(0, d).trim(); i = i.slice(d + 1); if (!e) continue; u += e.length; try { l.push(JSON.parse(e)); } catch { l.push(void 0); } } if (!l.length) continue; const f = l.reduce((e, t) => e + xActivityCost(t), 0); const _ = f ? e.api.spend.charge(f) : Promise.resolve(); if (f) g = _.catch(fail); y += u; b.push({ events: l, charged: _, chars: u }); m?.(); } } catch (t) { if (!(a && n.signal.aborted && !e.signal.aborted)) fail(t); } finally { d = true; m?.(); disarmIdleTimer(); } }; try { await checkBudget(); if (i) return; armIdleTimer(); const n = await e.api.openActivityStream(r); if (!n.body) throw new Error("X activity stream has no response body"); c = n.body.getReader(); r.addEventListener("abort", cancelOnAbort, { once: true }); if (r.aborted) cancelOnAbort(); disarmIdleTimer(); e.onConnected(); e.onStatus?.({ eventMode: "stream", streamConnected: true, streamBackoffMs: 0, message: "activity stream connected" }); u = receiveBatches(c); let o = false; try { await pollXMentions(e); } catch (t) { e.signal.throwIfAborted(); if (t instanceof XBudgetExceededError) pause(t.exhaustedUntil); else deferFailure(t); } l = (async () => { while (!r.aborted) { if (a) return; await sleepWithAbort(t, r); if (r.aborted || a) return; try { await pollXMentions(e); } catch (t) { e.signal.throwIfAborted(); if (t instanceof XBudgetExceededError) { pause(t.exhaustedUntil); return; } if (!r.aborted) e.onStatus?.({ message: "mentions backfill failed; retrying after the backfill interval" }); } } })().catch((e) => { if (!r.aborted) fail(e); }); let s = 0; for (;;) { e.signal.throwIfAborted(); const t = b.shift(); if (!t) { if (d) break; await new Promise((e) => { m = e; }); m = void 0; continue; } y -= t.chars; h?.(); await t.charged; for (const n of t.events) { e.signal.throwIfAborted(); const t = eventEnvelope(n); if (!t) { const t = asRecord(n); const r = asRecord(t.data).event_type; if (typeof r === "string" && r !== "post.mention.create") continue; if (++s === 3) { const n = `X activity stream: 3 consecutive events could not be parsed; type=${JSON.stringify(typeof r === "string" ? r.slice(0, 96) : "unknown")} keys=${JSON.stringify(Object.keys(t).slice(0, 20).map((e) => e.slice(0, 64)))}`; e.onWarning?.(n); e.onStatus?.({ message: n }); } continue; } if (s >= 3 && !r.aborted) e.onStatus?.({ message: "activity stream connected" }); s = 0; if (t.post.author_id === e.userId) continue; let i; if (o) i = { ...t, recipientPending: true }; else try { i = await resolveXRecipient({ api: e.api, post: t.post, users: t.users, userId: e.userId, signal: e.signal }); } catch (n) { e.signal.throwIfAborted(); if (!(n instanceof XBudgetExceededError)) { o = true; deferFailure(n); } i = { ...t, recipientPending: true }; } if (!i) continue; await e.onPost(i); e.onStatus?.({ lastEventAt: Date.now() }); } } if (f) throw f; } finally { o = true; x(); disarmIdleTimer(); n.abort(); await l; r.removeEventListener("abort", cancelOnAbort); await c?.cancel().catch(() => {}); await u; await g; c?.releaseLock(); e.onStatus?.({ streamConnected: false, ...i ? {} : { message: "activity stream disconnected" } }); } } async function runXEvents(e) { let t = e.mode !== "poll" && e.bearerConfigured; let n = 0; const pauseStream = (e) => { n = Math.max(n, e); }; let r = 1e3; let i = "mentions polling"; const fallback = (n) => { t = false; i = `${n instanceof Error ? n.message : "X Activity API request failed"}; polling`; e.onStatus?.({ eventMode: "poll", streamConnected: false, streamBackoffMs: 0, message: i }); }; try { if (t) try { await e.api.ensureActivitySubscriptions(e.userId, e.signal); } catch (t) { e.signal.throwIfAborted(); if (e.mode !== "stream" || t instanceof XApiError && t.status === 403) fallback(t); else throw t; } while (!e.signal.aborted) { if (t && Date.now() >= n) n = await e.api.spend.streamResumeAt() ?? 0; if (!t || Date.now() < n) { e.onStatus?.({ eventMode: "poll", streamConnected: false, ...n > Date.now() ? { message: `activity stream paused below $0.50 budget headroom; polling until ${new Date(n).toISOString()}` } : { message: i } }); try { await pollXMentions(e); } catch (t) { e.signal.throwIfAborted(); if (t instanceof XBudgetExceededError) { e.onStatus?.({ message: t.message, spend: await e.api.spend.status() }); await waitForXBudgetReset(t.exhaustedUntil, e.signal); continue; } e.onStatus?.({ message: "mentions poll failed; retrying after the poll interval" }); } const t = Math.max(15, e.pollSeconds ?? 60) * 1e3; await sleepWithAbort(n > Date.now() ? Math.min(t, n - Date.now()) : t, e.signal); continue; } try { await receiveStream({ ...e, onBudgetPause: pauseStream, onConnected: () => { r = 1e3; } }, Math.max(60, (e.pollSeconds ?? 60) * 4) * 1e3); } catch (t) { e.signal.throwIfAborted(); if (t instanceof XApiError && (t.status === 401 || t.status === 403)) { fallback(t); continue; } e.onStatus?.({ streamConnected: false, streamBackoffMs: r, message: "activity stream reconnect backoff" }); await sleepWithAbort(r, e.signal); r = Math.min(r * 2, 6e4); } } } catch (t) { if (!e.signal.aborted) throw t; } } //#endregion //#region extensions/x/src/public-thread.ts /** Never infer audience from a permalink, mention feed, or user-context API success. */ async function verifyPublicXThread(e, t, n, r) { if (!t.some((e) => e.id === r)) return false; try { const r = await e.getPublicPosts(t.map((e) => e.id), n); n.throwIfAborted(); const i = new Map(r.data.map((e) => [e.id, e])); const a = new Map(r.includes.users.map((e) => [e.id, e])); return t.every((e) => { const t = i.get(e.id); return t !== void 0 && t.text === e.text && t.author_id === e.author_id && t.conversation_id === e.conversation_id && !t.withheld && !e.withheld && a.get(e.author_id)?.protected === false; }); } catch { n.throwIfAborted(); return false; } } //#endregion //#region extensions/x/src/thread.ts function comparePosts(e, t) { return BigInt(e.id) < BigInt(t.id) ? -1 : BigInt(e.id) > BigInt(t.id) ? 1 : 0; } async function assembleXThread(e) { const t = Math.max(2, Math.floor(e.maxPosts ?? 50)); const n = /* @__PURE__ */ new Map([[e.mention.id, e.mention]]); const r = new Map((e.users ?? []).map((e) => [e.id, e])); const i = /* @__PURE__ */ new Set(); const quotedIds = () => [...n.values()].flatMap((e) => e.referenced_tweets?.filter((e) => e.type === "quoted").map((e) => e.id) ?? []); const merge = (e) => { for (const t of [...e.includes.tweets, ...e.data]) n.set(t.id, t); for (const t of e.includes.users) r.set(t.id, t); }; async function fetchPosts(t) { const r = [...new Set(t)].filter((e) => !i.has(e) && !n.has(e)); for (let t = 0; t < r.length; t += 100) { const n = r.slice(t, t + 100); n.forEach((e) => i.add(e)); merge(await e.api.getPosts(n, e.signal)); } } let a = false; try { let i; const a = /* @__PURE__ */ new Set(); do { const r = await e.api.searchConversation({ conversationId: e.mention.conversation_id, maxPosts: t - n.size, nextToken: i, signal: e.signal }); merge(r); i = r.meta.next_token; if (i && a.has(i)) throw new Error("X thread search pagination repeated a token"); if (i) a.add(i); } while (i && n.size < t); if (!r.has(e.mention.author_id)) merge(await e.api.getPosts([e.mention.id], e.signal)); await fetchPosts([e.mention.conversation_id]); let o = e.mention; for (let e = 0; o && e < t; e++) { const e = o.referenced_tweets?.find((e) => e.type === "replied_to")?.id; if (!e || e === o.id) break; await fetchPosts([e]); o = n.get(e); } await fetchPosts(quotedIds()); } catch (e) { if (!(e instanceof XBudgetExceededError)) throw e; a = true; } const o = n.get(e.mention.conversation_id); const s = /* @__PURE__ */ new Map(); if (o) s.set(o.id, o); s.set(e.mention.id, e.mention); for (const e of [...n.values()].sort(comparePosts).reverse()) { if (s.size >= t) break; s.set(e.id, e); } const c = [...s.values()].sort(comparePosts); const handle = (e) => `@${r.get(e.author_id)?.username ?? e.author_id}`; const l = new Set(quotedIds()); const u = c.map((t) => { const n = t.id === e.mention.id ? " [triggering mention]" : l.has(t.id) ? " [quoted post]" : ""; return `${handle(t)} (${t.created_at ?? "time unavailable"})${n}: ${t.text}`; }); const d = o ?? c[0] ?? e.mention; return { bodyForAgent: `X thread context (oldest to newest):\n${u.map((e) => e.split(/\r\n|[\r\n\u2028\u2029]/).map((e) => `> ${e}`).join("\n")).join("\n")}${a ? "\n[thread context truncated by budget]" : ""}\n\nReply to the triggering mention.`, label: `${handle(d)}: ${d.text.replace(/\s+/g, " ").slice(0, 80)}`, posts: c, users: [...r.values()] }; } //#endregion //#region extensions/x/src/monitor.ts const InvalidXEvent = createChannelIngressError("InvalidXEvent"); const SUMMARY_MAX_CHARS = 500; const REASON_LABELS = { failure: "reported failure", error: "error reply", unclassified: "no success tag" }; async function startXAccount(e) { const t = getXRuntime(); const n = e.account; const r = createRuntimeConfigReader(e.cfg); const i = await getXApi(n.accountId, e.cfg); const a = t.logging.getChildLogger({ channel: "x", accountId: n.accountId }); const o = { droppedMentions: 0 }; const s = openXGuestUsage(t); const publish = (t = {}) => { if (t.message && t.message !== o.message && !t.message.startsWith("X API ")) a.info(t.message); Object.assign(o, t); e.setStatus({ ...e.getStatus(), ...o, ...o.guests ? { guests: { ...o.guests, enabled: resolveXGuestSettings(resolveXAccount(r(), n.accountId)).enabled } } : {}, accountId: n.accountId, mode: o.eventMode, connected: o.eventMode === "poll" || o.streamConnected, tokenStatus: getXTokenState(n.accountId), lastInboundAt: o.lastEventAt }); }; const c = t.state.openKeyedStore({ namespace: "x.cursor", maxEntries: 1e3, overflowPolicy: "reject-new" }); const l = t.state.openChannelIngressQueue({ accountId: n.accountId }); const u = await c.lookup(n.accountId); if (u && u.userId !== n.userId) { if (!l.purge) throw new Error("X bot identity changed; this host cannot reset its ingress queue."); await l.purge({ signal: e.abortSignal }); } const assertCurrent = () => { e.abortSignal.throwIfAborted(); if (getXRuntime() !== t) throw new Error("X runtime was replaced"); }; if (!u || u.userId !== n.userId) await c.register(n.accountId, { userId: n.userId }, { assertCurrent }); const d = createChannelIngressMonitor({ queue: l, inspect: ({ post: e }) => ({ eventId: e.id, laneKey: e.conversation_id }), payload: { storage: "raw-event", version: 1, serialize: (e) => JSON.stringify(e), deserialize: (e) => { const t = parseXPostEnvelope(JSON.parse(e)); if (!t) throw new InvalidXEvent("Invalid stored X mention envelope"); return t; }, createClaimError: () => new InvalidXEvent("X mention identity changed after admission") }, pollIntervalMs: 1e3, retention: { completedMaxEntries: 2e3, completedTtlMs: 2592e6, failedMaxEntries: 1e3 }, abortSignal: e.abortSignal, deliver: async (c, l) => { let { post: u, users: d } = c; const dropMention = () => { publish({ droppedMentions: o.droppedMentions + 1, lastDroppedAuthor: u.author_id }); a.info(`mention post=${u.id} author=${u.author_id} dropped`); }; let f = r(); let p = await resolveXIngress(n.accountId, u, f); const m = p.ingress; if (u.author_id === n.userId || !m.senderAccess.allowed) { dropMention(); return; } if (c.recipientPending) for (;;) { f = r(); p = await resolveXIngress(n.accountId, u, f); if (u.author_id === n.userId || !p.ingress.senderAccess.allowed) { dropMention(); return; } try { const e = await resolveXRecipient({ api: i, post: u, users: d, userId: n.userId, signal: l.abortSignal }); if (!e) return; ({post: u, users: d} = e); break; } catch (e) { if (!(e instanceof XBudgetExceededError)) throw e; const t = setInterval(() => l.onDeferredHeartbeat?.(), l.deferredHeartbeatIntervalMs ?? 6e4); try { await waitForXBudgetReset(e.exhaustedUntil, l.abortSignal); } finally { clearInterval(t); } } } const admitGuest = async (e, i) => { const a = resolveXAccount(i, n.accountId); const c = resolveAgentRoute({ cfg: i, channel: "x", accountId: n.accountId, peer: { kind: "group", id: u.conversation_id } }); const d = resolveXGuestContainmentError(i, c.agentId); const assertGuestCurrent = () => { assertCurrent(); l.abortSignal.throwIfAborted(); e.assertCurrent(); if (i !== r()) throw new Error("X guest configuration changed during admission; retrying mention"); }; let f = false; let p = d; if (!p) try { f = await s.admit({ accountId: n.accountId, authorId: u.author_id, postId: u.id, limit: resolveXGuestSettings(a).maxMentionsPerAuthorPerDay, assertCurrent: assertGuestCurrent }); } catch (e) { if (!(e instanceof XGuestUsageUnavailableError)) throw e; p = e.message; } const m = await getXGuestStatus(t, a, i, c.agentId); assertGuestCurrent(); publish({ guests: m, guestModeBlockedReason: p, ...p ? { message: p } : {}, ...!f ? { droppedMentions: o.droppedMentions + 1, lastDroppedAuthor: u.author_id } : {} }); return f; }; const h = resolveXGuestSettings(resolveXAccount(f, n.accountId)); if (p.tier === "guest" && !await admitGuest(p, f)) return; const g = await assembleXThread({ api: i, mention: u, users: d, maxPosts: p.tier === "guest" ? h.threadContextMaxPosts : resolveXAccount(f, n.accountId).config.threadContext?.maxPosts ?? 50, signal: l.abortSignal }); f = r(); const _ = resolveAgentRoute({ cfg: f, channel: "x", accountId: n.accountId, peer: { kind: "group", id: u.conversation_id } }); const v = p.tier === "guest" ? `${_.sessionKey}:guest:${u.id}` : _.sessionKey; const y = p.tier === "maintainer" && resolveXAccount(f, n.accountId).config.autoPublishWorkSessions === true ? await openXAllowlist(t).readSnapshot(n.accountId, resolveXAccount(f, n.accountId).config.verifiedFromGitHub) : void 0; const b = y && await verifyPublicXThread(i, g.posts, l.abortSignal, u.conversation_id); const x = y && b ? { audience: "public", prepare: createXPublicationPreparation({ accountId: n.accountId, post: u, cfg: f, readConfig: r, route: _, assertActive: () => { l.abortSignal.throwIfAborted(); assertCurrent(); } }), assertCurrent: () => { l.abortSignal.throwIfAborted(); assertCurrent(); y.assertCurrent(); if (r() !== f) throw new Error("X work-session publication policy changed; send a new mention."); } } : void 0; const S = await resolveXIngress(n.accountId, u, f, { agentId: _.agentId, sessionKey: v, messageId: u.id, inboundEventKind: "user_request" }, x); const assertAdmissionCurrent = () => { assertCurrent(); l.abortSignal.throwIfAborted(); S.assertCurrent(); if (f !== r()) throw new Error("X routing configuration changed during admission; retrying mention"); }; const C = S.ingress; assertAdmissionCurrent(); if (!C.senderAccess.allowed) { dropMention(); return; } if (S.tier !== p.tier || S.tier === "guest" && h.threadContextMaxPosts !== resolveXGuestSettings(resolveXAccount(f, n.accountId)).threadContextMaxPosts) throw new XAllowlistChangedError(); const w = S.tier === "guest"; if (w && !await admitGuest(S, f)) return; const T = w ? "" : await buildXWorkSessionContext({ runtime: t, cfg: f, accountId: n.accountId, conversationId: u.conversation_id, requesterSessionKey: v }); const E = g.users.find((e) => e.id === u.author_id); const D = E?.username ?? u.author_id; const O = t.channel.inbound.buildContext({ channelIngress: C, access: { mentions: { ...xMentionFacts, requireMention: true, explicitlyMentionedBot: true } }, channel: "x", accountId: n.accountId, messageId: u.id, timestamp: u.created_at ? Date.parse(u.created_at) : void 0, from: `x:group:${u.conversation_id}`, sender: { id: u.author_id, name: `@${D}` }, conversation: { kind: "group", id: u.conversation_id, label: g.label }, route: { agentId: _.agentId, accountId: _.accountId, routeSessionKey: v }, reply: { to: `x:${u.id}`, replyToId: u.id }, message: { body: u.text, rawBody: u.text, commandBody: u.text, bodyForAgent: `${formatXSenderLine(S.tier, u.author_id, g.users.find((e) => e.id === u.author_id), S.github)}\n${g.bodyForAgent}${T ? `\n\n${T}` : ""}` } }); const k = []; const A = `https://x.com/${D}/status/${u.id}`; let j = "unclassified"; const withhold = async (e, t) => { const i = r(); const o = resolveXAccount(i, n.accountId).config.failureRoute; let s = " route=none"; if (o) { const n = ` route=${o.channel} result=`; const r = redactSensitiveText(t).replace(/\s+/gu, " ").trim(); const a = Array.from(r); const c = (a.length > SUMMARY_MAX_CHARS ? a.slice(0, SUMMARY_MAX_CHARS).join("") + "…" : r).replaceAll("@", "@​") || "(no text)"; const u = `X reply withheld (${REASON_LABELS[e]}) for @${D}: ${A}\n${c}`; let d; try { d = (await sendDurableMessageBatch({ cfg: i, channel: o.channel, to: o.to, ...o.accountId ? { accountId: o.accountId } : {}, payloads: [{ text: u }], signal: l.abortSignal })).status; } catch (e) { d = `failed: ${e instanceof Error ? e.message : "unknown error"}`; } s = `${n}${d}`; } a.info(`reply withheld post=${u.id} reason=${e}${s}`); }; a.info(`mention post=${u.id} author=${u.author_id} allowed`); assertAdmissionCurrent(); await t.channel.inbound.dispatch({ cfg: f, channel: "x", accountId: n.accountId, route: { agentId: _.agentId, sessionKey: v }, ctxPayload: O, ...bindIngressLifecycleToReplyOptions(l), replyOptions: { onVisibleWorkSessions: async (e, r) => { if (!w) { if (!E?.username) throw new Error("X work-session origin requires the author's handle; retry the mention."); const i = new Set(e.map((e) => e.sessionKey)); if (r) i.add(r.createdSessionKey); for (const e of i) await openXWorkOrigins(t).registerIfAbsent(e, { accountId: n.accountId, postId: u.id, postUrl: A, authorHandle: D, conversationId: u.conversation_id, senderTier: S.tier }); for (const t of e) if (!k.some((e) => e.sessionKey === t.sessionKey)) k.push(t); } } }, delivery: { preparePayload: async (e, t) => { if (t.kind !== "final") return null; const { outcome: n, text: r } = readXReplyOutcome(e.text ?? ""); if (e.isError || n === "failure") j = "failure"; else if (n === "success" && j !== "failure") j = "success"; if (e.isError) { await withhold("error", r); return null; } if (!Boolean(e.mediaUrl || e.mediaUrls?.length) && (!r || isSilentReplyText(r))) { a.info(`reply dropped post=${u.id} reason=${r ? "silent" : "empty"}`); return null; } if (j !== "success" && !e.isStatusNotice) { await withhold(j, r); return null; } return { ...e, text: r }; }, observeMessageSent: true, deliver: async (t) => { if (!t.text?.trim() && !t.mediaUrl && !t.mediaUrls?.length) return { visibleReplySent: false }; const i = r(); const a = await sendXDelivery({ cfg: i, accountId: n.accountId, to: `x:${u.id}`, text: t.text ?? "", mediaUrl: t.mediaUrl, mediaUrls: t.mediaUrls, mediaLocalRoots: getAgentScopedMediaLocalRoots(f, _.agentId), mediaAccess: resolveOutboundMediaAccessForConfig(i), mention: u, visibleWorkSessions: w ? void 0 : k, senderTier: S.tier, signal: l.abortSignal }); e.setStatus({ ...e.getStatus(), lastOutboundAt: Date.now() }); return { visibleReplySent: true, content: a.content, receipt: a.receipt }; } } }); }, onError: () => { a.warn("X ingress failed; pending mentions will retry"); }, drain: { resolveNonRetryableFailure: (e) => e instanceof InvalidXEvent ? { reason: "invalid-event", message: e.message } : null } }); const f = r(); o.guests = await getXGuestStatus(t, resolveXAccount(f, n.accountId), f); d.start(); e.setStatus({ ...e.getStatus(), running: true, lifecycle: "ready" }); publish(); let p = false; const publishSpend = async () => { try { const e = await i.spend.status(); if (!p) publish({ spend: e }); } catch { if (!p) publish({ message: "X spend accounting unavailable; paid requests paused" }); } }; const m = i.spend.subscribe(() => { publishSpend(); }); try { await publishSpend(); await runXEvents({ api: i, userId: n.userId, mode: n.config.events?.mode ?? "auto", pollSeconds: n.config.events?.pollSeconds ?? 60, bearerConfigured: Boolean(n.config.bearerToken), signal: e.abortSignal, onStatus: publish, onWarning: (e) => a.warn(e), getCursor: async () => await c.lookup(n.accountId) ?? {}, setCursor: async (e) => { await c.register(n.accountId, { ...e, userId: n.userId }, { assertCurrent }); }, onPost: async (e) => { await d.admit(e); } }); } finally { p = true; m(); await d.stop(); e.setStatus({ ...e.getStatus(), running: false, connected: false, lifecycle: "stopped" }); } } //#endregion export { startXAccount };