diff --git a/CHANGELOG.md b/CHANGELOG.md index 95c916b821b6..ec32ba3f5639 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,38 @@ You can install any of these versions: `npm install -g codex@version` +## `0.1.2504211509` + +### πŸš€ Features + +- Support multiple providers via Responses-Completion transformation (#247) +- Add user-defined safe commands configuration and approval logic #380 (#386) +- Allow switching approval modes when prompted to approve an edit/command (#400) +- Add support for `/diff` command autocomplete in TerminalChatInput (#431) +- Auto-open model selector if user selects deprecated model (#427) +- Read approvalMode from config file (#298) +- `/diff` command to view git diff (#426) +- Tab completions for file paths (#279) +- Add /command autocomplete (#317) +- Allow multi-line input (#438) + +### πŸ› Bug Fixes + +- `full-auto` support in quiet mode (#374) +- Enable shell option for child process execution (#391) +- Configure husky and lint-staged for pnpm monorepo (#384) +- Command pipe execution by improving shell detection (#437) +- Name of the file not matching the name of the component (#354) +- Allow proper exit from new Switch approval mode dialog (#453) +- Ensure /clear resets context and exclude system messages from approximateTokenUsed count (#443) +- `/clear` now clears terminal screen and resets context left indicator (#425) +- Correct fish completion function name in CLI script (#485) +- Auto-open model-selector when model is not found (#448) +- Remove unnecessary isLoggingEnabled() checks (#420) +- Improve test reliability for `raw-exec` (#434) +- Unintended tear down of agent loop (#483) +- Remove extraneous type casts (#462) + ## `0.1.2504181820` ### πŸš€ Features diff --git a/README.md b/README.md index 7741dc84f2b7..82e29dc8c5ab 100644 --- a/README.md +++ b/README.md @@ -68,9 +68,7 @@ Next, set your OpenAI API key as an environment variable: export OPENAI_API_KEY="your-api-key-here" ``` -> **Note:** This command sets the key only for your current terminal session. To make it permanent, add the `export` line to your shell's configuration file (e.g., `~/.zshrc`). -> -> **Tip:** You can also place your API key into a `.env` file at the root of your project: +> **Note:** This command sets the key only for your current terminal session. You can add the `export` line to your shell's configuration file (e.g., `~/.zshrc`) but we recommend setting for the session. **Tip:** You can also place your API key into a `.env` file at the root of your project: > > ```env > OPENAI_API_KEY=your-api-key-here @@ -78,6 +76,29 @@ export OPENAI_API_KEY="your-api-key-here" > > The CLI will automatically load variables from `.env` (via `dotenv/config`). +
+Use --provider to use other models + +> Codex also allows you to use other providers that support the OpenAI Chat Completions API. You can set the provider in the config file or use the `--provider` flag. The possible options for `--provider` are: +> +> - openai (default) +> - openrouter +> - gemini +> - ollama +> - mistral +> - deepseek +> - xai +> - groq +> +> If you use a provider other than OpenAI, you will need to set the API key for the provider in the config file or in the environment variable as: +> +> ```shell +> export _API_KEY="your-api-key-here" +> ``` + +
+
+ Run interactively: ```shell @@ -300,9 +321,6 @@ model: o4-mini # Default model approvalMode: suggest # or auto-edit, full-auto fullAutoErrorMode: ask-user # or ignore-and-continue notify: true # Enable desktop notifications for responses -safeCommands: - - npm test # Automatically approve npm test - - yarn lint # Automatically approve yarn lint ``` ```json @@ -381,7 +399,7 @@ OpenAI rejected the request. Error details: Status: 400, Code: unsupported_param **What can I do?** - If you are part of a ZDR organization, Codex CLI will not work until support is added. -- We are tracking this limitation and will update the documentation if support becomes available. +- We are tracking this limitation and will update the documentation once support becomes available. --- diff --git a/codex-cli/build.mjs b/codex-cli/build.mjs index 0fcd5c6eced5..465e8b9244cc 100644 --- a/codex-cli/build.mjs +++ b/codex-cli/build.mjs @@ -1,6 +1,8 @@ import * as esbuild from "esbuild"; import * as fs from "fs"; import * as path from "path"; + +const OUT_DIR = 'dist' /** * ink attempts to import react-devtools-core in an ESM-unfriendly way: * @@ -39,6 +41,11 @@ const isDevBuild = const plugins = [ignoreReactDevToolsPlugin]; +// Build Hygiene, ensure we drop previous dist dir and any leftover files +const outPath = path.resolve(OUT_DIR); +if (fs.existsSync(outPath)) { + fs.rmSync(outPath, { recursive: true, force: true }); +} // Add a shebang that enables source‑map support for dev builds so that stack // traces point to the original TypeScript lines without requiring callers to @@ -50,7 +57,7 @@ if (isDevBuild) { name: "dev-shebang", setup(build) { build.onEnd(async () => { - const outFile = path.resolve(isDevBuild ? "dist/cli-dev.js" : "dist/cli.js"); + const outFile = path.resolve(isDevBuild ? `${OUT_DIR}/cli-dev.js` : `${OUT_DIR}/cli.js`); let code = await fs.promises.readFile(outFile, "utf8"); if (code.startsWith("#!")) { code = code.replace(/^#!.*\n/, devShebangLine); @@ -69,7 +76,7 @@ esbuild format: "esm", platform: "node", tsconfig: "tsconfig.json", - outfile: isDevBuild ? "dist/cli-dev.js" : "dist/cli.js", + outfile: isDevBuild ? `${OUT_DIR}/cli-dev.js` : `${OUT_DIR}/cli.js`, minify: !isDevBuild, sourcemap: isDevBuild ? "inline" : true, plugins, diff --git a/codex-cli/package.json b/codex-cli/package.json index 2bfe93ce70a6..0e70895f3827 100644 --- a/codex-cli/package.json +++ b/codex-cli/package.json @@ -1,6 +1,6 @@ { "name": "@openai/codex", - "version": "0.1.2504181820", + "version": "0.1.2504211509", "license": "Apache-2.0", "bin": { "codex": "bin/codex.js" @@ -26,8 +26,7 @@ "release": "pnpm run release:readme && pnpm run release:version && pnpm install && pnpm run release:build-and-publish" }, "files": [ - "dist", - "src" + "dist" ], "dependencies": { "@inkjs/ui": "^2.0.0", diff --git a/codex-cli/src/approvals.ts b/codex-cli/src/approvals.ts index 3b3162af7f6b..ff37a8903f8a 100644 --- a/codex-cli/src/approvals.ts +++ b/codex-cli/src/approvals.ts @@ -4,7 +4,6 @@ import { identify_files_added, identify_files_needed, } from "./utils/agent/apply-patch"; -import { loadConfig } from "./utils/config"; import * as path from "path"; import { parse } from "shell-quote"; @@ -136,8 +135,8 @@ export function canAutoApprove( // bashCmd could be a mix of strings and operators, e.g.: // "ls || (true && pwd)" => [ 'ls', { op: '||' }, '(', 'true', { op: '&&' }, 'pwd', ')' ] // We try to ensure that *every* command segment is deemed safe and that - // all operators belong to an allow‑list. If so, the entire expression is - // considered auto‑approvable. + // all operators belong to an allow-list. If so, the entire expression is + // considered auto-approvable. const shellSafe = isEntireShellExpressionSafe(bashCmd); if (shellSafe != null) { @@ -297,24 +296,6 @@ export function isSafeCommand( ): SafeCommandReason | null { const [cmd0, cmd1, cmd2, cmd3] = command; - const config = loadConfig(); - if (config.safeCommands && Array.isArray(config.safeCommands)) { - for (const safe of config.safeCommands) { - // safe: "npm test" β†’ ["npm", "test"] - const safeArr = typeof safe === "string" ? safe.trim().split(/\s+/) : []; - if ( - safeArr.length > 0 && - safeArr.length <= command.length && - safeArr.every((v, i) => v === command[i]) - ) { - return { - reason: "User-defined safe command", - group: "User config", - }; - } - } - } - switch (cmd0) { case "cd": return { @@ -333,7 +314,7 @@ export function isSafeCommand( }; case "true": return { - reason: "No‑op (true)", + reason: "No-op (true)", group: "Utility", }; case "echo": @@ -348,11 +329,20 @@ export function isSafeCommand( reason: "Ripgrep search", group: "Searching", }; - case "find": - return { - reason: "Find files or directories", - group: "Searching", - }; + case "find": { + // Certain options to `find` allow executing arbitrary processes, so we + // cannot auto-approve them. + if ( + command.some((arg: string) => UNSAFE_OPTIONS_FOR_FIND_COMMAND.has(arg)) + ) { + break; + } else { + return { + reason: "Find files or directories", + group: "Searching", + }; + } + } case "grep": return { reason: "Text search (grep)", @@ -440,12 +430,27 @@ function isValidSedNArg(arg: string | undefined): boolean { return arg != null && /^(\d+,)?\d+p$/.test(arg); } +const UNSAFE_OPTIONS_FOR_FIND_COMMAND: ReadonlySet = new Set([ + // Options that can execute arbitrary commands. + "-exec", + "-execdir", + "-ok", + "-okdir", + // Option that deletes matching files. + "-delete", + // Options that write pathnames to a file. + "-fls", + "-fprint", + "-fprint0", + "-fprintf", +]); + // ---------------- Helper utilities for complex shell expressions ----------------- -// A conservative allow‑list of bash operators that do not, on their own, cause +// A conservative allow-list of bash operators that do not, on their own, cause // side effects. Redirections (>, >>, <, etc.) and command substitution `$()` // are intentionally excluded. Parentheses used for grouping are treated as -// strings by `shell‑quote`, so we do not add them here. Reference: +// strings by `shell-quote`, so we do not add them here. Reference: // https://github.com/substack/node-shell-quote#parsecmd-opts const SAFE_SHELL_OPERATORS: ReadonlySet = new Set([ "&&", // logical AND @@ -471,7 +476,7 @@ function isEntireShellExpressionSafe( } try { - // Collect command segments delimited by operators. `shell‑quote` represents + // Collect command segments delimited by operators. `shell-quote` represents // subshell grouping parentheses as literal strings "(" and ")"; treat them // as unsafe to keep the logic simple (since subshells could introduce // unexpected scope changes). @@ -539,7 +544,7 @@ function isParseEntryWithOp( return ( typeof entry === "object" && entry != null && - // Using the safe `in` operator keeps the check property‑safe even when + // Using the safe `in` operator keeps the check property-safe even when // `entry` is a `string`. "op" in entry && typeof (entry as { op?: unknown }).op === "string" diff --git a/codex-cli/src/cli.tsx b/codex-cli/src/cli.tsx index 948c0d3d90a0..65147b9e5bd5 100644 --- a/codex-cli/src/cli.tsx +++ b/codex-cli/src/cli.tsx @@ -14,7 +14,6 @@ import type { ResponseItem } from "openai/resources/responses/responses"; import App from "./app"; import { runSinglePass } from "./cli-singlepass"; import { AgentLoop } from "./utils/agent/agent-loop"; -import { initLogger } from "./utils/agent/log"; import { ReviewDecision } from "./utils/agent/review"; import { AutoApprovalMode } from "./utils/auto-approval-mode"; import { checkForUpdates } from "./utils/check-updates"; @@ -25,6 +24,7 @@ import { INSTRUCTIONS_FILEPATH, } from "./utils/config"; import { createInputItem } from "./utils/input-utils"; +import { initLogger } from "./utils/logger/log"; import { isModelSupportedForResponses } from "./utils/model-utils.js"; import { parseToolCall } from "./utils/parsers"; import { onExit, setInkRenderer } from "./utils/terminal"; @@ -54,6 +54,7 @@ const cli = meow( Options -h, --help Show usage and exit -m, --model Model to use for completions (default: o4-mini) + -p, --provider Provider to use for completions (default: openai) -i, --image Path(s) to image files to include as input -v, --view Inspect a previously saved rollout instead of starting a session -q, --quiet Non-interactive mode that only prints the assistant's final output @@ -136,7 +137,7 @@ const cli = meow( }, noProjectDoc: { type: "boolean", - description: "Disable automatic inclusion of project‑level codex.md", + description: "Disable automatic inclusion of project-level codex.md", }, projectDoc: { type: "string", @@ -190,7 +191,7 @@ _codex() { } _codex`, fish: `# fish completion for codex -complete -c codex -a '(_fish_complete_path)' -d 'file path'`, +complete -c codex -a '(__fish_complete_path)' -d 'file path'`, }; const script = scripts[shell]; if (!script) { @@ -202,19 +203,20 @@ complete -c codex -a '(_fish_complete_path)' -d 'file path'`, console.log(script); process.exit(0); } -// Show help if requested + +// For --help, show help and exit. if (cli.flags.help) { cli.showHelp(); } -// Handle config flag: open instructions file in editor and exit +// For --config, open custom instructions file in editor and exit. if (cli.flags.config) { - // Ensure configuration and instructions file exist try { - loadConfig(); + loadConfig(); // Ensures the file is created if it doesn't already exit. } catch { // ignore errors } + const filePath = INSTRUCTIONS_FILEPATH; const editor = process.env["EDITOR"] || (process.platform === "win32" ? "notepad" : "vi"); @@ -237,13 +239,13 @@ let config = loadConfig(undefined, undefined, { const prompt = cli.input[0]; const model = cli.flags.model ?? config.model; const imagePaths = cli.flags.image; -const provider = cli.flags.provider ?? config.provider; +const provider = cli.flags.provider ?? config.provider ?? "openai"; const apiKey = getApiKey(provider); if (!apiKey) { // eslint-disable-next-line no-console console.error( - `\n${chalk.red("Missing OpenAI API key.")}\n\n` + + `\n${chalk.red(`Missing ${provider} API key.`)}\n\n` + `Set the environment variable ${chalk.bold("OPENAI_API_KEY")} ` + `and re-run this command.\n` + `You can create a key here: ${chalk.bold( @@ -262,13 +264,11 @@ config = { provider, }; -// Check for updates after loading config -// This is important because we write state file in the config dir +// Check for updates after loading config. This is important because we write state file in +// the config dir. await checkForUpdates().catch(); -// --------------------------------------------------------------------------- -// --flex-mode validation (only allowed for o3 and o4-mini) -// --------------------------------------------------------------------------- +// For --flex-mode, validate and exit if incorrect. if (cli.flags.flexMode) { const allowedFlexModels = new Set(["o3", "o4-mini"]); if (!allowedFlexModels.has(config.model)) { @@ -282,13 +282,13 @@ if (cli.flags.flexMode) { } if ( - !(await isModelSupportedForResponses(config.model)) && + !(await isModelSupportedForResponses(provider, config.model)) && (!provider || provider.toLowerCase() === "openai") ) { // eslint-disable-next-line no-console console.error( `The model "${config.model}" does not appear in the list of models ` + - `available to your account. Double‑check the spelling (use\n` + + `available to your account. Double-check the spelling (use\n` + ` openai models list\n` + `to see the full list) or choose another model with the --model flag.`, ); @@ -297,6 +297,7 @@ if ( let rollout: AppRollout | undefined; +// For --view, optionally load an existing rollout from disk, display it and exit. if (cli.flags.view) { const viewPath = cli.flags.view; const absolutePath = path.isAbsolute(viewPath) @@ -312,7 +313,7 @@ if (cli.flags.view) { } } -// If we are running in --fullcontext mode, do that and exit. +// For --fullcontext, run the separate cli entrypoint and exit. if (fullContextMode) { await runSinglePass({ originalPrompt: prompt, @@ -328,11 +329,8 @@ const additionalWritableRoots: ReadonlyArray = ( cli.flags.writableRoot ?? [] ).map((p) => path.resolve(p)); -// If we are running in --quiet mode, do that and exit. -const quietMode = Boolean(cli.flags.quiet); -const fullStdout = Boolean(cli.flags.fullStdout); - -if (quietMode) { +// For --quiet, run the cli without user interactions and exit. +if (cli.flags.quiet) { process.env["CODEX_QUIET_MODE"] = "1"; if (!prompt || prompt.trim() === "") { // eslint-disable-next-line no-console @@ -389,7 +387,7 @@ const instance = render( imagePaths={imagePaths} approvalPolicy={approvalPolicy} additionalWritableRoots={additionalWritableRoots} - fullStdout={fullStdout} + fullStdout={Boolean(cli.flags.fullStdout)} />, { patchConsole: process.env["DEBUG"] ? false : true, @@ -501,13 +499,13 @@ process.on("SIGQUIT", exit); process.on("SIGTERM", exit); // --------------------------------------------------------------------------- -// Fallback for Ctrl‑C when stdin is in raw‑mode +// Fallback for Ctrl-C when stdin is in raw-mode // --------------------------------------------------------------------------- if (process.stdin.isTTY) { // Ensure we do not leave the terminal in raw mode if the user presses - // Ctrl‑C while some other component has focus and Ink is intercepting - // input. Node does *not* emit a SIGINT in raw‑mode, so we listen for the + // Ctrl-C while some other component has focus and Ink is intercepting + // input. Node does *not* emit a SIGINT in raw-mode, so we listen for the // corresponding byte (0x03) ourselves and trigger a graceful shutdown. const onRawData = (data: Buffer | string): void => { const str = Buffer.isBuffer(data) ? data.toString("utf8") : data; @@ -518,6 +516,6 @@ if (process.stdin.isTTY) { process.stdin.on("data", onRawData); } -// Ensure terminal clean‑up always runs, even when other code calls +// Ensure terminal clean-up always runs, even when other code calls // `process.exit()` directly. process.once("exit", onExit); diff --git a/codex-cli/src/components/chat/multiline-editor.tsx b/codex-cli/src/components/chat/multiline-editor.tsx index a91eceea343f..eea5ec4852cb 100644 --- a/codex-cli/src/components/chat/multiline-editor.tsx +++ b/codex-cli/src/components/chat/multiline-editor.tsx @@ -14,7 +14,7 @@ import React, { useRef, useState } from "react"; * The real `process.stdin` object exposed by Node.js inherits these methods * from `Socket`, but the lightweight stub used in tests only extends * `EventEmitter`. Ink calls the two methods when enabling/disabling raw - * mode, so make them harmless no‑ops when they're absent to avoid runtime + * mode, so make them harmless no-ops when they're absent to avoid runtime * failures during unit tests. * ----------------------------------------------------------------------- */ diff --git a/codex-cli/src/components/chat/terminal-chat-input-thinking.tsx b/codex-cli/src/components/chat/terminal-chat-input-thinking.tsx index fdc8bd218ce9..dd938b064050 100644 --- a/codex-cli/src/components/chat/terminal-chat-input-thinking.tsx +++ b/codex-cli/src/components/chat/terminal-chat-input-thinking.tsx @@ -1,4 +1,4 @@ -import { log } from "../../utils/agent/log.js"; +import { log } from "../../utils/logger/log.js"; import { Box, Text, useInput, useStdin } from "ink"; import React, { useState } from "react"; import { useInterval } from "use-interval"; diff --git a/codex-cli/src/components/chat/terminal-chat-input.tsx b/codex-cli/src/components/chat/terminal-chat-input.tsx index ddb9c7a1c907..aad2e6b3c3a0 100644 --- a/codex-cli/src/components/chat/terminal-chat-input.tsx +++ b/codex-cli/src/components/chat/terminal-chat-input.tsx @@ -9,10 +9,10 @@ import type { import MultilineTextEditor from "./multiline-editor"; import { TerminalChatCommandReview } from "./terminal-chat-command-review.js"; import TextCompletions from "./terminal-chat-completions.js"; -import { log } from "../../utils/agent/log.js"; import { loadConfig } from "../../utils/config.js"; import { getFileSystemSuggestions } from "../../utils/file-system-suggestions.js"; import { createInputItem } from "../../utils/input-utils.js"; +import { log } from "../../utils/logger/log.js"; import { setSessionId } from "../../utils/session.js"; import { SLASH_COMMANDS, type SlashCommand } from "../../utils/slash-commands"; import { @@ -191,6 +191,12 @@ export default function TerminalChatInput({ case "/bug": onSubmit(cmd); break; + case "/clear": + onSubmit(cmd); + break; + case "/clearhistory": + onSubmit(cmd); + break; default: break; } @@ -396,19 +402,29 @@ export default function TerminalChatInput({ setInput(""); setSessionId(""); setLastResponseId(""); + // Clear the terminal screen (including scrollback) before resetting context clearTerminal(); + // Emit a system notice in the chat; no raw console writes so Ink keeps control. + // Emit a system message to confirm the clear action. We *append* // it so Ink's treats it as new output and actually renders it. setItems((prev) => { const filteredOldItems = prev.filter((item) => { + // Remove any token‑heavy entries (user/assistant turns and function calls) if ( item.type === "message" && (item.role === "user" || item.role === "assistant") ) { return false; } - return true; + if ( + item.type === "function_call" || + item.type === "function_call_output" + ) { + return false; + } + return true; // keep developer/system and other meta entries }); return [ diff --git a/codex-cli/src/components/chat/terminal-chat-new-input.tsx b/codex-cli/src/components/chat/terminal-chat-new-input.tsx index 7dbe130e2c7a..b03cc9636dde 100644 --- a/codex-cli/src/components/chat/terminal-chat-new-input.tsx +++ b/codex-cli/src/components/chat/terminal-chat-new-input.tsx @@ -8,9 +8,9 @@ import type { import MultilineTextEditor from "./multiline-editor"; import { TerminalChatCommandReview } from "./terminal-chat-command-review.js"; -import { log } from "../../utils/agent/log.js"; import { loadConfig } from "../../utils/config.js"; import { createInputItem } from "../../utils/input-utils.js"; +import { log } from "../../utils/logger/log.js"; import { setSessionId } from "../../utils/session.js"; import { loadCommandHistory, @@ -263,17 +263,16 @@ export default function TerminalChatInput({ setInput(""); setSessionId(""); setLastResponseId(""); + // Clear the terminal screen (including scrollback) before resetting context clearTerminal(); - // Emit a system message to confirm the clear action. We *append* - // it so Ink's treats it as new output and actually renders it. - setItems((prev) => [ - ...prev, + // Print a clear confirmation and reset conversation items. + setItems([ { id: `clear-${Date.now()}`, type: "message", role: "system", - content: [{ type: "input_text", text: "Context cleared" }], + content: [{ type: "input_text", text: "Terminal cleared" }], }, ]); diff --git a/codex-cli/src/components/chat/terminal-chat-utils.ts b/codex-cli/src/components/chat/terminal-chat-utils.ts deleted file mode 100644 index 73ab3c971aee..000000000000 --- a/codex-cli/src/components/chat/terminal-chat-utils.ts +++ /dev/null @@ -1,113 +0,0 @@ -import type { ResponseItem } from "openai/resources/responses/responses.mjs"; - -import { approximateTokensUsed } from "../../utils/approximate-tokens-used.js"; - -/** - * Type‑guard that narrows a {@link ResponseItem} to one that represents a - * user‑authored message. The OpenAI SDK represents both input *and* output - * messages with a discriminated union where: - * β€’ `type` is the string literal "message" and - * β€’ `role` is one of "user" | "assistant" | "system" | "developer". - * - * For the purposes of de‑duplication we only care about *user* messages so we - * detect those here in a single, reusable helper. - */ -function isUserMessage( - item: ResponseItem, -): item is ResponseItem & { type: "message"; role: "user"; content: unknown } { - return item.type === "message" && (item as { role?: string }).role === "user"; -} - -/** - * Returns the maximum context length (in tokens) for a given model. - * These numbers are best‑effort guesses and provide a basis for UI percentages. - */ -export function maxTokensForModel(model: string): number { - const lower = model.toLowerCase(); - if (lower.includes("32k")) { - return 32000; - } - if (lower.includes("16k")) { - return 16000; - } - if (lower.includes("8k")) { - return 8000; - } - if (lower.includes("4k")) { - return 4000; - } - // Default to 128k for newer long‑context models - return 128000; -} - -/** - * Calculates the percentage of tokens remaining in context for a model. - */ -export function calculateContextPercentRemaining( - items: Array, - model: string, -): number { - const used = approximateTokensUsed(items); - const max = maxTokensForModel(model); - const remaining = Math.max(0, max - used); - return (remaining / max) * 100; -} - -/** - * Deduplicate the stream of {@link ResponseItem}s before they are persisted in - * component state. - * - * Historically we used the (optional) {@code id} field returned by the - * OpenAI streaming API as the primary key: the first occurrence of any given - * {@code id} β€œwon” and subsequent duplicates were dropped. In practice this - * proved brittle because locally‑generated user messages don’t include an - * {@code id}. The result was that if a user quickly pressed twice the - * exact same message would appear twice in the transcript. - * - * The new rules are therefore: - * 1. If a {@link ResponseItem} has an {@code id} keep only the *first* - * occurrence of that {@code id} (this retains the previous behaviour for - * assistant / tool messages). - * 2. Additionally, collapse *consecutive* user messages with identical - * content. Two messages are considered identical when their serialized - * {@code content} array matches exactly. We purposefully restrict this - * to **adjacent** duplicates so that legitimately repeated questions at - * a later point in the conversation are still shown. - */ -export function uniqueById(items: Array): Array { - const seenIds = new Set(); - const deduped: Array = []; - - for (const item of items) { - // ────────────────────────────────────────────────────────────────── - // Rule #1 – de‑duplicate by id when present - // ────────────────────────────────────────────────────────────────── - if (typeof item.id === "string" && item.id.length > 0) { - if (seenIds.has(item.id)) { - continue; // skip duplicates - } - seenIds.add(item.id); - } - - // ────────────────────────────────────────────────────────────────── - // Rule #2 – collapse consecutive identical user messages - // ────────────────────────────────────────────────────────────────── - if (isUserMessage(item) && deduped.length > 0) { - const prev = deduped[deduped.length - 1]!; - - if ( - isUserMessage(prev) && - // Note: the `content` field is an array of message parts. Performing - // a deep compare is over‑kill here; serialising to JSON is sufficient - // (and fast for the tiny payloads involved). - JSON.stringify(prev.content) === JSON.stringify(item.content) - ) { - continue; // skip duplicate user message - } - } - - deduped.push(item); - } - - return deduped; -} diff --git a/codex-cli/src/components/chat/terminal-chat.tsx b/codex-cli/src/components/chat/terminal-chat.tsx index 9ebcfbc75e3f..4859513a4fad 100644 --- a/codex-cli/src/components/chat/terminal-chat.tsx +++ b/codex-cli/src/components/chat/terminal-chat.tsx @@ -6,23 +6,23 @@ import type { ResponseItem } from "openai/resources/responses/responses.mjs"; import TerminalChatInput from "./terminal-chat-input.js"; import { TerminalChatToolCallCommand } from "./terminal-chat-tool-call-command.js"; -import { - calculateContextPercentRemaining, - uniqueById, -} from "./terminal-chat-utils.js"; import TerminalMessageHistory from "./terminal-message-history.js"; import { formatCommandForDisplay } from "../../format-command.js"; import { useConfirmation } from "../../hooks/use-confirmation.js"; import { useTerminalSize } from "../../hooks/use-terminal-size.js"; import { AgentLoop } from "../../utils/agent/agent-loop.js"; -import { log } from "../../utils/agent/log.js"; import { ReviewDecision } from "../../utils/agent/review.js"; import { generateCompactSummary } from "../../utils/compact-summary.js"; import { OPENAI_BASE_URL, saveConfig } from "../../utils/config.js"; import { extractAppliedPatches as _extractAppliedPatches } from "../../utils/extract-applied-patches.js"; import { getGitDiff } from "../../utils/get-diff.js"; import { createInputItem } from "../../utils/input-utils.js"; -import { getAvailableModels } from "../../utils/model-utils.js"; +import { log } from "../../utils/logger/log.js"; +import { + getAvailableModels, + calculateContextPercentRemaining, + uniqueById, +} from "../../utils/model-utils.js"; import { CLI_VERSION } from "../../utils/session.js"; import { shortCwd } from "../../utils/short-path.js"; import { saveRollout } from "../../utils/storage/save-rollout.js"; @@ -106,11 +106,8 @@ async function generateCommandExplanation( } catch (error) { log(`Error generating command explanation: ${error}`); - // Improved error handling with more specific error information let errorMessage = "Unable to generate explanation due to an error."; - if (error instanceof Error) { - // Include specific error message for better debugging errorMessage = `Unable to generate explanation: ${error.message}`; // If it's an API error, check for more specific information @@ -141,18 +138,17 @@ export default function TerminalChat({ additionalWritableRoots, fullStdout, }: Props): React.ReactElement { - // Desktop notification setting const notify = config.notify; const [model, setModel] = useState(config.model); const [provider, setProvider] = useState(config.provider || "openai"); const [lastResponseId, setLastResponseId] = useState(null); const [items, setItems] = useState>([]); const [loading, setLoading] = useState(false); - // Allow switching approval modes at runtime via an overlay. const [approvalPolicy, setApprovalPolicy] = useState( initialApprovalPolicy, ); const [thinkingSeconds, setThinkingSeconds] = useState(0); + const handleCompact = async () => { setLoading(true); try { @@ -185,6 +181,7 @@ export default function TerminalChat({ setLoading(false); } }; + const { requestConfirmation, confirmationPrompt, @@ -215,13 +212,13 @@ export default function TerminalChat({ // DEBUG: log every render w/ key bits of state // ──────────────────────────────────────────────────────────────── log( - `render – agent? ${Boolean(agentRef.current)} loading=${loading} items=${ + `render - agent? ${Boolean(agentRef.current)} loading=${loading} items=${ items.length }`, ); useEffect(() => { - // Skip recreating the agent if awaiting a decision on a pending confirmation + // Skip recreating the agent if awaiting a decision on a pending confirmation. if (confirmationPrompt != null) { log("skip AgentLoop recreation due to pending confirmationPrompt"); return; @@ -234,9 +231,10 @@ export default function TerminalChat({ )} approvalPolicy=${approvalPolicy}`, ); - // Tear down any existing loop before creating a new one + // Tear down any existing loop before creating a new one. agentRef.current?.terminate(); + const sessionId = crypto.randomUUID(); agentRef.current = new AgentLoop({ model, provider, @@ -249,7 +247,7 @@ export default function TerminalChat({ log(`onItem: ${JSON.stringify(item)}`); setItems((prev) => { const updated = uniqueById([...prev, item as ResponseItem]); - saveRollout(updated); + saveRollout(sessionId, updated); return updated; }); }, @@ -266,11 +264,9 @@ export default function TerminalChat({ , ); - // If the user wants an explanation, generate one and ask again + // If the user wants an explanation, generate one and ask again. if (review === ReviewDecision.EXPLAIN) { log(`Generating explanation for command: ${commandForDisplay}`); - - // Generate an explanation using the same model const explanation = await generateCommandExplanation( command, model, @@ -278,7 +274,7 @@ export default function TerminalChat({ ); log(`Generated explanation: ${explanation}`); - // Ask for confirmation again, but with the explanation + // Ask for confirmation again, but with the explanation. const confirmResult = await requestConfirmation( , ); - // Update the decision based on the second confirmation + // Update the decision based on the second confirmation. review = confirmResult.decision; customDenyMessage = confirmResult.customDenyMessage; - // Return the final decision with the explanation + // Return the final decision with the explanation. return { review, customDenyMessage, applyPatch, explanation }; } @@ -298,7 +294,7 @@ export default function TerminalChat({ }, }); - // force a render so JSX below can "see" the freshly created agent + // Force a render so JSX below can "see" the freshly created agent. forceUpdate(); log(`AgentLoop created: ${inspect(agentRef.current, { depth: 1 })}`); @@ -309,17 +305,12 @@ export default function TerminalChat({ agentRef.current = undefined; forceUpdate(); // re‑render after teardown too }; - }, [ - model, - provider, - config, - approvalPolicy, - confirmationPrompt, - requestConfirmation, - additionalWritableRoots, - ]); + // We intentionally omit 'approvalPolicy' and 'confirmationPrompt' from the deps + // so switching modes or showing confirmation dialogs doesn’t tear down the loop. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [model, provider, config, requestConfirmation, additionalWritableRoots]); - // whenever loading starts/stops, reset or start a timer β€” but pause the + // Whenever loading starts/stops, reset or start a timer β€” but pause the // timer while a confirmation overlay is displayed so we don't trigger a // re‑render every second during apply_patch reviews. useEffect(() => { @@ -344,14 +335,15 @@ export default function TerminalChat({ }; }, [loading, confirmationPrompt]); - // Notify desktop with a preview when an assistant response arrives + // Notify desktop with a preview when an assistant response arrives. const prevLoadingRef = useRef(false); useEffect(() => { - // Only notify when notifications are enabled + // Only notify when notifications are enabled. if (!notify) { prevLoadingRef.current = loading; return; } + if ( prevLoadingRef.current && !loading && @@ -388,7 +380,7 @@ export default function TerminalChat({ prevLoadingRef.current = loading; }, [notify, loading, confirmationPrompt, items, PWD]); - // Let's also track whenever the ref becomes available + // Let's also track whenever the ref becomes available. const agent = agentRef.current; useEffect(() => { log(`agentRef.current is now ${Boolean(agent)}`); @@ -411,7 +403,7 @@ export default function TerminalChat({ const inputItems = [ await createInputItem(initialPrompt || "", initialImagePaths || []), ]; - // Clear them to prevent subsequent runs + // Clear them to prevent subsequent runs. setInitialPrompt(""); setInitialImagePaths([]); agent?.run(inputItems); @@ -446,7 +438,7 @@ export default function TerminalChat({ // eslint-disable-next-line react-hooks/exhaustive-deps }, []); - // Just render every item in order, no grouping/collapse + // Just render every item in order, no grouping/collapse. const lastMessageBatch = items.map((item) => ({ item })); const groupCounts: Record = {}; const userMsgCount = items.filter( @@ -625,10 +617,10 @@ export default function TerminalChat({ agent?.cancel(); setLoading(false); - // Select default model for the new provider + // Select default model for the new provider. const defaultModel = model; - // Save provider to config + // Save provider to config. const updatedConfig = { ...config, provider: newProvider, @@ -668,13 +660,12 @@ export default function TerminalChat({ { - // update approval policy without cancelling an in-progress session + // Update approval policy without cancelling an in-progress session. if (newMode === approvalPolicy) { return; } - // update state + setApprovalPolicy(newMode as ApprovalPolicy); - // update existing AgentLoop instance if (agentRef.current) { ( agentRef.current as unknown as { diff --git a/codex-cli/src/components/chat/terminal-header.tsx b/codex-cli/src/components/chat/terminal-header.tsx index bdc49946a5e1..1bd08aef2a4b 100644 --- a/codex-cli/src/components/chat/terminal-header.tsx +++ b/codex-cli/src/components/chat/terminal-header.tsx @@ -34,9 +34,9 @@ const TerminalHeader: React.FC = ({ {terminalRows < 10 ? ( // Compact header for small terminal windows - ● Codex v{version} – {PWD} – {model} ({provider}) –{" "} + ● Codex v{version} - {PWD} - {model} ({provider}) -{" "} {approvalPolicy} - {flexModeEnabled ? " – flex-mode" : ""} + {flexModeEnabled ? " - flex-mode" : ""} ) : ( <> diff --git a/codex-cli/src/components/singlepass-cli-app.tsx b/codex-cli/src/components/singlepass-cli-app.tsx index c52ae1be3d5b..0c5eeb4e11d1 100644 --- a/codex-cli/src/components/singlepass-cli-app.tsx +++ b/codex-cli/src/components/singlepass-cli-app.tsx @@ -399,8 +399,8 @@ export function SinglePassApp({ }); const openai = new OpenAI({ - apiKey: getApiKey(config.provider), - baseURL: getBaseUrl(config.provider), + apiKey: getApiKey(config.provider ?? "openai"), + baseURL: getBaseUrl(config.provider ?? "openai"), timeout: OPENAI_TIMEOUT_MS, }); const chatResp = await openai.beta.chat.completions.parse({ diff --git a/codex-cli/src/hooks/use-confirmation.ts b/codex-cli/src/hooks/use-confirmation.ts index b10a309dc52e..07c9e75cd032 100644 --- a/codex-cli/src/hooks/use-confirmation.ts +++ b/codex-cli/src/hooks/use-confirmation.ts @@ -1,4 +1,3 @@ -// use-confirmation.ts import type { ReviewDecision } from "../utils/agent/review"; import type React from "react"; diff --git a/codex-cli/src/text-buffer.ts b/codex-cli/src/text-buffer.ts index d7ce15306080..fe4e2a4759c5 100644 --- a/codex-cli/src/text-buffer.ts +++ b/codex-cli/src/text-buffer.ts @@ -423,7 +423,7 @@ export default class TextBuffer { /** Delete the word to the *left* of the caret, mirroring common * Ctrl/Alt+Backspace behaviour in editors & terminals. Both the adjacent * whitespace *and* the word characters immediately preceding the caret are - * removed. If the caret is already at column‑0 this becomes a no‑op. */ + * removed. If the caret is already at column‑0 this becomes a no-op. */ deleteWordLeft(): void { dbg("deleteWordLeft", { beforeCursor: this.getCursor() }); @@ -710,7 +710,7 @@ export default class TextBuffer { } endSelection(): void { - // no‑op for now, kept for API symmetry + // no-op for now, kept for API symmetry // we rely on anchor + current cursor to compute selection } diff --git a/codex-cli/src/utils/agent/agent-loop.ts b/codex-cli/src/utils/agent/agent-loop.ts index 1d3a66027f1e..6cdd37ca3948 100644 --- a/codex-cli/src/utils/agent/agent-loop.ts +++ b/codex-cli/src/utils/agent/agent-loop.ts @@ -10,9 +10,7 @@ import type { } from "openai/resources/responses/responses.mjs"; import type { Reasoning } from "openai/resources.mjs"; -import { log } from "./log.js"; import { - OPENAI_BASE_URL, OPENAI_TIMEOUT_MS, DEFAULT_RATE_LIMIT_MAX_RETRIES, DEFAULT_RATE_LIMIT_INITIAL_RETRY_DELAY_MS, @@ -21,6 +19,7 @@ import { getApiKey, getBaseUrl, } from "../config.js"; +import { log } from "../logger/log.js"; import { parseToolCallArguments } from "../parsers.js"; import { responsesCreateViaChatCompletions } from "../responses.js"; import { @@ -803,7 +802,7 @@ export class AgentLoop { for await (const event of stream as AsyncIterable) { log(`AgentLoop.run(): response event ${event.type}`); - // process and surface each item (no‑op until we can depend on streaming events) + // process and surface each item (no-op until we can depend on streaming events) if (event.type === "response.output_item.done") { const item = event.item; // 1) if it's a reasoning item, annotate it @@ -995,7 +994,7 @@ export class AgentLoop { ], }); } catch { - /* no‑op – emitting the error message is best‑effort */ + /* no-op – emitting the error message is best‑effort */ } this.onLoading(false); return; diff --git a/codex-cli/src/utils/agent/handle-exec-command.ts b/codex-cli/src/utils/agent/handle-exec-command.ts index 97b78c08178d..aea2c3a70735 100644 --- a/codex-cli/src/utils/agent/handle-exec-command.ts +++ b/codex-cli/src/utils/agent/handle-exec-command.ts @@ -5,12 +5,12 @@ import type { ApplyPatchCommand, ApprovalPolicy } from "../../approvals.js"; import type { ResponseInputItem } from "openai/resources/responses/responses.mjs"; import { exec, execApplyPatch } from "./exec.js"; -import { isLoggingEnabled, log } from "./log.js"; import { ReviewDecision } from "./review.js"; import { FullAutoErrorMode } from "../auto-approval-mode.js"; import { SandboxType } from "./sandbox/interface.js"; import { canAutoApprove } from "../../approvals.js"; import { formatCommandForDisplay } from "../../format-command.js"; +import { isLoggingEnabled, log } from "../logger/log.js"; import { access } from "fs/promises"; // --------------------------------------------------------------------------- @@ -144,7 +144,7 @@ export async function handleExecCommand( abortSignal, ); // If the operation was aborted in the meantime, propagate the cancellation - // upward by returning an empty (no‑op) result so that the agent loop will + // upward by returning an empty (no-op) result so that the agent loop will // exit cleanly without emitting spurious output. if (abortSignal?.aborted) { return { diff --git a/codex-cli/src/utils/agent/platform-commands.ts b/codex-cli/src/utils/agent/platform-commands.ts index 085c575d44fd..161388f942b8 100644 --- a/codex-cli/src/utils/agent/platform-commands.ts +++ b/codex-cli/src/utils/agent/platform-commands.ts @@ -2,7 +2,7 @@ * Utility functions for handling platform-specific commands */ -import { log } from "./log.js"; +import { log } from "../logger/log.js"; /** * Map of Unix commands to their Windows equivalents diff --git a/codex-cli/src/utils/agent/sandbox/macos-seatbelt.ts b/codex-cli/src/utils/agent/sandbox/macos-seatbelt.ts index 760ba63d8cc0..934056d9af4c 100644 --- a/codex-cli/src/utils/agent/sandbox/macos-seatbelt.ts +++ b/codex-cli/src/utils/agent/sandbox/macos-seatbelt.ts @@ -2,7 +2,7 @@ import type { ExecResult } from "./interface.js"; import type { SpawnOptions } from "child_process"; import { exec } from "./raw-exec.js"; -import { log } from "../log.js"; +import { log } from "../../logger/log.js"; function getCommonRoots() { return [ diff --git a/codex-cli/src/utils/agent/sandbox/raw-exec.ts b/codex-cli/src/utils/agent/sandbox/raw-exec.ts index 22add83ed8b3..b3d1d8ec250a 100644 --- a/codex-cli/src/utils/agent/sandbox/raw-exec.ts +++ b/codex-cli/src/utils/agent/sandbox/raw-exec.ts @@ -7,7 +7,7 @@ import type { StdioPipe, } from "child_process"; -import { log } from "../log.js"; +import { log } from "../../logger/log.js"; import { adaptCommandForPlatform } from "../platform-commands.js"; import { spawn } from "child_process"; import * as os from "os"; diff --git a/codex-cli/src/utils/config.ts b/codex-cli/src/utils/config.ts index dff63447a48d..73e68bcd18e2 100644 --- a/codex-cli/src/utils/config.ts +++ b/codex-cli/src/utils/config.ts @@ -8,8 +8,8 @@ import type { FullAutoErrorMode } from "./auto-approval-mode.js"; -import { log } from "./agent/log.js"; import { AutoApprovalMode } from "./auto-approval-mode.js"; +import { log } from "./logger/log.js"; import { providers } from "./providers.js"; import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"; import { load as loadYaml, dump as dumpYaml } from "js-yaml"; @@ -47,7 +47,7 @@ export function setApiKey(apiKey: string): void { OPENAI_API_KEY = apiKey; } -export function getBaseUrl(provider: string = "openai"): string | undefined { +export function getBaseUrl(provider: string): string | undefined { const providerInfo = providers[provider.toLowerCase()]; if (providerInfo) { return providerInfo.baseURL; @@ -55,7 +55,7 @@ export function getBaseUrl(provider: string = "openai"): string | undefined { return undefined; } -export function getApiKey(provider: string = "openai"): string | undefined { +export function getApiKey(provider: string): string | undefined { const providerInfo = providers[provider.toLowerCase()]; if (providerInfo) { if (providerInfo.name === "Ollama") { @@ -92,8 +92,6 @@ export type StoredConfig = { saveHistory?: boolean; sensitivePatterns?: Array; }; - /** User-defined safe commands */ - safeCommands?: Array; }; // Minimal config written on first run. An *empty* model string ensures that @@ -128,8 +126,6 @@ export type AppConfig = { saveHistory: boolean; sensitivePatterns: Array; }; - /** User-defined safe commands */ - safeCommands?: Array; }; // --------------------------------------------------------------------------- @@ -312,7 +308,6 @@ export const loadConfig = ( instructions: combinedInstructions, notify: storedConfig.notify === true, approvalMode: storedConfig.approvalMode, - safeCommands: storedConfig.safeCommands ?? [], }; // ----------------------------------------------------------------------- @@ -390,13 +385,6 @@ export const loadConfig = ( }; } - // Load user-defined safe commands - if (Array.isArray(storedConfig.safeCommands)) { - config.safeCommands = storedConfig.safeCommands.map(String); - } else { - config.safeCommands = []; - } - // Add rate limit configuration if present, or use defaults if (storedConfig.rateLimits) { config.rateLimits = storedConfig.rateLimits; @@ -408,7 +396,6 @@ export const loadConfig = ( jitterFactor: DEFAULT_RATE_LIMIT_JITTER_FACTOR, }; } - return config; }; @@ -452,10 +439,6 @@ export const saveConfig = ( sensitivePatterns: config.history.sensitivePatterns, }; } - // Save: User-defined safe commands - if (config.safeCommands && config.safeCommands.length > 0) { - configToSave.safeCommands = config.safeCommands; - } // Add rate limits to configToSave if they exist if (config.rateLimits) { diff --git a/codex-cli/src/utils/agent/log.ts b/codex-cli/src/utils/logger/log.ts similarity index 100% rename from codex-cli/src/utils/agent/log.ts rename to codex-cli/src/utils/logger/log.ts diff --git a/codex-cli/src/utils/model-utils.ts b/codex-cli/src/utils/model-utils.ts index 946756cb24b1..31f1afe6c4d7 100644 --- a/codex-cli/src/utils/model-utils.ts +++ b/codex-cli/src/utils/model-utils.ts @@ -1,3 +1,6 @@ +import type { ResponseItem } from "openai/resources/responses/responses.mjs"; + +import { approximateTokensUsed } from "./approximate-tokens-used.js"; import { getBaseUrl, getApiKey } from "./config"; import OpenAI from "openai"; @@ -11,9 +14,8 @@ export const RECOMMENDED_MODELS: Array = ["o4-mini", "o3"]; * enters interactive mode. The request is made exactly once during the * lifetime of the process and the results are cached for subsequent calls. */ - async function fetchModels(provider: string): Promise> { - // If the user has not configured an API key we cannot hit the network. + // If the user has not configured an API key we cannot retrieve the models. if (!getApiKey(provider)) { throw new Error("No API key configured for provider: " + provider); } @@ -26,7 +28,7 @@ async function fetchModels(provider: string): Promise> { for await (const model of list as AsyncIterable<{ id?: string }>) { if (model && typeof model.id === "string") { let modelStr = model.id; - // fix for gemini + // Fix for gemini. if (modelStr.startsWith("models/")) { modelStr = modelStr.replace("models/", ""); } @@ -40,6 +42,7 @@ async function fetchModels(provider: string): Promise> { } } +/** Returns the list of models available for the provided key / credentials. */ export async function getAvailableModels( provider: string, ): Promise> { @@ -47,11 +50,11 @@ export async function getAvailableModels( } /** - * Verify that the provided model identifier is present in the set returned by - * {@link getAvailableModels}. The list of models is fetched from the OpenAI - * `/models` endpoint the first time it is required and then cached in‑process. + * Verifies that the provided model identifier is present in the set returned by + * {@link getAvailableModels}. */ export async function isModelSupportedForResponses( + provider: string, model: string | undefined | null, ): Promise { if ( @@ -64,7 +67,7 @@ export async function isModelSupportedForResponses( try { const models = await Promise.race>([ - getAvailableModels("openai"), + getAvailableModels(provider), new Promise>((resolve) => setTimeout(() => resolve([]), MODEL_LIST_TIMEOUT_MS), ), @@ -82,3 +85,110 @@ export async function isModelSupportedForResponses( return true; } } + +/** Returns the maximum context length (in tokens) for a given model. */ +function maxTokensForModel(model: string): number { + // TODO: These numbers are best‑effort guesses and provide a basis for UI percentages. They + // should be provider & model specific instead of being wild guesses. + + const lower = model.toLowerCase(); + if (lower.includes("32k")) { + return 32000; + } + if (lower.includes("16k")) { + return 16000; + } + if (lower.includes("8k")) { + return 8000; + } + if (lower.includes("4k")) { + return 4000; + } + return 128000; // Default to 128k for any other model. +} + +/** Calculates the percentage of tokens remaining in context for a model. */ +export function calculateContextPercentRemaining( + items: Array, + model: string, +): number { + const used = approximateTokensUsed(items); + const max = maxTokensForModel(model); + const remaining = Math.max(0, max - used); + return (remaining / max) * 100; +} + +/** + * Type‑guard that narrows a {@link ResponseItem} to one that represents a + * user‑authored message. The OpenAI SDK represents both input *and* output + * messages with a discriminated union where: + * β€’ `type` is the string literal "message" and + * β€’ `role` is one of "user" | "assistant" | "system" | "developer". + * + * For the purposes of de‑duplication we only care about *user* messages so we + * detect those here in a single, reusable helper. + */ +function isUserMessage( + item: ResponseItem, +): item is ResponseItem & { type: "message"; role: "user"; content: unknown } { + return item.type === "message" && (item as { role?: string }).role === "user"; +} + +/** + * Deduplicate the stream of {@link ResponseItem}s before they are persisted in + * component state. + * + * Historically we used the (optional) {@code id} field returned by the + * OpenAI streaming API as the primary key: the first occurrence of any given + * {@code id} β€œwon” and subsequent duplicates were dropped. In practice this + * proved brittle because locally‑generated user messages don’t include an + * {@code id}. The result was that if a user quickly pressed twice the + * exact same message would appear twice in the transcript. + * + * The new rules are therefore: + * 1. If a {@link ResponseItem} has an {@code id} keep only the *first* + * occurrence of that {@code id} (this retains the previous behaviour for + * assistant / tool messages). + * 2. Additionally, collapse *consecutive* user messages with identical + * content. Two messages are considered identical when their serialized + * {@code content} array matches exactly. We purposefully restrict this + * to **adjacent** duplicates so that legitimately repeated questions at + * a later point in the conversation are still shown. + */ +export function uniqueById(items: Array): Array { + const seenIds = new Set(); + const deduped: Array = []; + + for (const item of items) { + // ────────────────────────────────────────────────────────────────── + // Rule #1 – de‑duplicate by id when present + // ────────────────────────────────────────────────────────────────── + if (typeof item.id === "string" && item.id.length > 0) { + if (seenIds.has(item.id)) { + continue; // skip duplicates + } + seenIds.add(item.id); + } + + // ────────────────────────────────────────────────────────────────── + // Rule #2 – collapse consecutive identical user messages + // ────────────────────────────────────────────────────────────────── + if (isUserMessage(item) && deduped.length > 0) { + const prev = deduped[deduped.length - 1]!; + + if ( + isUserMessage(prev) && + // Note: the `content` field is an array of message parts. Performing + // a deep compare is over‑kill here; serialising to JSON is sufficient + // (and fast for the tiny payloads involved). + JSON.stringify(prev.content) === JSON.stringify(item.content) + ) { + continue; // skip duplicate user message + } + } + + deduped.push(item); + } + + return deduped; +} diff --git a/codex-cli/src/utils/session.ts b/codex-cli/src/utils/session.ts index 06f404f15543..923143d72a55 100644 --- a/codex-cli/src/utils/session.ts +++ b/codex-cli/src/utils/session.ts @@ -1,4 +1,4 @@ -export const CLI_VERSION = "0.1.2504181820"; // Must be in sync with package.json. +export const CLI_VERSION = "0.1.2504211509"; // Must be in sync with package.json. export const ORIGIN = "codex_cli_ts"; export type TerminalChatSession = { diff --git a/codex-cli/src/utils/storage/command-history.ts b/codex-cli/src/utils/storage/command-history.ts index 997c4872ad1e..d774b53340f4 100644 --- a/codex-cli/src/utils/storage/command-history.ts +++ b/codex-cli/src/utils/storage/command-history.ts @@ -1,12 +1,13 @@ +import { log } from "../logger/log.js"; import { existsSync } from "fs"; import fs from "fs/promises"; import os from "os"; import path from "path"; const HISTORY_FILE = path.join(os.homedir(), ".codex", "history.json"); -const DEFAULT_HISTORY_SIZE = 1000; +const DEFAULT_HISTORY_SIZE = 10_000; -// Regex patterns for sensitive commands that should not be saved +// Regex patterns for sensitive commands that should not be saved. const SENSITIVE_PATTERNS = [ /\b[A-Za-z0-9-_]{20,}\b/, // API keys and tokens /\bpassword\b/i, @@ -18,7 +19,7 @@ const SENSITIVE_PATTERNS = [ export interface HistoryConfig { maxSize: number; saveHistory: boolean; - sensitivePatterns: Array; // Array of regex patterns as strings + sensitivePatterns: Array; // Regex patterns. } export interface HistoryEntry { @@ -32,9 +33,6 @@ export const DEFAULT_HISTORY_CONFIG: HistoryConfig = { sensitivePatterns: [], }; -/** - * Loads command history from the history file - */ export async function loadCommandHistory(): Promise> { try { if (!existsSync(HISTORY_FILE)) { @@ -45,26 +43,21 @@ export async function loadCommandHistory(): Promise> { const history = JSON.parse(data) as Array; return Array.isArray(history) ? history : []; } catch (error) { - // Use error logger but for production would use a proper logging system - // eslint-disable-next-line no-console - console.error("Failed to load command history:", error); + log(`error: failed to load command history: ${error}`); return []; } } -/** - * Saves command history to the history file - */ export async function saveCommandHistory( history: Array, config: HistoryConfig = DEFAULT_HISTORY_CONFIG, ): Promise { try { - // Create directory if it doesn't exist + // Create directory if it doesn't exist. const dir = path.dirname(HISTORY_FILE); await fs.mkdir(dir, { recursive: true }); - // Trim history to max size + // Trim history to max size. const trimmedHistory = history.slice(-config.maxSize); await fs.writeFile( @@ -73,14 +66,10 @@ export async function saveCommandHistory( "utf-8", ); } catch (error) { - // eslint-disable-next-line no-console - console.error("Failed to save command history:", error); + log(`error: failed to save command history: ${error}`); } } -/** - * Adds a command to history if it's not sensitive - */ export async function addToHistory( command: string, history: Array, @@ -90,46 +79,41 @@ export async function addToHistory( return history; } - // Check if command contains sensitive information - if (isSensitiveCommand(command, config.sensitivePatterns)) { + // Skip commands with sensitive information. + if (commandHasSensitiveInfo(command, config.sensitivePatterns)) { return history; } - // Check for duplicate (don't add if it's the same as the last command) + // Check for duplicate (don't add if it's the same as the last command). const lastEntry = history[history.length - 1]; if (lastEntry && lastEntry.command === command) { return history; } - // Add new entry - const newEntry: HistoryEntry = { - command, - timestamp: Date.now(), - }; - - const newHistory = [...history, newEntry]; - - // Save to file + // Add new entry. + const newHistory: Array = [ + ...history, + { + command, + timestamp: Date.now(), + }, + ]; await saveCommandHistory(newHistory, config); - return newHistory; } -/** - * Checks if a command contains sensitive information - */ -function isSensitiveCommand( +function commandHasSensitiveInfo( command: string, additionalPatterns: Array = [], ): boolean { - // Check built-in patterns + // Check built-in patterns. for (const pattern of SENSITIVE_PATTERNS) { if (pattern.test(command)) { return true; } } - // Check additional patterns from config + // Check additional patterns from config. for (const patternStr of additionalPatterns) { try { const pattern = new RegExp(patternStr); @@ -137,23 +121,19 @@ function isSensitiveCommand( return true; } } catch (error) { - // Invalid regex pattern, skip it + // Invalid regex pattern, skip it. } } return false; } -/** - * Clears the command history - */ export async function clearCommandHistory(): Promise { try { if (existsSync(HISTORY_FILE)) { await fs.writeFile(HISTORY_FILE, JSON.stringify([]), "utf-8"); } } catch (error) { - // eslint-disable-next-line no-console - console.error("Failed to clear command history:", error); + log(`error: failed to clear command history: ${error}`); } } diff --git a/codex-cli/src/utils/storage/save-rollout.ts b/codex-cli/src/utils/storage/save-rollout.ts index 76d931fd9fa9..d6b5a491902b 100644 --- a/codex-cli/src/utils/storage/save-rollout.ts +++ b/codex-cli/src/utils/storage/save-rollout.ts @@ -1,20 +1,19 @@ -/* eslint-disable no-console */ - import type { ResponseItem } from "openai/resources/responses/responses"; import { loadConfig } from "../config"; +import { log } from "../logger/log.js"; import fs from "fs/promises"; import os from "os"; import path from "path"; const SESSIONS_ROOT = path.join(os.homedir(), ".codex", "sessions"); -async function saveRolloutToHomeSessions( +async function saveRolloutAsync( + sessionId: string, items: Array, ): Promise { await fs.mkdir(SESSIONS_ROOT, { recursive: true }); - const sessionId = crypto.randomUUID(); const timestamp = new Date().toISOString(); const ts = timestamp.replace(/[:.]/g, "-").slice(0, 10); const filename = `rollout-${ts}-${sessionId}.json`; @@ -39,23 +38,15 @@ async function saveRolloutToHomeSessions( "utf8", ); } catch (error) { - console.error(`Failed to save rollout to ${filePath}: `, error); + log(`error: failed to save rollout to ${filePath}: ${error}`); } } -let debounceTimer: NodeJS.Timeout | null = null; -let pendingItems: Array | null = null; - -export function saveRollout(items: Array): void { - pendingItems = items; - if (debounceTimer) { - clearTimeout(debounceTimer); - } - debounceTimer = setTimeout(() => { - if (pendingItems) { - saveRolloutToHomeSessions(pendingItems).catch(() => {}); - pendingItems = null; - } - debounceTimer = null; - }, 2000); +export function saveRollout( + sessionId: string, + items: Array, +): void { + // Best-effort. We also do not log here in case of failure as that should be taken care of + // by `saveRolloutAsync` already. + saveRolloutAsync(sessionId, items).catch(() => {}); } diff --git a/codex-cli/src/utils/terminal-chat-utils.ts b/codex-cli/src/utils/terminal-chat-utils.ts new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/codex-cli/src/utils/terminal.ts b/codex-cli/src/utils/terminal.ts index e8187eba6b8b..296cbb39b208 100644 --- a/codex-cli/src/utils/terminal.ts +++ b/codex-cli/src/utils/terminal.ts @@ -50,6 +50,8 @@ export function clearTerminal(): void { if (inkRenderer) { inkRenderer.clear(); } + // Also clear scrollback and primary buffer to ensure a truly blank slate + process.stdout.write("\x1b[3J\x1b[H\x1b[2J"); } export function onExit(): void { diff --git a/codex-cli/tests/agent-project-doc.test.ts b/codex-cli/tests/agent-project-doc.test.ts index 4b8951e7a0eb..d421c268c0cb 100644 --- a/codex-cli/tests/agent-project-doc.test.ts +++ b/codex-cli/tests/agent-project-doc.test.ts @@ -50,7 +50,7 @@ vi.mock("openai", () => { // The AgentLoop pulls these helpers in order to decide whether a command can // be auto‑approved. None of that matters for this test, so we stub the module -// with minimal no‑op implementations. +// with minimal no-op implementations. vi.mock("../src/approvals.js", () => { return { __esModule: true, diff --git a/codex-cli/tests/approvals.test.ts b/codex-cli/tests/approvals.test.ts index a4c08b04a6eb..a90abad6eb67 100644 --- a/codex-cli/tests/approvals.test.ts +++ b/codex-cli/tests/approvals.test.ts @@ -1,13 +1,7 @@ import type { SafetyAssessment } from "../src/approvals"; import { canAutoApprove } from "../src/approvals"; -import { describe, test, expect, vi } from "vitest"; - -vi.mock("../src/utils/config", () => ({ - loadConfig: () => ({ - safeCommands: ["npm test", "sl"], - }), -})); +import { describe, test, expect } from "vitest"; describe("canAutoApprove()", () => { const env = { @@ -79,7 +73,7 @@ describe("canAutoApprove()", () => { test("true command is considered safe", () => { expect(check(["true"])).toEqual({ type: "auto-approve", - reason: "No‑op (true)", + reason: "No-op (true)", group: "Utility", runInSandbox: false, }); @@ -96,26 +90,55 @@ describe("canAutoApprove()", () => { expect(check(["cargo", "build"])).toEqual({ type: "ask-user" }); }); - test("commands in safeCommands config should be safe", async () => { - expect(check(["npm", "test"])).toEqual({ + test("find", () => { + expect(check(["find", ".", "-name", "file.txt"])).toEqual({ type: "auto-approve", - reason: "User-defined safe command", - group: "User config", + reason: "Find files or directories", + group: "Searching", runInSandbox: false, }); - expect(check(["sl"])).toEqual({ - type: "auto-approve", - reason: "User-defined safe command", - group: "User config", - runInSandbox: false, + // Options that can execute arbitrary commands. + expect( + check(["find", ".", "-name", "file.txt", "-exec", "rm", "{}", ";"]), + ).toEqual({ + type: "ask-user", + }); + expect( + check(["find", ".", "-name", "*.py", "-execdir", "python3", "{}", ";"]), + ).toEqual({ + type: "ask-user", + }); + expect( + check(["find", ".", "-name", "file.txt", "-ok", "rm", "{}", ";"]), + ).toEqual({ + type: "ask-user", + }); + expect( + check(["find", ".", "-name", "*.py", "-okdir", "python3", "{}", ";"]), + ).toEqual({ + type: "ask-user", }); - expect(check(["npm", "test", "--watch"])).toEqual({ - type: "auto-approve", - reason: "User-defined safe command", - group: "User config", - runInSandbox: false, + // Option that deletes matching files. + expect(check(["find", ".", "-delete", "-name", "file.txt"])).toEqual({ + type: "ask-user", + }); + + // Options that write pathnames to a file. + expect(check(["find", ".", "-fls", "/etc/passwd"])).toEqual({ + type: "ask-user", + }); + expect(check(["find", ".", "-fprint", "/etc/passwd"])).toEqual({ + type: "ask-user", + }); + expect(check(["find", ".", "-fprint0", "/etc/passwd"])).toEqual({ + type: "ask-user", + }); + expect( + check(["find", ".", "-fprintf", "/root/suid.txt", "%#m %u %p\n"]), + ).toEqual({ + type: "ask-user", }); }); }); diff --git a/codex-cli/tests/clear-command.test.tsx b/codex-cli/tests/clear-command.test.tsx new file mode 100644 index 000000000000..bab9b84c9b35 --- /dev/null +++ b/codex-cli/tests/clear-command.test.tsx @@ -0,0 +1,174 @@ +import React from "react"; +import type { ComponentProps } from "react"; +import { describe, it, expect, vi } from "vitest"; +import { renderTui } from "./ui-test-helpers.js"; +import TerminalChatInput from "../src/components/chat/terminal-chat-input.js"; +import TerminalChatNewInput from "../src/components/chat/terminal-chat-new-input.js"; +import * as TermUtils from "../src/utils/terminal.js"; + +// ------------------------------------------------------------------------------------------------- +// Helpers +// ------------------------------------------------------------------------------------------------- + +async function type( + stdin: NodeJS.WritableStream, + text: string, + flush: () => Promise, +): Promise { + stdin.write(text); + await flush(); +} + +// ------------------------------------------------------------------------------------------------- +// Tests +// ------------------------------------------------------------------------------------------------- + +describe("/clear command", () => { + it("invokes clearTerminal and resets context in TerminalChatInput", async () => { + const clearSpy = vi + .spyOn(TermUtils, "clearTerminal") + .mockImplementation(() => {}); + + const setItems = vi.fn(); + + // Minimal stub of a ResponseItem – cast to bypass exhaustive type checks in this test context + const existingItems = [ + { + id: "dummy-1", + type: "message", + role: "system", + content: [{ type: "input_text", text: "Old item" }], + }, + ] as Array; + + const props: ComponentProps = { + isNew: false, + loading: false, + submitInput: () => {}, + confirmationPrompt: null, + explanation: undefined, + submitConfirmation: () => {}, + setLastResponseId: () => {}, + setItems, + contextLeftPercent: 100, + openOverlay: () => {}, + openModelOverlay: () => {}, + openApprovalOverlay: () => {}, + openHelpOverlay: () => {}, + openDiffOverlay: () => {}, + onCompact: () => {}, + interruptAgent: () => {}, + active: true, + thinkingSeconds: 0, + items: existingItems, + }; + + const { stdin, flush, cleanup } = renderTui( + , + ); + + await flush(); + + await type(stdin, "/clear", flush); + await type(stdin, "\r", flush); // press Enter + + // Allow any asynchronous state updates to propagate + await flush(); + + expect(clearSpy).toHaveBeenCalledTimes(2); + expect(setItems).toHaveBeenCalledTimes(2); + + const stateUpdater = setItems.mock.calls[0]![0]; + expect(typeof stateUpdater).toBe("function"); + const newItems = stateUpdater(existingItems); + expect(Array.isArray(newItems)).toBe(true); + expect(newItems).toHaveLength(2); + expect(newItems.at(-1)).toMatchObject({ + role: "system", + type: "message", + content: [{ type: "input_text", text: "Terminal cleared" }], + }); + + cleanup(); + clearSpy.mockRestore(); + }); + + it("invokes clearTerminal and resets context in TerminalChatNewInput", async () => { + const clearSpy = vi + .spyOn(TermUtils, "clearTerminal") + .mockImplementation(() => {}); + + const setItems = vi.fn(); + + const props: ComponentProps = { + isNew: false, + loading: false, + submitInput: () => {}, + confirmationPrompt: null, + explanation: undefined, + submitConfirmation: () => {}, + setLastResponseId: () => {}, + setItems, + contextLeftPercent: 100, + openOverlay: () => {}, + openModelOverlay: () => {}, + openApprovalOverlay: () => {}, + openHelpOverlay: () => {}, + openDiffOverlay: () => {}, + interruptAgent: () => {}, + active: true, + thinkingSeconds: 0, + }; + + const { stdin, flush, cleanup } = renderTui( + , + ); + + await flush(); + + await type(stdin, "/clear", flush); + await type(stdin, "\r", flush); // press Enter + + await flush(); + + expect(clearSpy).toHaveBeenCalledTimes(1); + expect(setItems).toHaveBeenCalledTimes(1); + + const firstArg = setItems.mock.calls[0]![0]; + expect(Array.isArray(firstArg)).toBe(true); + expect(firstArg).toHaveLength(1); + expect(firstArg[0]).toMatchObject({ + role: "system", + type: "message", + content: [{ type: "input_text", text: "Terminal cleared" }], + }); + + cleanup(); + clearSpy.mockRestore(); + }); +}); + +describe("clearTerminal", () => { + it("writes escape sequence to stdout", () => { + const originalQuiet = process.env["CODEX_QUIET_MODE"]; + delete process.env["CODEX_QUIET_MODE"]; + + process.env["CODEX_QUIET_MODE"] = "0"; + + const writeSpy = vi + .spyOn(process.stdout, "write") + .mockImplementation(() => true); + + TermUtils.clearTerminal(); + + expect(writeSpy).toHaveBeenCalledWith("\x1b[3J\x1b[H\x1b[2J"); + + writeSpy.mockRestore(); + + if (originalQuiet !== undefined) { + process.env["CODEX_QUIET_MODE"] = originalQuiet; + } else { + delete process.env["CODEX_QUIET_MODE"]; + } + }); +}); diff --git a/codex-cli/tests/config.test.tsx b/codex-cli/tests/config.test.tsx index 0cfdf2f5a363..81dc98df63e9 100644 --- a/codex-cli/tests/config.test.tsx +++ b/codex-cli/tests/config.test.tsx @@ -33,7 +33,7 @@ vi.mock("fs", async () => { memfs[path] = data; }, mkdirSync: () => { - // no‑op in in‑memory store + // no-op in in‑memory store }, rmSync: (path: string) => { // recursively delete any key under this prefix diff --git a/codex-cli/tests/model-utils-network-error.test.ts b/codex-cli/tests/model-utils-network-error.test.ts index f67b4fc4dbfa..537e7fdb35f5 100644 --- a/codex-cli/tests/model-utils-network-error.test.ts +++ b/codex-cli/tests/model-utils-network-error.test.ts @@ -44,7 +44,7 @@ describe("model-utils – offline resilience", () => { "../src/utils/model-utils.js" ); - const supported = await isModelSupportedForResponses("o4-mini"); + const supported = await isModelSupportedForResponses("openai", "o4-mini"); expect(supported).toBe(true); }); @@ -63,8 +63,11 @@ describe("model-utils – offline resilience", () => { "../src/utils/model-utils.js" ); - // Should resolve true despite the network failure - const supported = await isModelSupportedForResponses("some-model"); + // Should resolve true despite the network failure. + const supported = await isModelSupportedForResponses( + "openai", + "some-model", + ); expect(supported).toBe(true); }); }); diff --git a/codex-cli/tests/multiline-history-behavior.test.tsx b/codex-cli/tests/multiline-history-behavior.test.tsx index cada52ddab6e..ee46d3d5c1f4 100644 --- a/codex-cli/tests/multiline-history-behavior.test.tsx +++ b/codex-cli/tests/multiline-history-behavior.test.tsx @@ -57,7 +57,7 @@ async function type( await flush(); } -/** Build a set of no‑op callbacks so renders with minimal +/** Build a set of no-op callbacks so renders with minimal * scaffolding. */ function stubProps(): any { diff --git a/codex-cli/tests/text-buffer.test.ts b/codex-cli/tests/text-buffer.test.ts index c3f33d0fa1dd..e5c532f7cb10 100644 --- a/codex-cli/tests/text-buffer.test.ts +++ b/codex-cli/tests/text-buffer.test.ts @@ -127,7 +127,7 @@ describe("TextBuffer – basic editing parity with Rust suite", () => { expect(buf.getCursor()).toEqual([0, 2]); // after 'b' }); - it("is a no‑op at the very beginning of the buffer", () => { + it("is a no-op at the very beginning of the buffer", () => { const buf = new TextBuffer("ab"); buf.backspace(); // caret starts at (0,0) diff --git a/codex-cli/tests/typeahead-scroll.test.tsx b/codex-cli/tests/typeahead-scroll.test.tsx index fab7c753b883..e0e496adac95 100644 --- a/codex-cli/tests/typeahead-scroll.test.tsx +++ b/codex-cli/tests/typeahead-scroll.test.tsx @@ -26,7 +26,7 @@ vi.mock("../src/components/select-input/select-input.js", () => { // Ink's toggles raw‑mode which calls .ref() / .unref() on stdin. // The test environment's mock streams don't implement those methods, so we -// polyfill them to no‑ops on the prototype *before* the component tree mounts. +// polyfill them to no-ops on the prototype *before* the component tree mounts. import { EventEmitter } from "node:events"; if (!(EventEmitter.prototype as any).ref) { (EventEmitter.prototype as any).ref = () => {}; diff --git a/package.json b/package.json index 215616bec154..b516ce40faeb 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "build": "pnpm --filter @openai/codex run build", "test": "pnpm --filter @openai/codex run test", "lint": "pnpm --filter @openai/codex run lint", + "lint:fix": "pnpm --filter @openai/codex run lint:fix", "typecheck": "pnpm --filter @openai/codex run typecheck", "changelog": "git-cliff --config cliff.toml --output CHANGELOG.ignore.md $LAST_RELEASE_TAG..HEAD", "prepare": "husky",