Skip to content

An open-source, faster Devin alternative

TypeScript

cli: model connect second review round (work 082)

Igor Zalutski via Computer37d79bf5c934
diff --git a/cli/src/codex-oauth.test.ts b/cli/src/codex-oauth.test.ts
index ea6c5742..8af2c9a1 100644
--- a/cli/src/codex-oauth.test.ts
+++ b/cli/src/codex-oauth.test.ts
@@ -37,3 +37,24 @@ test("Codex OAuth callback closes its listener before resolving", async () => {
rebound.close((error) => (error ? reject(error) : resolve())),
);
});
+
+test("Codex OAuth callback says what holds port 1455 when it is in use", async () => {
+ const holder = http.createServer();
+ await new Promise<void>((resolve) => holder.listen(0, "127.0.0.1", resolve));
+ const port = (holder.address() as AddressInfo).port;
+ try {
+ await assert.rejects(
+ exchangeCodeOnCallback("https://auth.openai.com/oauth/authorize", "state", port, () => {
+ assert.fail("the browser must not open when the port cannot be bound");
+ }),
+ (error: unknown) =>
+ error instanceof Error &&
+ (error as NodeJS.ErrnoException).code === "EADDRINUSE" &&
+ error.message === `Port ${String(port)} is in use: another Codex sign-in is holding it; close it and retry.`,
+ );
+ } finally {
+ await new Promise<void>((resolve, reject) =>
+ holder.close((error) => (error ? reject(error) : resolve())),
+ );
+ }
+});
diff --git a/cli/src/codex-oauth.ts b/cli/src/codex-oauth.ts
index a80f0412..b4be3eae 100644
--- a/cli/src/codex-oauth.ts
+++ b/cli/src/codex-oauth.ts
@@ -39,7 +39,13 @@ function base64url(bytes: Uint8Array): string {
.replace(/=+$/, "");
}
-export async function codexLogin(): Promise<{
+/**
+ * Browser sign-in to ChatGPT. `originator` is the client the token is issued
+ * for; it must match the Originator header the token is later used with (the
+ * computer's Codex harness sends `codex_cli_rs`, the serverless-agents proxy
+ * `opencode`).
+ */
+export async function codexLogin(originator = "opencode"): Promise<{
credential: RelayedCodexCredential;
accountHint: string;
/** The OpenID id_token; a computer's Codex auth.json needs it (work 082). */
@@ -65,7 +71,7 @@ export async function codexLogin(): Promise<{
authorizeUrl.searchParams.set("code_challenge_method", "S256");
authorizeUrl.searchParams.set("id_token_add_organizations", "true");
authorizeUrl.searchParams.set("codex_cli_simplified_flow", "true");
- authorizeUrl.searchParams.set("originator", "opencode");
+ authorizeUrl.searchParams.set("originator", originator);
const authCode = await exchangeCodeOnCallback(
authorizeUrl.toString(),
@@ -152,7 +158,9 @@ export function exchangeCodeOnCallback(
finish(200, "Authorized. You can close this window.", { code });
});
- server.on("error", (error) => {
+ server.on("error", (error: NodeJS.ErrnoException) => {
+ if (error.code === "EADDRINUSE")
+ error.message = `Port ${String(port)} is in use: another Codex sign-in is holding it; close it and retry.`;
reject(error);
});
diff --git a/cli/src/commands.ts b/cli/src/commands.ts
index 4f669633..e4babcc3 100644
--- a/cli/src/commands.ts
+++ b/cli/src/commands.ts
@@ -334,7 +334,8 @@ async function connectComputerSubscription(
display.write(
"Opening your browser to sign in to ChatGPT. Use the account that has your plan.\n",
);
- const { credential, idToken } = await codexLogin();
+ // The computer's Codex harness uses the token as codex_cli_rs.
+ const { credential, idToken } = await codexLogin("codex_cli_rs");
body = {
code,
provider,
diff --git a/cli/src/computer-connect.test.ts b/cli/src/computer-connect.test.ts
index 54a7e071..39ed55bf 100644
--- a/cli/src/computer-connect.test.ts
+++ b/cli/src/computer-connect.test.ts
@@ -13,6 +13,7 @@ import {
codexAuthJson,
connectError,
findExecutable,
+ isClaudeSetupToken,
normalizeConnectCode,
runClaudeSetupToken,
sendComputerConnect,
@@ -57,10 +58,14 @@ test("model connect parses --code and --token-stdin", () => {
assert.deepEqual(rest, ["--project", "demo"]);
});
-test("connect codes are trimmed and accepted in any case", () => {
+test("connect codes are trimmed, accepted in any case, and read I/L as 1 and O as 0", () => {
assert.equal(normalizeConnectCode(" oc_7kqm2xp94htrwn3f\n"), CODE);
assert.equal(normalizeConnectCode("OC_7KQM2XP94HTRWN3F"), CODE);
assert.deepEqual(parse("codex", ["--code", " Oc_7kQm2Xp94hTrWn3F "]), { code: CODE, tokenStdin: false });
+ // The same reading as the server's, so a retyped code is sent as it means.
+ assert.equal(normalizeConnectCode("oc_1O0IL2XP94HTRWN3"), "oc_100112XP94HTRWN3");
+ assert.equal(normalizeConnectCode(" oc_iLoO2xp94htrwn3f "), "oc_11002XP94HTRWN3F");
+ assert.deepEqual(parse("claude", ["--code", "oc_7KQM2XP94HTRWN3F\t"]), { code: CODE, tokenStdin: false });
for (const bad of [
"oc_7KQM2XP94HTRWN3",
"oc_7KQM2XP94HTRWN3FF",
@@ -68,6 +73,7 @@ test("connect codes are trimmed and accepted in any case", () => {
"oc_7KQM 2XP94HTRWN3",
"occ_YWNjdF8xMjM.Zm9vYmFy",
"7KQM2XP94HTRWN3F",
+ "oc-7KQM2XP94HTRWN3F",
])
assert.equal(normalizeConnectCode(bad), undefined, bad);
});
@@ -223,6 +229,16 @@ test("connect errors read well and never carry the credential", async (context)
}),
new Response("not found", { status: 404 }),
Response.json({ error: { code: "internal", message: "boom" } }, { status: 500 }),
+ // An edge that predates connect codes answers 401 for the missing key.
+ Response.json({ error: { code: "unauthorized", message: "missing or invalid API key" } }, { status: 401 }),
+ Response.json(
+ { error: { code: "connect_in_slack", message: "Connect this plan from Slack: /opencomputer connect." } },
+ { status: 409 },
+ ),
+ Response.json(
+ { error: { code: "computer_harness_unavailable", message: "This computer has no Claude harness." } },
+ { status: 403 },
+ ),
];
context.mock.method(globalThis, "fetch", async () => answers.shift()!);
const client = new OpenComputerClient({ apiUrl: "https://app.opencomputer.dev" });
@@ -250,7 +266,26 @@ test("connect errors read well and never carry the credential", async (context)
assert.equal(problem.code, "connect_rejected");
assert.equal((await attempt()).code, "connect_unavailable");
- assert.equal((await attempt()).code, "internal");
+ const internal = await attempt();
+ assert.equal(internal.code, "internal");
+ assert.match(internal.hint, /Retry the command/);
+
+ // A 401 that is not the connect-code error keeps the server's words.
+ const oldEdge = await attempt();
+ assert.equal(oldEdge.code, "unauthorized");
+ assert.equal(oldEdge.message, "missing or invalid API key");
+ assert.match(oldEdge.hint, /Retry the command/);
+
+ // 403/409 cannot succeed on a retry: the server's message, no retry hint.
+ for (const [code, message] of [
+ ["connect_in_slack", "Connect this plan from Slack: /opencomputer connect."],
+ ["computer_harness_unavailable", "This computer has no Claude harness."],
+ ]) {
+ const refused = await attempt();
+ assert.equal(refused.code, code);
+ assert.equal(refused.message, message);
+ assert.equal(refused.hint, "");
+ }
for (const failure of [invalid, refused, problem])
assert.doesNotMatch(JSON.stringify(failure), /sk-ant-oat/);
@@ -314,6 +349,17 @@ test("a token repainted over an earlier frame is read from the screen, not the s
assert.doesNotMatch(output.replace(/\x1b\[[0-9;]*[A-Za-z]/g, ""), new RegExp(TOKEN));
});
+test("a setup token is what the server accepts: oat01 and a 20-400 character body", () => {
+ assert.ok(isClaudeSetupToken(TOKEN));
+ assert.ok(isClaudeSetupToken(`sk-ant-oat01-${"a".repeat(20)}`));
+ assert.ok(isClaudeSetupToken(`sk-ant-oat01-${"a".repeat(400)}`));
+ assert.ok(!isClaudeSetupToken(`sk-ant-oat01-${"a".repeat(19)}`));
+ assert.ok(!isClaudeSetupToken(`sk-ant-oat01-${"a".repeat(401)}`));
+ assert.ok(!isClaudeSetupToken(TOKEN.replace("oat01", "oat02")));
+ assert.ok(!isClaudeSetupToken(`${TOKEN}.`));
+ assert.equal(claudeTokenFromScreen([TOKEN.replace("oat01", "oat02")]), undefined);
+});
+
test("the last token on screen wins and partial tokens are ignored", () => {
assert.equal(claudeTokenFromScreen(["sk-ant-oat01-short"]), undefined);
const other = TOKEN.replace("AbCd", "WxYz");
@@ -388,6 +434,30 @@ process.stdout.write("\\r\\n \\x1b[2mStore this token securely.\\x1b[22m\\r\\n")
});
assert.equal(result.token, TOKEN);
assert.match(Buffer.concat(shown).toString("utf8"), /Store this token securely/);
+
+ // A long sign-in: the TUI repaints its frame on every spinner tick, so
+ // more than the capture limit is drawn before the token appears. The
+ // tail is what is kept, and the token is in it.
+ const slow = join(directory, "slow-setup-token.mjs");
+ await writeFile(
+ slow,
+ `import { writeSync } from "node:fs";
+if (!process.stdout.isTTY) process.exit(3);
+const t = ${JSON.stringify(TOKEN)};
+const frame = "\\x1b[2K\\r \\x1b[36m⠋\\x1b[39m Waiting for sign-in…".padEnd(1024, " ");
+for (let drawn = 0; drawn < 5 * 1024 * 1024; drawn += frame.length) writeSync(1, frame);
+writeSync(1, "\\x1b[2K\\r\\x1b[2GYour\\x1b[7GOAuth\\x1b[13Gtoken:\\r\\n\\r\\n");
+for (let i = 0; i < t.length; i += 50) writeSync(1, " \\x1b[33m" + t.slice(i, i + 50) + "\\x1b[39m\\r\\n");
+writeSync(1, "\\r\\n \\x1b[2mStore this token securely.\\x1b[22m\\r\\n");
+`,
+ );
+ const long = await runClaudeSetupToken(new PassThrough().resume(), {
+ command: "script",
+ args: ["-q", "-c", `${process.execPath} ${slow}`, "/dev/null"],
+ shell: false,
+ pty: true,
+ });
+ assert.equal(long.token, TOKEN);
} finally {
await rm(directory, { recursive: true, force: true });
}
diff --git a/cli/src/computer-connect.ts b/cli/src/computer-connect.ts
index 3c89588d..2b67bcdb 100644
--- a/cli/src/computer-connect.ts
+++ b/cli/src/computer-connect.ts
@@ -18,17 +18,25 @@ export type ComputerConnectProvider = "claude" | "codex";
export const DASHBOARD_CONNECT_HINT =
"Get a connect command from the dashboard (Computer → Agent).";
-/** `oc_` + 16 Crockford base32 characters (no I, L, O, U). */
-const CONNECT_CODE = /^oc_[0-9A-HJKMNP-TV-Z]{16}$/;
+const CONNECT_CODE_PREFIX = "oc_";
+/** 16 Crockford base32 characters (no I, L, O, U). */
+const CONNECT_CODE_BODY = /^[0-9A-HJKMNP-TV-Z]{16}$/;
/**
* The canonical connect code (`oc_` + upper-case body), accepting surrounding
- * whitespace and any letter case; undefined when it is not a connect code.
+ * whitespace, any letter case, and I/L for 1 and O for 0 (the same reading as
+ * the server's); undefined when it is not a connect code.
*/
export function normalizeConnectCode(value: string): string | undefined {
const trimmed = value.trim();
- const code = `${trimmed.slice(0, 3).toLowerCase()}${trimmed.slice(3).toUpperCase()}`;
- return CONNECT_CODE.test(code) ? code : undefined;
+ if (trimmed.slice(0, CONNECT_CODE_PREFIX.length).toLowerCase() !== CONNECT_CODE_PREFIX)
+ return undefined;
+ const body = trimmed
+ .slice(CONNECT_CODE_PREFIX.length)
+ .toUpperCase()
+ .replace(/[IL]/g, "1")
+ .replace(/O/g, "0");
+ return CONNECT_CODE_BODY.test(body) ? `${CONNECT_CODE_PREFIX}${body}` : undefined;
}
export interface ModelConnectArgs {
@@ -91,10 +99,10 @@ export function codexAuthJson(token: {
// ---------------------------------------------------------------------------
// Claude: `claude setup-token` and reading its token.
-const TOKEN_PREFIX = /sk-ant-oat\d{2}-/;
+const TOKEN_PREFIX = /sk-ant-oat01-/;
const TOKEN_CHARS = /^[A-Za-z0-9_-]+$/;
-/** A setup token: the prefix and a body far longer than any word wrap leaves. */
-const SETUP_TOKEN = /^sk-ant-oat\d{2}-[A-Za-z0-9_-]{32,}$/;
+/** A setup token, as the server accepts it: the oat01 prefix and a 20–400 character body. */
+const SETUP_TOKEN = /^sk-ant-oat01-[A-Za-z0-9_-]{20,400}$/;
export function isClaudeSetupToken(value: string): boolean {
return SETUP_TOKEN.test(value);
@@ -113,7 +121,7 @@ export function claudeTokenFromScreen(lines: readonly string[]): string | undefi
const match = TOKEN_PREFIX.exec(text);
if (!match) continue;
const rest = text.slice(match.index);
- const run = /^sk-ant-oat\d{2}-[A-Za-z0-9_-]*/.exec(rest)![0];
+ const run = /^sk-ant-oat01-[A-Za-z0-9_-]*/.exec(rest)![0];
let token = run;
if (run.length === rest.length) {
for (let next = index + 1; next < lines.length; next++) {
@@ -220,6 +228,12 @@ export interface SetupTokenResult {
pty: boolean;
}
+/**
+ * How much of the TUI's output is kept: the tail, since the TUI repaints its
+ * whole frame on every spinner tick and a long sign-in draws far more than
+ * this before the token appears. A full repaint re-establishes the screen,
+ * so the screen model needs only the recent stream.
+ */
const MAX_CAPTURE_CHARS = 4 * 1024 * 1024;
/** Runs `claude setup-token` interactively and reads the token it prints. */
@@ -237,7 +251,7 @@ export function runClaudeSetupToken(
let captured = "";
child.stdout?.on("data", (chunk: Buffer) => {
display.write(chunk);
- if (captured.length < MAX_CAPTURE_CHARS) captured += decoder.write(chunk);
+ captured = (captured + decoder.write(chunk)).slice(-MAX_CAPTURE_CHARS);
});
// Ctrl-C normally reaches the TUI as a keystroke (the PTY is raw); a
// signal to this process (kill, terminal closed) must not orphan it.
@@ -274,9 +288,13 @@ export function runClaudeSetupToken(
child.once("close", (exitCode, signal) => {
cleanup();
captured += decoder.end();
- const token = spec.pty
- ? claudeTokenFromTerminalOutput(captured, process.stdout.rows)
- : undefined;
+ // `script` sizes the PTY from stdin; stdout may be a pipe (no rows).
+ // Node types stdin as a plain ReadStream; a TTY stdin has rows.
+ const rows =
+ (process.stdin as NodeJS.ReadStream & { rows?: number }).rows ??
+ process.stdout.rows ??
+ 24;
+ const token = spec.pty ? claudeTokenFromTerminalOutput(captured, rows) : undefined;
captured = "";
// A SIGKILLed `script` cannot restore the terminal mode it changed.
if (forceKilled && spec.pty && process.stdin.isTTY)
@@ -329,7 +347,7 @@ export function connectError(
const message = redactSecrets(error.message, secrets);
const details = { status: error.status, ...(error.code ? { apiCode: error.code } : {}) };
const plan = provider === "claude" ? "Claude" : "ChatGPT";
- if (error.code === "computer_connect_code_invalid" || error.status === 401)
+ if (error.code === "computer_connect_code_invalid")
return new CLIError(
"connect_code_invalid",
"That connect code is not valid. Get a new one from the dashboard.",
@@ -352,6 +370,10 @@ export function connectError(
: `The code is still good: run the command again and sign in with the account that has your ${plan} plan.`,
details,
);
+ // 403/409 (no computer, connect in Slack, not a member) cannot succeed on a
+ // retry: the server's message says what to do, so there is no fix line.
+ if (error.status === 403 || error.status === 409)
+ return new CLIError(error.code ?? "connect_refused", message, "", details);
return new CLIError(
error.code ?? "connect_failed",
message,
diff --git a/cli/src/index.ts b/cli/src/index.ts
index 5a0d3900..961c9efa 100644
--- a/cli/src/index.ts
+++ b/cli/src/index.ts
@@ -172,7 +172,7 @@ main().catch((error: unknown) => {
process.stderr.write(`${JSON.stringify({ error: failure })}\n`);
} else {
process.stderr.write(
- `opencomputer: ${failure.message}\nfix: ${failure.hint}\n`,
+ `opencomputer: ${failure.message}\n${failure.hint ? `fix: ${failure.hint}\n` : ""}`,
);
}
process.exitCode = 1;