File size: 12,197 Bytes
34810d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
import { expectDefined } from "@openclaw/normalization-core";
// Channel login/logout command helpers for local config and gateway reconciliation.
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
import { sanitizeForLog } from "../../packages/terminal-core/src/ansi.js";
import { resolveChannelDefaultAccountId } from "../channels/plugins/helpers.js";
import {
  getChannelPlugin,
  listChannelPlugins,
  normalizeChannelId,
} from "../channels/plugins/index.js";
import { resolveInstallableChannelPlugin } from "../commands/channel-setup/channel-plugin-resolution.js";
import { parseAccountSelector } from "../commands/channels/account-selector.js";
import { requireValidConfigForWrite } from "../commands/config-validation.js";
import { getRuntimeConfig, type OpenClawConfig } from "../config/config.js";
import { applyPluginAutoEnable } from "../config/plugin-auto-enable.js";
import { callGateway } from "../gateway/call.js";
import type { ChannelAccountStartOutcome } from "../gateway/server-channel-runtime.types.js";
import { setVerbose } from "../globals.js";
import { formatErrorMessage } from "../infra/errors.js";
import { isBlockedObjectKey } from "../infra/prototype-keys.js";
import { commitConfigWithPendingPluginInstalls } from "../plugins/install-record-commit.js";
import { defaultRuntime, type RuntimeEnv } from "../runtime.js";
import { GATEWAY_CLIENT_MODES, GATEWAY_CLIENT_NAMES } from "../utils/message-channel.js";
import { formatCliCommand } from "./command-format.js";
import { formatUnsupportedChannelActionMessage } from "./error-format.js";

type ChannelAuthOptions = {
  agent?: string;
  channel?: string;
  account?: string;
  verbose?: boolean;
};

type ChannelPlugin = NonNullable<ReturnType<typeof getChannelPlugin>>;
type ChannelAuthMode = "login" | "logout";

function supportsChannelAuthMode(plugin: ChannelPlugin, mode: ChannelAuthMode): boolean {
  return mode === "login" ? Boolean(plugin.auth?.login) : Boolean(plugin.gateway?.logoutAccount);
}

function isConfiguredAuthPlugin(plugin: ChannelPlugin, cfg: OpenClawConfig): boolean {
  const key = plugin.id;
  if (isBlockedObjectKey(key)) {
    return false;
  }
  const channelCfg = (cfg.channels as Record<string, unknown> | undefined)?.[key];
  if (
    channelCfg &&
    typeof channelCfg === "object" &&
    "enabled" in channelCfg &&
    (channelCfg as { enabled?: unknown }).enabled === false
  ) {
    return false;
  }

  for (const accountId of plugin.config.listAccountIds(cfg)) {
    try {
      const account = plugin.config.resolveAccount(cfg, accountId);
      const enabled = plugin.config.isEnabled
        ? plugin.config.isEnabled(account, cfg)
        : account && typeof account === "object"
          ? ((account as { enabled?: boolean }).enabled ?? true)
          : true;
      if (enabled) {
        return true;
      }
    } catch {
      continue;
    }
  }

  return false;
}

function resolveConfiguredAuthChannelInput(mode: ChannelAuthMode): string {
  // Account callbacks need runtime values; this auto-enabled view is never persisted.
  const cfg = applyPluginAutoEnable({ config: getRuntimeConfig(), env: process.env }).config;
  const configured = listChannelPlugins()
    .filter((plugin): plugin is ChannelPlugin => supportsChannelAuthMode(plugin, mode))
    .filter((plugin) => isConfiguredAuthPlugin(plugin, cfg))
    .map((plugin) => plugin.id);

  if (configured.length === 1) {
    return expectDefined(configured[0], "configured entry at 0");
  }
  if (configured.length === 0) {
    throw new Error(
      `No configured channel supports ${mode}. Run ${formatCliCommand("openclaw channels status")} to inspect channels or ${formatCliCommand("openclaw channels add --channel <channel>")} to add one.`,
    );
  }
  const safeIds = configured.map(sanitizeForLog);
  throw new Error(
    `Multiple configured channels support ${mode}: ${safeIds.join(", ")}. Choose one with --channel <channel>.`,
  );
}

