fix: enhance error handling and output for non-interactive authentication in JSON and STREAM_JSON modes

This commit is contained in:
mingholy.lmh
2025-11-18 11:34:46 +08:00
parent 93999e45e7
commit cfa7f43572
6 changed files with 478 additions and 72 deletions

View File

@@ -9,7 +9,9 @@ import { AuthType, OutputFormat } from '@qwen-code/qwen-code-core';
import { USER_SETTINGS_PATH } from './config/settings.js';
import { validateAuthMethod } from './config/auth.js';
import { type LoadedSettings } from './config/settings.js';
import { handleError } from './utils/errors.js';
import { JsonOutputAdapter } from './nonInteractive/io/JsonOutputAdapter.js';
import { StreamJsonOutputAdapter } from './nonInteractive/io/StreamJsonOutputAdapter.js';
import { runExitCleanup } from './utils/cleanup.js';
function getAuthTypeFromEnv(): AuthType | undefined {
if (process.env['OPENAI_API_KEY']) {
@@ -27,7 +29,7 @@ export async function validateNonInteractiveAuth(
useExternalAuth: boolean | undefined,
nonInteractiveConfig: Config,
settings: LoadedSettings,
) {
): Promise<Config> {
try {
const enforcedType = settings.merged.security?.auth?.enforcedType;
if (enforcedType) {
@@ -58,15 +60,38 @@ export async function validateNonInteractiveAuth(
await nonInteractiveConfig.refreshAuth(authType);
return nonInteractiveConfig;
} catch (error) {
if (nonInteractiveConfig.getOutputFormat() === OutputFormat.JSON) {
handleError(
error instanceof Error ? error : new Error(String(error)),
nonInteractiveConfig,
1,
);
} else {
console.error(error instanceof Error ? error.message : String(error));
const outputFormat = nonInteractiveConfig.getOutputFormat();
// In JSON and STREAM_JSON modes, emit error result and exit
if (
outputFormat === OutputFormat.JSON ||
outputFormat === OutputFormat.STREAM_JSON
) {
let adapter;
if (outputFormat === OutputFormat.JSON) {
adapter = new JsonOutputAdapter(nonInteractiveConfig);
} else {
adapter = new StreamJsonOutputAdapter(
nonInteractiveConfig,
nonInteractiveConfig.getIncludePartialMessages(),
);
}
const errorMessage =
error instanceof Error ? error.message : String(error);
adapter.emitResult({
isError: true,
errorMessage,
durationMs: 0,
apiDurationMs: 0,
numTurns: 0,
usage: undefined,
});
await runExitCleanup();
process.exit(1);
}
// For other modes (text), use existing error handling
console.error(error instanceof Error ? error.message : String(error));
process.exit(1);
}
}