File size: 1,909 Bytes
7a1ad33 | 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 | /**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import readline from 'node:readline';
import { CoreEvent, coreEvents } from './events.js';
import { FatalAuthenticationError } from './errors.js';
import { createWorkingStdio, writeToStdout } from './stdio.js';
import { isHeadlessMode } from './headless.js';
/**
* Requests consent from the user for OAuth login.
* Handles both interactive and non-interactive (headless) modes.
*/
export async function getConsentForOauth(prompt: string): Promise<boolean> {
const finalPrompt =
(prompt ? prompt + ' ' : '') +
'Opening authentication page in your browser. ';
if (isHeadlessMode()) {
return getOauthConsentNonInteractive(finalPrompt);
} else if (coreEvents.listenerCount(CoreEvent.ConsentRequest) > 0) {
return getOauthConsentInteractive(finalPrompt);
}
throw new FatalAuthenticationError(
'Authentication consent could not be obtained.\n' +
'Please run Gemini CLI in an interactive terminal to authenticate, ' +
'or use NO_BROWSER=true for manual authentication.',
);
}
async function getOauthConsentNonInteractive(prompt: string) {
const rl = readline.createInterface({
input: process.stdin,
output: createWorkingStdio().stdout,
terminal: true,
});
const fullPrompt = prompt + 'Do you want to continue? [Y/n]: ';
writeToStdout(`\n${fullPrompt}`);
return new Promise<boolean>((resolve) => {
rl.on('line', (answer) => {
rl.close();
resolve(['y', ''].includes(answer.trim().toLowerCase()));
});
});
}
async function getOauthConsentInteractive(prompt: string) {
const fullPrompt = prompt + '\n\nDo you want to continue?';
return new Promise<boolean>((resolve) => {
coreEvents.emitConsentRequest({
prompt: fullPrompt,
onConfirm: (confirmed: boolean) => {
resolve(confirmed);
},
});
});
}
|