Skip to content

An open-source, faster Devin alternative

TypeScript

cli: model connect claude|codex --code for the computer (work 082)

Igor Zalutski via Computer0be78d180f35
diff --git a/cli/README.md b/cli/README.md
index 3546e8cf..abefa44c 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -44,6 +44,32 @@ opencomputer run hello-world "Say hello"
The CLI calls the public OpenComputer API and uses OpenComputer authentication.
It does not require a separate backend account, key, or CLI.
+## Connect a Claude or ChatGPT plan to your computer
+
+The dashboard (Computer → Agent) shows one command per plan, with a connect
+code that works once and lasts 10 minutes. Run it anywhere; it needs no
+OpenComputer login:
+
+```bash
+npx -y @opencomputer/cli model connect claude --code <code>
+npx -y @opencomputer/cli model connect codex --code <code>
+```
+
+`claude` runs `claude setup-token` (through `npx -y @anthropic-ai/claude-code`
+when Claude Code is not installed): sign in, and the CLI reads the token it
+prints and sends it with the code. On macOS and Linux the TUI runs under
+`script` so the CLI can read what it draws; elsewhere you paste the token when
+asked. To supply the token yourself, pipe it in:
+`printf %s "$TOKEN" | npx -y @opencomputer/cli model connect claude --code <code> --token-stdin`.
+
+`codex` opens a ChatGPT sign-in in your browser. Each connect is its own
+sign-in; it never reads or reuses `~/.codex/auth.json`, so your own Codex CLI
+stays signed in.
+
+Neither command prints or stores the credential. A rejected credential leaves
+the code usable; run the command again. `--json` prints the API's answer.
+`model` also answers to `models` and `model-access`.
+
## Agent webhooks
Create an environment-scoped webhook that starts a fresh session for the
diff --git a/cli/src/api.ts b/cli/src/api.ts
index 4f34b304..a4b0a384 100644
--- a/cli/src/api.ts
+++ b/cli/src/api.ts
@@ -482,11 +482,31 @@ function errorMessage(body: unknown, status: number): string {
const message = (record.error as Record<string, unknown>).message;
if (typeof message === "string") return message;
}
+ if (typeof record.detail === "string") return record.detail;
if (typeof record.message === "string") return record.message;
+ if (typeof record.title === "string") return record.title;
}
return `OpenComputer request failed (${status})`;
}
+/** `POST /api/managed-agents/computer/agent/connect`: the connect code is the only credential. */
+export interface ComputerConnectRequest {
+ code: string;
+ provider: "claude" | "codex";
+ /** Claude: the `claude setup-token` token. */
+ token?: string;
+ /** Codex: the Codex CLI auth.json object. */
+ authJson?: {
+ auth_mode: "chatgpt";
+ tokens: { id_token: string; access_token: string; refresh_token: string };
+ };
+}
+
+export interface ComputerConnectResponse {
+ provider: "claude" | "codex";
+ connected: boolean;
+}
+
export class OpenComputerClient {
constructor(
private readonly config: ResolvedConfig,
@@ -622,6 +642,15 @@ export class OpenComputerClient {
return this.request<OpenComputerIdentity>("/api/whoami");
}
+ /** Unauthenticated on purpose: no API key is sent even when one is configured. */
+ connectComputerAgent(body: ComputerConnectRequest) {
+ return this.request<ComputerConnectResponse>(
+ "/api/managed-agents/computer/agent/connect",
+ { method: "POST", body: JSON.stringify(body) },
+ false,
+ );
+ }
+
revokeCredential() {
return this.request<void>("/auth/cli/credential", { method: "DELETE" });
}
diff --git a/cli/src/codex-oauth.ts b/cli/src/codex-oauth.ts
index 0c7a4639..a80f0412 100644
--- a/cli/src/codex-oauth.ts
+++ b/cli/src/codex-oauth.ts
@@ -25,6 +25,7 @@ export interface RelayedCodexCredential {
interface TokenResponse {
access_token: string;
+ id_token?: string;
refresh_token?: string;
token_type?: string;
expires_in: number;
@@ -41,6 +42,8 @@ function base64url(bytes: Uint8Array): string {
export async function codexLogin(): Promise<{
credential: RelayedCodexCredential;
accountHint: string;
+ /** The OpenID id_token; a computer's Codex auth.json needs it (work 082). */
+ idToken?: string;
}> {
const codeVerifier = base64url(randomBytes(32));
const challengeBytes = await crypto.subtle.digest(
@@ -86,6 +89,7 @@ export async function codexLogin(): Promise<{
expires_at: Date.now() + token.expires_in * 1_000,
},
accountHint: token.access_token.slice(0, 8),
+ idToken: typeof token.id_token === "string" ? token.id_token : undefined,
};
}
diff --git a/cli/src/commands.ts b/cli/src/commands.ts
index cf170647..5d442233 100644
--- a/cli/src/commands.ts
+++ b/cli/src/commands.ts
@@ -1,5 +1,6 @@
import {
OpenComputerClient,
+ type ComputerConnectRequest,
type ManagedAgentEvent,
type ManagedAgentLog,
type ManagedGitHubInstallation,
@@ -22,6 +23,15 @@ import {
UPGRADE_PLAN,
} from "./billing.js";
import { codexLogin } from "./codex-oauth.js";
+import {
+ codexAuthJson,
+ type ComputerConnectProvider,
+ connectSuccessMessage,
+ isClaudeSetupToken,
+ runClaudeSetupToken,
+ sendComputerConnect,
+ takeModelConnectArgs,
+} from "./computer-connect.js";
import { resolveConfig } from "./config.js";
import {
publishProjectDeployment,
@@ -286,22 +296,120 @@ function printDatabaseResult(result: {
);
}
-function consumeModelAccessProvider(
- args: string[],
-): "claude" | "codex" | "openrouter" | "openai-compatible" {
- if (
- args[0] === "claude" ||
- args[0] === "codex" ||
- args[0] === "openrouter" ||
- args[0] === "openai-compatible"
- ) {
- return args.shift() as
- "claude" | "codex" | "openrouter" | "openai-compatible";
- }
+type ModelAccessProvider = "claude" | "codex" | "openrouter" | "openai-compatible";
+
+function isModelAccessProvider(value: string | undefined): value is ModelAccessProvider {
+ return (
+ value === "claude" ||
+ value === "codex" ||
+ value === "openrouter" ||
+ value === "openai-compatible"
+ );
+}
+
+function consumeModelAccessProvider(args: string[]): ModelAccessProvider {
+ if (isModelAccessProvider(args[0])) return args.shift() as ModelAccessProvider;
return "codex";
}
-async function readTemplateSecretValue(): Promise<string> {
+/**
+ * `model connect claude|codex --code <code>`: obtain a fresh subscription
+ * credential on this machine and hand it, with the dashboard's connect code,
+ * to the organization's computer. Never reads ~/.codex/auth.json or Claude
+ * Code's own login: a separate login keeps the person's own CLIs signed in.
+ */
+async function connectComputerSubscription(
+ provider: ComputerConnectProvider,
+ code: string,
+ tokenStdin: boolean,
+ client: OpenComputerClient,
+ globals: GlobalOptions,
+): Promise<void> {
+ // Progress and the provider's own UI go to stderr under --json so stdout
+ // carries only the JSON answer.
+ const display = globals.json ? process.stderr : process.stdout;
+ let body: ComputerConnectRequest;
+ if (provider === "codex") {
+ display.write(
+ "Opening your browser to sign in to ChatGPT. Use the account that has your plan.\n",
+ );
+ const { credential, idToken } = await codexLogin();
+ body = {
+ code,
+ provider,
+ authJson: codexAuthJson({
+ idToken,
+ accessToken: credential.access_token,
+ refreshToken: credential.refresh_token,
+ }),
+ };
+ } else {
+ body = {
+ code,
+ provider,
+ token: tokenStdin
+ ? await claudeTokenFromStdin()
+ : await claudeTokenFromSetupToken(display),
+ };
+ }
+ const response = await sendComputerConnect(client, body);
+ if (globals.json) printJSON(response);
+ else process.stdout.write(connectSuccessMessage(provider));
+}
+
+async function claudeTokenFromStdin(): Promise<string> {
+ const token = (await readStdinValue(true)).trim();
+ if (!isClaudeSetupToken(token))
+ throw new CLIError(
+ "claude_token_invalid",
+ "Standard input is not a Claude setup token (sk-ant-oat01-…).",
+ "Pipe exactly the token `claude setup-token` printed.",
+ );
+ return token;
+}
+
+async function claudeTokenFromSetupToken(
+ display: NodeJS.WriteStream,
+): Promise<string> {
+ if (!process.stdin.isTTY)
+ throw new CLIError(
+ "interactive_terminal_required",
+ "`claude setup-token` needs an interactive terminal.",
+ "Run this in a terminal, or run `claude setup-token` yourself and pipe its token in with --token-stdin.",
+ );
+ display.write(
+ "Running `claude setup-token`. Sign in with the Claude account that has your plan;\n" +
+ "the token it creates goes to your computer and is not saved on this machine.\n\n",
+ );
+ const result = await runClaudeSetupToken(display);
+ if (result.token) {
+ display.write("\nRead the token. Connecting it to your computer…\n");
+ return result.token;
+ }
+ if (result.signal || (result.exitCode !== null && result.exitCode !== 0))
+ throw new CLIError(
+ "claude_setup_token_failed",
+ "`claude setup-token` did not finish.",
+ "Run the command again; the connect code still works until it is used or expires.",
+ );
+ // Windows (no PTY recorder), or output this CLI could not read: ask.
+ const pasted = (
+ await readTemplateSecretValue(
+ "Paste the token `claude setup-token` printed (input hidden): ",
+ )
+ ).replace(/\s+/g, "");
+ if (!isClaudeSetupToken(pasted))
+ throw new CLIError(
+ "claude_token_invalid",
+ "That is not a Claude setup token (sk-ant-oat01-…).",
+ "Run the command again and paste the whole token, or pipe it in with --token-stdin.",
+ );
+ return pasted;
+}
+
+async function readTemplateSecretValue(
+ prompt = "Secret value (hidden): ",
+): Promise<string> {
if (!process.stdin.isTTY) {
const chunks: Buffer[] = [];
for await (const chunk of process.stdin) {
@@ -313,7 +421,7 @@ async function readTemplateSecretValue(): Promise<string> {
if (!value) throw new Error("Secret value was empty");
return value;
}
- process.stderr.write("Secret value (hidden): ");
+ process.stderr.write(prompt);
process.stdin.setRawMode(true);
process.stdin.resume();
return new Promise<string>((resolve, reject) => {
@@ -2102,19 +2210,39 @@ export async function runCommand(
);
}
- if (command === "model-access") {
+ // `model` is the noun; `models` and `model-access` (the original name) are
+ // aliases with identical behaviour.
+ if (command === "model" || command === "models" || command === "model-access") {
const action = args.shift();
if (action === "connect") {
+ const namedProvider = isModelAccessProvider(args[0]);
+ const provider = consumeModelAccessProvider(args);
+ if (provider === "claude" || provider === "codex") {
+ // A connect code from the dashboard: connect the subscription to the
+ // organization's computer (work 082). No OpenComputer login needed.
+ const connect = takeModelConnectArgs(provider, args, {
+ option: (name) => option(args, name),
+ flag: (name) => flag(args, name),
+ });
+ if (connect.code !== undefined) {
+ if (!namedProvider)
+ throw new Error(
+ "Usage: opencomputer model connect claude|codex --code <code>",
+ );
+ await connectComputerSubscription(
+ provider,
+ connect.code,
+ connect.tokenStdin,
+ client,
+ globals,
+ );
+ return;
+ }
+ }
// Local Codex-account OAuth: open a localhost callback
// server, complete the flow in the user's browser, then relay the
// credential to OpenComputer as a connected account. Nothing secret
// is echoed or persisted locally.
- const provider = consumeModelAccessProvider(args);
- if (provider === "claude") {
- throw new Error(
- "Claude account BYOK is not supported. Connect a Codex account instead.",
- );
- }
if (provider === "openrouter" || provider === "openai-compatible") {
const projectReference = option(args, "--project");
const baseUrl = option(args, "--base-url");
diff --git a/cli/src/computer-connect.test.ts b/cli/src/computer-connect.test.ts
new file mode 100644
index 00000000..318d44c3
--- /dev/null
+++ b/cli/src/computer-connect.test.ts
@@ -0,0 +1,384 @@
+import assert from "node:assert/strict";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { PassThrough } from "node:stream";
+import test from "node:test";
+
+import { APIError, OpenComputerClient } from "./api.js";
+import { runCommand } from "./commands.js";
+import {
+ claudeTokenFromScreen,
+ claudeTokenFromTerminalOutput,
+ codexAuthJson,
+ connectError,
+ findExecutable,
+ runClaudeSetupToken,
+ sendComputerConnect,
+ setupTokenCommand,
+ takeModelConnectArgs,
+} from "./computer-connect.js";
+import { CLIError, structuredError } from "./errors.js";
+import { renderTerminalScreen } from "./terminal-screen.js";
+
+const TOKEN =
+ "sk-ant-oat01-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789_-AbCdEfGhIjKlMnOpQrStUvWxYz0123456789-ZyXwVu-QAA";
+const CODE = "occ_YWNjdF8xMjM.Zm9vYmFyYmF6cXV4cXV1eA";
+
+function parse(provider: "claude" | "codex", args: string[]) {
+ return takeModelConnectArgs(provider, args, {
+ option(name) {
+ const index = args.indexOf(name);
+ if (index < 0) return undefined;
+ const value = args[index + 1];
+ args.splice(index, 2);
+ return value;
+ },
+ flag(name) {
+ const index = args.indexOf(name);
+ if (index < 0) return false;
+ args.splice(index, 1);
+ return true;
+ },
+ });
+}
+
+test("model connect parses --code and --token-stdin", () => {
+ assert.deepEqual(parse("claude", ["--code", CODE]), { code: CODE, tokenStdin: false });
+ assert.deepEqual(parse("claude", ["--token-stdin", "--code", CODE]), {
+ code: CODE,
+ tokenStdin: true,
+ });
+ assert.deepEqual(parse("codex", ["--code", CODE]), { code: CODE, tokenStdin: false });
+ // codex without a code is left to the serverless-agent connect.
+ const rest = ["--project", "demo"];
+ assert.deepEqual(parse("codex", rest), { code: undefined, tokenStdin: false });
+ assert.deepEqual(rest, ["--project", "demo"]);
+});
+
+test("model connect rejects a missing or malformed code and stray arguments", () => {
+ assert.throws(
+ () => parse("claude", []),
+ (error: unknown) =>
+ error instanceof CLIError &&
+ error.code === "connect_code_required" &&
+ error.hint === "Get a connect command from the dashboard (Computer → Agent).",
+ );
+ assert.throws(
+ () => parse("claude", ["--code", "not-a-code"]),
+ (error: unknown) => error instanceof CLIError && error.code === "connect_code_invalid",
+ );
+ assert.throws(() => parse("codex", ["--code", CODE, "--token-stdin"]), /only for/);
+ assert.throws(() => parse("claude", ["--code", CODE, "--project", "x"]), /Unexpected argument: --project/);
+});
+
+async function withIsolatedConfig(fn: () => Promise<void>): Promise<void> {
+ const directory = await mkdtemp(join(tmpdir(), "oc-connect-"));
+ const previous = {
+ config: process.env.OPENCOMPUTER_CONFIG,
+ key: process.env.OPENCOMPUTER_API_KEY,
+ url: process.env.OPENCOMPUTER_API_URL,
+ };
+ process.env.OPENCOMPUTER_CONFIG = join(directory, "config.json");
+ delete process.env.OPENCOMPUTER_API_KEY;
+ delete process.env.OPENCOMPUTER_API_URL;
+ try {
+ await fn();
+ } finally {
+ for (const [name, value] of [
+ ["OPENCOMPUTER_CONFIG", previous.config],
+ ["OPENCOMPUTER_API_KEY", previous.key],
+ ["OPENCOMPUTER_API_URL", previous.url],
+ ] as const) {
+ if (value === undefined) delete process.env[name];
+ else process.env[name] = value;
+ }
+ await rm(directory, { recursive: true, force: true });
+ }
+}
+
+test("model, models and model-access are the same command", async (context) => {
+ await withIsolatedConfig(async () => {
+ const requests: Request[] = [];
+ context.mock.method(globalThis, "fetch", async (input: string | URL | Request, init?: RequestInit) => {
+ requests.push(new Request(input, init));
+ return Response.json({ data: [] });
+ });
+ const writes: string[] = [];
+ context.mock.method(process.stdout, "write", (chunk: string) => {
+ writes.push(String(chunk));
+ return true;
+ });
+ for (const noun of ["model", "models", "model-access"]) {
+ await assert.rejects(
+ runCommand(noun, ["connect", "claude"], { json: false }),
+ (error: unknown) => error instanceof CLIError && error.code === "connect_code_required",
+ );
+ await assert.rejects(
+ runCommand(noun, ["bogus"], { json: false }),
+ /Use `opencomputer model-access connect\|list\|disconnect`/,
+ );
+ await runCommand(noun, ["list"], { json: false, apiKey: "osb_test" });
+ }
+ assert.equal(requests.length, 3);
+ for (const request of requests) {
+ assert.equal(
+ request.url,
+ "https://app.opencomputer.dev/api/managed-agents/model-access/connections",
+ );
+ assert.equal(request.headers.get("x-api-key"), "osb_test");
+ }
+ assert.deepEqual(writes, Array(3).fill("No model access connections.\n"));
+ });
+});
+
+test("--code needs a named provider", async () => {
+ await withIsolatedConfig(async () => {
+ await assert.rejects(
+ runCommand("model", ["connect", "--code", CODE], { json: false }),
+ /Usage: opencomputer model connect claude\|codex --code <code>/,
+ );
+ });
+});
+
+test("Codex auth.json is the Codex CLI shape and needs every token", () => {
+ assert.deepEqual(
+ codexAuthJson({ idToken: "id.jwt", accessToken: "access", refreshToken: "refresh" }),
+ {
+ auth_mode: "chatgpt",
+ tokens: { id_token: "id.jwt", access_token: "access", refresh_token: "refresh" },
+ },
+ );
+ assert.throws(
+ () => codexAuthJson({ accessToken: "access", refreshToken: "refresh" }),
+ (error: unknown) => error instanceof CLIError && error.code === "codex_login_incomplete",
+ );
+ assert.throws(() => codexAuthJson({ idToken: "id", accessToken: "access" }), CLIError);
+});
+
+test("connect posts the code and credential without any API key", async (context) => {
+ const requests: Request[] = [];
+ context.mock.method(globalThis, "fetch", async (input: string | URL | Request, init?: RequestInit) => {
+ requests.push(new Request(input, init));
+ return Response.json({ provider: "claude", connected: true });
+ });
+ // Even with a key configured, the connect request must not carry it.
+ const client = new OpenComputerClient({ apiUrl: "http://localhost:8787", apiKey: "osb_secret" });
+ const response = await sendComputerConnect(client, { code: CODE, provider: "claude", token: TOKEN });
+ assert.deepEqual(response, { provider: "claude", connected: true });
+ const request = requests[0]!;
+ assert.equal(request.method, "POST");
+ assert.equal(request.url, "http://localhost:8787/api/managed-agents/computer/agent/connect");
+ assert.equal(request.headers.get("x-api-key"), null);
+ assert.equal(request.headers.get("authorization"), null);
+ assert.equal(request.headers.get("content-type"), "application/json");
+ assert.deepEqual(await request.json(), { code: CODE, provider: "claude", token: TOKEN });
+
+ await sendComputerConnect(client, {
+ code: CODE,
+ provider: "codex",
+ authJson: codexAuthJson({ idToken: "i", accessToken: "a", refreshToken: "r" }),
+ });
+ assert.deepEqual(await requests[1]!.json(), {
+ code: CODE,
+ provider: "codex",
+ authJson: { auth_mode: "chatgpt", tokens: { id_token: "i", access_token: "a", refresh_token: "r" } },
+ });
+});
+
+test("connect errors read well and never carry the credential", async (context) => {
+ const answers = [
+ Response.json(
+ {
+ error: {
+ code: "computer_connect_code_invalid",
+ message: "That connect code is not valid. Get a new one from the dashboard.",
+ },
+ },
+ { status: 401 },
+ ),
+ Response.json(
+ { error: { code: "computer_agent_claude_token", message: `Claude refused ${TOKEN}` } },
+ { status: 422 },
+ ),
+ new Response(JSON.stringify({ title: "Bad", detail: "The token was not accepted." }), {
+ status: 422,
+ headers: { "content-type": "application/problem+json" },
+ }),
+ new Response("not found", { status: 404 }),
+ Response.json({ error: { code: "internal", message: "boom" } }, { status: 500 }),
+ ];
+ context.mock.method(globalThis, "fetch", async () => answers.shift()!);
+ const client = new OpenComputerClient({ apiUrl: "https://app.opencomputer.dev" });
+ const attempt = async () => {
+ try {
+ await sendComputerConnect(client, { code: CODE, provider: "claude", token: TOKEN });
+ } catch (error) {
+ return structuredError(error);
+ }
+ assert.fail("expected a failure");
+ };
+
+ const invalid = await attempt();
+ assert.equal(invalid.code, "connect_code_invalid");
+ assert.equal(invalid.message, "That connect code is not valid. Get a new one from the dashboard.");
+ assert.match(invalid.hint, /Computer → Agent/);
+
+ const refused = await attempt();
+ assert.equal(refused.code, "computer_agent_claude_token");
+ assert.equal(refused.message, "Claude refused [redacted]");
+ assert.match(refused.hint, /code is still good/);
+
+ const problem = await attempt();
+ assert.equal(problem.message, "The token was not accepted.");
+ assert.equal(problem.code, "connect_rejected");
+
+ assert.equal((await attempt()).code, "connect_unavailable");
+ assert.equal((await attempt()).code, "internal");
+
+ for (const failure of [invalid, refused, problem])
+ assert.doesNotMatch(JSON.stringify(failure), /sk-ant-oat/);
+});
+
+test("connectError redacts secrets from non-API errors too", () => {
+ const error = connectError(new Error(`odd failure for ${TOKEN}`), "claude", [TOKEN]);
+ assert.equal((error as Error).message, "odd failure for [redacted]");
+ const unreachable = connectError(new TypeError("fetch failed"), "claude", [TOKEN]);
+ assert.ok(unreachable instanceof CLIError && unreachable.code === "connect_unreachable");
+ assert.equal(unreachable.message, "Could not reach OpenComputer: fetch failed");
+ const api = connectError(new APIError("x", 413, "payload_too_large"), "codex");
+ assert.ok(api instanceof CLIError && api.code === "payload_too_large");
+});
+
+// ---------------------------------------------------------------------------
+// Reading the token from `claude setup-token` output.
+
+const ESC = "\x1b";
+
+test("token is read from plain output", () => {
+ const output = `✓ Long-lived authentication token created successfully!\n\nYour OAuth token (valid for 1 year):\n\n${TOKEN}\n\nStore this token securely. You won't be able to see it again.\n`;
+ assert.equal(claudeTokenFromTerminalOutput(output), TOKEN);
+});
+
+test("token is read through colours, cursor jumps and OSC sequences", () => {
+ const output =
+ `${ESC}7${ESC}[r${ESC}8${ESC}[?25l${ESC}[?2004h` +
+ `${ESC}[2GYour${ESC}[7GOAuth${ESC}[13Gtoken${ESC}[19G(valid${ESC}[26Gfor${ESC}[30G1${ESC}[32Gyear):\r\n\r\n` +
+ `${ESC}]8;;https://example.com${ESC}\\${ESC}[2G${ESC}[33m${TOKEN}${ESC}[39m${ESC}]8;;\x07\r\n\r\n` +
+ `${ESC}[2G${ESC}[2mStore${ESC}[8Gthis${ESC}[13Gtoken${ESC}[22m\r\n${ESC}[>0q${ESC}[?u`;
+ assert.equal(claudeTokenFromTerminalOutput(output), TOKEN);
+});
+
+test("a token wrapped across lines is joined, and stops at the blank line", () => {
+ const width = 40;
+ const pieces: string[] = [];
+ for (let i = 0; i < TOKEN.length; i += width) pieces.push(TOKEN.slice(i, i + width));
+ const output =
+ `Your OAuth token (valid for 1 year):\r\n\r\n` +
+ pieces.map((piece) => ` ${ESC}[33m${piece}${ESC}[39m`).join("\r\n") +
+ `\r\n\r\n ${ESC}[2mStore this token securely.${ESC}[22m\r\n`;
+ assert.equal(claudeTokenFromTerminalOutput(output), TOKEN);
+
+ // Without the blank line, a following word that is not token-shaped ends it.
+ assert.equal(
+ claudeTokenFromScreen([...pieces, "Store this token securely."]),
+ TOKEN,
+ );
+});
+
+test("a token repainted over an earlier frame is read from the screen, not the stream", () => {
+ // Frame 1 draws a line; frame 2 moves back up and writes the token over it,
+ // skipping the cells that already show the right character (as diffing
+ // renderers do). The raw stream then lacks those characters.
+ const first = TOKEN.slice(0, 20) + "x".repeat(TOKEN.length - 20);
+ const output =
+ `${first}\r\nPaste code here >\r\n` +
+ `${ESC}[2A\r${ESC}[21G${TOKEN.slice(20)}\r\n${ESC}[2K\r\n`;
+ assert.equal(claudeTokenFromTerminalOutput(output), TOKEN);
+ assert.doesNotMatch(output.replace(/\x1b\[[0-9;]*[A-Za-z]/g, ""), new RegExp(TOKEN));
+});
+
+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");
+ assert.equal(claudeTokenFromScreen([other, "", TOKEN, ""]), TOKEN);
+ assert.equal(claudeTokenFromTerminalOutput("Paste code here if prompted >"), undefined);
+});
+
+test("screen model handles erase, save/restore and absolute positions", () => {
+ assert.deepEqual(renderTerminalScreen("hello world\r\x1b[6G\x1b[K!"), ["hello!"]);
+ assert.deepEqual(renderTerminalScreen("ab\x1b7cd\x1b8XY"), ["abXY"]);
+ assert.deepEqual(renderTerminalScreen("1\r\n2\r\n3\x1b[1;1HA", 24), ["A", "2", "3"]);
+ assert.deepEqual(renderTerminalScreen("abc\r\ndef\x1b[1A\x1b[2K\r\x1b[J"), [""]);
+});
+
+test("setup-token runs under script on macOS/Linux, falls back to npx, and runs directly on Windows", () => {
+ const all = (name: string) => `/usr/bin/${name}`;
+ assert.deepEqual(setupTokenCommand({}, "linux", all), {
+ command: "script",
+ args: ["-q", "-c", "claude setup-token", "/dev/null"],
+ shell: false,
+ pty: true,
+ });
+ assert.deepEqual(setupTokenCommand({}, "darwin", all), {
+ command: "script",
+ args: ["-q", "/dev/null", "claude", "setup-token"],
+ shell: false,
+ pty: true,
+ });
+ assert.deepEqual(
+ setupTokenCommand({}, "linux", (name) => (name === "script" ? "/usr/bin/script" : undefined)).args,
+ ["-q", "-c", "npx -y @anthropic-ai/claude-code setup-token", "/dev/null"],
+ );
+ assert.deepEqual(setupTokenCommand({}, "win32", all), {
+ command: "claude",
+ args: ["setup-token"],
+ shell: true,
+ pty: false,
+ });
+ assert.deepEqual(setupTokenCommand({}, "linux", () => undefined), {
+ command: "npx",
+ args: ["-y", "@anthropic-ai/claude-code", "setup-token"],
+ shell: false,
+ pty: false,
+ });
+});
+
+test(
+ "a TUI under script is shown and its wrapped token is read",
+ { skip: process.platform !== "linux" || !findExecutable("script") },
+ async () => {
+ const directory = await mkdtemp(join(tmpdir(), "oc-setup-token-"));
+ try {
+ const fake = join(directory, "fake-setup-token.mjs");
+ // Prints like the TUI: only when stdout is a terminal, wrapped, coloured.
+ await writeFile(
+ fake,
+ `if (!process.stdout.isTTY) process.exit(3);
+const t = ${JSON.stringify(TOKEN)};
+process.stdout.write("\\x1b[2GYour\\x1b[7GOAuth\\x1b[13Gtoken:\\r\\n\\r\\n");
+for (let i = 0; i < t.length; i += 50) process.stdout.write(" \\x1b[33m" + t.slice(i, i + 50) + "\\x1b[39m\\r\\n");
+process.stdout.write("\\r\\n \\x1b[2mStore this token securely.\\x1b[22m\\r\\n");
+`,
+ );
+ const display = new PassThrough();
+ const shown: Buffer[] = [];
+ display.on("data", (chunk: Buffer) => shown.push(chunk));
+ const result = await runClaudeSetupToken(display, {
+ command: "script",
+ args: ["-q", "-c", `${process.execPath} ${fake}`, "/dev/null"],
+ shell: false,
+ pty: true,
+ });
+ assert.equal(result.token, TOKEN);
+ assert.match(Buffer.concat(shown).toString("utf8"), /Store this token securely/);
+ } finally {
+ await rm(directory, { recursive: true, force: true });
+ }
+ },
+);
+
+test("findExecutable searches PATH", () => {
+ assert.equal(findExecutable("definitely-not-a-binary-oc", { PATH: "/usr/bin" }, "linux"), undefined);
+ assert.equal(findExecutable("node", { PATH: process.execPath.replace(/\/node$/, "") }, "linux"), process.execPath);
+});
diff --git a/cli/src/computer-connect.ts b/cli/src/computer-connect.ts
new file mode 100644
index 00000000..db930527
--- /dev/null
+++ b/cli/src/computer-connect.ts
@@ -0,0 +1,363 @@
+import { spawn } from "node:child_process";
+import { accessSync, constants } from "node:fs";
+import { delimiter, join } from "node:path";
+import { StringDecoder } from "node:string_decoder";
+
+import { APIError, type ComputerConnectRequest } from "./api.js";
+import { CLIError } from "./errors.js";
+import { renderTerminalScreen } from "./terminal-screen.js";
+
+// `opencomputer model connect claude|codex --code <code>` (work 082): connect
+// a Claude or ChatGPT subscription to the organization's computer with the
+// one-time connect code the dashboard minted. No OpenComputer login: the code
+// is the only credential sent. The subscription credential goes straight from
+// this process to the connect endpoint; it is never printed or written here.
+
+export type ComputerConnectProvider = "claude" | "codex";
+
+export const DASHBOARD_CONNECT_HINT =
+ "Get a connect command from the dashboard (Computer → Agent).";
+
+export interface ModelConnectArgs {
+ code?: string;
+ tokenStdin: boolean;
+}
+
+/** Takes `--code` and `--token-stdin` out of `args`; leaves the rest. */
+export function takeModelConnectArgs(
+ provider: ComputerConnectProvider,
+ args: string[],
+ take: { option(name: string): string | undefined; flag(name: string): boolean },
+): ModelConnectArgs {
+ const code = take.option("--code");
+ const tokenStdin = take.flag("--token-stdin");
+ if (tokenStdin && provider !== "claude")
+ throw new Error("--token-stdin is only for `model connect claude`");
+ if (code !== undefined && !/^occ_[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(code))
+ throw new CLIError(
+ "connect_code_invalid",
+ "That is not a connect code (it starts with occ_).",
+ `Copy the whole command again. ${DASHBOARD_CONNECT_HINT}`,
+ );
+ if (provider === "claude" && code === undefined)
+ throw new CLIError(
+ "connect_code_required",
+ "`model connect claude` needs a connect code (--code).",
+ DASHBOARD_CONNECT_HINT,
+ );
+ if (code !== undefined && args.length)
+ throw new Error(`Unexpected argument: ${args[0]}`);
+ return { code, tokenStdin };
+}
+
+// ---------------------------------------------------------------------------
+// Codex: the Codex CLI's auth.json shape, built from a fresh browser login.
+
+export function codexAuthJson(token: {
+ idToken?: string;
+ accessToken: string;
+ refreshToken?: string;
+}): { auth_mode: "chatgpt"; tokens: { id_token: string; access_token: string; refresh_token: string } } {
+ if (!token.idToken || !token.refreshToken)
+ throw new CLIError(
+ "codex_login_incomplete",
+ "ChatGPT sign-in did not return the tokens a computer needs.",
+ "Run the command again and finish the ChatGPT sign-in in the browser.",
+ );
+ return {
+ auth_mode: "chatgpt",
+ tokens: {
+ id_token: token.idToken,
+ access_token: token.accessToken,
+ refresh_token: token.refreshToken,
+ },
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Claude: `claude setup-token` and reading its token.
+
+const TOKEN_PREFIX = /sk-ant-oat\d{2}-/;
+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,}$/;
+
+export function isClaudeSetupToken(value: string): boolean {
+ return SETUP_TOKEN.test(value);
+}
+
+/**
+ * The token `claude setup-token` printed, from the lines on screen. The TUI
+ * wraps a token longer than the terminal onto following lines, so a token
+ * that runs to the end of its line continues with each next line made only of
+ * token characters; the blank line the TUI leaves after it ends it. The last
+ * token on screen wins.
+ */
+export function claudeTokenFromScreen(lines: readonly string[]): string | undefined {
+ for (let index = lines.length - 1; index >= 0; index--) {
+ const text = lines[index]!.replace(/\s+$/, "");
+ 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];
+ let token = run;
+ if (run.length === rest.length) {
+ for (let next = index + 1; next < lines.length; next++) {
+ const continuation = lines[next]!.trim();
+ if (!continuation || !TOKEN_CHARS.test(continuation)) break;
+ token += continuation;
+ }
+ }
+ if (isClaudeSetupToken(token)) return token;
+ }
+ return undefined;
+}
+
+/** The token in a captured terminal stream (ANSI codes, cursor moves, wraps). */
+export function claudeTokenFromTerminalOutput(
+ output: string,
+ rows?: number,
+): string | undefined {
+ return (
+ claudeTokenFromScreen(renderTerminalScreen(output, rows)) ??
+ // A stream the screen model misreads: escape codes stripped as a fallback.
+ claudeTokenFromScreen(
+ output
+ .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, "")
+ .replace(/\x1b\[[0-9;?<>=]*[ -/]*[@-~]/g, "")
+ .split(/\r?\n|\r/),
+ )
+ );
+}
+
+export interface CommandSpec {
+ command: string;
+ args: string[];
+ /** Run through the shell (Windows `.cmd` shims). */
+ shell: boolean;
+ /** Runs the program behind a pseudo-terminal recorder whose output we read. */
+ pty: boolean;
+}
+
+export function findExecutable(
+ name: string,
+ env: NodeJS.ProcessEnv = process.env,
+ platform: NodeJS.Platform = process.platform,
+): string | undefined {
+ const extensions =
+ platform === "win32"
+ ? ["", ...(env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)]
+ : [""];
+ for (const directory of (env.PATH ?? env.Path ?? "").split(platform === "win32" ? ";" : delimiter)) {
+ if (!directory) continue;
+ for (const extension of extensions) {
+ const candidate = join(directory, name + extension);
+ try {
+ accessSync(candidate, platform === "win32" ? constants.F_OK : constants.X_OK);
+ return candidate;
+ } catch {
+ // keep looking
+ }
+ }
+ }
+ return undefined;
+}
+
+function shellQuote(value: string): string {
+ return /^[A-Za-z0-9_@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
+}
+
+/**
+ * How to run `claude setup-token` so the person can use its TUI and we can
+ * read what it prints. Its TUI draws nothing useful when stdout is a pipe, so
+ * on macOS/Linux it runs under `script`, which gives it a real pseudo-terminal
+ * (sized like the person's terminal, with their keystrokes passed through)
+ * and copies everything it draws to our pipe. Without `script` (Windows) it
+ * runs on the person's terminal directly and they paste the token afterwards.
+ */
+export function setupTokenCommand(
+ env: NodeJS.ProcessEnv = process.env,
+ platform: NodeJS.Platform = process.platform,
+ find: (name: string) => string | undefined = (name) => findExecutable(name, env, platform),
+): CommandSpec {
+ const program = find("claude")
+ ? ["claude", "setup-token"]
+ : ["npx", "-y", "@anthropic-ai/claude-code", "setup-token"];
+ if (platform !== "win32" && find("script")) {
+ const args =
+ platform === "linux"
+ ? ["-q", "-c", program.map(shellQuote).join(" "), "/dev/null"]
+ : ["-q", "/dev/null", ...program];
+ return { command: "script", args, shell: false, pty: true };
+ }
+ return {
+ command: program[0]!,
+ args: program.slice(1),
+ shell: platform === "win32",
+ pty: false,
+ };
+}
+
+export interface SetupTokenResult {
+ /** The token read from the TUI's output, when it was captured. */
+ token?: string;
+ exitCode: number | null;
+ signal: NodeJS.Signals | null;
+ pty: boolean;
+}
+
+const MAX_CAPTURE_CHARS = 4 * 1024 * 1024;
+
+/** Runs `claude setup-token` interactively and reads the token it prints. */
+export function runClaudeSetupToken(
+ display: NodeJS.WritableStream,
+ spec: CommandSpec = setupTokenCommand(),
+): Promise<SetupTokenResult> {
+ return new Promise((resolve, reject) => {
+ const child = spawn(spec.command, spec.args, {
+ stdio: spec.pty ? ["inherit", "pipe", "inherit"] : "inherit",
+ shell: spec.shell,
+ env: process.env,
+ });
+ const decoder = new StringDecoder("utf8");
+ let captured = "";
+ child.stdout?.on("data", (chunk: Buffer) => {
+ display.write(chunk);
+ if (captured.length < MAX_CAPTURE_CHARS) captured += decoder.write(chunk);
+ });
+ // 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.
+ // `script` ignores SIGHUP, so it gets SIGTERM, then SIGKILL; either way
+ // its PTY closes and the TUI behind it is hung up.
+ let interrupted: NodeJS.Signals | undefined;
+ let escalation: NodeJS.Timeout | undefined;
+ const forward = (signal: NodeJS.Signals): void => {
+ interrupted ??= signal;
+ child.kill("SIGTERM");
+ escalation ??= setTimeout(() => child.kill("SIGKILL"), 2_000);
+ escalation.unref();
+ };
+ const signals: NodeJS.Signals[] = ["SIGINT", "SIGTERM", "SIGHUP"];
+ for (const signal of signals) process.on(signal, forward);
+ const cleanup = (): void => {
+ for (const signal of signals) process.off(signal, forward);
+ if (escalation) clearTimeout(escalation);
+ };
+ child.once("error", (error) => {
+ cleanup();
+ reject(
+ new CLIError(
+ "claude_setup_token_unavailable",
+ `Could not run \`${[spec.command, ...spec.args].join(" ")}\`: ${error.message}`,
+ "Install Claude Code (https://claude.com/claude-code) or Node.js with npx, or pipe a token from `claude setup-token` into this command with --token-stdin.",
+ ),
+ );
+ });
+ child.once("close", (exitCode, signal) => {
+ cleanup();
+ captured += decoder.end();
+ const token = spec.pty
+ ? claudeTokenFromTerminalOutput(captured, process.stdout.rows)
+ : undefined;
+ captured = "";
+ if (interrupted) {
+ reject(
+ new CLIError(
+ "cancelled",
+ "Cancelled; nothing was connected.",
+ "Run the command again when ready; the connect code still works until it expires.",
+ ),
+ );
+ return;
+ }
+ resolve({ token, exitCode, signal, pty: spec.pty });
+ });
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Request and errors.
+
+/** Removes any secret the request carried from text shown to the person. */
+export function redactSecrets(text: string, secrets: readonly string[]): string {
+ let result = text;
+ for (const secret of secrets) if (secret) result = result.split(secret).join("[redacted]");
+ return result.replace(/sk-ant-[A-Za-z0-9_-]+/g, "[redacted]");
+}
+
+/** A failed connect as a readable CLI error, without any secret in it. */
+export function connectError(
+ error: unknown,
+ provider: ComputerConnectProvider,
+ secrets: readonly string[] = [],
+): unknown {
+ if (!(error instanceof APIError)) {
+ if (error instanceof CLIError || !(error instanceof Error)) return error;
+ const reason = redactSecrets(error.message, secrets);
+ // fetch rejects with a TypeError when the API cannot be reached, and with
+ // a TimeoutError/AbortError when it does not answer in time.
+ if (error.name === "TypeError" || error.name === "TimeoutError" || error.name === "AbortError")
+ return new CLIError(
+ "connect_unreachable",
+ `Could not reach OpenComputer: ${reason}`,
+ "Check your connection (and --api-url), then run the command again; the code still works until it is used or expires.",
+ );
+ error.message = reason;
+ return error;
+ }
+ 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)
+ return new CLIError(
+ "connect_code_invalid",
+ "That connect code is not valid. Get a new one from the dashboard.",
+ `Codes work once and last 10 minutes. ${DASHBOARD_CONNECT_HINT}`,
+ details,
+ );
+ if (error.status === 404 || error.status === 405)
+ return new CLIError(
+ "connect_unavailable",
+ "This OpenComputer API does not accept connect codes.",
+ "Check --api-url / OPENCOMPUTER_API_URL, or use the command the dashboard shows.",
+ details,
+ );
+ if (error.status === 400 || error.status === 413 || error.status === 422)
+ return new CLIError(
+ error.code ?? "connect_rejected",
+ message,
+ provider === "claude"
+ ? `The code is still good: run the command again to make a new token with the account that has your ${plan} plan.`
+ : `The code is still good: run the command again and sign in with the account that has your ${plan} plan.`,
+ details,
+ );
+ return new CLIError(
+ error.code ?? "connect_failed",
+ message,
+ "Retry the command; if the code has expired, get a new one from the dashboard.",
+ details,
+ );
+}
+
+export function connectSuccessMessage(provider: ComputerConnectProvider): string {
+ return provider === "claude"
+ ? "Connected your Claude plan to your computer. You can close this.\n"
+ : "Connected your ChatGPT plan to your computer. You can close this.\n";
+}
+
+export async function sendComputerConnect(
+ client: { connectComputerAgent(body: ComputerConnectRequest): Promise<unknown> },
+ body: ComputerConnectRequest,
+): Promise<unknown> {
+ const secrets = [body.token ?? "", ...codexSecrets(body.authJson)];
+ try {
+ return await client.connectComputerAgent(body);
+ } catch (error) {
+ throw connectError(error, body.provider, secrets);
+ }
+}
+
+function codexSecrets(authJson: ComputerConnectRequest["authJson"]): string[] {
+ if (!authJson || typeof authJson !== "object") return [];
+ return Object.values(authJson.tokens).filter((value): value is string => typeof value === "string");
+}
diff --git a/cli/src/index.ts b/cli/src/index.ts
index a0754e61..5a0d3900 100644
--- a/cli/src/index.ts
+++ b/cli/src/index.ts
@@ -94,11 +94,18 @@ Usage:
opencomputer connection remove <alias|connection-id> [--service <name>]
opencomputer github status [--project <id|slug>]
opencomputer github connect [--new | --connection <id|account>] [--environment development|production] [--project <id|slug>] [--no-wait]
- opencomputer model-access connect codex [--project <id|slug>]
- opencomputer model-access connect openrouter [--api-key-stdin] [--project <id|slug>]
- opencomputer model-access connect openai-compatible --base-url <url> [--api-key-stdin] [--project <id|slug>]
- opencomputer model-access list
- opencomputer model-access disconnect codex
+ opencomputer model connect claude --code <code> [--token-stdin]
+ opencomputer model connect codex --code <code>
+ connects your Claude or ChatGPT plan to your organization's computer with the
+ connect code from the dashboard (Computer → Agent); no login needed. claude runs
+ \`claude setup-token\` (or reads its token from stdin with --token-stdin); codex
+ opens a ChatGPT sign-in in your browser
+ opencomputer model connect codex [--project <id|slug>]
+ opencomputer model connect openrouter [--api-key-stdin] [--project <id|slug>]
+ opencomputer model connect openai-compatible --base-url <url> [--api-key-stdin] [--project <id|slug>]
+ opencomputer model list
+ opencomputer model disconnect codex
+ "models" and "model-access" are aliases of "model"
opencomputer model-route set --project <id|slug> --connection <id> --model <model> [--agent <agent>] [--fallback fail|managed]
opencomputer model-route list --project <id|slug>
opencomputer model-route delete --project <id|slug> [--agent <agent>]
diff --git a/cli/src/terminal-screen.ts b/cli/src/terminal-screen.ts
new file mode 100644
index 00000000..ab0082a2
--- /dev/null
+++ b/cli/src/terminal-screen.ts
@@ -0,0 +1,130 @@
+// A minimal terminal screen model: replays a captured terminal byte stream
+// (text, cursor movement, erases) onto a grid and returns the lines a person
+// would see at the end. Full-screen TUIs such as `claude setup-token` draw
+// with cursor addressing and only repaint the cells that changed, so the
+// stream with escape codes stripped is not the text on the screen: a word can
+// be split by cursor jumps, and a character already on screen from an earlier
+// frame is never written again. Reading the final screen avoids both.
+//
+// Deliberately small: no scroll regions, alternate screen, or wide-character
+// widths. Every code point is one cell. It is used to find a token on the
+// screen, not to render.
+
+export function renderTerminalScreen(stream: string, rows = 24): string[] {
+ const lines: string[][] = [[]];
+ let row = 0;
+ let col = 0;
+ let saved = { row: 0, col: 0 };
+
+ const line = (index: number): string[] => {
+ while (lines.length <= index) lines.push([]);
+ return lines[index]!;
+ };
+ const viewportTop = (): number => Math.max(0, lines.length - rows);
+ const put = (character: string): void => {
+ const target = line(row);
+ while (target.length < col) target.push(" ");
+ target[col] = character;
+ col += 1;
+ };
+ const eraseLine = (mode: number): void => {
+ const target = line(row);
+ if (mode === 0) target.length = Math.min(target.length, col);
+ else if (mode === 1) for (let i = 0; i <= col && i < target.length; i++) target[i] = " ";
+ else target.length = 0;
+ };
+
+ const characters = Array.from(stream);
+ for (let i = 0; i < characters.length; i++) {
+ const character = characters[i]!;
+ if (character === "\x1b") {
+ const next = characters[i + 1];
+ if (next === "[") {
+ // CSI: parameters, intermediates, one final byte in @..~.
+ let j = i + 2;
+ let body = "";
+ while (j < characters.length && !/[@-~]/.test(characters[j]!)) {
+ body += characters[j]!;
+ j += 1;
+ }
+ const final = characters[j];
+ i = j;
+ if (final === undefined) break;
+ if (/^[?<>=]/.test(body)) continue; // private modes and queries
+ const params = body.split(";").map((value) => Number.parseInt(value, 10));
+ const n = (index = 0, fallback = 1): number => {
+ const value = params[index];
+ return value === undefined || Number.isNaN(value) || value === 0 ? fallback : value;
+ };
+ switch (final) {
+ case "A": row = Math.max(0, row - n()); break;
+ case "B": row += n(); break;
+ case "C": col += n(); break;
+ case "D": col = Math.max(0, col - n()); break;
+ case "E": row += n(); col = 0; break;
+ case "F": row = Math.max(0, row - n()); col = 0; break;
+ case "G": case "`": col = n() - 1; break;
+ case "d": row = viewportTop() + n() - 1; break;
+ case "H": case "f": row = viewportTop() + n(0) - 1; col = n(1) - 1; break;
+ case "K": eraseLine(Number.isNaN(params[0]!) ? 0 : params[0]!); break;
+ case "J": {
+ const mode = Number.isNaN(params[0]!) ? 0 : params[0]!;
+ if (mode === 0) {
+ eraseLine(0);
+ lines.length = Math.min(lines.length, row + 1);
+ } else if (mode === 1) {
+ for (let r = 0; r < row; r++) line(r).length = 0;
+ eraseLine(1);
+ } else {
+ const top = viewportTop();
+ for (let r = top; r < lines.length; r++) line(r).length = 0;
+ }
+ break;
+ }
+ case "X": {
+ const target = line(row);
+ for (let k = col; k < col + n() && k < target.length; k++) target[k] = " ";
+ break;
+ }
+ case "P": line(row).splice(col, n()); break;
+ case "@": {
+ const target = line(row);
+ if (col < target.length) target.splice(col, 0, ...Array<string>(n()).fill(" "));
+ break;
+ }
+ case "s": saved = { row, col }; break;
+ case "u": ({ row, col } = saved); break;
+ default: break; // SGR (m) and everything else do not move text
+ }
+ continue;
+ }
+ if (next === "]" || next === "P" || next === "_" || next === "^" || next === "X") {
+ // OSC / DCS / APC / PM / SOS: skip to BEL or ST. The text an OSC 8
+ // hyperlink wraps is outside the sequence and is printed normally.
+ let j = i + 2;
+ while (
+ j < characters.length &&
+ characters[j] !== "\x07" &&
+ !(characters[j] === "\x1b" && characters[j + 1] === "\\")
+ ) j += 1;
+ i = characters[j] === "\x07" ? j : j + 1;
+ continue;
+ }
+ if (next === "7") saved = { row, col };
+ else if (next === "8") ({ row, col } = saved);
+ else if (next === "M") row = Math.max(0, row - 1);
+ else if (next === "E") { row += 1; col = 0; }
+ else if (next === "D") row += 1;
+ else if (next === "(" || next === ")" || next === "#" || next === "%") i += 1;
+ i += 1;
+ continue;
+ }
+ if (character === "\r") col = 0;
+ else if (character === "\n" || character === "\v" || character === "\f") row += 1;
+ else if (character === "\b") col = Math.max(0, col - 1);
+ else if (character === "\t") col = (Math.floor(col / 8) + 1) * 8;
+ else if (character >= " " && character !== "\x7f") put(character);
+ // other C0 controls (BEL, SI, SO, ...) do not print
+ }
+ return lines.map((cells) => cells.join("").replace(/\s+$/, ""));
+}