-
-
Notifications
You must be signed in to change notification settings - Fork 80.8k
Expand file tree
/
Copy pathprovider-auth-choice.ts
More file actions
613 lines (573 loc) · 20.1 KB
/
Copy pathprovider-auth-choice.ts
File metadata and controls
613 lines (573 loc) · 20.1 KB
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
// Formats provider authentication choices exposed by plugin setup flows.
import { sanitizeTerminalText } from "../../packages/terminal-core/src/safe-text.js";
import {
resolveDefaultAgentId,
resolveAgentDir,
resolveAgentWorkspaceDir,
} from "../agents/agent-scope.js";
import { upsertAuthProfileWithLock } from "../agents/auth-profiles.js";
import { formatLiteralProviderPrefixedModelRef } from "../agents/model-ref-shared.js";
import { resolveDefaultAgentWorkspaceDir } from "../agents/workspace.js";
import { normalizeAgentModelRefForConfig } from "../config/model-input.js";
import type { OpenClawConfig } from "../config/types.openclaw.js";
import { openUrl } from "../infra/browser-open.js";
import { isRemoteEnvironment } from "../infra/remote-env.js";
import type { RuntimeEnv } from "../runtime.js";
import { t } from "../wizard/i18n/index.js";
import type { WizardPrompter } from "../wizard/prompts.js";
import { enablePluginInConfig } from "./enable.js";
import {
applyProviderAuthConfigPatch,
applyDefaultModel,
pickAuthMethod,
resolveProviderMatch,
} from "./provider-auth-choice-helpers.js";
import {
resolveManifestProviderAuthChoice,
type ProviderAuthChoiceMetadata,
} from "./provider-auth-choices.js";
import { applyAuthProfileConfig } from "./provider-auth-helpers.js";
import { resolveProviderInstallCatalogEntry } from "./provider-install-catalog.js";
import { createVpsAwareOAuthHandlers } from "./provider-oauth-flow.js";
import type { ProviderAuthMethod, ProviderAuthOptionBag, ProviderPlugin } from "./types.js";
type UpsertAuthProfileParams = Parameters<typeof upsertAuthProfileWithLock>[0];
export type ApplyProviderAuthChoiceParams = {
authChoice: string;
config: OpenClawConfig;
env?: NodeJS.ProcessEnv;
prompter: WizardPrompter;
runtime: RuntimeEnv;
agentDir?: string;
setDefaultModel: boolean;
preserveExistingDefaultModel?: boolean;
agentId?: string;
opts?: Partial<ProviderAuthOptionBag>;
};
export type ApplyProviderAuthChoiceResult = {
config: OpenClawConfig;
agentModelOverride?: string;
retrySelection?: boolean;
};
export type PluginProviderAuthChoiceOptions = {
authChoice: string;
pluginId: string;
providerId: string;
methodId?: string;
label: string;
};
function formatModelRefForDisplay(modelRef: string, provider: ProviderPlugin): string {
if (!provider.preserveLiteralProviderPrefix) {
return modelRef;
}
return formatLiteralProviderPrefixedModelRef(provider.id, modelRef);
}
function restoreConfiguredPrimaryModel(
nextConfig: OpenClawConfig,
originalConfig: OpenClawConfig,
): OpenClawConfig {
const originalModel = originalConfig.agents?.defaults?.model;
const nextAgents = nextConfig.agents;
const nextDefaults = nextAgents?.defaults;
if (!nextDefaults) {
return nextConfig;
}
if (originalModel !== undefined) {
return {
...nextConfig,
agents: {
...nextAgents,
defaults: {
...nextDefaults,
model: originalModel,
},
},
};
}
const { model: _model, ...restDefaults } = nextDefaults;
return {
...nextConfig,
agents: {
...nextAgents,
defaults: restDefaults,
},
};
}
function resolveConfiguredDefaultModelPrimary(cfg: OpenClawConfig): string | undefined {
const model = cfg.agents?.defaults?.model;
if (typeof model === "string") {
return model;
}
if (model && typeof model === "object" && typeof model.primary === "string") {
return model.primary;
}
return undefined;
}
async function noteDefaultModelResult(params: {
previousPrimary: string | undefined;
selectedModel: string;
selectedModelDisplay?: string;
preserveExistingDefaultModel: boolean | undefined;
prompter: WizardPrompter;
}): Promise<void> {
const selectedModelDisplay = params.selectedModelDisplay ?? params.selectedModel;
if (
params.preserveExistingDefaultModel === true &&
params.previousPrimary &&
params.previousPrimary !== params.selectedModel
) {
await params.prompter.note(
t("wizard.model.keptExistingDefault", {
current: params.previousPrimary,
selected: selectedModelDisplay,
}),
t("wizard.model.configuredTitle"),
);
return;
}
await params.prompter.note(
t("wizard.model.defaultSet", { model: selectedModelDisplay }),
t("wizard.model.configuredTitle"),
);
}
async function applyDefaultModelFromAuthChoice(params: {
config: OpenClawConfig;
configBeforeProviderAuth?: OpenClawConfig;
selectedModel: string;
selectedModelDisplay?: string;
preserveExistingDefaultModel: boolean | undefined;
prompter: WizardPrompter;
runtime: RuntimeEnv;
workspaceDir?: string;
runSelectedModelHook: (config: OpenClawConfig) => Promise<void>;
}): Promise<OpenClawConfig> {
const defaultModelBaseConfig = params.configBeforeProviderAuth ?? params.config;
const previousPrimary = resolveConfiguredDefaultModelPrimary(defaultModelBaseConfig);
const preservesDifferentPrimary =
params.preserveExistingDefaultModel === true &&
previousPrimary !== undefined &&
previousPrimary !== params.selectedModel;
const defaultModelConfig =
params.preserveExistingDefaultModel === true
? restoreConfiguredPrimaryModel(params.config, defaultModelBaseConfig)
: params.config;
let nextConfig = applyDefaultModel(defaultModelConfig, params.selectedModel, {
preserveExistingPrimary: params.preserveExistingDefaultModel === true,
});
if (!preservesDifferentPrimary) {
const { CODEX_RUNTIME_PLUGIN_ID, ensureCodexRuntimePluginForModelSelection } =
await import("../commands/codex-runtime-plugin-install.js");
const codexInstall = await ensureCodexRuntimePluginForModelSelection({
cfg: nextConfig,
model: params.selectedModel,
prompter: params.prompter,
runtime: params.runtime,
...(params.workspaceDir !== undefined ? { workspaceDir: params.workspaceDir } : {}),
});
nextConfig = codexInstall.cfg;
await params.runSelectedModelHook(nextConfig);
if (codexInstall.installed) {
// Offer Codex CLI state migration whenever the harness is in place for
// the selected model, regardless of whether this run was a fresh install
// or a repair against an already-present harness. The user can always
// decline the prompt; surfacing it again costs nothing if there is no
// migratable state to find.
const { offerPostInstallMigrations } =
await import("../wizard/setup.post-install-migration.js");
const migrationResult = await offerPostInstallMigrations({
config: nextConfig,
runtime: params.runtime,
prompter: params.prompter,
installedPluginIds: [CODEX_RUNTIME_PLUGIN_ID],
});
nextConfig = migrationResult.config;
}
const { ensureCopilotRuntimePluginForModelSelection } =
await import("../commands/copilot-runtime-plugin-install.js");
const copilotInstall = await ensureCopilotRuntimePluginForModelSelection({
cfg: nextConfig,
model: params.selectedModel,
prompter: params.prompter,
runtime: params.runtime,
...(params.workspaceDir !== undefined ? { workspaceDir: params.workspaceDir } : {}),
});
nextConfig = copilotInstall.cfg;
}
await noteDefaultModelResult({
previousPrimary,
selectedModel: params.selectedModel,
selectedModelDisplay: params.selectedModelDisplay,
preserveExistingDefaultModel: params.preserveExistingDefaultModel,
prompter: params.prompter,
});
return nextConfig;
}
type ProviderAuthChoiceRuntime = typeof import("./provider-auth-choice.runtime.js");
const defaultProviderAuthChoiceDeps = {
loadPluginProviderRuntime: async (): Promise<ProviderAuthChoiceRuntime> =>
import("./provider-auth-choice.runtime.js"),
};
let providerAuthChoiceDeps = defaultProviderAuthChoiceDeps;
async function loadPluginProviderRuntime() {
return await providerAuthChoiceDeps.loadPluginProviderRuntime();
}
function resolveManifestAuthChoiceScope(params: {
authChoice: string;
config: OpenClawConfig;
workspaceDir: string;
env?: NodeJS.ProcessEnv;
}): ProviderAuthChoiceMetadata | undefined {
return resolveManifestProviderAuthChoice(params.authChoice, {
config: params.config,
workspaceDir: params.workspaceDir,
env: params.env,
includeUntrustedWorkspacePlugins: false,
});
}
function withProviderPluginId(provider: ProviderPlugin, pluginId: string): ProviderPlugin {
return provider.pluginId === pluginId ? provider : { ...provider, pluginId };
}
export const testing = {
resetDepsForTest(): void {
providerAuthChoiceDeps = defaultProviderAuthChoiceDeps;
},
setDepsForTest(deps: Partial<typeof defaultProviderAuthChoiceDeps>): void {
providerAuthChoiceDeps = {
...defaultProviderAuthChoiceDeps,
...deps,
};
},
} as const;
export async function runProviderPluginAuthMethod(params: {
config: OpenClawConfig;
env?: NodeJS.ProcessEnv;
runtime: RuntimeEnv;
prompter: WizardPrompter;
method: ProviderAuthMethod;
agentDir?: string;
agentId?: string;
workspaceDir?: string;
emitNotes?: boolean;
secretInputMode?: ProviderAuthOptionBag["secretInputMode"];
allowSecretRefPrompt?: boolean;
opts?: Partial<ProviderAuthOptionBag>;
}): Promise<{ config: OpenClawConfig; defaultModel?: string }> {
const agentId = params.agentId ?? resolveDefaultAgentId(params.config);
const agentDir = params.agentDir ?? resolveAgentDir(params.config, agentId);
const workspaceDir =
params.workspaceDir ??
resolveAgentWorkspaceDir(params.config, agentId) ??
resolveDefaultAgentWorkspaceDir();
const result = await params.method.run({
config: params.config,
env: params.env,
agentDir,
workspaceDir,
prompter: params.prompter,
runtime: params.runtime,
opts: params.opts,
secretInputMode: params.secretInputMode,
allowSecretRefPrompt: params.allowSecretRefPrompt,
isRemote: isRemoteEnvironment(),
openUrl: async (url) => {
await openUrl(url);
},
oauth: {
createVpsAwareHandlers: (opts) => createVpsAwareOAuthHandlers(opts),
},
});
let nextConfig = params.config;
if (result.configPatch) {
nextConfig = applyProviderAuthConfigPatch(nextConfig, result.configPatch, {
replaceDefaultModels: result.replaceDefaultModels,
});
}
for (const profile of result.profiles) {
await upsertAuthProfileWithLockOrThrow({
profileId: profile.profileId,
credential: profile.credential,
agentDir,
});
nextConfig = applyAuthProfileConfig(nextConfig, {
profileId: profile.profileId,
provider: profile.credential.provider,
mode: profile.credential.type === "token" ? "token" : profile.credential.type,
...("email" in profile.credential && profile.credential.email
? { email: profile.credential.email }
: {}),
...("displayName" in profile.credential && profile.credential.displayName
? { displayName: profile.credential.displayName }
: {}),
});
}
if (params.emitNotes !== false && result.notes && result.notes.length > 0) {
await params.prompter.note(result.notes.join("\n"), "Provider notes");
}
const defaultModel = result.defaultModel
? normalizeAgentModelRefForConfig(result.defaultModel)
: undefined;
return {
config: nextConfig,
...(defaultModel ? { defaultModel } : {}),
};
}
export async function applyAuthChoiceLoadedPluginProvider(
params: ApplyProviderAuthChoiceParams,
): Promise<ApplyProviderAuthChoiceResult | null> {
const agentId = params.agentId ?? resolveDefaultAgentId(params.config);
const workspaceDir =
resolveAgentWorkspaceDir(params.config, agentId) ?? resolveDefaultAgentWorkspaceDir();
let nextConfig = params.config;
let enabledConfig = params.config;
const {
resolvePluginProviders,
resolvePluginSetupProvider,
resolveProviderPluginChoice,
runProviderModelSelectedHook,
} = await loadPluginProviderRuntime();
const manifestAuthChoice = resolveManifestAuthChoiceScope({
authChoice: params.authChoice,
config: nextConfig,
workspaceDir,
env: params.env,
});
const installCatalogEntry = resolveProviderInstallCatalogEntry(params.authChoice, {
config: nextConfig,
workspaceDir,
env: params.env,
includeUntrustedWorkspacePlugins: false,
});
const choicePlugin = manifestAuthChoice
? { pluginId: manifestAuthChoice.pluginId, label: manifestAuthChoice.choiceLabel }
: installCatalogEntry
? { pluginId: installCatalogEntry.pluginId, label: installCatalogEntry.label }
: undefined;
if (choicePlugin) {
const enableResult = enablePluginInConfig(nextConfig, choicePlugin.pluginId);
if (!enableResult.enabled) {
const safeLabel = sanitizeTerminalText(choicePlugin.label);
await params.prompter.note(
`${safeLabel} plugin is disabled (${enableResult.reason ?? "blocked"}).`,
safeLabel,
);
return { config: nextConfig };
}
enabledConfig = enableResult.config;
}
const resolveScopedRuntimeProviders = (config: OpenClawConfig): ProviderPlugin[] =>
resolvePluginProviders({
config,
workspaceDir,
env: params.env,
mode: "setup",
...(manifestAuthChoice
? {
onlyPluginIds: [manifestAuthChoice.pluginId],
}
: {}),
});
const setupProvider = manifestAuthChoice
? resolvePluginSetupProvider({
provider: manifestAuthChoice.providerId,
config: enabledConfig,
workspaceDir,
env: params.env,
pluginIds: [manifestAuthChoice.pluginId],
})
: undefined;
let providers = setupProvider
? [withProviderPluginId(setupProvider, manifestAuthChoice!.pluginId)]
: resolveScopedRuntimeProviders(enabledConfig);
let resolved = resolveProviderPluginChoice({
providers,
choice: params.authChoice,
});
if (!resolved && setupProvider) {
providers = resolveScopedRuntimeProviders(enabledConfig);
resolved = resolveProviderPluginChoice({
providers,
choice: params.authChoice,
});
}
if (!resolved && installCatalogEntry) {
const { ensureOnboardingPluginInstalled } =
await import("../commands/onboarding-plugin-install.js");
const installResult = await ensureOnboardingPluginInstalled({
cfg: nextConfig,
entry: {
pluginId: installCatalogEntry.pluginId,
label: installCatalogEntry.label,
install: installCatalogEntry.install,
...(installCatalogEntry.origin === "bundled"
? { trustedSourceLinkedOfficialInstall: true }
: {}),
},
prompter: params.prompter,
runtime: params.runtime,
workspaceDir,
});
if (!installResult.installed) {
return { config: installResult.cfg, retrySelection: true };
}
nextConfig = installResult.cfg;
providers = resolveScopedRuntimeProviders(nextConfig);
resolved = resolveProviderPluginChoice({
providers,
choice: params.authChoice,
});
}
if (!resolved) {
return nextConfig === params.config ? null : { config: nextConfig, retrySelection: true };
}
if (nextConfig === params.config && enabledConfig !== params.config) {
nextConfig = enabledConfig;
}
const configBeforeProviderAuth = nextConfig;
const applied = await runProviderPluginAuthMethod({
config: nextConfig,
env: params.env,
runtime: params.runtime,
prompter: params.prompter,
method: resolved.method,
agentDir: params.agentDir,
agentId: params.agentId,
workspaceDir,
secretInputMode: params.opts?.secretInputMode,
allowSecretRefPrompt: false,
opts: params.opts,
});
nextConfig = applied.config;
let agentModelOverride: string | undefined;
if (applied.defaultModel) {
const selectedModel = applied.defaultModel;
const selectedModelDisplay = formatModelRefForDisplay(selectedModel, resolved.provider);
if (params.setDefaultModel) {
nextConfig = await applyDefaultModelFromAuthChoice({
config: nextConfig,
configBeforeProviderAuth,
selectedModel,
selectedModelDisplay,
preserveExistingDefaultModel: params.preserveExistingDefaultModel,
prompter: params.prompter,
runtime: params.runtime,
workspaceDir,
runSelectedModelHook: async (config) => {
await runProviderModelSelectedHook({
config,
model: selectedModel,
prompter: params.prompter,
agentDir: params.agentDir,
workspaceDir,
});
},
});
return { config: nextConfig };
}
nextConfig = restoreConfiguredPrimaryModel(nextConfig, params.config);
agentModelOverride = selectedModel;
}
return { config: nextConfig, agentModelOverride };
}
export async function applyAuthChoicePluginProvider(
params: ApplyProviderAuthChoiceParams,
options: PluginProviderAuthChoiceOptions,
): Promise<ApplyProviderAuthChoiceResult | null> {
if (params.authChoice !== options.authChoice) {
return null;
}
const enableResult = enablePluginInConfig(params.config, options.pluginId);
let nextConfig = enableResult.config;
if (!enableResult.enabled) {
await params.prompter.note(
`${options.label} plugin is disabled (${enableResult.reason ?? "blocked"}).`,
options.label,
);
return { config: nextConfig };
}
const agentId = params.agentId ?? resolveDefaultAgentId(nextConfig);
const agentDir = params.agentDir ?? resolveAgentDir(nextConfig, agentId);
const workspaceDir =
resolveAgentWorkspaceDir(nextConfig, agentId) ?? resolveDefaultAgentWorkspaceDir();
const { resolvePluginProviders, runProviderModelSelectedHook } =
await loadPluginProviderRuntime();
const providers = resolvePluginProviders({
config: nextConfig,
workspaceDir,
env: params.env,
mode: "setup",
});
const provider = resolveProviderMatch(providers, options.providerId);
if (!provider) {
await params.prompter.note(
`${options.label} auth plugin is not available. Install or enable the plugin, then rerun onboarding. If this started after an update, run "openclaw doctor --fix" first.`,
options.label,
);
return { config: nextConfig };
}
const method = pickAuthMethod(provider, options.methodId) ?? provider.auth[0];
if (!method) {
await params.prompter.note(`${options.label} auth method missing.`, options.label);
return { config: nextConfig };
}
const configBeforeProviderAuth = nextConfig;
const applied = await runProviderPluginAuthMethod({
config: nextConfig,
env: params.env,
runtime: params.runtime,
prompter: params.prompter,
method,
agentDir,
agentId,
workspaceDir,
secretInputMode: params.opts?.secretInputMode,
allowSecretRefPrompt: false,
opts: params.opts,
});
nextConfig = applied.config;
if (applied.defaultModel) {
const selectedModel = applied.defaultModel;
const selectedModelDisplay = formatModelRefForDisplay(selectedModel, provider);
if (params.setDefaultModel) {
nextConfig = await applyDefaultModelFromAuthChoice({
config: nextConfig,
configBeforeProviderAuth,
selectedModel,
selectedModelDisplay,
preserveExistingDefaultModel: params.preserveExistingDefaultModel,
prompter: params.prompter,
runtime: params.runtime,
workspaceDir,
runSelectedModelHook: async (config) => {
await runProviderModelSelectedHook({
config,
model: selectedModel,
prompter: params.prompter,
agentDir,
workspaceDir,
});
},
});
return { config: nextConfig };
}
if (params.agentId) {
await params.prompter.note(
t("wizard.model.defaultSetForAgent", {
agent: params.agentId,
model: selectedModelDisplay,
}),
t("wizard.model.configuredTitle"),
);
}
nextConfig = restoreConfiguredPrimaryModel(nextConfig, params.config);
return { config: nextConfig, agentModelOverride: selectedModel };
}
return { config: nextConfig };
}
async function upsertAuthProfileWithLockOrThrow(params: UpsertAuthProfileParams): Promise<void> {
const updated = await upsertAuthProfileWithLock(params);
if (!updated) {
throw new Error(
"Failed to update auth profile store; the auth store lock may be busy. Wait a moment and retry.",
);
}
}
export { testing as __testing };