openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
236 lines (235 loc) • 8.72 kB
JavaScript
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs";
import { n as isProviderLoginPatchPersisted, t as decideProviderLoginSessionAdoption } from "./auth-profile-override-provenance-B7WULxR7.mjs";
import { p as formatProviderLoginCommand } from "./oauth-refresh-failure-DxrQiYzV.mjs";
import { t as escapeHtml } from "./html-escape-BB_nPhWX.mjs";
import { t as danger } from "./globals-CgepmiqE.mjs";
import { i as resolveCommandAuthorization } from "./command-auth-CC1Z19Eh.mjs";
import "./string-coerce-runtime-BwAZZDf5.mjs";
import "./runtime-config-snapshot-Dy0VFqWf.mjs";
import { a as createDeferred } from "./extension-shared-CJ4teJ7p.mjs";
import "./text-utility-runtime-Ds8jsG0J.mjs";
import "./runtime-env-D-Pa5lD6.mjs";
import { n as formatProviderLoginCompletion, r as formatProviderLoginFailure } from "./provider-login-recovery-zWN-LIXU.mjs";
import { f as prepareSessionEntryPatch } from "./session-store-runtime-D5peOAR8.mjs";
import "./command-auth-native-DT07BMZD.mjs";
import { a as offerProviderLoginModelAccess, c as releaseProviderLoginFlow, d as runProviderChannelLoginFlow, i as createProviderLoginFlowRegistry, l as reserveProviderLoginFlow, o as prepareProviderChannelLogin, r as cancelProviderLoginFlow, s as refreshProviderLoginAuthState, t as answerProviderLoginModelAccess } from "./provider-auth-login-flow-runtime-hbSnuGVb.mjs";
import { n as withTelegramApiErrorLogging } from "./api-logging-D-u3hsql.mjs";
import { s as buildTelegramRoutingTarget } from "./helpers-CoGccTxe.mjs";
import { t as loadTelegramSendModule } from "./send-runtime-CZEXtMaJ.mjs";
//#region extensions/telegram/src/bot-native-command-login.ts
const activeTelegramProviderLoginFlows = createProviderLoginFlowRegistry();
function formatTelegramLoginDeviceCode(e) {
return [
`<b>${escapeHtml(e.title)}</b>`,
"",
...e.message ? [escapeHtml(e.message)] : [],
`Code: <code>${escapeHtml(e.code)}</code>`,
...e.expiresInMinutes ? [`Code expires in ${e.expiresInMinutes} minutes. Never share it.`] : []
].join("\n");
}
async function executeTelegramLoginCommand(e) {
const { dispatch: t } = e;
const n = t.threadSpec.id == null ? t.threadSpec.scope : `${t.threadSpec.scope}:${t.threadSpec.id}`;
const r = {
flows: activeTelegramProviderLoginFlows,
flowKey: [
"telegram",
t.route.accountId,
String(t.chatId),
n,
t.route.agentId
].join(":")
};
let i = 0;
const sendLoginMessage = async (n, r) => {
await withTelegramApiErrorLogging({
operation: "sendMessage",
runtime: t.runtime,
fn: () => t.bot.api.sendMessage(t.chatId, n, {
...t.threadParams,
...r ? { parse_mode: r } : {}
})
});
await t.recordDeliveredReply(e.commandText, r === "HTML" ? n.replace(/<[^>]*>/g, "") : n, String(++i));
};
const assertCurrent = (e = readRuntimeConfig()) => {
t.assertOwnerCurrent?.();
const n = resolveCommandAuthorization({
cfg: e,
ctx: t.ownerContext,
commandAuthorized: t.commandAuthorized
});
if (!t.senderIsOwner || !n.senderIsOwner || !n.isAuthorizedSender) throw new Error("Provider login authority is no longer active.");
};
const sendLoginReply = async (n) => {
const { deliverReplies: r } = await t.loadDeliveryRuntime();
const a = await r({
replies: [n],
...t.deliveryOptions
});
if (a.delivered && n.text) await t.recordDeliveredReply(e.commandText, n.text, String(++i));
return a.delivered;
};
const a = await prepareProviderChannelLogin({
commandText: e.commandText,
commandAuthorized: t.commandAuthorized,
senderIsOwner: t.senderIsOwner,
isPrivateChat: t.msg.chat.type === "private",
config: t.runtimeCfg,
agentId: t.route.agentId,
signal: t.opts.accountAbortSignal,
refreshAuth: () => refreshProviderLoginAuthState({
agentId: t.route.agentId,
readConfig: readRuntimeConfig,
assertCurrent: (e) => {
t.opts.accountAbortSignal?.throwIfAborted();
assertCurrent(e);
}
}),
cancelLogin: () => cancelProviderLoginFlow(r),
answerChoice: (e) => answerProviderLoginModelAccess({
...r,
command: e,
agentId: t.route.agentId,
readConfig: readRuntimeConfig,
runtime: t.runtime,
signal: t.opts.accountAbortSignal,
assertCurrent
})
});
if (!a) return false;
if (a.status !== "ready") {
if (!a.reply.presentation) {
await sendLoginMessage(a.reply.text);
return a.status === "reply";
}
return await sendLoginReply(a.reply) && a.status === "reply";
}
const o = a.choice;
const s = reserveProviderLoginFlow({
...r,
providerLabel: o.providerLabel,
signal: t.opts.accountAbortSignal
});
if (s.status === "active") {
await sendLoginMessage(`${s.providerLabel} sign-in is already in progress. Finish it, or send /login cancel to cancel.`);
return true;
}
const c = s.record.signal;
const l = createDeferred();
let u = false;
const sendLoginAction = async (e) => {
c.throwIfAborted();
if (await e() === false) throw new Error("Provider sign-in action could not be delivered.");
c.throwIfAborted();
u = true;
l.resolve();
};
const d = (async () => {
let n;
let a;
try {
const r = await t.nativeCommandRuntime.getSessionEntryAsync({
agentId: t.route.agentId,
sessionKey: t.targetSessionKey,
storePath: resolveSessionStorePathCore(t.runtimeCfg.session?.store, { agentId: t.route.agentId })
});
const i = await runProviderChannelLoginFlow({
choice: o,
agentId: t.route.agentId,
config: t.runtimeCfg,
readConfig: readRuntimeConfig,
runtime: t.runtime,
signal: c,
assertCurrent,
sendMessage: sendLoginMessage,
sendReply: (e) => sendLoginAction(() => sendLoginReply(e)),
onModelAccessRequested: (e) => {
a = e;
},
sendDeviceCode: (e) => sendLoginAction(() => sendLoginMessage(formatTelegramLoginDeviceCode(e), "HTML")),
unsupportedPromptMessage: "This provider needs input that Telegram cannot collect. Open Control UI → Models and choose Sign in."
});
c.throwIfAborted();
const s = i.profiles.find((e) => normalizeLowercaseStringOrEmpty(e.provider) === normalizeLowercaseStringOrEmpty(o.providerId))?.profileId;
let l = !s;
if (s && normalizeLowercaseStringOrEmpty(e.currentProvider) === normalizeLowercaseStringOrEmpty(o.providerId)) {
const n = resolveSessionStorePathCore(t.runtimeCfg.session?.store, { agentId: t.route.agentId });
let i;
try {
const a = await prepareSessionEntryPatch({
sessionKey: t.targetSessionKey,
storePath: n,
requireWriteSuccess: true,
skipMaintenance: true,
authority: {
kind: "host",
assertCurrent() {
c.throwIfAborted();
assertCurrent();
}
},
prepare: (t) => {
i = decideProviderLoginSessionAdoption({
currentModelProvider: e.currentProvider,
loginProvider: o.providerId,
nextProfileId: s,
snapshot: r,
current: t
});
return i.status === "patch" ? i.patch : null;
}
});
c.throwIfAborted();
if (i && (i.status === "rejected" || !a || i.status === "patch" && !isProviderLoginPatchPersisted(a, s))) l = true;
} catch (e) {
c.throwIfAborted();
t.runtime.error?.(danger(`telegram ${formatProviderLoginCommand(o.command)} completed but failed to update session auth profile: ${String(e)}`));
l = true;
}
}
const u = r?.modelOverride ?? r?.model;
n = formatProviderLoginCompletion(o, i.authRefresh, l, s && u ? {
model: u,
profileId: s
} : void 0);
} catch (e) {
a = void 0;
if (c.aborted) return;
t.runtime.error?.(danger(`telegram ${formatProviderLoginCommand(o.command)} failed: ${String(e)}`));
n = formatProviderLoginFailure(o, e);
}
if (c.aborted) return;
try {
if (a) {
const e = offerProviderLoginModelAccess({
...r,
prepared: a,
terminalMessage: n
});
await sendLoginAction(() => sendLoginReply(e));
} else {
const { sendMessageTelegram: r } = await loadTelegramSendModule();
await r(buildTelegramRoutingTarget(t.chatId, t.threadSpec), n, {
cfg: t.runtimeCfg,
token: t.opts.token,
accountId: t.route.accountId
});
await t.recordDeliveredReply(e.commandText, n, String(++i));
}
} catch (e) {
t.runtime.error?.(danger(`telegram ${formatProviderLoginCommand(o.command)} result notification failed: ${String(e)}`));
}
})().finally(() => {
releaseProviderLoginFlow({
...r,
record: s.record
});
});
await Promise.race([l.promise, d]);
return u;
}
//#endregion
export { executeTelegramLoginCommand };