async function resolveChannelPluginForMode(
  opts: ChannelAuthOptions,
  mode: ChannelAuthMode,
  runtime: RuntimeEnv,
): Promise<{
  cfg: OpenClawConfig;
  channelInput: string;
  channelId: string;
  plugin: ChannelPlugin;
} | null> {
  parseAccountSelector(opts.account);
  const writeSnapshot = await requireValidConfigForWrite(runtime);
  if (!writeSnapshot) {
    return null;
  }
  // Runtime defaults are not authored plugin enablement intent.
  const autoEnabled = applyPluginAutoEnable({
    config: writeSnapshot.snapshot.sourceConfig,
    env: process.env,
  });
  const cfg = autoEnabled.config;
  const explicitChannel = opts.channel?.trim();
  const channelInput = explicitChannel || resolveConfiguredAuthChannelInput(mode);
  const normalizedChannelId = normalizeChannelId(channelInput);

  const resolved = await resolveInstallableChannelPlugin({
    cfg,
    runtime,
    agentId: opts.agent,
    rawChannel: channelInput,
    ...(normalizedChannelId ? { channelId: normalizedChannelId } : {}),
    allowInstall: true,
    supports: (candidate) => supportsChannelAuthMode(candidate, mode),
  });
  const channelId = resolved.channelId ?? normalizedChannelId;
  if (!channelId) {
    throw new Error(
      `Unsupported channel "${channelInput}". Run ${formatCliCommand("openclaw channels list")} to see available channels.`,
    );
  }
  const plugin = resolved.plugin;
  if (!plugin || !supportsChannelAuthMode(plugin, mode)) {
    throw new Error(
      formatUnsupportedChannelActionMessage({
        channel: channelId,
        action: mode,
        inspectCommand: "openclaw channels status --channel " + channelId,
      }),
    );
  }
  if (autoEnabled.changes.length > 0 || resolved.configChanged) {
    await commitConfigWithPendingPluginInstalls({
      sourceConfig: resolved.cfg,
      baseHash: writeSnapshot.snapshot.hash,
      writeOptions: writeSnapshot.writeOptions,
    });
  }
  return {
    // Execution needs resolved runtime values; successful writes refresh this snapshot.
    cfg: getRuntimeConfig(),
    channelInput,
    channelId,
    plugin,
  };
}

function resolveAccountContext(
  plugin: ChannelPlugin,
  opts: ChannelAuthOptions,
  cfg: OpenClawConfig,
) {
  const accountId =
    normalizeOptionalString(opts.account) || resolveChannelDefaultAccountId({ plugin, cfg });
  return { accountId };
}

function isChannelMissingFromGatewayRegistry(error: unknown): error is Error {
  const requestError = error as (Error & { gatewayCode?: unknown }) | undefined;
  return (
    requestError instanceof Error &&
    requestError.name === "GatewayClientRequestError" &&
    requestError.gatewayCode === "INVALID_REQUEST" &&
    requestError.message === "invalid channels.start channel"
  );
}

async function reconcileGatewayRuntimeAfterLocalLogin(params: {
  cfg: OpenClawConfig;
  plugin: ChannelPlugin;
  channelId: string;
  accountId: string;
  runtime: RuntimeEnv;
}) {
  // Local auth writes are durable even when the gateway restart hook is unavailable or remote.
  if (!params.plugin.gateway?.startAccount) {
    return;
  }
  if (params.cfg.gateway?.mode === "remote") {
    params.runtime.log(
      `Gateway is in remote mode; local login saved auth for ${params.channelId}/${params.accountId} but did not start the remote runtime.`,
    );
    return;
  }
  try {
    const result = await callGateway<{ outcome?: ChannelAccountStartOutcome }>({
      config: params.cfg,
      method: "channels.start",
      params: {
        channel: params.channelId,
        accountId: params.accountId,
      },
      mode: GATEWAY_CLIENT_MODES.BACKEND,
      clientName: GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,
      deviceIdentity: null,
    });
    // Older Gateways return only the runtime snapshot, without a start decision.
    if (result.outcome && result.outcome.status !== "handed-off") {
      params.runtime.log(
        `Local login saved auth for ${params.channelId}/${params.accountId}. Gateway start: ${result.outcome.reason}. Check ${formatCliCommand(`openclaw channels status --channel ${params.channelId} --probe`)}.`,
      );
    }
  } catch (error) {
    // A plugin installed or enabled after Gateway startup is absent from its
    // process-stable registry. Restart only for that exact RPC rejection.
    if (isChannelMissingFromGatewayRegistry(error)) {
      try {
        await callGateway({
          config: params.cfg,
          method: "gateway.restart.request",
          params: { reason: `channel login: load ${params.channelId}` },
          mode: GATEWAY_CLIENT_MODES.BACKEND,
          clientName: GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,
          deviceIdentity: null,
        });
        params.runtime.log(
          `Gateway restart requested to load ${params.channelId}; the channel will start after restart.`,
        );
        return;
      } catch {
        // Fall through to the generic warning if the restart request also fails.
      }
    }
    params.runtime.log(
      `Local login saved auth for ${params.channelId}/${params.accountId}, but the running gateway did not restart it: ${formatErrorMessage(error)}`,
    );
  }
}

