Official
codex
Codex agent provider: runs the Codex CLI's app-server for each account.
The app opens the listing; nothing installs until an agent in your Plugins workspace has read the files and you enable the plugin. In a terminal: dvg install divergence/codex@0.2.4
Permissions in 0.2.4
Files
auth.ts5.9 KB
// Account and gateway authorization finish only when Codex confirms success.
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import * as z from "zod";
import { Kernel } from "divergence/effect";
import type { CodexAgent } from "./agent.ts";
import { ProviderError, errorMessage } from "../sdk/errors.ts";
export const authenticate = Effect.fn("Codex.authenticate")(function* (this: CodexAgent, params?: { method: string }) {
if (params?.method.startsWith("gateway:")) return yield* gatewayLogin(this, params.method.slice("gateway:".length));
if (params && params.method !== "chatgpt") return yield* new ProviderError({ message: "Codex did not advertise that sign-in method." });
const { connection } = yield* this.client();
const response = yield* this.request(
connection,
"account/login/start",
{ type: "chatgpt" },
{ timeout: null },
).pipe(
Effect.mapError((error) => new ProviderError({ message: `account/login/start failed: ${errorMessage(error)}` })),
);
const login = Deferred.makeUnsafe<void, ProviderError>();
this.logins.set(response.loginId, login);
yield* Effect.gen(function* () {
const url = response.authUrl ?? response.verificationUrl;
if (typeof url === "string" && url) {
const kernel = yield* Kernel;
const result = yield* kernel
.call("open_url", { url })
.pipe(
Effect.mapError(
(error) => new ProviderError({ message: `open ${url} in a browser to sign in (${errorMessage(error)})` }),
),
);
if (result.opened === false)
return yield* new ProviderError({
message: `open ${url} in a browser to sign in (${result.reason ?? "the link was not opened"})`,
});
}
yield* Deferred.await(login);
}).pipe(
// A sign-in left behind (the page could not be opened, or the host
// gave up) is cancelled, so Codex stops waiting for its browser.
Effect.onError(() =>
Deferred.isDoneUnsafe(login)
? Effect.void
: this.request(connection, "account/login/cancel", { loginId: response.loginId }).pipe(
Effect.catchTag(["TransportFailed", "ParseFailed"], (error) =>
Effect.sync(() => console.warn(`could not cancel the codex sign-in: ${errorMessage(error)}`)),
),
),
),
Effect.ensuring(Effect.sync(() => this.logins.delete(response.loginId))),
);
this.accountDirty = true;
this.invalidateQuota();
return {};
});
export const gatewayChanged = Effect.fn("Codex.gatewayChanged")(function* (agent: CodexAgent, params: unknown) {
const event = z.object({ providerId: z.string(), loginId: z.string().nullable(), authUrl: z.string().nullable(), status: z.string(), error: z.string().nullable() }).safeParse(params);
if (!event.success) {
agent.notice("", "warning", `Codex sent an unreadable gateway sign-in update: ${event.error.message}`);
return;
}
const { providerId, authUrl, status, error } = event.data;
const pending = agent.gatewayLogins.get(providerId);
if (!pending || (pending.loginId !== undefined && pending.loginId !== event.data.loginId)) return;
const login = pending.done;
if (authUrl) {
const opened = yield* Effect.result(openSignIn(authUrl));
if (opened._tag === "Failure") {
Deferred.doneUnsafe(login, Effect.fail(new ProviderError({ message: errorMessage(opened.failure) })));
return;
}
}
if (status === "succeeded" || status === "failed") Deferred.doneUnsafe(login, status === "succeeded" ? Effect.void : Effect.fail(new ProviderError({ message: error ?? "Gateway sign-in failed." })));
});
const openSignIn = Effect.fn("Codex.openSignIn")(function* (url: string) {
const kernel = yield* Kernel;
const result = yield* kernel.call("open_url", { url });
if (result.opened === false) return yield* new ProviderError({ message: `Open ${url} to sign in (${result.reason ?? "the link was not opened"}).` });
});
const gatewayLogin = Effect.fn("Codex.gatewayLogin")(function* (agent: CodexAgent, provider: string) {
const { connection } = yield* agent.client();
const state = yield* agent.request(connection, "account/gatewayOAuth/read", { modelProvider: provider });
if (!state.required) return yield* new ProviderError({ message: `${state.providerName} does not use gateway sign-in.` });
if (agent.gatewayLogins.size) return yield* new ProviderError({ message: "Finish the pending gateway sign-in first." });
const login = Deferred.makeUnsafe<void, ProviderError>();
const pending: { done: typeof login; loginId?: string | null } = { done: login };
agent.gatewayLogins.set(provider, pending);
yield* Effect.gen(function* () {
const response = yield* agent.request(connection, "account/gatewayOAuth/login", { modelProvider: provider, deviceAuth: state.supportsDeviceAuth === true }, { timeout: null });
pending.loginId = response.prompt?.loginId ?? null;
if (response.prompt) {
agent.notice("", "info", `Enter code ${response.prompt.userCode} at ${response.prompt.verificationUrl} to sign in to ${state.providerName}.`);
yield* openSignIn(response.prompt.verificationUrl);
}
if (!response.prompt) {
const current = yield* agent.request(connection, "account/gatewayOAuth/read", { modelProvider: provider });
if (current.status === "succeeded") Deferred.doneUnsafe(login, Effect.void);
if (current.status === "failed") Deferred.doneUnsafe(login, Effect.fail(new ProviderError({ message: current.error ?? "Gateway sign-in failed." })));
}
yield* Deferred.await(login);
}).pipe(
Effect.onError(() => agent.request(connection, "account/gatewayOAuth/cancel").pipe(Effect.catchTag(["TransportFailed", "ParseFailed"], (error) => Effect.sync(() => console.warn(`Could not cancel gateway sign-in: ${errorMessage(error)}`))))),
Effect.ensuring(Effect.sync(() => agent.gatewayLogins.delete(provider))),
);
agent.models.delete(provider);
agent.accountDirty = true;
agent.invalidateQuota();
return {};
});
No comments yet.