openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
4 lines • 6.93 kB
JavaScript
import{o as normalizeLowercaseStringOrEmpty}from"./string-coerce-CpTFcSwY.mjs";import{l as resolveSessionStorePathCore}from"./paths-CcxgiC3g.mjs";import{h as readRuntimeConfig}from"./runtime-snapshot-Bg5K4JNu.mjs";import{n as isProviderLoginPatchPersisted,t as decideProviderLoginSessionAdoption}from"./auth-profile-override-provenance-D5ZYWRNQ.mjs";import{i as resolveCommandAuthorization}from"./command-auth-CCzMsjar.mjs";import{p as formatProviderLoginCommand}from"./oauth-refresh-failure-BdZMhNvV.mjs";import{t as escapeHtml}from"./html-escape-wAM7yA-h.mjs";import{t as danger}from"./globals-l9I53ZKA.mjs";import"./string-coerce-runtime-BYDH9Quw.mjs";import"./runtime-config-snapshot-N0DER8v5.mjs";import{a as createDeferred}from"./extension-shared--VNeNF-V.mjs";import"./text-utility-runtime-CDtGqkrl.mjs";import"./runtime-env-Qb8DG6sI.mjs";import{n as formatProviderLoginCompletion,r as formatProviderLoginFailure}from"./provider-login-recovery-9hr-eZBr.mjs";import{f as prepareSessionEntryPatch}from"./session-store-runtime-BiMBNaHL.mjs";import"./command-auth-native-Bl-iUqlk.mjs";import{a as refreshProviderLoginAuthState,i as prepareProviderChannelLogin,l as runProviderChannelLoginFlow,n as cancelProviderLoginFlow,o as releaseProviderLoginFlow,r as createProviderLoginFlowRegistry,s as reserveProviderLoginFlow}from"./provider-auth-login-flow-runtime-BMnZzZXV.mjs";import{X as withTelegramApiErrorLogging,s as buildTelegramRoutingTarget}from"./helpers-B2EnHAZw.mjs";import{t as loadTelegramSendModule}from"./send-runtime-D4dB3iVP.mjs";
//!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(`
`)}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)});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;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)),sendDeviceCode:e=>sendLoginAction(()=>sendLoginMessage(formatTelegramLoginDeviceCode(e),`HTML`)),unsupportedPromptMessage:`This provider needs input that Telegram cannot collect. Open Models in the OpenClaw app and choose Sign in.`});c.throwIfAborted();const a=i.profiles.find(e=>normalizeLowercaseStringOrEmpty(e.provider)===normalizeLowercaseStringOrEmpty(o.providerId))?.profileId;let s=!a;if(a&&normalizeLowercaseStringOrEmpty(e.currentProvider)===normalizeLowercaseStringOrEmpty(o.providerId)){const n=resolveSessionStorePathCore(t.runtimeCfg.session?.store,{agentId:t.route.agentId});let i;try{const l=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:a,snapshot:r,current:t});return i.status===`patch`?i.patch:null}});c.throwIfAborted();if(i&&(i.status===`rejected`||!l||i.status===`patch`&&!isProviderLoginPatchPersisted(l,a)))s=true}catch(e){c.throwIfAborted();t.runtime.error?.(danger(`telegram ${formatProviderLoginCommand(o.command)} completed but failed to update session auth profile: ${String(e)}`));s=true}}const l=r?.modelOverride??r?.model;n=[formatProviderLoginCompletion(o,i.authRefresh,s,a&&l?{model:l,profileId:a}:void 0),i.modelAccess?.message].filter(Boolean).join(` `)}catch(e){if(c.aborted)return;t.runtime.error?.(danger(`telegram ${formatProviderLoginCommand(o.command)} failed: ${String(e)}`));n=formatProviderLoginFailure(o,e)}if(c.aborted)return;try{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}export{executeTelegramLoginCommand};