async function logoutViaGatewayRuntime(params: {
  cfg: OpenClawConfig;
  channelId: string;
  accountId: string;
  runtime: RuntimeEnv;
}) {
  try {
    return await callGateway<{ cleared: boolean; loggedOut?: boolean }>({
      config: params.cfg,
      method: "channels.logout",
      params: {
        channel: params.channelId,
        accountId: params.accountId,
      },
      mode: GATEWAY_CLIENT_MODES.BACKEND,
      clientName: GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,
      deviceIdentity: null,
    });
  } catch (error) {
    if (params.cfg.gateway?.mode === "remote") {
      throw error;
    }
    params.runtime.log(
      `Local logout will clear auth for ${params.channelId}/${params.accountId}, but the running gateway did not stop it: ${formatErrorMessage(error)}`,
    );
    return null;
  }
}

export async function runChannelLogin(
  opts: ChannelAuthOptions,
  runtime: RuntimeEnv = defaultRuntime,
) {
  const resolvedChannel = await resolveChannelPluginForMode(opts, "login", runtime);
  if (!resolvedChannel) {
    return;
  }
  const { cfg, channelInput, plugin } = resolvedChannel;
  const login = plugin.auth?.login;
  if (!login) {
    throw new Error(
      formatUnsupportedChannelActionMessage({
        channel: channelInput,
        action: "login",
        inspectCommand: "openclaw channels status --channel " + channelInput,
      }),
    );
  }
  // Auth-only flow: do not mutate channel config here.
  setVerbose(Boolean(opts.verbose));
  const { accountId } = resolveAccountContext(plugin, opts, cfg);
  await login({
    cfg,
    accountId,
    runtime,
    verbose: Boolean(opts.verbose),
    channelInput,
  });
  await reconcileGatewayRuntimeAfterLocalLogin({
    cfg,
    plugin,
    channelId: plugin.id,
    accountId,
    runtime,
  });
}

export async function runChannelLogout(
  opts: ChannelAuthOptions,
  runtime: RuntimeEnv = defaultRuntime,
) {
  const resolvedChannel = await resolveChannelPluginForMode(opts, "logout", runtime);
  if (!resolvedChannel) {
    return;
  }
  const { cfg, channelInput, plugin } = resolvedChannel;
  const logoutAccount = plugin.gateway?.logoutAccount;
  if (!logoutAccount) {
    throw new Error(
      formatUnsupportedChannelActionMessage({
        channel: channelInput,
        action: "logout",
        inspectCommand: "openclaw channels status --channel " + channelInput,
      }),
    );
  }
  // Prefer the live gateway so logout also stops any active channel runtime.
  const { accountId } = resolveAccountContext(plugin, opts, cfg);
  let result = await logoutViaGatewayRuntime({
    cfg,
    channelId: plugin.id,
    accountId,
    runtime,
  });
  if (!result) {
    const account = plugin.config.resolveAccount(cfg, accountId);
    result = await logoutAccount({
      cfg,
      accountId,
      account,
      runtime,
    });
  }
  const scope = sanitizeForLog(`${plugin.id}/${accountId}`);
  runtime.log(
    `${result.cleared ? "Cleared saved auth" : "No saved auth was cleared"} for ${scope}.${
      result.loggedOut === false ? " Other credentials may still be active." : ""
    }`,
  );
}