Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Merge pull request #4063 from gaokui2010/fix/chatgpt-plan-token-refresh

milind-sonid14d7a833ede
diff --cc server/drivers/codex-plan-token.test.ts
index 0000000000,0000000000..bcbe314d87
new file mode 100644
--- /dev/null
+++ b/server/drivers/codex-plan-token.test.ts
@@@ -1,0 -1,0 +1,33 @@@
++import { describe, expect, it, vi } from "vitest";
++import { planTokenRenewal } from "./codex-plan-token.ts";
++
++describe("Codex plan token renewal check", () => {
++ it("reads the version once, and again only after a snapshot saw another one", async () => {
++ const readVersion = vi.fn(async () => ({ version: "codex-cli 0.164.0" }));
++ const renewal = planTokenRenewal(readVersion);
++ expect(await renewal.supported()).toBe(false);
++ expect(await renewal.supported()).toBe(false);
++ expect(readVersion).toHaveBeenCalledTimes(1);
++ expect(renewal.noteVersion("codex-cli 0.165.0")).toBe(true);
++ expect(await renewal.supported()).toBe(true);
++ expect(renewal.noteVersion("codex-cli 0.164.0")).toBe(false);
++ expect(await renewal.supported()).toBe(false);
++ expect(readVersion).toHaveBeenCalledTimes(1);
++ });
++
++ it("shares a read in flight and asks again after a failed one", async () => {
++ let answer!: (probe: { version: string } | { reason: string }) => void;
++ const readVersion = vi.fn(() => new Promise<{ version: string } | { reason: string }>((resolve) => { answer = resolve; }));
++ const renewal = planTokenRenewal(readVersion);
++ const first = renewal.supported(), concurrent = renewal.supported();
++ expect(readVersion).toHaveBeenCalledTimes(1);
++ answer({ reason: "timed out" });
++ expect(await Promise.all([first, concurrent])).toEqual([false, false]);
++ const next = renewal.supported();
++ expect(readVersion).toHaveBeenCalledTimes(2);
++ answer({ version: "codex-cli 1.0.0" });
++ expect(await next).toBe(true);
++ expect(await renewal.supported()).toBe(true);
++ expect(readVersion).toHaveBeenCalledTimes(2);
++ });
++});
diff --cc server/drivers/codex-plan-token.ts
index 0000000000,0000000000..df97e1b707
new file mode 100644
--- /dev/null
+++ b/server/drivers/codex-plan-token.ts
@@@ -1,0 -1,0 +1,78 @@@
++// A ChatGPT plan run's sign-in, renewed while Codex works: Codex asks its `auth.command` for a token whenever it needs
++// one, and that command reads the current token from a local bridge only this run holds the secret for.
++import { SPAWNED_PROXIES } from "../proxy-paths.ts";
++import { startChatGptTokenBridge } from "./chatgpt-plan-token-bridge.ts";
++
++/** What a bridged run adds to Codex's environment; none of it may reach the agent's shell. */
++export const PLAN_TOKEN_BRIDGE_ENV = ["OMB_CODEX_AUTH_SOCKET", "OMB_CODEX_AUTH_SECRET", "ELECTRON_RUN_AS_NODE"];
++
++export interface PlanTokenBridge {
++ env: Record<string, string>;
++ close(): void;
++}
++
++/** The token-sharing Responses bridge carries no hosted tool_search (Codex 0.159.0 sends none), so
++ * a plan turn's MCP tools load up front. `renewing` hands Codex the token command in place of a fixed token. */
++export function chatgptPlanCodexArgs(renewing = false): string[] {
++ return [
++ "-c", 'model_provider="openai_chatgpt_plan"',
++ "-c", 'model_providers.openai_chatgpt_plan.name="ChatGPT plan"',
++ "-c", 'model_providers.openai_chatgpt_plan.base_url="https://api.openai.com/v1"',
++ ...(renewing ? [
++ "-c", `model_providers.openai_chatgpt_plan.auth.command=${JSON.stringify(process.execPath)}`,
++ "-c", `model_providers.openai_chatgpt_plan.auth.args=[${JSON.stringify(SPAWNED_PROXIES.chatgptPlanToken)}]`,
++ "-c", "model_providers.openai_chatgpt_plan.auth.refresh_interval_ms=30000",
++ "-c", "model_providers.openai_chatgpt_plan.auth.timeout_ms=60000",
++ ] : ["-c", 'model_providers.openai_chatgpt_plan.env_key="OPENMAUSBOT_CHATGPT_TOKEN"']),
++ "-c", 'model_providers.openai_chatgpt_plan.wire_api="responses"',
++ "-c", "model_providers.openai_chatgpt_plan.requires_openai_auth=false",
++ "-c", "model_providers.openai_chatgpt_plan.supports_websockets=false",
++ "-c", 'cli_auth_credentials_store="ephemeral"',
++ "-c", "features.tool_search=false",
++ "-c", "shell_environment_policy.ignore_default_excludes=false",
++ // OPENMAUSBOT_CHATGPT_TOKEN is excluded via extendShellExclusions: a `-c exclude` here would replace the lower layers' list.
++ ];
++}
++
++const renewsToken = (version: string) => {
++ const match = version.match(/\b(\d+)\.(\d+)\.(\d+)\b/);
++ return !!match && (Number(match[1]) > 0 || Number(match[2]) >= 165);
++};
++
++/** Whether this driver's Codex (0.165.0 or later) can renew the token through `auth.command`. The answer is kept
++ * until a snapshot reads another version, after an update, so a turn does not wait on `codex --version` each time.
++ * A failed read is not kept: the next turn asks again. */
++export function planTokenRenewal(readVersion: () => Promise<{ version: string } | { reason: string }>) {
++ let known: boolean | undefined;
++ let pending: Promise<boolean> | undefined;
++ return {
++ supported(): Promise<boolean> {
++ if (known !== undefined) return Promise.resolve(known);
++ pending ??= readVersion().then((probe) => "version" in probe ? (known = renewsToken(probe.version)) : false)
++ .finally(() => { pending = undefined; });
++ return pending;
++ },
++ /** Records the version a snapshot just read and answers whether it renews. */
++ noteVersion(version: string): boolean {
++ return (known = renewsToken(version));
++ },
++ };
++}
++
++/** `stillCurrent` throws once the account changed or the task ended; it runs before and after every token read. */
++export async function startPlanTokenBridge(accessToken: () => Promise<string>, stillCurrent: () => void): Promise<PlanTokenBridge> {
++ const bridge = await startChatGptTokenBridge(async () => {
++ stillCurrent();
++ const token = await accessToken();
++ stillCurrent();
++ return token;
++ });
++ try {
++ stillCurrent();
++ } catch (error) {
++ bridge.close();
++ throw error;
++ }
++ // The token command runs on this app's own runtime, which in the desktop app is Electron.
++ return { env: { ...bridge.env, ELECTRON_RUN_AS_NODE: "1" }, close: () => bridge.close() };
++}
diff --cc server/drivers/codex.ts
index e08aaf5b38,0d6883e3ef..8f9e0d538d
--- a/server/drivers/codex.ts
+++ b/server/drivers/codex.ts
@@@ -21,9 -16,11 +21,11 @@@ import { hostedWorkspaceConfigured } fr
import { cloudHomeConfigured } from "../cloud-home.ts";
import { serverVersion } from "../environment.ts";
import { ChatGptPlanAuthController } from "./chatgpt-plan-auth.ts";
-import { startChatGptTokenBridge } from "./chatgpt-plan-token-bridge.ts";
-import { chatgptPlanCodexArgs, managedCodexArgs, decodeManagedCodex, createDynamicPlanSupport } from "./codex-provider-config.ts";
-export { chatgptPlanCodexArgs, managedCodexArgs } from "./codex-provider-config.ts";
-import { captureCliTree, cliVersionReader, describeSpawnFailure, execCli, killCliTree, spawnCli, waitForExit } from "../procs.ts";
-import { codexLaunch, codexLaunchesStarting, codexLaunchSlot, codexRpcTimeoutMs, keepStopping, RELAUNCH_EXIT_WAIT_MS, spawnHoldingSlot, tomlInlineTable, tryCodexLaunchSlot } from "./codex-process.ts";
++import { chatgptPlanCodexArgs, PLAN_TOKEN_BRIDGE_ENV, planTokenRenewal, startPlanTokenBridge, type PlanTokenBridge } from "./codex-plan-token.ts";
++export { chatgptPlanCodexArgs } from "./codex-plan-token.ts";
+import { captureCliTree, describeSpawnFailure, killCliTree, spawnCli, waitForExit } from "../procs.ts";
+import { cliVersionProbe } from "../cli-version-probe.ts";
+import { codexLaunch, codexLaunchesStarting, codexLaunchSlot, codexRpcTimeoutMs, keepStopping, RELAUNCH_EXIT_WAIT_MS, spawnHoldingSlot, tryCodexLaunchSlot } from "./codex-process.ts";
import { isReservedMcpEnvEntry } from "../mcp-registry.ts";
import type {
@@@ -361,16 -447,14 +345,18 @@@ export const CodexDriver: ProviderDrive
delete env.OPENAI_API_KEY;
stripWorkspaceCredentialEnv(env);
delete env.OPENMAUSBOT_CHATGPT_TOKEN;
- delete env.OMB_CODEX_AUTH_SOCKET;
- delete env.OMB_CODEX_AUTH_SECRET;
+ delete env.OPENMAUSBOT_CODEX_API_KEY;
++ for (const name of PLAN_TOKEN_BRIDGE_ENV) delete env[name];
+ if (config.endpoint) {
+ env.OPENMAUSBOT_CODEX_API_KEY = input.environment.OPENMAUSBOT_CODEX_API_KEY;
+ env.CODEX_HOME = input.environment.CODEX_HOME;
+ }
if (plan) env.CODEX_HOME = join(planDirectory, "codex");
return env;
};
const catalogEnv = childEnv();
const planAuth = plan ? new ChatGptPlanAuthController({ directory: planDirectory }) : null;
- const dynamicPlanSupport = plan && !planUnavailable ? createDynamicPlanSupport(config.cli, catalogEnv, execCli) : async () => false;
++ const planRenewal = planTokenRenewal(() => readCliVersion(catalogEnv));
let planGeneration = 0;
let planSigningOut = false;
let disposed = false;
@@@ -534,10 -599,9 +520,10 @@@
const chatgptTurn = ownLogin &&
decodeCodexSelection(turn.model || models.default).modelProvider === OFFICIAL_CODEX_PROVIDER;
const route: CodexRoute = plan ? "plan" : chatgptTurn ? "own" : "other";
- const signedOut = chatgptTurn && await loginCheck(childEnv()) === "missing";
- assertPlanCurrent();
- if (active.has(threadId)) throw new Error("a turn is already running on this thread");
+ const hideRefusedModel = (raw: string) => hidePlanRefusedModel(turn.model, raw, route);
+ const signedOut = chatgptTurn && await loginCheck.check(childEnv()) === "missing";
- assertPlanCurrent();
- if (active.has(threadId)) throw new Error("a turn is already running on this thread");
++ const authBridge = planAuth && await planRenewal.supported() ? await startPlanTokenBridge(() => planAuth.accessToken(), () => { assertPlanCurrent(); if (stopRequested) throw new Error("This task has ended."); }) : null;
++ try { assertPlanCurrent(); if (active.has(threadId)) throw new Error("a turn is already running on this thread"); } catch (error) { authBridge?.close(); throw error; }
const turnId = newId();
if (signedOut) {
emit({ ...base(threadId, turnId), type: "turn.started" });
@@@ -555,7 -631,8 +541,7 @@@
emit({ ...base(threadId, turnId), type: "runtime.notice", message: `Waiting for a free Codex slot: ${codexLaunchesStarting()} Codex runs are starting on this computer. This one starts on its own.` });
const slot = await codexLaunchSlot(stopSignal.signal);
if (slot && !stopRequested) return slot;
-- slot?.();
- authBridge?.close();
++ slot?.(); authBridge?.close();
if (active.get(threadId) === waiting) {
active.delete(threadId);
emit({ ...base(threadId, turnId), type: "turn.completed", ok: false, stopReason: "interrupted", cost: null });
@@@ -565,10 -642,11 +551,10 @@@
const launchAttempt = async (attempt: number): Promise<void> => {
const env = childEnv();
const launchedLogin = chatgptTurn ? storedCodexLogin(env) : null;
- if (planToken) env.OPENMAUSBOT_CHATGPT_TOKEN = planToken;
- const appServerArgs = ["app-server", ...(plan ? chatgptPlanCodexArgs() : config.endpoint ? endpointCodexArgs(config.endpoint) : config.managed ? managedCodexArgs(config.managed) : codexSelectedProviderArgs(env, turn.model)), ...codexToolSurfaceArgs(),
- if (planToken && !authBridge) env.OPENMAUSBOT_CHATGPT_TOKEN = planToken;
- if (authBridge) Object.assign(env, authBridge.env, { ELECTRON_RUN_AS_NODE: "1" });
- const appServerArgs = ["app-server", ...(plan ? chatgptPlanCodexArgs(!!authBridge) : config.managed ? managedCodexArgs(config.managed) : codexLocalProviderArgs(env, turn.model)), ...codexToolSurfaceArgs(),
++ if (authBridge) Object.assign(env, authBridge.env); else if (planToken) env.OPENMAUSBOT_CHATGPT_TOKEN = planToken;
++ const appServerArgs = ["app-server", ...(plan ? chatgptPlanCodexArgs(!!authBridge) : config.endpoint ? endpointCodexArgs(config.endpoint) : config.managed ? managedCodexArgs(config.managed) : codexSelectedProviderArgs(env, turn.model)), ...codexToolSurfaceArgs(),
// Native shell snapshots can restore variables the shell policy removed.
- ...(turn.toolScope === undefined ? [] : ["-c", "features.shell_snapshot=false"]),
+ ...(turn.toolScope === undefined && !authBridge ? [] : ["-c", "features.shell_snapshot=false"]),
// A guest-driven turn: no shell, no file reads (-c wins over config files).
...(turn.guestConfined ? GUEST_CONFINED_CODEX_ARGS : [])];
const baseEnv = new Map(Object.entries(env).filter(([, value]) => value !== undefined));
@@@ -797,7 -871,8 +783,7 @@@
const settle = async (ok: boolean, stopReason: string | null) => {
if (state.settled) return;
-- state.settled = true;
- authBridge?.close();
++ state.settled = true; authBridge?.close();
for (const finish of Array.from(asks.values())) finish("deny", "OpenMausBot: the turn ended", "system");
for (const p of rpcPending.values()) p.reject(new Error("turn settled"));
rpcPending.clear();
@@@ -826,7 -901,7 +812,7 @@@
return settle(false, failedStop);
}
await interruptibleDelay(Math.max(1, Math.round(delayMs * retryScale)), stopSignal.signal).promise;
-- if (!stopRequested) void launchAttempt(attempt).catch(() => {});
++ if (!stopRequested) void launchAttempt(attempt).catch(() => authBridge?.close());
else await settle(false, "interrupted");
};
@@@ -1357,7 -1430,7 +1343,7 @@@
throw new Error("Codex could not confirm its shell environment policy. No prompt was sent.");
}
selectionConfig.config = { ...selectionConfig.config,
- ...extendShellExclusions((rawPolicy ?? {}) as Record<string, unknown>, [...(plan ? ["OPENMAUSBOT_CHATGPT_TOKEN"] : []), ...privateEnv]) };
- ...extendShellExclusions((rawPolicy ?? {}) as Record<string, unknown>, [...(plan ? ["OPENMAUSBOT_CHATGPT_TOKEN"] : []), ...(authBridge ? ["OMB_CODEX_AUTH_SOCKET", "OMB_CODEX_AUTH_SECRET", "ELECTRON_RUN_AS_NODE"] : []), ...privateEnv]) };
++ ...extendShellExclusions((rawPolicy ?? {}) as Record<string, unknown>, [...(plan ? ["OPENMAUSBOT_CHATGPT_TOKEN"] : []), ...(authBridge ? PLAN_TOKEN_BRIDGE_ENV : []), ...privateEnv]) };
}
if (turn.toolScope !== undefined) {
const catalog = (effectiveConfig as { mcp_servers?: unknown } | null)?.mcp_servers;
@@@ -1546,7 -1616,12 +1532,7 @@@
}
};
- void launchAttempt(0).catch(() => {});
- void launchAttempt(0).catch((error: unknown) => {
- authBridge?.close();
- if (active.get(threadId)?.turnId === turnId) active.delete(threadId);
- emit({ ...base(threadId, turnId), type: "runtime.error", message: error instanceof Error ? error.message : String(error) });
- emit({ ...base(threadId, turnId), type: "turn.completed", ok: false, stopReason: "launch_error", cost: null });
- });
++ void launchAttempt(0).catch(() => authBridge?.close());
return { turnId };
};
@@@ -1554,12 -1629,16 +1540,13 @@@
const snapshot = async (): Promise<ProviderSnapshot> => {
if (planUnavailable) return { state: "unavailable", authenticated: false, chatgptPlan: true, reason: planUnavailable, authenticationUnavailableReason: planUnavailable };
const env = childEnv();
- const probe = await new Promise<ReturnType<typeof versionOf>>((resolve) => {
- execCli(config.cli, ["--version"], { timeout: 8000, env }, (err, stdout) => resolve(versionOf(err, stdout)));
- });
+ const probe = await readCliVersion(env);
if (!("version" in probe)) return { state: "unavailable", reason: probe.reason, ...(plan ? { chatgptPlan: true } : {}) };
const { version } = probe;
- if (planAuth) {
- const warning = planWarning ?? (!(await dynamicPlanSupport()) ? "Update Codex to 0.165.0 or newer to renew ChatGPT credentials during a running task." : undefined);
- return { state: "available", version, chatgptPlan: true, billing: "subscription", ...await planAuth.snapshot(), update: await codexReleaseUpdate(version, config.cli),
- ...(warning ? { warning: { title: "Check ChatGPT connection", message: warning } } : {}) };
- }
++ const warning = planWarning ?? (planAuth && !planRenewal.noteVersion(version) ? "Update Codex to 0.165.0 or newer to renew ChatGPT credentials during a running task." : undefined);
+ if (planAuth) return { state: "available", version, chatgptPlan: true, billing: "subscription", ...await planAuth.snapshot(), update: await codexReleaseUpdate(version, config.cli),
- ...(planWarning ? { warning: { title: "Check ChatGPT connection", message: planWarning } } : {}) };
++ ...(warning ? { warning: { title: "Check ChatGPT connection", message: warning } } : {}) };
+ if (config.endpoint) return { state: "available", version, authenticated: Boolean(input.environment.OPENMAUSBOT_CODEX_API_KEY && input.environment.CODEX_HOME), billing: "metered" };
if (config.managed) return { state: "available", version, authenticated: Boolean(input.environment.OPENMAUSBOT_COMPANY_API_KEY && input.environment.CODEX_HOME), billing: "metered" };
const previousCliVersion = modelsCliVersion;
modelsCliVersion = version;
@@@ -1589,39 -1667,45 +1576,46 @@@
if (planUnavailable) throw new Error(planUnavailable);
const env = childEnv();
let providerArgs: string[] = [];
- let authBridge: Awaited<ReturnType<typeof startChatGptTokenBridge>> | null = null;
++ let authBridge: PlanTokenBridge | null = null;
if (planAuth) {
if (planSigningOut) throw new Error("This ChatGPT account is being disconnected.");
+ const generation = planGeneration;
++ const stillCurrent = () => { if (planSigningOut || disposed || generation !== planGeneration) throw new Error("This ChatGPT account changed."); };
if (!models.options.length) await refreshModels();
- env.OPENMAUSBOT_CHATGPT_TOKEN = await planAuth.accessToken();
- if (planSigningOut || disposed) throw new Error("This ChatGPT account is being disconnected.");
+ const token = await planAuth.accessToken();
- if (planSigningOut || disposed || generation !== planGeneration) throw new Error("This ChatGPT account changed.");
- mkdirSync(join(planDirectory, "codex"), { recursive: true, mode: 0o700 });
- const dynamic = await dynamicPlanSupport();
- if (planSigningOut || disposed || generation !== planGeneration) throw new Error("This ChatGPT account changed.");
- if (dynamic) {
- authBridge = await startChatGptTokenBridge(async () => {
- if (planSigningOut || disposed || generation !== planGeneration) throw new Error("This ChatGPT account changed.");
- const value = await planAuth.accessToken();
- if (planSigningOut || disposed || generation !== planGeneration) throw new Error("This ChatGPT account changed.");
- return value;
- });
- if (planSigningOut || disposed || generation !== planGeneration) { authBridge.close(); throw new Error("This ChatGPT account changed."); }
- Object.assign(env, authBridge.env, { ELECTRON_RUN_AS_NODE: "1" });
- } else env.OPENMAUSBOT_CHATGPT_TOKEN = token;
++ stillCurrent();
+ linkSharedCodexHome(codexHome({ ...process.env, ...input.environment }), join(planDirectory, "codex"));
- providerArgs = chatgptPlanCodexArgs();
++ const renewing = await planRenewal.supported();
++ stillCurrent();
++ authBridge = renewing ? await startPlanTokenBridge(() => planAuth.accessToken(), stillCurrent) : null;
++ Object.assign(env, authBridge?.env ?? { OPENMAUSBOT_CHATGPT_TOKEN: token });
+ providerArgs = chatgptPlanCodexArgs(!!authBridge);
+ } else if (config.endpoint) {
+ if (!input.environment.OPENMAUSBOT_CODEX_API_KEY || !input.environment.CODEX_HOME) throw new Error("Direct API key or isolated Codex home is missing. Edit the endpoint in Settings.");
+ mkdirSync(input.environment.CODEX_HOME, { recursive: true, mode: 0o700 });
+ providerArgs = endpointCodexArgs(config.endpoint);
} else if (config.managed) {
if (!input.environment.OPENMAUSBOT_COMPANY_API_KEY || !input.environment.CODEX_HOME) {
throw new Error("Company model access is unavailable. Reconnect your organization; personal billing will not be used.");
}
providerArgs = managedCodexArgs(config.managed);
}
- const route = codexBackgroundRoute(models, smallModelsUsable(), options.fallback);
+ const route = codexBackgroundRoute(models, smallModelsUsable(), options.fallback, openaiUnreachable);
- if (!route) throw new Error("Codex lists no model for background calls. Refresh models in Settings → Model providers → Codex.");
- return runCodexBackgroundRoute(route, (id) => {
+ if (!route) { authBridge?.close(); throw new Error("Codex lists no model for background calls. Refresh models in Settings → Model providers → Codex."); }
+ try { return await runCodexBackgroundRoute(route, (id) => {
- const selection = planAuth || config.managed ? { model: id, modelProvider: null } : decodeCodexSelection(id);
+ const selection = planAuth || routed ? { model: id, modelProvider: null } : decodeCodexSelection(id);
return runCodexOneShot({
spawn: spawnCli, kill: killCliTree, cli: config.cli, env, prompt, options,
model: selection.model ?? id,
modelProvider: selection.modelProvider,
- providerArgs: planAuth || config.managed ? providerArgs : codexLocalProviderArgs(env, id),
- describeError: (message) => codexUserError(message, planAuth ? "plan" : selection.modelProvider === OFFICIAL_CODEX_PROVIDER ? "own" : "other"),
+ providerArgs: planAuth || routed ? providerArgs : codexBackgroundProviderArgs(env, id),
+ describeError: (message) => {
+ const route: CodexRoute = planAuth ? "plan" : selection.modelProvider === OFFICIAL_CODEX_PROVIDER ? "own" : "other";
+ hidePlanRefusedModel(selection.model ?? id, message, route);
+ return codexUserError(message, route);
+ },
});
- }, options, planAuth || config.managed ? undefined : () => { openaiUnreachable = true; });
- }, options); } finally { authBridge?.close(); }
++ }, options, planAuth || config.managed ? undefined : () => { openaiUnreachable = true; }); } finally { authBridge?.close(); }
};
return {
@@@ -1637,40 -1721,40 +1631,41 @@@
...(startupModelRefresh ? { startupModelRefresh } : {}),
generateMemoryText,
...(plan ? { authenticationMethod: "browser-pkce" as const } : {}),
- startAuthentication: async () => {
- if (planUnavailable) throw new Error(planUnavailable);
- if (planSigningOut || disposed) throw new Error("This account is being disconnected. Wait before signing in again.");
- // A new login may replace the account before its status is polled.
- if (planAuth) planGeneration++;
- return (planAuth ?? authentication).start();
- },
- getAuthentication: async (flowId) => {
- const result = await (planAuth ?? authentication).get(flowId);
- if (planAuth && result.phase === "succeeded") planWarning = undefined;
- if (planAuth && result.phase === "succeeded" && !models.options.length) await refreshModels();
- return result;
- },
- cancelAuthentication: () => (planAuth ?? authentication).cancel(),
- signOut: async () => {
- if (!planAuth) {
- const mark = loginMark();
- await authentication.signOut();
- loginAccepted(mark);
- return;
- }
- planSigningOut = true;
- planGeneration++;
- try {
- const stopped = await Promise.all([...active.values()].map(({ stop }) => stop()));
- if (stopped.some(value => !value)) throw new Error("A ChatGPT task could not stop safely. Stop the task before signing out.");
- models = { default: "", options: [] };
- await planAuth.signOut();
- planWarning = undefined;
- } catch (error) {
- if ((error as { code?: string }).code !== "chatgpt_revocation_unconfirmed") throw error;
- planWarning = (error as Error).message;
- } finally { planSigningOut = false; }
- },
+ ...(!config.endpoint ? {
+ startAuthentication: async () => {
+ if (planUnavailable) throw new Error(planUnavailable);
+ if (planSigningOut || disposed) throw new Error("This account is being disconnected. Wait before signing in again.");
++ if (planAuth) planGeneration++; // a new login may replace the account before its status is polled
+ return (planAuth ?? authentication).start();
+ },
+ getAuthentication: async (flowId: string) => {
+ const result = await (planAuth ?? authentication).get(flowId);
+ if (planAuth && result.phase === "succeeded") planWarning = undefined;
+ if (planAuth && result.phase === "succeeded" && !models.options.length) await refreshModels();
+ return result;
+ },
+ cancelAuthentication: () => (planAuth ?? authentication).cancel(),
+ signOut: async () => {
+ if (!planAuth) {
+ const mark = loginMark();
+ await authentication.signOut();
+ loginAccepted(mark);
+ return;
+ }
+ planSigningOut = true;
+ planGeneration++;
+ try {
+ const stopped = await Promise.all([...active.values()].map(({ stop }) => stop()));
+ if (stopped.some(value => !value)) throw new Error("A ChatGPT task could not stop safely. Stop the task before signing out.");
+ models = { default: "", options: [] };
+ await planAuth.signOut();
+ planWarning = undefined;
+ } catch (error) {
+ if ((error as { code?: string }).code !== "chatgpt_revocation_unconfirmed") throw error;
+ planWarning = (error as Error).message;
+ } finally { planSigningOut = false; }
+ },
+ } : {}),
snapshot,
adapter: {
provider: DRIVER_KIND,