UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,076 lines (1,075 loc) • 34.6 kB
import { s as __toESM } from "./rolldown-runtime-C_OpTf0N.mjs"; import { l as asNonNegativeFiniteNumber } from "./number-coercion-D6u-4YD8.mjs"; import { a as resolveGlobalSingleton, r as resolveGlobalMap } from "./global-singleton-D7yf05nR.mjs"; import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs"; import { v as resolveSecretInputString } from "./types.secrets-BmNLLnHp.mjs"; import { d as sleepWithAbort, o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs"; import { n as materializeErrorStack } from "./error-graph-internal-DdjdM90N.mjs"; import { n as createRuntimeConfigReader } from "./runtime-snapshot-WbwbY5b7.mjs"; import { i as readOAuthRefreshErrorReason, n as createOAuthRefreshResponseError, r as isRecoverableOAuthRefreshFailure, t as createOAuthRefreshError } from "./oauth-refresh-outcome-DGKa-Dzy.mjs"; import { i as readResponseWithLimit } from "./http-response-body-B-i_0116.mjs"; import "./provider-oauth-runtime-C_hG37Q1.mjs"; import "./string-coerce-runtime-BwAZZDf5.mjs"; import "./runtime-config-snapshot-Dy0VFqWf.mjs"; import "./retry-runtime-DOUvdfOa.mjs"; import "./number-runtime-W4chuk8B.mjs"; import "./time-runtime-DoAwjF0T.mjs"; import { r as PlatformMessageNotDispatchedError } from "./deliver-types-BnSKrpHG.mjs"; import "./error-runtime-BM740gJj.mjs"; import "./response-limit-runtime-DkiFHsEX.mjs"; import { t as LinkifyIt } from "./build-DFq1Ushr.mjs"; import { t as bufferToBlobPart } from "./blob-runtime-QF_Wblu0.mjs"; import "./secret-input-CpgOwFAi.mjs"; import { t as require_tlds } from "./tlds-BwaXZDt3.mjs"; import { i as resolveXAccount } from "./accounts-Bg4ihS1J.mjs"; import { t as getXRuntime } from "./runtime-SL1x_YwB.mjs"; import { createHash, randomUUID } from "node:crypto"; import { isDeepStrictEqual } from "node:util"; //#region extensions/x/src/fetch.ts async function fetchXService(e, t, n, r, i) { const a = `https://${e}${t}`; const authorize = (e) => async (t, n) => { const a = await r?.(); n?.signal?.throwIfAborted(); a?.(); i?.(); return e(t, n); }; const [{ fetchWithSsrFGuard: o }, { responseWithRelease: s }, { fetchWithRuntimeDispatcher: c }] = await Promise.all([ import("./plugin-sdk/ssrf-runtime.js"), import("./plugin-sdk/fetch-runtime.js"), import("./plugin-sdk/runtime-fetch.js") ]); const l = await o({ url: a, init: n, capture: false, requireHttps: true, policy: { hostnameAllowlist: [e] }, maxRedirects: 0, fetchImpl: authorize(c) }); return s(l.response, l.release); } //#endregion //#region extensions/x/src/media-api.ts const CHUNK_BYTES = 4194304; const PROCESSING_TIMEOUT_MS = 3e5; function mediaError(e, t = false) { return new PlatformMessageNotDispatchedError(e, { cause: void 0, retryable: t }); } async function readUploadResponse(e, t = false) { const n = await e.text(); if (t && !n.trim()) return; let r; try { r = JSON.parse(n); } catch { throw mediaError("X media upload returned an unreadable response; no Post was created"); } const i = asOptionalRecord(r); if (!i || Array.isArray(i.errors) && i.errors.length) throw mediaError("X media upload was not accepted; no Post was created"); return asOptionalRecord(i.data); } async function uploadXMedia(e, t) { const send = (n, r, i) => t(n, { method: r, body: i, signal: e.signal, assertActive: e.assertActive }); const n = (await readUploadResponse(await send("/2/media/upload/initialize", "POST", { media_type: e.contentType, total_bytes: e.buffer.length, media_category: e.mediaCategory })))?.id; if (typeof n !== "string" || !/^[0-9]{1,19}$/.test(n)) throw mediaError("X media upload returned no valid media ID; no Post was created"); const r = "/2/media/upload/" + n; for (let t = 0, n = 0; t < e.buffer.length; t += CHUNK_BYTES, n++) { e.signal?.throwIfAborted(); const i = new FormData(); i.set("segment_index", String(n)); i.set("media", new Blob([bufferToBlobPart(e.buffer.subarray(t, t + CHUNK_BYTES))], { type: e.contentType }), e.fileName); await readUploadResponse(await send(r + "/append", "POST", i), true); } let i = await readUploadResponse(await send(r + "/finalize", "POST")); const a = performance.now() + PROCESSING_TIMEOUT_MS; let o = false; for (;;) { e.signal?.throwIfAborted(); if (i?.id !== n) throw mediaError("X media upload returned an invalid media result; no Post was created"); if (i.processing_info === void 0 && !o) return n; const t = asOptionalRecord(i.processing_info); if (t?.state === "succeeded") return n; if (t?.state === "failed") throw mediaError("X media processing failed; check the file format and encoding before retrying"); if (t?.state !== "pending" && t?.state !== "in_progress") throw mediaError("X media upload returned an invalid processing state; no Post was created"); const r = Math.max(1, asNonNegativeFiniteNumber(t.check_after_secs) ?? 1) * 1e3; if (performance.now() + r >= a) throw mediaError("X media processing timed out before posting; try again later", true); await sleepWithAbort(r, e.signal); e.signal?.throwIfAborted(); if (performance.now() >= a) throw mediaError("X media processing timed out before posting; try again later", true); i = await readUploadResponse(await send("/2/media/upload?command=STATUS&media_id=" + n, "GET")); o = true; } } //#endregion //#region extensions/x/src/oauth.ts const failureMessage = "X token refresh failed; check the account credentials and token storage"; function unknownFailure() { return createOAuthRefreshError(failureMessage, { version: 1, phase: "after-token-response", outcome: "unknown" }); } async function exchange(e, t) { const n = AbortSignal.timeout(3e4); let r = false; let i; try { i = await fetchXService("api.x.com", "/2/oauth2/token", { method: "POST", redirect: "error", headers: { Authorization: "Basic " + Buffer.from(encodeURIComponent(e.clientId) + ":" + encodeURIComponent(e.clientSecret)).toString("base64"), "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: t }).toString(), signal: n }, () => e.assertCurrent, () => { r = true; }); } catch { throw createOAuthRefreshError(failureMessage, r ? { version: 1, phase: "token-response", outcome: "unknown" } : { version: 1, phase: "before-dispatch", outcome: "not-attempted", recovery: { kind: "later", evidence: "dispatch-not-started" } }); } let a; try { const e = await readResponseWithLimit(i, 262144, { signal: n, timeoutMs: 3e4 }); a = asOptionalRecord(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(e))); } catch { throw unknownFailure(); } if (!i.ok || readOAuthRefreshErrorReason(a)) throw createOAuthRefreshResponseError("X token refresh", i.status, a); if (!a || typeof a.access_token !== "string" || !a.access_token.trim() || a.refresh_token !== void 0 && (typeof a.refresh_token !== "string" || !a.refresh_token.trim()) || a.token_type !== void 0 && (typeof a.token_type !== "string" || a.token_type.toLowerCase() !== "bearer") || a.expires_in !== void 0 && (typeof a.expires_in !== "number" || !Number.isFinite(a.expires_in) || a.expires_in < 0)) throw unknownFailure(); const o = Date.now() + (typeof a.expires_in === "number" ? Math.max(0, a.expires_in - 30) : 7170) * 1e3; if (!Number.isSafeInteger(Math.ceil(o))) throw unknownFailure(); return { accessToken: a.access_token, refreshToken: typeof a.refresh_token === "string" ? a.refresh_token : t, expiresAt: o }; } /** One in-flight owner; request cancellation detaches the caller, not this exchange. */ function createXOAuthAccess(e) { let t; let n = 0; let r = e.refreshToken; let i = false; let a; let o; async function refresh() { let o; e.onTokenState?.("refreshing"); try { let s; if (a) { s = a.token; await a.claim.commit(s.refreshToken); } else { if (i) throw unknownFailure(); const t = await e.claimRefreshToken(); r = t.refreshToken; i = true; try { s = await exchange(e, r); } catch (e) { if (isRecoverableOAuthRefreshFailure(e)) { await t.restore(); i = false; } o = e; throw e; } r = s.refreshToken; a = { token: s, claim: t }; await t.commit(r); } a = void 0; i = false; e.assertCurrent?.(); t = s.accessToken; n = s.expiresAt; e.onTokenState?.("ready"); } catch (n) { t = void 0; e.onTokenState?.("error"); if (n === o) throw n; throw unknownFailure(); } } return { async ensure(r) { r?.throwIfAborted(); e.assertCurrent?.(); if (!t || Date.now() >= n) { o ??= refresh().finally(() => { o = void 0; }); await racePromiseWithAbortSignal(o, r); } e.assertCurrent?.(); return t; }, invalidate(e) { if (t === e) t = void 0; }, currentRefreshToken: () => r }; } //#endregion //#region extensions/x/src/urls.ts var import_tlds = /* @__PURE__ */ __toESM(require_tlds(), 1); const links = new LinkifyIt({ fuzzyLink: true, tlds: import_tlds.default }); function findXUrls(e) { return (links.match(e) ?? []).filter((e) => !e.schema || [ "http:", "https:", "//" ].includes(e.schema)); } //#endregion //#region extensions/x/src/pricing.ts const X_POST_READ_MICRO_USD = 5e3; const X_USER_READ_MICRO_USD = 1e4; const X_POST_EVENT_MICRO_USD = 5e3; const X_REPLY_MICRO_USD = 15e3; const X_LINK_REPLY_MICRO_USD = 2e5; function xReplyCost(e) { return findXUrls(e).length ? X_LINK_REPLY_MICRO_USD : X_REPLY_MICRO_USD; } function xReadCost(e, t) { const n = asOptionalRecord(e); const r = asOptionalRecord(n?.includes); const count = (e) => Array.isArray(e) ? e.length : asOptionalRecord(e) ? 1 : 0; return count(n?.data) * (t === "posts" ? X_POST_READ_MICRO_USD : X_USER_READ_MICRO_USD) + count(r?.tweets) * X_POST_READ_MICRO_USD + count(r?.users) * X_USER_READ_MICRO_USD; } function xActivityCost(e) { const t = asOptionalRecord(asOptionalRecord(e)?.data); return (typeof t?.event_type === "string" && t.event_type.startsWith("post.") ? X_POST_EVENT_MICRO_USD : 0) + xReadCost({ includes: t?.includes }, "posts"); } //#endregion //#region extensions/x/src/spend.ts const X_STREAM_HEADROOM_MICRO_USD = 5e5; const MICRO_USD = 1e6; const RETENTION_MS = 6048e6; const XBudgetExceededError = resolveGlobalSingleton(Symbol.for("openclaw.x.budget-exceeded-error"), () => class extends Error { constructor(e, t) { super(e); this.exhaustedUntil = t; this.name = "XBudgetExceededError"; } }); const owners = resolveGlobalMap(Symbol.for("openclaw.x.spend"), async (e) => { await Promise.all([...e.values()].map((e) => e.close())); e.clear(); }, "close-and-restart"); function periodAt(e, t) { const n = new Date(e); const r = n.getUTCFullYear(); const i = n.getUTCMonth(); const a = n.getUTCDate() < t ? i - 1 : i; return { day: n.toISOString().slice(0, 10), cycle: new Date(Date.UTC(r, a, t)).toISOString().slice(0, 10), dayEnd: Date.UTC(r, i, n.getUTCDate() + 1), cycleEnd: Date.UTC(r, a + 1, t) }; } function checkedAmount(e) { if (!Number.isSafeInteger(e) || e < 0) throw new Error("X spend must be a nonnegative safe integer in micro-dollars"); return e; } function createSpendOwner(e, t, n) { const r = `${encodeURIComponent(t)}:`; const openStore = (e) => e.state.openKeyedStore({ namespace: "x.spend", maxEntries: 2e5, overflowPolicy: "reject-new", defaultTtlMs: RETENTION_MS }); let i = openStore(e); let a = e.state; let o = e.logging.getChildLogger({ channel: "x", accountId: t }); let s = n; let c = Promise.resolve(); let l = false; let u; let d = 0; let f; let p; const m = /* @__PURE__ */ new Map(); const h = /* @__PURE__ */ new Set(); const notify = () => { for (const e of h) e(); }; const serialized = (e) => { const t = c.then(async () => { if (u) throw u; try { return await e(); } catch (e) { if (!(e instanceof XBudgetExceededError)) { u = new Error("X spend accounting unavailable; paid requests paused", { cause: e }); materializeErrorStack(u); notify(); } throw e; } }); c = t.catch(() => void 0); return t; }; const bucketKey = (e, t) => `${r}${e}:${t}`; const read = async (e, t) => checkedAmount(await i.lookup(bucketKey(e, t)) ?? 0); const add = async (e, t, n) => { if (n) await i.register(bucketKey(e, t), checkedAmount(await read(e, t) + n)); }; const finish = async (e, t) => { const n = periodAt(Date.now(), s().cycleStartDay); for (const r of /* @__PURE__ */ new Set([e.day, n.day])) await add("day", r, t); for (const r of /* @__PURE__ */ new Set([e.cycle, n.cycle])) await add("cycle", r, t); if (e.day !== n.day && t) { const a = `${r}overlap:${e.day}:${n.day}`; await i.register(a, checkedAmount(checkedAmount(await i.lookup(a) ?? 0) + t)); } await i.delete(e.key); m.delete(e.key); }; const initialize = async () => { if (l) return; const e = `${r}pending:`; for (const t of await i.entries()) { if (!t.key.startsWith(e)) continue; const [n, r] = t.key.slice(e.length).split(":"); if (!n || !r || !/^\d{4}-\d{2}-\d{2}$/.test(n) || !/^\d{4}-\d{2}-\d{2}$/.test(r)) throw new Error("Invalid persisted X spend reservation"); const i = { key: t.key, amount: checkedAmount(t.value), day: n, cycle: r }; await finish(i, i.amount); } l = true; }; const snapshot = async () => { await initialize(); const e = s(); const t = periodAt(Date.now(), e.cycleStartDay); if (p !== t.cycle) { const e = `${r}day:`; const n = `${r}overlap:`; const inCycle = (e) => e >= t.cycle && e <= t.day; let a = 0; let o = 0; for (const t of await i.entries()) if (t.key.startsWith(e)) { if (inCycle(t.key.slice(e.length))) a = checkedAmount(a + checkedAmount(t.value)); } else if (t.key.startsWith(n)) { const [e, r] = t.key.slice(n.length).split(":"); if (e && r && inCycle(e) && inCycle(r)) o = checkedAmount(o + checkedAmount(t.value)); } const s = checkedAmount(a - o); if (s > await read("cycle", t.cycle)) await i.register(bucketKey("cycle", t.cycle), s); p = t.cycle; } const n = [...m.values()].reduce((e, t) => checkedAmount(e + t.amount), 0); return { config: e, period: t, held: n, day: checkedAmount(await read("day", t.day) + n), cycle: checkedAmount(await read("cycle", t.cycle) + n), dailyLimit: Math.floor(e.dailyUsd * MICRO_USD), monthlyLimit: Math.floor(e.monthlyUsd * MICRO_USD) }; }; const refusal = (e, t, n = false) => { const r = n ? e.day + t > e.dailyLimit : e.day + t >= e.dailyLimit; const i = n ? e.cycle + t > e.monthlyLimit : e.cycle + t >= e.monthlyLimit; if (!r && !i) return; const a = Math.max(r ? e.period.dayEnd : 0, i ? e.period.cycleEnd : 0); const o = i ? `billing-cycle budget of $${e.config.monthlyUsd}` : `daily budget of $${e.config.dailyUsd}`; return new XBudgetExceededError(`X API ${o} reached; resumes at ${new Date(a).toISOString().replace(":00.000Z", "Z")}`, a); }; const updateNotice = (e) => { const t = refusal(e, d, d > 0); const n = d ? t : refusal({ ...e, day: e.day - e.held, cycle: e.cycle - e.held }, 0); if (f !== void 0 && (Date.now() >= f || !n)) { o.info("X API budget reset; paid requests may resume"); f = void 0; } if (!t) d = 0; else if (n && f === void 0) { f = n.exhaustedUntil; o.warn(n.message); } return t; }; const reserve = async (e, t, n) => { checkedAmount(e); const a = await snapshot(); updateNotice(a); const o = e ? refusal(a, e, true) : void 0; if (t && o) { d = Math.max(d, e); updateNotice(a); throw o; } const s = n === void 0 ? a.period : periodAt(n, a.config.cycleStartDay); const c = { key: `${r}pending:${s.day}:${s.cycle}:${randomUUID()}`, amount: e, day: s.day, cycle: s.cycle }; await i.register(c.key, e); m.set(c.key, c); notify(); return c; }; return { api: { async reserve(e) { const t = await serialized(() => reserve(e, true)); let n = false; return { settle: (e) => serialized(async () => { if (n) return; checkedAmount(e); n = true; await finish(t, e); updateNotice(await snapshot()); notify(); }) }; }, charge: (e) => { const t = Date.now(); return serialized(async () => { const n = await reserve(e, false, t); await finish(n, e); updateNotice(await snapshot()); notify(); }); }, status: () => serialized(async () => { const e = await snapshot(); const t = updateNotice(e); const dollars = (e) => Math.round(e / 1e4) / 100; return { dayUsd: dollars(e.day), cycleUsd: dollars(e.cycle), dailyLimitUsd: dollars(e.dailyLimit), monthlyLimitUsd: dollars(e.monthlyLimit), cycleStart: e.period.cycle, ...t ? { exhaustedUntil: new Date(t.exhaustedUntil).toISOString() } : {} }; }), streamResumeAt: () => serialized(async () => { const e = await snapshot(); updateNotice(e); return refusal(e, X_STREAM_HEADROOM_MICRO_USD, true)?.exhaustedUntil; }), subscribe(e) { h.add(e); return () => { h.delete(e); }; } }, failed: () => u !== void 0, update(e, n) { s = n; o = e.logging.getChildLogger({ channel: "x", accountId: t }); if (a !== e.state) { i = openStore(e); a = e.state; } }, async close() { u = /* @__PURE__ */ new Error("X spend owner closed; pending reservations retained for recovery"); materializeErrorStack(u); await c; } }; } function openXSpend(e, t, n) { const r = JSON.stringify([e.state.resolveStateDir(), t]); let i = owners.get(r); if (!i || i.failed()) { i = createSpendOwner(e, t, n); owners.set(r, i); } else i.update(e, n); return i.api; } //#endregion //#region extensions/x/src/api.ts const POST_FIELDS = "author_id,conversation_id,created_at,in_reply_to_user_id,referenced_tweets,entities,withheld"; var XApiError = class extends Error { constructor(e, t, n) { super(`X API ${t} failed (HTTP ${e})${n ? `: ${n}` : ""}`); this.status = e; this.operation = t; this.name = "XApiError"; } }; async function readErrorDetail(e, t, n) { try { const { readResponseWithLimit: r } = await import("./plugin-sdk/response-limit-runtime.js"); const i = asOptionalRecord(JSON.parse((await r(e, 16384, { signal: t, timeoutMs: 3e4 })).toString())); const a = asOptionalRecord(Array.isArray(i?.errors) ? i.errors[0] : void 0); let o = [ a?.message, a?.detail, a?.title, i?.detail, i?.message, i?.title ].find((e) => typeof e === "string" && Boolean(e.trim())); if (!o) return; for (const e of n.filter((e) => Boolean(e)).toSorted((e, t) => t.length - e.length)) o = o.replaceAll(e, "[redacted]"); return o.replace(/\s+/g, " ").trim().slice(0, 512); } catch { return; } } async function readJson(e) { try { return await e.json(); } catch { throw new Error("X API returned an unreadable JSON response"); } } function parseXPost(e) { const t = asOptionalRecord(e); if (!t || typeof t.id !== "string" || !/^\d+$/.test(t.id) || typeof t.text !== "string" || typeof t.author_id !== "string" || !/^\d+$/.test(t.author_id) || typeof t.conversation_id !== "string" || !/^\d+$/.test(t.conversation_id)) return; const n = []; for (const e of Array.isArray(t.referenced_tweets) ? t.referenced_tweets : []) { const t = asOptionalRecord(e); if (t && typeof t.id === "string" && /^\d+$/.test(t.id) && (t.type === "replied_to" || t.type === "quoted" || t.type === "retweeted")) n.push({ id: t.id, type: t.type }); } const r = asOptionalRecord(t.entities); const i = []; for (const e of Array.isArray(r?.mentions) ? r.mentions : []) { const t = asOptionalRecord(e); if (t && typeof t.username === "string") i.push({ username: t.username, ...typeof t.id === "string" ? { id: t.id } : {} }); } return { id: t.id, text: t.text, author_id: t.author_id, conversation_id: t.conversation_id, ...t.withheld !== void 0 ? { withheld: true } : {}, ...typeof t.created_at === "string" ? { created_at: t.created_at } : {}, ...typeof t.in_reply_to_user_id === "string" ? { in_reply_to_user_id: t.in_reply_to_user_id } : {}, ...n.length ? { referenced_tweets: n } : {}, ...r ? { entities: Array.isArray(r.mentions) ? { mentions: i } : {} } : {} }; } function parseUser(e) { const t = asOptionalRecord(e); return t && typeof t.id === "string" && /^\d+$/.test(t.id) && typeof t.username === "string" ? { id: t.id, username: t.username, ...typeof t.protected === "boolean" ? { protected: t.protected } : {}, ...typeof t.name === "string" ? { name: t.name } : {} } : void 0; } function parseXPostEnvelope(e) { const t = asOptionalRecord(e); const n = parseXPost(t?.post); return n ? { post: n, users: (Array.isArray(t?.users) ? t.users : []).flatMap((e) => parseUser(e) ?? []), ...t?.recipientPending === true ? { recipientPending: true } : {} } : void 0; } function parsePage(e) { const t = asOptionalRecord(e); if (!t || t.data !== void 0 && !Array.isArray(t.data)) throw new Error("X API returned an invalid post page"); const n = (t.data ?? []).map((e) => { const t = parseXPost(e); if (!t) throw new Error("X API returned an invalid post"); return t; }); const r = asOptionalRecord(t.includes); const i = asOptionalRecord(t.meta); return { data: n, includes: { users: (Array.isArray(r?.users) ? r.users : []).flatMap((e) => parseUser(e) ?? []), tweets: (Array.isArray(r?.tweets) ? r.tweets : []).flatMap((e) => parseXPost(e) ?? []) }, meta: { ...typeof i?.newest_id === "string" ? { newest_id: i.newest_id } : {}, ...typeof i?.next_token === "string" ? { next_token: i.next_token } : {} } }; } function createXApiClient(e) { let t; const n = createXOAuthAccess(e); function requestSignal(e) { const t = AbortSignal.timeout(3e4); return e ? AbortSignal.any([e, t]) : t; } async function request(r, i = {}) { for (let a = 0; a < 2; a++) { const o = i.billing ? await e.spend.reserve(i.billing.maximum) : void 0; let s = 0; try { if (!i.appOnly) t = await n.ensure(i.signal); const o = i.appOnly ? e.bearerToken : t; if (!o) throw new Error("X Activity API requires a bearer token"); const c = i.stream ? i.signal ?? AbortSignal.any([]) : requestSignal(i.signal); c.throwIfAborted(); const l = i.body instanceof FormData ? i.body : i.body ? JSON.stringify(i.body) : void 0; const u = l instanceof FormData; let d; let f = false; let p; try { d = await fetchXService("api.x.com", r, { method: i.method ?? "GET", redirect: "error", headers: { Authorization: `Bearer ${o}`, ...i.body && !u ? { "Content-Type": "application/json" } : {} }, ...l ? { body: l } : {}, signal: c }, i.assertActive || e.assertCurrent ? async () => { try { const t = await i.assertActive?.(); return () => { try { t?.(); e.assertCurrent?.(); } catch (e) { f = true; p = e; throw e; } }; } catch (e) { f = true; p = e; throw e; } } : void 0, () => { s = i.billing?.maximum ?? 0; i.onDispatch?.(); }); } catch { if (f) throw p; c.throwIfAborted(); throw new Error("X API network request failed"); } if (d.status >= 400 && d.status < 500) { s = 0; if (i.billing) { const e = await readJson(d).catch(() => void 0); s = i.billing.actual(e); } } if (d.status === 401) { i.onAuthenticationRejected?.(); if (!i.appOnly && a === 0) { await d.body?.cancel().catch(() => {}); if (t === o) { n.invalidate(o); t = void 0; } continue; } } if (!d.ok) { let i; if (r.startsWith("/2/activity/") || r.startsWith("/2/media/")) i = await readErrorDetail(d, c, [ o, t, e.bearerToken, n.currentRefreshToken(), e.refreshToken, e.clientSecret ]); else await d.body?.cancel().catch(() => {}); if (r.startsWith("/2/media/") && (d.status === 401 || d.status === 403)) i = `${i ? `${i}; ` : ""}check the app permissions and reauthorize the X account with the media.write scope`; throw new XApiError(d.status, r.split("?")[0] ?? r, i); } if (!i.billing) return d; const m = await readJson(d); const h = i.billing.parse(m); s = i.billing.actual(m); return h; } finally { await o?.settle(s); } } throw new Error("X user token was rejected after refresh"); } async function page(e, t, n, r, i = false) { const a = new URLSearchParams({ "tweet.fields": POST_FIELDS, expansions: "author_id", "user.fields": "username,name,protected" }); for (const [e, n] of Object.entries(t)) if (n !== void 0) a.set(e, n); return request(`${e}?${a}`, { signal: r, appOnly: i, billing: { maximum: n * (X_POST_READ_MICRO_USD + X_USER_READ_MICRO_USD), actual: (e) => xReadCost(e, "posts"), parse: parsePage } }); } return { get spend() { return e.spend; }, getMentions: (e) => page(`/2/users/${encodeURIComponent(e.userId)}/mentions`, { since_id: e.sinceId, pagination_token: e.paginationToken, max_results: "10" }, 10, e.signal), getPosts: (e, t) => { if (!e.length || e.length > 100) throw new Error("X post lookup requires 1–100 post ids"); return page("/2/tweets", { ids: e.join(",") }, e.length, t); }, getPublicPosts: (t, n) => { if (!e.bearerToken || !t.length || t.length > 100) throw new Error("Public X lookup requires an app-only bearer token and 1–100 post ids"); return page("/2/tweets", { ids: t.join(",") }, t.length, n, true); }, searchConversation: (e) => page("/2/tweets/search/recent", { query: `conversation_id:${e.conversationId}`, next_token: e.nextToken, max_results: String(Math.max(10, Math.min(Math.floor(e.maxPosts), 100))), sort_order: "recency" }, Math.max(10, Math.min(Math.floor(e.maxPosts), 100)), e.signal), async getUsersByUsernames(e, t, n) { const r = e.map((e) => e.replace(/^@/, "")); if (!r.length || r.length > 100 || r.some((e) => !/^[A-Za-z0-9_]{1,15}$/.test(e))) throw new Error("X user lookup requires 1–100 valid usernames"); return request(`/2/users/by?${new URLSearchParams({ usernames: r.join(","), "user.fields": "id,username,name" })}`, { signal: t, assertActive: n, billing: { maximum: r.length * X_USER_READ_MICRO_USD, actual: (e) => xReadCost(e, "users"), parse: (e) => { const t = asOptionalRecord(e); if (!t || t.data !== void 0 && !Array.isArray(t.data)) throw new Error("X API returned an invalid users response"); return (t.data ?? []).map((e) => { const t = parseUser(e); if (!t || !/^[A-Za-z0-9_]{1,15}$/.test(t.username)) throw new Error("X API returned an invalid user"); return t; }); } } }); }, async getUserByUsername(e, t, n) { const r = await request(`/2/users/by/username/${encodeURIComponent(e.replace(/^@/, ""))}?user.fields=id,username,name`, { signal: t, assertActive: n, billing: { maximum: X_USER_READ_MICRO_USD, actual: (e) => xReadCost(e, "users"), parse: (e) => { const t = asOptionalRecord(e); if (!t) throw new Error("X API returned an invalid user response"); if (t.data === void 0) return; const n = parseUser(t.data); if (!n) throw new Error("X API returned no matching user"); return n; } } }); if (!r) throw new Error("X API returned no matching user"); return r; }, async uploadMedia(e) { try { e.signal?.throwIfAborted(); return await uploadXMedia(e, request); } catch (t) { if (t instanceof PlatformMessageNotDispatchedError) throw t; throw new PlatformMessageNotDispatchedError(t instanceof Error ? t.message : "X media upload failed before posting", { cause: t, retryable: !e.signal?.aborted && !(t instanceof XBudgetExceededError) && (!(t instanceof XApiError) || t.status === 429 || t.status >= 500) }); } }, async reply(e) { let t = false; try { e.signal?.throwIfAborted(); return await request("/2/tweets", { billing: { maximum: xReplyCost(e.text), actual: (t) => asOptionalRecord(asOptionalRecord(t)?.data)?.id ? xReplyCost(e.text) : 0, parse: (e) => { const t = asOptionalRecord(asOptionalRecord(e)?.data)?.id; if (typeof t !== "string" || !/^\d+$/.test(t)) throw new Error("X API returned no reply id; delivery outcome is unknown"); return t; } }, method: "POST", body: { ...e.text ? { text: e.text } : {}, reply: { in_reply_to_tweet_id: e.inReplyToId }, ...e.mediaIds?.length ? { media: { media_ids: e.mediaIds } } : {} }, signal: e.signal, assertActive: e.assertActive, onDispatch: () => { t = true; }, onAuthenticationRejected: () => { t = false; } }); } catch (n) { if (n instanceof PlatformMessageNotDispatchedError) throw n; if (n instanceof XBudgetExceededError) throw new PlatformMessageNotDispatchedError(n.message, { cause: n, retryable: false }); if (n instanceof XApiError && n.status < 500) throw new PlatformMessageNotDispatchedError(n.message, { cause: n, retryable: n.status === 429 }); if (t) throw n; throw new PlatformMessageNotDispatchedError(n instanceof Error ? n.message : "X reply failed before dispatch", { cause: n, retryable: !e.signal?.aborted }); } }, async ensureActivitySubscriptions(e, t) { const n = await request("/2/activity/subscriptions", { appOnly: true, signal: t }); const r = asOptionalRecord(await readJson(n))?.data; if ((Array.isArray(r) ? r : []).some((t) => { const n = asOptionalRecord(t); return n?.event_type === "post.mention.create" && asOptionalRecord(n.filter)?.user_id === e; })) return; await (await request("/2/activity/subscriptions", { method: "POST", body: { event_type: "post.mention.create", filter: { user_id: e } }, appOnly: false, signal: t })).body?.cancel(); }, openActivityStream: (e) => request("/2/activity/stream", { appOnly: true, stream: true, signal: e }) }; } //#endregion //#region extensions/x/src/client.ts const clients = /* @__PURE__ */ new WeakMap(); function getXTokenState(e) { return clients.get(getXRuntime())?.get(e)?.tokenState ?? "idle"; } async function getXApi(e, t) { const n = getXRuntime(); const r = resolveXAccount(t, e); if (!r.enabled || !r.configured) throw new Error("X account is disabled or incomplete; configure userId, username, clientId, clientSecret and refreshToken."); const secret = (n) => resolveSecretInputString({ value: r.config[n], defaults: t.secrets?.defaults, path: `channels.x.accounts.${e}.${n}`, mode: "strict" }).value; const i = secret("clientSecret"); const a = secret("refreshToken"); const o = secret("bearerToken"); const s = createHash("sha256").update(JSON.stringify([ r.userId, r.config.clientId, a ])).digest("hex"); let c = clients.get(n); if (!c) { c = /* @__PURE__ */ new Map(); clients.set(n, c); } const l = createRuntimeConfigReader(t); const u = openXSpend(n, e, () => resolveXAccount(l(), e).costLimits); const d = c.get(e); if (d?.lineageFingerprint === s) { d.options.clientSecret = i; d.options.bearerToken = o; d.options.spend = u; return d.api; } const f = c; const assertCurrent = () => { const t = n.config.current({ clone: true }); const r = resolveXAccount(t, e); const i = resolveSecretInputString({ value: r.config.refreshToken, defaults: t.secrets?.defaults, path: `channels.x.accounts.${e}.refreshToken`, mode: "strict" }).value; const a = createHash("sha256").update(JSON.stringify([ r.userId, r.config.clientId, i ])).digest("hex"); if (getXRuntime() !== n || f.get(e) !== m || !r.enabled || !r.configured || a !== s) throw new Error("X account was replaced during token refresh"); }; const p = { spend: u, clientId: r.config.clientId, clientSecret: i, refreshToken: a, bearerToken: o, assertCurrent, claimRefreshToken: async () => { let t = await h.observe(e); if (t.value?.lineageFingerprint !== s) { const n = await h.compareAndApply(e, t.comparison, { operation: "update", action: "set", value: { lineageFingerprint: s, refreshToken: a } }); t = n.status === "conflict" ? n.current : await h.observe(e); } const n = t.value; if (!n || n.lineageFingerprint !== s || !("refreshToken" in n)) throw new Error("X token refresh is pending or uncertain; reauthorize this account"); const r = randomUUID(); const i = { lineageFingerprint: s, claim: r }; if ((await h.compareAndApply(e, t.comparison, { operation: "update", action: "set", value: i })).status !== "applied") throw new Error("X OAuth owner changed before refresh"); const settle = async (t) => { const n = await h.observe(e); if (isDeepStrictEqual(n.value, t)) { assertCurrent(); return; } if (!isDeepStrictEqual(n.value, i)) throw new Error("X OAuth owner changed before settlement"); if ((await h.compareAndApply(e, n.comparison, { operation: "update", action: "set", value: t })).status !== "applied") throw new Error("X OAuth owner changed before settlement"); assertCurrent(); }; return { refreshToken: n.refreshToken, commit: async (e) => { await settle({ lineageFingerprint: s, refreshToken: e, settledClaim: r }); }, restore: async () => { await settle(n); } }; }, onTokenState: (e) => { m.tokenState = e; } }; const m = { lineageFingerprint: s, options: p, tokenState: "idle", api: createXApiClient(p) }; c.set(e, m); let h; try { h = n.state.openKeyedStoreV2({ namespace: "x.oauth", maxEntries: 1e3, overflowPolicy: "reject-new" }, { assertCurrent }); } catch (t) { if (d) f.set(e, d); else f.delete(e); throw t; } return m.api; } //#endregion export { XBudgetExceededError as a, findXUrls as c, parseXPostEnvelope as i, fetchXService as l, getXTokenState as n, openXSpend as o, XApiError as r, xActivityCost as s, getXApi as t };