diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000000..8fd2c0d502 --- /dev/null +++ b/TODO.md @@ -0,0 +1 @@ +# To do list with go here diff --git a/codex-cli/README.md b/codex-cli/README.md index e988b384ab..3babc9d90c 100644 --- a/codex-cli/README.md +++ b/codex-cli/README.md @@ -1,736 +1,23 @@ -
Lightweight coding agent that runs in your terminal
- -npm i -g @openai/codex
--provider
to use other modelso3
or o4-mini
not work for me?;u".
if (input.startsWith("[") && input.endsWith("u")) {
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 714cc59fb3..6eceaf606e 100644
--- a/codex-cli/src/components/chat/terminal-chat-input-thinking.tsx
+++ b/codex-cli/src/components/chat/terminal-chat-input-thinking.tsx
@@ -1,7 +1,7 @@
import { log } from "../../utils/logger/log.js";
-import { Box, Text, useInput, useStdin } from "ink";
-import React, { useState } from "react";
-import { useInterval } from "use-interval";
+import { Box, Text, useInput } from "ink";
+import React, { useEffect, useMemo, useState } from "react";
+import { ANIMATION_CYCLE_MS } from "./animation-config";
// Retaining a single static placeholder text for potential future use. The
// more elaborate randomised thinking prompts were removed to streamline the
@@ -10,51 +10,35 @@ import { useInterval } from "use-interval";
export default function TerminalChatInputThinking({
onInterrupt,
active,
- thinkingSeconds,
+ thinkingSeconds: _thinkingSeconds,
+ title,
}: {
onInterrupt: () => void;
active: boolean;
thinkingSeconds: number;
+ title?: string;
}): React.ReactElement {
const [awaitingConfirm, setAwaitingConfirm] = useState(false);
- const [dots, setDots] = useState("");
+ const [persistentTitle, setPersistentTitle] = useState("");
+ const [phase, setPhase] = useState(0);
- // Animate the ellipsis
- useInterval(() => {
- setDots((prev) => (prev.length < 3 ? prev + "." : ""));
- }, 500);
+ // Avoid forcing raw-mode globally; rely on Ink's useInput handling with isActive
- const { stdin, setRawMode } = useStdin();
+ // No timers required beyond tracking the elapsed seconds supplied via props.
- React.useEffect(() => {
- if (!active) {
- return;
+ // Keep last non-empty, non-default (not "Thinking") title visible until a new one arrives
+ useEffect(() => {
+ const incoming = typeof title === "string" ? title.trim() : "";
+ const isDefaultThinking = /^thinking$/i.test(incoming);
+ if (
+ incoming.length > 0 &&
+ !isDefaultThinking &&
+ incoming !== persistentTitle
+ ) {
+ setPersistentTitle(incoming);
+ setPhase(0);
}
-
- setRawMode?.(true);
-
- const onData = (data: Buffer | string) => {
- if (awaitingConfirm) {
- return;
- }
-
- const str = Buffer.isBuffer(data) ? data.toString("utf8") : data;
- if (str === "\x1b\x1b") {
- log(
- "raw stdin: received collapsed ESC ESC – starting confirmation timer",
- );
- setAwaitingConfirm(true);
- setTimeout(() => setAwaitingConfirm(false), 1500);
- }
- };
-
- stdin?.on("data", onData);
- return () => {
- stdin?.off("data", onData);
- };
- }, [stdin, awaitingConfirm, onInterrupt, active, setRawMode]);
-
- // No timers required beyond tracking the elapsed seconds supplied via props.
+ }, [title, persistentTitle]);
useInput(
(_input, key) => {
@@ -75,48 +59,79 @@ export default function TerminalChatInputThinking({
{ isActive: active },
);
- // Custom ball animation including the elapsed seconds
- const ballFrames = [
- "( ● )",
- "( ● )",
- "( ● )",
- "( ● )",
- "( ●)",
- "( ● )",
- "( ● )",
- "( ● )",
- "( ● )",
- "(● )",
- ];
-
- const [frame, setFrame] = useState(0);
-
- useInterval(() => {
- setFrame((idx) => (idx + 1) % ballFrames.length);
- }, 80);
+ // Animate a sliding shimmer over the title using levels 0..3 (white→dark gray)
+ const animatedNodes = useMemo(() => {
+ const text = (persistentTitle || "Thinking").split("");
+ const n = text.length;
+ // More ranges with darkest in the middle (peak)
+ // Intensities 0 (white) .. 8 (darkest)
+ const kernel = [
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 6,
+ 7,
+ 8, // ramp up to darkest
+ 8,
+ 7,
+ 6,
+ 5,
+ 4,
+ 3,
+ 2,
+ 1, // ramp down symmetrically
+ ];
+ const levels = new Array(n).fill(0);
+ const center = phase % Math.max(1, n); // center position moves across text
+ const half = Math.floor(kernel.length / 2);
+ for (let k = 0; k < kernel.length; k += 1) {
+ const idx = (center - half + k + n) % n; // wrap kernel around text
+ levels[idx] = kernel[k] ?? 0;
+ }
- // Preserve the spinner (ball) animation while keeping the elapsed seconds
- // text static. We achieve this by rendering the bouncing ball inside the
- // parentheses and appending the seconds counter *after* the spinner rather
- // than injecting it directly next to the ball (which caused the counter to
- // move horizontally together with the ball).
+ // Palette from white (0) to very dark gray (8)
+ const palette = [
+ "#FFFFFF", // 0
+ "#EDEDED", // 1
+ "#DBDBDB", // 2
+ "#C9C9C9", // 3
+ "#B7B7B7", // 4
+ "#A5A5A5", // 5
+ "#8F8F8F", // 6
+ "#6F6F6F", // 7
+ "#4A4A4A", // 8 darkest
+ ];
+
+ return text.map((ch, i) => {
+ const lvl = levels[i] ?? 0;
+ const color = palette[Math.max(0, Math.min(palette.length - 1, lvl))];
+ return (
+
+ {ch}
+
+ );
+ });
+ }, [persistentTitle, phase]);
- const frameTemplate = ballFrames[frame] ?? ballFrames[0];
- const frameWithSeconds = `${frameTemplate} ${thinkingSeconds}s`;
+ useEffect(() => {
+ if (!active) {
+ return;
+ }
+ const textLen = (persistentTitle || "Thinking").length;
+ const cycle = Math.max(1, textLen); // number of positions for a full pass
+ const frameMs = Math.max(16, Math.round(ANIMATION_CYCLE_MS / cycle));
+ const id = setInterval(() => {
+ setPhase((p) => (p + 1) % cycle);
+ }, frameMs);
+ return () => clearInterval(id);
+ }, [active, persistentTitle]);
return (
-
-
- {frameWithSeconds}
-
- Thinking
- {dots}
-
-
-
- Press Esc twice to interrupt
-
+
+ {animatedNodes}
{awaitingConfirm && (
diff --git a/codex-cli/src/components/chat/terminal-chat-input.tsx b/codex-cli/src/components/chat/terminal-chat-input.tsx
index 66428f8463..220b414c03 100644
--- a/codex-cli/src/components/chat/terminal-chat-input.tsx
+++ b/codex-cli/src/components/chat/terminal-chat-input.tsx
@@ -60,6 +60,7 @@ export default function TerminalChatInput({
active,
thinkingSeconds,
items = [],
+ onBlinkTrigger,
}: {
isNew: boolean;
loading: boolean;
@@ -85,6 +86,8 @@ export default function TerminalChatInput({
thinkingSeconds: number;
// New: current conversation items so we can include them in bug reports
items?: Array;
+ // Trigger header blinking animation without sending to agent or history
+ onBlinkTrigger?: () => void;
}): React.ReactElement {
// Slash command suggestion index
const [selectedSlashSuggestion, setSelectedSlashSuggestion] =
@@ -471,6 +474,13 @@ export default function TerminalChatInput({
async (value: string) => {
const inputValue = value.trim();
+ // Special: first-turn "blink" → trigger header animation only.
+ if (isNew && inputValue.toLowerCase() === "blink") {
+ setInput("");
+ onBlinkTrigger?.();
+ return;
+ }
+
// If the user only entered a slash, do not send a chat message.
if (inputValue === "/") {
setInput("");
@@ -762,53 +772,52 @@ export default function TerminalChatInput({
return (
- {loading ? (
-
- ) : (
-
- {
- setDraftInput(txt);
- if (historyIndex != null) {
- setHistoryIndex(null);
- }
- setInput(txt);
- }}
- key={editorState.key}
- initialCursorOffset={editorState.initialCursorOffset}
- initialText={input}
- height={6}
- focus={active}
- onSubmit={(txt) => {
- // If final token is an @path, replace with filesystem suggestion if available
- const {
- text: replacedText,
- suggestion,
- wasReplaced,
- } = getFileSystemSuggestion(txt, true);
-
- // If we replaced @path token with a directory, don't submit
- if (wasReplaced && suggestion?.isDirectory) {
- applyFsSuggestion(replacedText);
- // Update suggestions for the new directory
- updateFsSuggestions(replacedText, true);
- return;
- }
-
- onSubmit(replacedText);
- setEditorState((s) => ({ key: s.key + 1 }));
- setInput("");
+
+ {
+ setDraftInput(txt);
+ if (historyIndex != null) {
setHistoryIndex(null);
- setDraftInput("");
- }}
- />
-
- )}
+ }
+ setInput(txt);
+ }}
+ key={editorState.key}
+ initialCursorOffset={editorState.initialCursorOffset}
+ initialText={input}
+ height={6}
+ focus={active}
+ onSubmit={(txt) => {
+ // If the assistant is currently thinking, keep the composed text
+ // but do not submit a new prompt. Users can interrupt (Esc Esc)
+ // and submit afterwards.
+ if (loading) {
+ return;
+ }
+
+ // If final token is an @path, replace with filesystem suggestion if available
+ const {
+ text: replacedText,
+ suggestion,
+ wasReplaced,
+ } = getFileSystemSuggestion(txt, true);
+
+ // If we replaced @path token with a directory, don't submit
+ if (wasReplaced && suggestion?.isDirectory) {
+ applyFsSuggestion(replacedText);
+ // Update suggestions for the new directory
+ updateFsSuggestions(replacedText, true);
+ return;
+ }
+
+ onSubmit(replacedText);
+ setEditorState((s) => ({ key: s.key + 1 }));
+ setInput("");
+ setHistoryIndex(null);
+ setDraftInput("");
+ }}
+ />
+
{/* Slash command autocomplete suggestions */}
{input.trim().startsWith("/") && (
@@ -878,140 +887,3 @@ export default function TerminalChatInput({
);
}
-
-function TerminalChatInputThinking({
- onInterrupt,
- active,
- thinkingSeconds,
-}: {
- onInterrupt: () => void;
- active: boolean;
- thinkingSeconds: number;
-}) {
- const [awaitingConfirm, setAwaitingConfirm] = useState(false);
- const [dots, setDots] = useState("");
-
- // Animate ellipsis
- useInterval(() => {
- setDots((prev) => (prev.length < 3 ? prev + "." : ""));
- }, 500);
-
- // Spinner frames with embedded seconds
- const ballFrames = [
- "( ● )",
- "( ● )",
- "( ● )",
- "( ● )",
- "( ●)",
- "( ● )",
- "( ● )",
- "( ● )",
- "( ● )",
- "(● )",
- ];
- const [frame, setFrame] = useState(0);
-
- useInterval(() => {
- setFrame((idx) => (idx + 1) % ballFrames.length);
- }, 80);
-
- // Keep the elapsed‑seconds text fixed while the ball animation moves.
- const frameTemplate = ballFrames[frame] ?? ballFrames[0];
- const frameWithSeconds = `${frameTemplate} ${thinkingSeconds}s`;
-
- // ---------------------------------------------------------------------
- // Raw stdin listener to catch the case where the terminal delivers two
- // consecutive ESC bytes ("\x1B\x1B") in a *single* chunk. Ink's `useInput`
- // collapses that sequence into one key event, so the regular two‑step
- // handler above never sees the second press. By inspecting the raw data
- // we can identify this special case and trigger the interrupt while still
- // requiring a double press for the normal single‑byte ESC events.
- // ---------------------------------------------------------------------
-
- const { stdin, setRawMode } = useStdin();
-
- React.useEffect(() => {
- if (!active) {
- return;
- }
-
- // Ensure raw mode – already enabled by Ink when the component has focus,
- // but called defensively in case that assumption ever changes.
- setRawMode?.(true);
-
- const onData = (data: Buffer | string) => {
- if (awaitingConfirm) {
- return; // already awaiting a second explicit press
- }
-
- // Handle both Buffer and string forms.
- const str = Buffer.isBuffer(data) ? data.toString("utf8") : data;
- if (str === "\x1b\x1b") {
- // Treat as the first Escape press – prompt the user for confirmation.
- log(
- "raw stdin: received collapsed ESC ESC – starting confirmation timer",
- );
- setAwaitingConfirm(true);
- setTimeout(() => setAwaitingConfirm(false), 1500);
- }
- };
-
- stdin?.on("data", onData);
-
- return () => {
- stdin?.off("data", onData);
- };
- }, [stdin, awaitingConfirm, onInterrupt, active, setRawMode]);
-
- // No local timer: the parent component supplies the elapsed time via props.
-
- // Listen for the escape key to allow the user to interrupt the current
- // operation. We require two presses within a short window (1.5s) to avoid
- // accidental cancellations.
- useInput(
- (_input, key) => {
- if (!key.escape) {
- return;
- }
-
- if (awaitingConfirm) {
- log("useInput: second ESC detected – triggering onInterrupt()");
- onInterrupt();
- setAwaitingConfirm(false);
- } else {
- log("useInput: first ESC detected – waiting for confirmation");
- setAwaitingConfirm(true);
- setTimeout(() => setAwaitingConfirm(false), 1500);
- }
- },
- { isActive: active },
- );
-
- return (
-
-
-
- {frameWithSeconds}
-
- Thinking
- {dots}
-
-
-
- press Esc {" "}
- {awaitingConfirm ? (
- again
- ) : (
- twice
- )}{" "}
- to interrupt
-
-
-
- );
-}
diff --git a/codex-cli/src/components/chat/terminal-chat-response-item.tsx b/codex-cli/src/components/chat/terminal-chat-response-item.tsx
index bab4aa317f..759d3a49d5 100644
--- a/codex-cli/src/components/chat/terminal-chat-response-item.tsx
+++ b/codex-cli/src/components/chat/terminal-chat-response-item.tsx
@@ -13,7 +13,7 @@ import type { FileOpenerScheme } from "src/utils/config";
import { useTerminalSize } from "../../hooks/use-terminal-size";
import { collapseXmlBlocks } from "../../utils/file-tag-utils";
import { parseToolCall, parseToolCallOutput } from "../../utils/parsers";
-import chalk, { type ForegroundColorName } from "chalk";
+import chalk from "chalk";
import { Box, Text } from "ink";
import { parse, setOptions } from "marked";
import TerminalRenderer from "marked-terminal";
@@ -115,11 +115,6 @@ export function TerminalChatResponseReasoning({
);
}
-const colorsByRole: Record = {
- assistant: "magentaBright",
- user: "blueBright",
-};
-
function TerminalChatResponseMessage({
message,
setOverlayMode,
@@ -141,29 +136,43 @@ function TerminalChatResponseMessage({
}
}, [message, setOverlayMode]);
+ const contentBody = (
+
+ {message.content
+ .map(
+ (c) =>
+ c.type === "output_text"
+ ? c.text
+ : c.type === "refusal"
+ ? c.refusal
+ : c.type === "input_text"
+ ? collapseXmlBlocks(c.text)
+ : c.type === "input_image"
+ ? ""
+ : c.type === "input_file"
+ ? c.filename
+ : "", // unknown content type
+ )
+ .join(" ")}
+
+ );
+
+ if (message.role === "user") {
+ return (
+
+
+ {contentBody}
+
+
+ );
+ }
+ // Assistant: no top label – prefix content with a single "> " marker
return (
-
- {message.role === "assistant" ? "codex" : message.role}
-
-
- {message.content
- .map(
- (c) =>
- c.type === "output_text"
- ? c.text
- : c.type === "refusal"
- ? c.refusal
- : c.type === "input_text"
- ? collapseXmlBlocks(c.text)
- : c.type === "input_image"
- ? ""
- : c.type === "input_file"
- ? c.filename
- : "", // unknown content type
- )
- .join(" ")}
-
+
+ {"> "}
+ {contentBody}
+
);
}
@@ -174,17 +183,105 @@ function TerminalChatResponseToolCall({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
message: ResponseFunctionToolCallItem | any;
}) {
+ // Detect non-shell tool calls (e.g., read_file, searched, listed_files) and render
+ // concise, human-readable summaries for them. Fallback to shell/command layout.
let workdir: string | undefined;
let cmdReadableText: string | undefined;
+ let toolName: string | undefined;
+ let toolArgs: Record | undefined;
+
if (message.type === "function_call") {
+ // Prefer shell rendering when parseable as a command
const details = parseToolCall(message);
workdir = details?.workdir;
cmdReadableText = details?.cmdReadableText;
+
+ // Also capture generic function info for non-shell tools
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const fn = (message as any).function;
+ if (fn && typeof fn.name === "string") {
+ toolName = fn.name;
+ try {
+ if (typeof fn.arguments === "string" && fn.arguments.length > 0) {
+ toolArgs = JSON.parse(fn.arguments) as Record;
+ }
+ } catch {
+ toolArgs = undefined;
+ }
+ }
} else if (message.type === "local_shell_call") {
const action = message.action;
workdir = action.working_directory;
cmdReadableText = formatCommandForDisplay(action.command);
}
+
+ const renderNonShellTool = (
+ name: string,
+ args: Record | undefined,
+ ): React.ReactElement => {
+ const lower = name.toLowerCase();
+ const getString = (v: unknown) => (typeof v === "string" ? v : undefined);
+ const pathish =
+ getString(args?.["path"]) ||
+ getString(args?.["file"]) ||
+ getString(args?.["filepath"]) ||
+ getString(args?.["filename"]);
+ const pattern = getString(args?.["pattern"]) || getString(args?.["query"]);
+
+ let summary: string = name;
+ if (lower === "read_file") {
+ summary = pathish ? `read_file ${pathish}` : "read_file";
+ } else if (lower === "searched") {
+ if (pattern && pathish) {
+ summary = `searched "${pattern}" in ${pathish}`;
+ } else if (pattern) {
+ summary = `searched "${pattern}"`;
+ } else if (pathish) {
+ summary = `searched in ${pathish}`;
+ } else {
+ summary = "searched";
+ }
+ } else if (lower === "listed_files") {
+ summary = pathish ? `listed_files ${pathish}` : "listed_files";
+ } else {
+ // Generic fallback: show tool name plus one interesting arg
+ const interestingKeys = [
+ "path",
+ "file",
+ "filepath",
+ "filename",
+ "pattern",
+ ];
+ const kv = interestingKeys
+ .map((k) => {
+ const val = args?.[k as keyof typeof args];
+ return typeof val === "string" && val.length > 0
+ ? `${k}: ${val}`
+ : "";
+ })
+ .find((s) => s);
+ summary = kv ? `${name} ${kv}` : name;
+ }
+ return (
+
+
+ {name}
+
+ {summary}
+
+ );
+ };
+
+ // If this is a non-shell function call we recognize, render the humanized view
+ if (
+ toolName &&
+ (!cmdReadableText ||
+ (toolName !== "container.exec" && toolName !== "shell"))
+ ) {
+ return renderNonShellTool(toolName, toolArgs);
+ }
+
+ // Default: shell command layout
return (
diff --git a/codex-cli/src/components/chat/terminal-chat.tsx b/codex-cli/src/components/chat/terminal-chat.tsx
index d41a94990f..2c06f13508 100644
--- a/codex-cli/src/components/chat/terminal-chat.tsx
+++ b/codex-cli/src/components/chat/terminal-chat.tsx
@@ -7,6 +7,7 @@ import type { ResponseItem } from "openai/resources/responses/responses.mjs";
import TerminalChatInput from "./terminal-chat-input.js";
import TerminalChatPastRollout from "./terminal-chat-past-rollout.js";
+import TerminalChatInputThinking from "./terminal-chat-input-thinking.js";
import { TerminalChatToolCallCommand } from "./terminal-chat-tool-call-command.js";
import TerminalMessageHistory from "./terminal-message-history.js";
import { formatCommandForDisplay } from "../../format-command.js";
@@ -154,6 +155,22 @@ export default function TerminalChat({
initialApprovalPolicy,
);
const [thinkingSeconds, setThinkingSeconds] = useState(0);
+ const [thinkingTitle, setThinkingTitle] = useState("");
+ // Header blinking indicator support (triggered by first user message "blink")
+ const BLINKING = [
+ ">_",
+ ">_",
+ ">_",
+ "-_",
+ ">_",
+ "-_",
+ ">_",
+ ">_",
+ ">_",
+ ">_",
+ ] as const;
+ const [blinkingActive, setBlinkingActive] = useState(false);
+ const [blinkFrame, setBlinkFrame] = useState(0);
const handleCompact = async () => {
setLoading(true);
@@ -254,13 +271,41 @@ export default function TerminalChat({
onLastResponseId: setLastResponseId,
onItem: (item) => {
log(`onItem: ${JSON.stringify(item)}`);
+ // Intercept reasoning summaries: update thinking title instead of rendering in history
+ if ((item as any).type === "reasoning") {
+ // Prefer latest summary headline/text
+ const summaries = (item as any).summary as
+ | Array<{ headline?: string; text?: string }>
+ | undefined;
+ const last =
+ summaries && summaries.length > 0
+ ? summaries[summaries.length - 1]
+ : undefined;
+ const rawTitle =
+ (last?.headline || last?.text || "Thinking").split("\n")[0] ??
+ "Thinking";
+ const cleaned = rawTitle
+ .replace(/\*\*/g, "")
+ .replace(/\s*\.\.\.$/, "")
+ .trim();
+ setThinkingTitle(cleaned);
+ return;
+ }
setItems((prev) => {
const updated = uniqueById([...prev, item as ResponseItem]);
saveRollout(sessionId, updated);
return updated;
});
},
- onLoading: setLoading,
+ onLoading: (v: boolean) => {
+ setLoading(v);
+ if (v) {
+ setThinkingTitle("Thinking");
+ setThinkingSeconds(0);
+ } else {
+ setThinkingTitle("");
+ }
+ },
getCommandConfirmation: async (
command: Array,
applyPatch: ApplyPatchCommand | undefined,
@@ -455,6 +500,29 @@ export default function TerminalChat({
(i) => i.type === "message" && i.role === "user",
).length;
+ // Provide a trigger function for the header blinking animation
+ const triggerBlink = React.useCallback(() => {
+ setBlinkingActive(true);
+ setBlinkFrame(0);
+ }, []);
+
+ // Advance blinking animation frames
+ useEffect(() => {
+ if (!blinkingActive) return;
+ const id = setInterval(() => {
+ setBlinkFrame((f) => {
+ const next = f + 1;
+ if (next >= BLINKING.length) {
+ // stop after one pass
+ setBlinkingActive(false);
+ return BLINKING.length - 1;
+ }
+ return next;
+ });
+ }, 200);
+ return () => clearInterval(id);
+ }, [blinkingActive]);
+
const contextLeftPercent = useMemo(
() => calculateContextPercentRemaining(items, model),
[items, model],
@@ -495,6 +563,7 @@ export default function TerminalChat({
agent,
initialImagePaths,
flexModeEnabled: Boolean(config.flexMode),
+ blinkingIndicator: blinkingActive ? BLINKING[blinkFrame] : ">_",
}}
fileOpener={config.fileOpener}
/>
@@ -504,83 +573,127 @@ export default function TerminalChat({
)}
{overlayMode === "none" && agent && (
-
- submitConfirmation({
- decision,
- customDenyMessage,
- })
- }
- contextLeftPercent={contextLeftPercent}
- openOverlay={() => setOverlayMode("history")}
- openModelOverlay={() => setOverlayMode("model")}
- openApprovalOverlay={() => setOverlayMode("approval")}
- openHelpOverlay={() => setOverlayMode("help")}
- openSessionsOverlay={() => setOverlayMode("sessions")}
- openDiffOverlay={() => {
- const { isGitRepo, diff } = getGitDiff();
- let text: string;
- if (isGitRepo) {
- text = diff;
- } else {
- text = "`/diff` — _not inside a git repository_";
- }
- setItems((prev) => [
- ...prev,
- {
- id: `diff-${Date.now()}`,
- type: "message",
- role: "system",
- content: [{ type: "input_text", text }],
- },
- ]);
- // Ensure no overlay is shown.
- setOverlayMode("none");
- }}
- onCompact={handleCompact}
- active={overlayMode === "none"}
- interruptAgent={() => {
- if (!agent) {
- return;
+ <>
+ {loading && (
+ <>
+ {/* Spacer line between message history and loading indicator */}
+
+
+
+
+ {
+ if (!agent) {
+ return;
+ }
+ log(
+ "TerminalChat: interruptAgent invoked – calling agent.cancel()",
+ );
+ agent.cancel();
+ setLoading(false);
+
+ // Add a system message to indicate the interruption
+ setItems((prev) => [
+ ...prev,
+ {
+ id: `interrupt-${Date.now()}`,
+ type: "message",
+ role: "system",
+ content: [
+ {
+ type: "input_text",
+ text: "⏹️ Execution interrupted by user. You can continue typing.",
+ },
+ ],
+ },
+ ]);
+ }}
+ active={overlayMode === "none"}
+ thinkingSeconds={thinkingSeconds}
+ title={thinkingTitle}
+ />
+
+ >
+ )}
+
+ submitConfirmation({
+ decision,
+ customDenyMessage,
+ })
}
- log(
- "TerminalChat: interruptAgent invoked – calling agent.cancel()",
- );
- agent.cancel();
- setLoading(false);
-
- // Add a system message to indicate the interruption
- setItems((prev) => [
- ...prev,
- {
- id: `interrupt-${Date.now()}`,
- type: "message",
- role: "system",
- content: [
- {
- type: "input_text",
- text: "⏹️ Execution interrupted by user. You can continue typing.",
- },
- ],
- },
- ]);
- }}
- submitInput={(inputs) => {
- agent.run(inputs, lastResponseId || "");
- return {};
- }}
- items={items}
- thinkingSeconds={thinkingSeconds}
- />
+ contextLeftPercent={contextLeftPercent}
+ openOverlay={() => setOverlayMode("history")}
+ openModelOverlay={() => setOverlayMode("model")}
+ openApprovalOverlay={() => setOverlayMode("approval")}
+ openHelpOverlay={() => setOverlayMode("help")}
+ openSessionsOverlay={() => setOverlayMode("sessions")}
+ openDiffOverlay={() => {
+ const { isGitRepo, diff } = getGitDiff();
+ let text: string;
+ if (isGitRepo) {
+ text = diff;
+ } else {
+ text = "`/diff` — _not inside a git repository_";
+ }
+ setItems((prev) => [
+ ...prev,
+ {
+ id: `diff-${Date.now()}`,
+ type: "message",
+ role: "system",
+ content: [{ type: "input_text", text }],
+ },
+ ]);
+ // Ensure no overlay is shown.
+ setOverlayMode("none");
+ }}
+ onCompact={handleCompact}
+ active={overlayMode === "none"}
+ interruptAgent={() => {
+ if (!agent) {
+ return;
+ }
+ log(
+ "TerminalChat: interruptAgent invoked – calling agent.cancel()",
+ );
+ agent.cancel();
+ setLoading(false);
+
+ // Add a system message to indicate the interruption
+ setItems((prev) => [
+ ...prev,
+ {
+ id: `interrupt-${Date.now()}`,
+ type: "message",
+ role: "system",
+ content: [
+ {
+ type: "input_text",
+ text: "⏹️ Execution interrupted by user. You can continue typing.",
+ },
+ ],
+ },
+ ]);
+ }}
+ submitInput={(inputs) => {
+ agent.run(inputs, lastResponseId || "");
+ return {};
+ }}
+ items={items}
+ thinkingSeconds={thinkingSeconds}
+ onBlinkTrigger={triggerBlink}
+ />
+ >
)}
{overlayMode === "history" && (
setOverlayMode("none")} />
diff --git a/codex-cli/src/components/chat/terminal-header.tsx b/codex-cli/src/components/chat/terminal-header.tsx
index 9ba16e6fde..c7eb9a2f42 100644
--- a/codex-cli/src/components/chat/terminal-header.tsx
+++ b/codex-cli/src/components/chat/terminal-header.tsx
@@ -1,6 +1,7 @@
import type { AgentLoop } from "../../utils/agent/agent-loop.js";
import { Box, Text } from "ink";
+// import { Onboarding } from "../animations/onboarding.s";
import path from "node:path";
import React from "react";
@@ -15,11 +16,14 @@ export interface TerminalHeaderProps {
agent?: AgentLoop;
initialImagePaths?: Array;
flexModeEnabled?: boolean;
+ /** Optional dynamic cursor/indicator to show before the title (e.g. blinking >_) */
+ blinkingIndicator?: string;
}
const TerminalHeader: React.FC = ({
terminalRows,
- version,
+ // keeping version for potential future use; prefix to silence unused warnings
+ version: _version,
PWD,
model,
provider = "openai",
@@ -28,68 +32,108 @@ const TerminalHeader: React.FC = ({
agent,
initialImagePaths,
flexModeEnabled = false,
+ blinkingIndicator,
}) => {
+ {
+ /*
+ const widenedOnboarding = React.useMemo(() => {
+ try {
+ return Onboarding.split("\n")
+ .map((line) => line.split("").join(" "))
+ .join("\n");
+ } catch {
+ return Onboarding;
+ }
+ }, []);
+ */
+ }
return (
<>
{terminalRows < 10 ? (
- // Compact header for small terminal windows
- ● Codex v{version} - {PWD} - {model} ({provider}) -{" "}
- {approvalPolicy}
- {flexModeEnabled ? " - flex-mode" : ""}
+ You are using OpenAI Codex in {PWD}
) : (
<>
+ {(blinkingIndicator ?? ">_") + " "}
- ● OpenAI Codex {" "}
-
- (research preview) v{version}
-
+ You are using OpenAI Codex in{" "}
+ {PWD}
+ {/*
+
+ {widenedOnboarding}
+
+ */}
-
- localhost session: {" "}
-
- {agent?.sessionId ?? ""}
-
-
- ↳ workdir: {PWD}
+ Describe a task to get started or try one of the following
+ commands:
-
- ↳ model: {model}
+
+
+ /init - create an AGENTS.md file
+ with instructions for Codex
-
- ↳ provider:{" "}
- {provider}
+
+ /status - show current session
+ configuration and token usage
-
- ↳ approval:{" "}
-
- {approvalPolicy}
+
+ {false && (
+
+
+ localhost session: {" "}
+
+ {agent?.sessionId ?? ""}
+
-
- {flexModeEnabled && (
- ↳ flex-mode:{" "}
- enabled
+ ↳ workdir:{" "}
+ {PWD}
- )}
- {initialImagePaths?.map((img, idx) => (
-
- ↳ image:{" "}
- {path.basename(img)}
+
+ ↳ model:{" "}
+ {model}
- ))}
-
+
+ ↳ provider:{" "}
+ {provider}
+
+
+ ↳ approval:{" "}
+
+ {approvalPolicy}
+
+
+ {flexModeEnabled && (
+
+ ↳ flex-mode:{" "}
+ enabled
+
+ )}
+ {initialImagePaths?.map((img, idx) => (
+
+ ↳ image:{" "}
+ {path.basename(img)}
+
+ ))}
+
+ )}
>
)}
>
diff --git a/codex-cli/src/components/chat/terminal-message-history.tsx b/codex-cli/src/components/chat/terminal-message-history.tsx
index 5036f0813d..b24962a418 100644
--- a/codex-cli/src/components/chat/terminal-message-history.tsx
+++ b/codex-cli/src/components/chat/terminal-message-history.tsx
@@ -1,12 +1,24 @@
import type { OverlayModeType } from "./terminal-chat.js";
import type { TerminalHeaderProps } from "./terminal-header.js";
import type { GroupedResponseItem } from "./use-message-grouping.js";
-import type { ResponseItem } from "openai/resources/responses/responses.mjs";
+import type {
+ ResponseItem,
+ ResponseFunctionToolCall,
+} from "openai/resources/responses/responses.mjs";
import type { FileOpenerScheme } from "src/utils/config.js";
import TerminalChatResponseItem from "./terminal-chat-response-item.js";
import TerminalHeader from "./terminal-header.js";
-import { Box, Static } from "ink";
+import { formatCommandForDisplay } from "../../format-command.js";
+import {
+ classifyRunningTitle,
+ classifySuccessTitle,
+ classifyFailureTitle,
+ extractBeforeFirstUnquotedPipe,
+} from "./tools/classify.js";
+import { CommandStatus } from "./tools/command-status.js";
+import { parseToolCall, parseToolCallOutput } from "../../utils/parsers.js";
+import { Box, Text } from "ink";
import React, { useMemo } from "react";
// A batch entry can either be a standalone response item or a grouped set of
@@ -37,44 +49,240 @@ const TerminalMessageHistory: React.FC = ({
setOverlayMode,
fileOpener,
}) => {
- // Flatten batch entries to response items.
- const messages = useMemo(() => batch.map(({ item }) => item!), [batch]);
+ // Build a dynamic view that collapses command tool-calls with their outputs
+ // into a single renderable entry that transitions from "⏳ Running" to
+ // "⚡ Ran" (and other states) by swapping the rendered item.
+ const sourceItems: Array = useMemo(
+ () => batch.map(({ item }) => item!).filter(Boolean) as Array,
+ [batch],
+ );
- return (
-
- {/* The dedicated thinking indicator in the input area now displays the
- elapsed time, so we no longer render a separate counter here. */}
-
- {(item, index) => {
- if (item === "header") {
- return ;
- }
+ type CommandState = "running" | "success" | "failure" | "aborted";
+ type DisplayItem =
+ | { kind: "response"; item: ResponseItem }
+ | {
+ kind: "command";
+ key: string;
+ commandText: string;
+ workdir?: string;
+ state: CommandState;
+ outputText?: string;
+ exitCode?: number;
+ customSuccessTitle?: string;
+ customRunningTitle?: string;
+ };
+
+ const displayItems: Array = useMemo(() => {
+ const outputsByCallId = new Map<
+ string,
+ { output: string; exit?: number }
+ >();
+ const consumedOutputs = new Set();
+
+ for (const it of sourceItems) {
+ // Include Outputs from function calls (local shell output uses SDK‑unknown type)
+ if (
+ (it as { type?: string }).type === "function_call_output" ||
+ (it as { type?: string }).type ===
+ ("local_shell_call_output" as unknown as string)
+ ) {
+ const callId = (it as unknown as { call_id?: string }).call_id;
+ if (!callId) {
+ continue;
+ }
+ const outputRaw = (it as { output?: string }).output ?? "{}";
+ const { output, metadata } = parseToolCallOutput(outputRaw);
+ outputsByCallId.set(callId, {
+ output,
+ exit:
+ typeof metadata?.exit_code === "number"
+ ? metadata.exit_code
+ : undefined,
+ });
+ }
+ }
+
+ const result: Array = [];
+ for (const it of sourceItems) {
+ // Collapse tool calls with their outputs (local shell call uses SDK‑unknown type)
+ if (
+ (it as { type?: string }).type === "function_call" ||
+ (it as { type?: string }).type ===
+ ("local_shell_call" as unknown as string)
+ ) {
+ // Compute stable call id
+ const anyIt = it as unknown as {
+ call_id?: string;
+ id?: string;
+ action?: { command?: Array; working_directory?: string };
+ };
+ const callId: string | undefined = anyIt.call_id ?? anyIt.id;
+
+ let commandText = "";
+ let workdir: string | undefined = undefined;
+ if (it.type === "function_call") {
+ const details = parseToolCall(
+ it as unknown as ResponseFunctionToolCall,
+ );
+ commandText = details?.cmdReadableText ?? commandText;
+ workdir = details?.workdir;
+ } else {
+ // local_shell_call
+ const cmdArr: Array = Array.isArray(anyIt.action?.command)
+ ? (anyIt.action?.command as Array)
+ : [];
+ commandText = formatCommandForDisplay(cmdArr);
+ workdir = anyIt.action?.working_directory;
+ }
- // After the guard above, item is a ResponseItem
- const message = item as ResponseItem;
- // Suppress empty reasoning updates (i.e. items with an empty summary).
- const msg = message as unknown as { summary?: Array };
- if (msg.summary?.length === 0) {
- return null;
+ const out = callId ? outputsByCallId.get(callId) : undefined;
+ if (callId && out) {
+ consumedOutputs.add(callId);
+ }
+
+ const exit = out?.exit;
+ const isAborted = out?.output === "aborted";
+ const state: CommandState = isAborted
+ ? "aborted"
+ : typeof exit === "number" && exit !== 0
+ ? "failure"
+ : out
+ ? "success"
+ : "running";
+
+ // Optional human-readable titles for running/success
+ const customSuccessTitle = classifySuccessTitle(
+ commandText,
+ out?.output,
+ );
+ const customRunningTitle = classifyRunningTitle(commandText);
+
+ result.push({
+ kind: "command",
+ key: callId ?? `${it.id}`,
+ commandText,
+ workdir,
+ state,
+ outputText: out?.output,
+ exitCode: exit,
+ customSuccessTitle,
+ customRunningTitle,
+ });
+ continue;
+ }
+
+ // Skip standalone outputs that have already been merged into their calls
+ if (
+ (it as { type?: string }).type === "function_call_output" ||
+ (it as { type?: string }).type ===
+ ("local_shell_call_output" as unknown as string)
+ ) {
+ const callId = (it as unknown as { call_id?: string }).call_id;
+ if (callId && consumedOutputs.has(callId)) {
+ continue;
+ }
+ }
+
+ // Suppress all reasoning items from history – thinking indicator shows summaries.
+ if ((it as { type?: string }).type === "reasoning") {
+ continue;
+ }
+
+ // Default: render original item
+ result.push({ kind: "response", item: it });
+ }
+ return result;
+ }, [sourceItems]);
+
+ // Group consecutive successful "📖 Read " items
+ type ReadGroupItem = {
+ kind: "read_group";
+ key: string;
+ files: Array;
+ };
+ type ListGroupItem = { kind: "list_group"; key: string; total: number };
+ const renderItems: Array =
+ useMemo(() => {
+ const items: Array = [];
+ for (let i = 0; i < displayItems.length; i += 1) {
+ const d = displayItems[i]!;
+ if (
+ d.kind === "command" &&
+ d.state === "success" &&
+ typeof d.customSuccessTitle === "string" &&
+ /^(?:●|📖)\s+Read\s+/.test(d.customSuccessTitle)
+ ) {
+ const files: Array = [];
+ const seen = new Set();
+ let j = i;
+ while (
+ j < displayItems.length &&
+ displayItems[j]!.kind === "command" &&
+ (displayItems[j] as typeof d).state === "success" &&
+ typeof (displayItems[j] as typeof d).customSuccessTitle ===
+ "string" &&
+ /^(?:●|📖)\s+Read\s+/.test(
+ (displayItems[j] as typeof d).customSuccessTitle as string,
+ )
+ ) {
+ const title = (displayItems[j] as typeof d).customSuccessTitle!;
+ const fname = title.replace(/^(?:●|📖)\s+Read\s+/, "");
+ if (!seen.has(fname)) {
+ files.push(fname);
+ seen.add(fname);
+ }
+ j += 1;
}
+ items.push({ kind: "read_group", key: d.key, files });
+ i = j - 1;
+ } else if (
+ d.kind === "command" &&
+ d.state === "success" &&
+ typeof d.customSuccessTitle === "string" &&
+ /^📁 Listed\s+\d+\s+paths/.test(d.customSuccessTitle)
+ ) {
+ // Sum consecutive Listed counts into a single running total
+ let total = 0;
+ let j = i;
+ while (
+ j < displayItems.length &&
+ displayItems[j]!.kind === "command" &&
+ (displayItems[j] as typeof d).state === "success" &&
+ typeof (displayItems[j] as typeof d).customSuccessTitle ===
+ "string" &&
+ /^📁 Listed\s+\d+\s+paths/.test(
+ (displayItems[j] as typeof d).customSuccessTitle as string,
+ )
+ ) {
+ const title = (displayItems[j] as typeof d)
+ .customSuccessTitle as string;
+ const m = title.match(/📁 Listed\s+(\d+)\s+paths/);
+ const n = m ? Number(m[1]) : 0;
+ total += n;
+ j += 1;
+ }
+ items.push({ kind: "list_group", key: d.key, total });
+ i = j - 1;
+ } else {
+ items.push(d);
+ }
+ }
+ return items;
+ }, [displayItems]);
+
+ return (
+
+
+ {renderItems.map((d, index) => {
+ if (d.kind === "response") {
+ const message = d.item;
return (
= ({
/>
);
- }}
-
+ }
+
+ const prev = renderItems[index - 1];
+ const prevIsUserMessage =
+ prev &&
+ (prev as any).kind === "response" &&
+ (prev as any).item?.type === "message" &&
+ (prev as any).item?.role === "user";
+ if (d.kind === "list_group") {
+ return (
+
+
+
+ );
+ }
+
+ // Render grouped reads
+ if (d.kind === "read_group") {
+ const n = d.files.length;
+ const header = `● Read ${n} ${n === 1 ? "file" : "files"}`;
+ return (
+
+
+ {d.files.map((f, idx) => (
+
+ {idx === 0 ? "⎿ " : " "}
+ {f}
+
+ ))}
+
+ );
+ }
+
+ // Render combined command item with state swapping.
+ let title: string;
+ if (d.state === "running") {
+ title = d.customRunningTitle ?? `● Running ${d.commandText}`;
+ } else if (d.state === "success") {
+ title = d.customSuccessTitle ?? `● Ran ${d.commandText}`;
+ } else if (d.state === "failure") {
+ const custom = classifyFailureTitle(d.commandText, d.outputText);
+ if (custom) {
+ title = custom;
+ } else {
+ const beforePipe = extractBeforeFirstUnquotedPipe(d.commandText);
+ const firstWord = beforePipe.trim().split(/\s+/)[0] || beforePipe;
+ title = `⨯ Failed ${firstWord}`;
+ }
+ } else {
+ title = `● Aborted ${d.commandText}`;
+ }
+ const outputForDisplay =
+ d.state !== "running" ? d.outputText : undefined;
+ return (
+
+ );
+ })}
);
};
export default React.memo(TerminalMessageHistory);
+// (helpers moved to ./tools/*)
diff --git a/codex-cli/src/components/chat/tools/classify.ts b/codex-cli/src/components/chat/tools/classify.ts
new file mode 100644
index 0000000000..241fbbaf83
--- /dev/null
+++ b/codex-cli/src/components/chat/tools/classify.ts
@@ -0,0 +1,334 @@
+// Utilities for classifying shell commands into human-readable titles
+
+/** Return the portion of the string before the first unquoted pipe character. */
+export function extractBeforeFirstUnquotedPipe(input: string): string {
+ let inSingle = false;
+ let inDouble = false;
+ for (let i = 0; i < input.length; i += 1) {
+ const ch = input[i];
+ if (ch === "'" && !inDouble) {
+ inSingle = !inSingle;
+ } else if (ch === '"' && !inSingle) {
+ inDouble = !inDouble;
+ } else if (ch === "|" && !inSingle && !inDouble) {
+ return input.slice(0, i).trim();
+ }
+ }
+ return input;
+}
+
+/** Count non-empty lines in a string. */
+function countLines(s?: string): number {
+ return (s ? s.split("\n").filter((l) => l.trim().length > 0) : []).length;
+}
+
+/** Build a human-readable success title for known commands. */
+export function classifySuccessTitle(
+ commandText: string,
+ outputText?: string,
+): string | undefined {
+ const cmd = commandText.trim();
+ const beforePipe = extractBeforeFirstUnquotedPipe(cmd);
+ const lower = beforePipe.toLowerCase();
+
+ // Tests (vitest / npm test / pnpm test)
+ if (/(vitest|\b(pnpm|npm|yarn)\s+(run\s+)?test\b)/.test(lower)) {
+ return "● Tests";
+ }
+
+ // 1) ripgrep listings: rg --files
+ if (/\brg\b/.test(lower) && /--files(\b|=)/.test(lower)) {
+ const n = countLines(outputText);
+ return `● Listed ${n} ${n === 1 ? "path" : "paths"}`;
+ }
+
+ // 2) ripgrep search: rg [opts] PATTERN [PATH]
+ if (/\brg\b/.test(lower) && !/--files(\b|=)/.test(lower)) {
+ const patternMatch = beforePipe.match(/rg\s+[^"']*(["'])(.*?)\1/);
+ const pattern = patternMatch ? patternMatch[2] : undefined;
+ const tokens = beforePipe.replace(/\s+/g, " ").trim().split(" ");
+ let path: string | undefined;
+ for (let i = tokens.length - 1; i >= 0; i -= 1) {
+ const t = tokens[i] ?? "";
+ if (t === "rg") {
+ break;
+ }
+ if (t.startsWith("-")) {
+ continue;
+ }
+ if (pattern && (t === `"${pattern}"` || t === `'${pattern}'`)) {
+ continue;
+ }
+ path = t;
+ break;
+ }
+ if (pattern && path) {
+ return `● Searched for "${pattern}" in "${path}"`;
+ }
+ if (pattern) {
+ return `● Searched for "${pattern}"`;
+ }
+ }
+
+ // 2a) grep search: grep [opts] PATTERN [PATH]
+ if (/\bgrep\b/.test(lower)) {
+ const patternMatch = beforePipe.match(/grep\s+[^"']*(["'])(.*?)\1/);
+ const pattern = patternMatch ? patternMatch[2] : undefined;
+ const tokens = beforePipe.replace(/\s+/g, " ").trim().split(" ");
+ let path: string | undefined;
+ for (let i = tokens.length - 1; i >= 0; i -= 1) {
+ const t = tokens[i] ?? "";
+ if (t === "grep") {
+ break;
+ }
+ if (t.startsWith("-")) {
+ continue;
+ }
+ if (pattern && (t === `"${pattern}"` || t === `'${pattern}'`)) {
+ continue;
+ }
+ path = t;
+ break;
+ }
+ if (pattern && path) {
+ return `● Searched for "${pattern}" in "${path}"`;
+ }
+ if (pattern) {
+ return `● Searched for "${pattern}"`;
+ }
+ }
+
+ // 3) sed -n '1,200p' FILE => treat as reading FILE
+ if (/\bsed\b/.test(lower) && /-n\b/.test(lower) && /p['"]?\b/.test(lower)) {
+ const tokens = beforePipe.replace(/\s+/g, " ").trim().split(" ");
+ const last = tokens[tokens.length - 1];
+ if (last && !last.startsWith("-") && !/['"]\d+,\d+p['"]/.test(last)) {
+ return `● Read ${last}`;
+ }
+ }
+
+ // 4) cat FILE => Read FILE
+ if (/^cat\s+/.test(lower)) {
+ const m = beforePipe.match(/^cat\s+([^\s|&;]+)/);
+ if (m && m[1]) {
+ return `● Read ${m[1]}`;
+ }
+ }
+
+ // 4a) head/tail FILE => Read FILE
+ if (/^(head|tail)\b/.test(lower)) {
+ const tokens = beforePipe.replace(/\s+/g, " ").trim().split(" ");
+ for (let i = tokens.length - 1; i >= 1; i -= 1) {
+ const t = tokens[i] ?? "";
+ if (!t.startsWith("-")) {
+ return `● Read ${t}`;
+ }
+ }
+ }
+
+ // 4b) nl FILE => Read FILE (common when piping through sed for ranges)
+ if (/^nl\b/.test(lower)) {
+ const m = beforePipe.match(/^nl\s+(?:-[^-\s][^\s]*\s+)*([^\s|&;]+)/);
+ if (m && m[1] && !m[1].startsWith("-")) {
+ return `● Read ${m[1]}`;
+ }
+ }
+
+ // 5) ls/find directory listings – fallback to listed paths using output count
+ if (/^(ls|find)\b/.test(lower)) {
+ const n = countLines(outputText);
+ if (n > 0) {
+ return `● Listed ${n} ${n === 1 ? "path" : "paths"}`;
+ }
+ }
+
+ // 6) Console prints: echo / node -e console.log(...)
+ if (/^echo\s+/.test(lower)) {
+ return "● Printed output";
+ }
+ if (/\bnode\b\s+-e\b/.test(lower) && /console\.log\s*\(/i.test(cmd)) {
+ return "● Printed output";
+ }
+
+ // 6) Generic counters via wc -l pipeline with numeric output
+ if (/\|\s*wc\s+-l\b/.test(cmd) && /^\s*\d+\s*$/.test(outputText ?? "")) {
+ const n = Number((outputText ?? "0").trim());
+ // Count kinds by upstream command
+ if (/\brg\b/.test(lower) && /--files(\b|=)/.test(lower)) {
+ return `● Counted ${n} ${n === 1 ? "path" : "paths"}`;
+ }
+ if (/\bfind\b/.test(lower) || /\bls\b/.test(lower)) {
+ return `● Counted ${n} ${n === 1 ? "entry" : "entries"}`;
+ }
+ const pat = beforePipe.match(/rg\s+[^"']*(["'])(.*?)\1/);
+ if (/\brg\b/.test(lower) && pat) {
+ return `● Found ${n} ${n === 1 ? "match" : "matches"}`;
+ }
+ return `● Counted ${n} ${n === 1 ? "line" : "lines"}`;
+ }
+
+ return undefined;
+}
+
+/** Build a human-readable running title for known commands. */
+export function classifyRunningTitle(commandText: string): string | undefined {
+ const cmd = commandText.trim();
+ const beforePipe = extractBeforeFirstUnquotedPipe(cmd);
+ const lower = beforePipe.toLowerCase();
+
+ // Tests (vitest / npm test / pnpm test)
+ if (/(vitest|\b(pnpm|npm|yarn)\s+(run\s+)?test\b)/.test(lower)) {
+ return "⏳ Running tests";
+ }
+
+ // rg --files => Listing files
+ if (/\brg\b/.test(lower) && /--files(\b|=)/.test(lower)) {
+ return `⏳ Listing files`;
+ }
+
+ // rg pattern path => Searching
+ if (/\brg\b/.test(lower) && !/--files(\b|=)/.test(lower)) {
+ const patternMatch = beforePipe.match(/rg\s+[^"']*(["'])(.*?)\1/);
+ const pattern = patternMatch ? patternMatch[2] : undefined;
+ const tokens = beforePipe.replace(/\s+/g, " ").trim().split(" ");
+ let path: string | undefined;
+ for (let i = tokens.length - 1; i >= 0; i -= 1) {
+ const t = tokens[i] ?? "";
+ if (t === "rg") {
+ break;
+ }
+ if (t.startsWith("-")) {
+ continue;
+ }
+ if (pattern && (t === `"${pattern}"` || t === `'${pattern}'`)) {
+ continue;
+ }
+ path = t;
+ break;
+ }
+ if (pattern && path) {
+ return `⏳ Searching for "${pattern}" in "${path}"`;
+ }
+ if (pattern) {
+ return `⏳ Searching for "${pattern}"`;
+ }
+ return `⏳ Searching ${commandText}`;
+ }
+
+ // grep pattern => Searching
+ if (/\bgrep\b/.test(lower)) {
+ const patternMatch = beforePipe.match(/grep\s+[^"']*(["'])(.*?)\1/);
+ const pattern = patternMatch ? patternMatch[2] : undefined;
+ const tokens = beforePipe.replace(/\s+/g, " ").trim().split(" ");
+ let path: string | undefined;
+ for (let i = tokens.length - 1; i >= 0; i -= 1) {
+ const t = tokens[i] ?? "";
+ if (t === "grep") {
+ break;
+ }
+ if (t.startsWith("-")) {
+ continue;
+ }
+ if (pattern && (t === `"${pattern}"` || t === `'${pattern}'`)) {
+ continue;
+ }
+ path = t;
+ break;
+ }
+ if (pattern && path) {
+ return `⏳ Searching for "${pattern}" in "${path}"`;
+ }
+ if (pattern) {
+ return `⏳ Searching for "${pattern}"`;
+ }
+ return `⏳ Searching ${commandText}`;
+ }
+
+ // sed/cat => Reading
+ if (
+ (/\bsed\b/.test(lower) && /-n\b/.test(lower) && /p['"]?\b/.test(lower)) ||
+ /^cat\s+/.test(lower)
+ ) {
+ // Prefer extracting the concrete filename so we only show the file being read
+ if (/\bsed\b/.test(lower)) {
+ const tokens = beforePipe.replace(/\s+/g, " ").trim().split(" ");
+ const last = tokens[tokens.length - 1];
+ if (last && !last.startsWith("-") && !/['"]\d+,\d+p['"]/.test(last)) {
+ return `⏳ Reading ${last}`;
+ }
+ return `⏳ Reading`;
+ }
+ if (/^cat\s+/.test(lower)) {
+ const m = beforePipe.match(/^cat\s+([^\s|&;]+)/);
+ if (m && m[1]) {
+ return `⏳ Reading ${m[1]}`;
+ }
+ return `⏳ Reading`;
+ }
+ }
+
+ // head/tail/nl => Reading
+ if (/^(head|tail)\b/.test(lower)) {
+ const tokens = beforePipe.replace(/\s+/g, " ").trim().split(" ");
+ for (let i = tokens.length - 1; i >= 1; i -= 1) {
+ const t = tokens[i] ?? "";
+ if (!t.startsWith("-")) {
+ return `⏳ Reading ${t}`;
+ }
+ }
+ return `⏳ Reading`;
+ }
+ if (/^nl\b/.test(lower)) {
+ const m = beforePipe.match(/^nl\s+(?:-[^-\s][^\s]*\s+)*([^\s|&;]+)/);
+ if (m && m[1] && !m[1].startsWith("-")) {
+ return `⏳ Reading ${m[1]}`;
+ }
+ return `⏳ Reading`;
+ }
+
+ // ls/find => Listing files
+ if (/^(ls|find)\b/.test(lower)) {
+ return `⏳ Listing files`;
+ }
+
+ return undefined;
+}
+
+/** Build a human-readable failure title for known error modes. */
+export function classifyFailureTitle(
+ commandText: string,
+ outputText?: string,
+): string | undefined {
+ const cmd = commandText.trim();
+ const beforePipe = extractBeforeFirstUnquotedPipe(cmd);
+ const lower = beforePipe.toLowerCase();
+ const out = (outputText ?? "").toLowerCase();
+
+ // sed: file not found
+ if (/\bsed\b/.test(lower) && /no such file or directory/i.test(out)) {
+ const tokens = beforePipe.replace(/\s+/g, " ").trim().split(" ");
+ const last = tokens[tokens.length - 1];
+ if (last && !last.startsWith("-")) {
+ return `📄 File not found ${last}`;
+ }
+ return "📄 File not found";
+ }
+
+ // Tests failed
+ if (/(vitest|\b(pnpm|npm|yarn)\s+(run\s+)?test\b)/.test(lower)) {
+ return "⨯ Tests failed";
+ }
+
+ // Command not found
+ if (/command not found/i.test(out)) {
+ const first = beforePipe.split(/\s+/)[0] ?? "command";
+ return `⨯ Command not found ${first}`;
+ }
+
+ // Permission denied
+ if (/permission denied/i.test(out)) {
+ return "⨯ Permission denied";
+ }
+
+ return undefined;
+}
diff --git a/codex-cli/src/components/chat/tools/command-status.tsx b/codex-cli/src/components/chat/tools/command-status.tsx
new file mode 100644
index 0000000000..41ddb3e4e8
--- /dev/null
+++ b/codex-cli/src/components/chat/tools/command-status.tsx
@@ -0,0 +1,189 @@
+import { ANIMATION_CYCLE_MS } from "../animation-config";
+import { Box, Text } from "ink";
+import React, { type ReactElement, useEffect, useState } from "react";
+
+export function CommandStatus({
+ title,
+ workdir,
+ outputText,
+ fullStdout,
+ marginTop,
+}: {
+ title: string;
+ workdir?: string;
+ outputText?: string;
+ fullStdout?: boolean;
+ marginTop?: number;
+}): ReactElement {
+ const { label, tail, color, suppressOutput } = splitLabelTailAndColor(title);
+
+ // Animated cursor for running states – replaces the static hourglass.
+ const CURSOR_FRAMES = ["·", "•", "●", "•"] as const;
+ const isRunningLabel =
+ /^(?:⏳|●)\s+(Running|Searching|Listing|Reading)\b/u.test(label);
+ const [frameIdx, setFrameIdx] = useState(0);
+ useEffect(() => {
+ if (!isRunningLabel) {
+ return;
+ }
+ const frameMs = Math.max(
+ 16,
+ Math.round(ANIMATION_CYCLE_MS / CURSOR_FRAMES.length),
+ );
+ const id = setInterval(
+ () => setFrameIdx((i) => (i + 1) % CURSOR_FRAMES.length),
+ frameMs,
+ );
+ return () => clearInterval(id);
+ }, [isRunningLabel]);
+ const animatedCursor = CURSOR_FRAMES[frameIdx];
+ const labelSansIcon = isRunningLabel
+ ? label.replace(/^(?:⏳|●)\s+/, "")
+ : label;
+
+ const startsWithFailureX = /^⨯\s+/u.test(label);
+ return (
+
+
+ {isRunningLabel ? (
+
+ {animatedCursor} {labelSansIcon}
+
+ ) : startsWithFailureX ? (
+ <>
+
+ ⨯
+
+
+
+ {label.replace(/^⨯\s+/u, "")}
+
+ >
+ ) : (
+
+ {label}
+
+ )}
+ {/* Tail with special formatting for "[Ctrl J to inspect]" */}
+ {(() => {
+ if (!tail) {
+ return {tail} ;
+ }
+ const HINT = "[Ctrl J to inspect]";
+ const idx = tail.indexOf(HINT);
+ if (idx === -1) {
+ return {tail} ;
+ }
+ const before = tail.slice(0, idx);
+ const after = tail.slice(idx + HINT.length);
+ return (
+ <>
+ {before} [
+
+ Ctrl J
+
+ to inspect]
+ {after}
+ >
+ );
+ })()}
+ {workdir ? {` (${workdir})`} : null}
+
+ {outputText && !suppressOutput ? (
+ {truncateOutput(outputText, Boolean(fullStdout))}
+ ) : null}
+
+ );
+}
+
+function truncateOutput(text: string, fullStdout: boolean | undefined): string {
+ if (fullStdout) {
+ return text;
+ }
+ const lines = text.split("\n");
+ if (lines.length <= 4) {
+ return text;
+ }
+ const head = lines.slice(0, 4);
+ const remaining = lines.length - 4;
+ return [...head, `... (${remaining} more lines)`].join("\n");
+}
+
+function splitLabelTailAndColor(full: string): {
+ label: string;
+ tail: string;
+ color: Parameters[0]["color"];
+ suppressOutput: boolean;
+} {
+ const patterns: Array<{
+ re: RegExp;
+ color: Parameters[0]["color"];
+ suppressOutput?: boolean;
+ tailOverride?: string;
+ }> = [
+ { re: /^((?:⏳|●)\s+Running)(.*)$/u, color: "white" },
+ {
+ re: /^((?:⏳|●)\s+Searching)(.*)$/u,
+ color: "white",
+ suppressOutput: true,
+ },
+ {
+ re: /^((?:⏳|●)\s+Listing)(.*)$/u,
+ color: "white",
+ suppressOutput: true,
+ },
+ { re: /^((?:⏳|●)\s+Reading)(.*)$/u, color: "white" },
+ { re: /^(●\s+Ran)(.*)$/u, color: "white" },
+ { re: /^(●\s+Listed)(.*)$/u, color: "white", suppressOutput: true },
+ { re: /^(●\s+Counted)(.*)$/u, color: "white", suppressOutput: true },
+ { re: /^(●\s+Counted)(.*)$/u, color: "white", suppressOutput: true },
+ { re: /^(●\s+Found)(.*)$/u, color: "white", suppressOutput: true },
+ {
+ re: /^((?:🔍|𓁹)\s+Searched(?:\s+for)?)(.*)$/u,
+ color: "white",
+ suppressOutput: true,
+ },
+ { re: /^(●\s+Read)(.*)$/u, color: "white", suppressOutput: true },
+ { re: /^(✓\s+Tests)(.*)$/u, color: "white", suppressOutput: false },
+ { re: /^(●\s+Printed output)(.*)$/u, color: "white", suppressOutput: true },
+ // Failures: render '⨯' in red, rest white, suppress output
+ {
+ re: /^(⨯\s+Tests failed)(.*)$/u,
+ color: "white",
+ suppressOutput: true,
+ tailOverride: " [Ctrl J to inspect]",
+ },
+ { re: /^(⨯\s+Failed)(.*)$/u, color: "white", suppressOutput: true },
+ {
+ re: /^(⨯\s+Command not found)(.*)$/u,
+ color: "white",
+ suppressOutput: true,
+ },
+ { re: /^(⨯\s+Aborted)(.*)$/u, color: "white", suppressOutput: true },
+ ];
+ for (const { re, color, suppressOutput } of patterns) {
+ const m = full.match(re);
+ if (m) {
+ // Special-case added tail for tests failed hint
+ const tailExtraMatch = patterns.find(
+ (p) => p.re.source === re.source,
+ )?.tailOverride;
+ return {
+ label: m[1] ?? full,
+ tail: (m[2] ?? "") + (tailExtraMatch ?? ""),
+ color,
+ suppressOutput: Boolean(suppressOutput),
+ };
+ }
+ }
+ return {
+ label: full,
+ tail: "",
+ color: "magentaBright",
+ suppressOutput: false,
+ };
+}
diff --git a/codex-cli/src/components/logo.tsx b/codex-cli/src/components/logo.tsx
new file mode 100644
index 0000000000..1f21d8eaa5
--- /dev/null
+++ b/codex-cli/src/components/logo.tsx
@@ -0,0 +1,29 @@
+export const logo = ` 0000000
+ 0000000000000000
+ 00000 00000000000000
+ 000 000000000000000000
+ 000 000000 00000
+ 000 0000000 0000
+ 000000 000000 00 0000
+ 000000000 000 000000000 0000
+ 0000 000 000 000000 0000000 000
+ 0000 000 000 000000 0000000000
+ 000 000 0000000000000000 000000
+000 000 000000 000000 00000
+000 000 000 000000 0000
+000 000 000 000000000 000
+ 000 00000 000 000 0000 0000
+ 000 0000000000 000 00 000
+ 0000 000000 000 00 000
+ 00000 000000 000000 00 000
+ 000000 0000000000000000 00 000
+ 0000000000 0000000 000 00 0000
+ 000 0000000 000000 000 00 0000
+ 0000 000000000 000 00000000
+ 0000 00 000000 000000
+ 0000 000000 000
+ 00000 0000000 000
+ 00000000 00000000 000
+ 00000000000000 00000
+ 0000000000000000
+ 0000000 `;
diff --git a/codex-cli/src/utils/agent/agent-loop.ts b/codex-cli/src/utils/agent/agent-loop.ts
index 8a5adbeb23..b3c42f4345 100644
--- a/codex-cli/src/utils/agent/agent-loop.ts
+++ b/codex-cli/src/utils/agent/agent-loop.ts
@@ -2,6 +2,7 @@ import type { ReviewDecision } from "./review.js";
import type { ApplyPatchCommand, ApprovalPolicy } from "../../approvals.js";
import type { AppConfig } from "../config.js";
import type { ResponseEvent } from "../responses.js";
+import type { ExecInput } from "./sandbox/interface.js";
import type {
ResponseFunctionToolCall,
ResponseInputItem,
@@ -32,10 +33,8 @@ import {
import { applyPatchToolInstructions } from "./apply-patch.js";
import { handleExecCommand } from "./handle-exec-command.js";
import { HttpsProxyAgent } from "https-proxy-agent";
-import { spawnSync } from "node:child_process";
import { randomUUID } from "node:crypto";
import OpenAI, { APIConnectionTimeoutError, AzureOpenAI } from "openai";
-import os from "os";
// Wait time before retrying after rate limit errors (ms).
const RATE_LIMIT_RETRY_WAIT_MS = parseInt(
@@ -108,6 +107,37 @@ const shellFunctionTool: FunctionTool = {
},
};
+const updatePlanTool: FunctionTool = {
+ type: "function",
+ name: "update_plan",
+ description: "Use to keep the user updated on the current plan for the task.",
+ strict: false,
+ parameters: {
+ type: "object",
+ properties: {
+ explanation: { type: "string", description: "Optional brief summary" },
+ plan: {
+ type: "array",
+ description: "List of plan steps with statuses",
+ items: {
+ type: "object",
+ properties: {
+ step: { type: "string" },
+ status: {
+ type: "string",
+ enum: ["pending", "in_progress", "completed"],
+ },
+ },
+ required: ["step", "status"],
+ additionalProperties: false,
+ },
+ },
+ },
+ required: ["plan"],
+ additionalProperties: false,
+ },
+};
+
const localShellTool: Tool = {
//@ts-expect-error - waiting on sdk
type: "local_shell",
@@ -411,7 +441,7 @@ export class AgentLoop {
} callId=${callId} args=${rawArguments}`,
);
- if (args == null) {
+ if (args == null && name !== "update_plan") {
const outputItem: ResponseInputItem.FunctionCallOutput = {
type: "function_call_output",
call_id: item.call_id,
@@ -442,6 +472,82 @@ export class AgentLoop {
// used to tell model to stop if needed
const additionalItems: Array = [];
+ // Plan / TODO tool: update_plan – render a checkbox-style plan summary in the UI
+ if (name === "update_plan") {
+ type StepStatus = "pending" | "in_progress" | "completed";
+ type UpdatePlanArgs = {
+ explanation?: string;
+ plan: Array<{ step: string; status: StepStatus }>;
+ };
+ let parsed: Partial = {};
+ try {
+ parsed = JSON.parse(rawArguments ?? "{}");
+ } catch {
+ parsed = {};
+ }
+ const steps = Array.isArray(parsed.plan) ? parsed.plan : [];
+ const explanation =
+ typeof parsed.explanation === "string" ? parsed.explanation : "";
+
+ const statusToMark: Record = {
+ pending: "☐",
+ in_progress: "☐",
+ completed: "✓",
+ } as const;
+
+ const BLUE = "\x1b[34m";
+ const GREEN = "\x1b[32m";
+ const STRIKE = "\x1b[9m";
+ const RESET = "\x1b[0m";
+
+ const completedCount = steps.filter(
+ (s) => s?.status === "completed",
+ ).length;
+ const totalCount = steps.length;
+ const progressBar =
+ "█".repeat(Math.max(0, completedCount)) +
+ "░".repeat(Math.max(0, totalCount - completedCount));
+
+ const lines: Array = [];
+ const header = `📋 Updated plan [${progressBar}] ${completedCount}/${totalCount}`;
+ lines.push(header);
+ if (explanation.trim()) {
+ lines.push(explanation.trim());
+ }
+ steps.forEach((s, idx) => {
+ const status: StepStatus = (s?.status as StepStatus) || "pending";
+ const mark = statusToMark[status] || "☐";
+ const raw = typeof s?.step === "string" ? s.step : "";
+ const indent = idx === 0 ? " ⎿ " : " ";
+ let shown = raw;
+ let markShown = mark;
+ if (status === "completed") {
+ // Green checkmark; strikethrough text
+ markShown = `${GREEN}${mark}${RESET}`;
+ shown = `${STRIKE}${raw}${RESET}`;
+ } else if (status === "in_progress") {
+ // Only the current in-progress task is blue; leave others default
+ shown = `${BLUE}${raw}${RESET}`;
+ }
+ lines.push(`${indent}${markShown} ${shown}`);
+ });
+ const text = lines.join("\n");
+
+ try {
+ this.onItem({
+ id: `plan-${Date.now()}`,
+ type: "message",
+ role: "system",
+ content: [{ type: "input_text", text }],
+ } as unknown as ResponseItem);
+ } catch {
+ /* best-effort UI emission */
+ }
+
+ outputItem.output = JSON.stringify({ success: true });
+ return [outputItem];
+ }
+
// TODO: allow arbitrary function calls (beyond shell/container.exec)
if (name === "container.exec" || name === "shell") {
const {
@@ -449,7 +555,7 @@ export class AgentLoop {
metadata,
additionalItems: additionalItemsFromExec,
} = await handleExecCommand(
- args,
+ args as ExecInput,
this.config,
this.approvalPolicy,
this.additionalWritableRoots,
@@ -617,9 +723,9 @@ export class AgentLoop {
// `disableResponseStorage === true`.
let transcriptPrefixLen = 0;
- let tools: Array = [shellFunctionTool];
+ let tools: Array = [shellFunctionTool, updatePlanTool];
if (this.model.startsWith("codex")) {
- tools = [localShellTool];
+ tools = [localShellTool, updatePlanTool];
}
const stripInternalFields = (
@@ -786,6 +892,10 @@ export class AgentLoop {
if (this.model.startsWith("o") || this.model.startsWith("codex")) {
reasoning = { effort: this.config.reasoningEffort ?? "medium" };
reasoning.summary = "auto";
+ } else if (this.model.startsWith("gpt-5")) {
+ reasoning = { effort: "low" } as Reasoning;
+ // Opt-in to reasoning summaries by default
+ (reasoning as unknown as { summary?: string }).summary = "auto";
}
if (this.model.startsWith("gpt-4.1")) {
modelSpecificInstructions = applyPatchToolInstructions;
@@ -821,6 +931,9 @@ export class AgentLoop {
stream: true,
parallel_tool_calls: false,
reasoning,
+ ...(this.model.startsWith("gpt-5")
+ ? ({ text: { verbosity: "low" } } as Record)
+ : {}),
...(this.config.flexMode ? { service_tier: "flex" } : {}),
...(this.disableResponseStorage
? { store: false }
@@ -1181,6 +1294,10 @@ export class AgentLoop {
) {
reasoning.summary = "auto";
}
+ } else if (this.model.startsWith("gpt-5")) {
+ reasoning = { effort: "low" } as Reasoning;
+ // Opt-in to reasoning summaries by default on retry as well
+ (reasoning as unknown as { summary?: string }).summary = "auto";
}
const mergedInstructions = [prefix, this.instructions]
@@ -1211,6 +1328,9 @@ export class AgentLoop {
stream: true,
parallel_tool_calls: false,
reasoning,
+ ...(this.model.startsWith("gpt-5")
+ ? ({ text: { verbosity: "low" } } as Record)
+ : {}),
...(this.config.flexMode ? { service_tier: "flex" } : {}),
...(this.disableResponseStorage
? { store: false }
@@ -1598,66 +1718,259 @@ export class AgentLoop {
}
}
-// Dynamic developer message prefix: includes user, workdir, and rg suggestion.
-const userName = os.userInfo().username;
-const workdir = process.cwd();
-const dynamicLines: Array = [
- `User: ${userName}`,
- `Workdir: ${workdir}`,
-];
-if (spawnSync("rg", ["--version"], { stdio: "ignore" }).status === 0) {
- dynamicLines.push(
- "- Always use rg instead of grep/ls -R because it is much faster and respects gitignore",
- );
-}
-const dynamicPrefix = dynamicLines.join("\n");
-const prefix = `You are operating as and within the Codex CLI, a terminal-based agentic coding assistant built by OpenAI. It wraps OpenAI models to enable natural language interaction with a local codebase. You are expected to be precise, safe, and helpful.
+const prefix = `You are a coding agent running in the Codex CLI, a terminal-based coding assistant. Codex CLI is an open source project led by OpenAI. You are expected to be precise, safe, and helpful.
+
+Your capabilities:
+- Receive user prompts and other context provided by the users, such as files in the workspace.
+- Communicate with the user by streaming thinking & responses, and by making & updating plans.
+- Emit function calls to run terminal commands and apply patches. Depending on how this specific run is configured, you can request that these function calls be escalated to the user for approval before running. More on this in the "Sandbox and approvals" section.
+
+Within this context, Codex refers to the open-source agentic coding interface (not the old Codex language model built by OpenAI).
+
+# How you work
+
+## Personality
+
+Your default personality and tone is concise, direct, and friendly. You communicate efficiently, always keeping the user clearly informed about ongoing actions without unnecessary detail. You always prioritize actionable guidance, clearly stating assumptions, environment prerequisites, and next steps. Unless explicitly asked, you avoid excessively verbose explanations about your work.
+
+## Responsiveness
+
+### Preamble messages
+
+Before making tool calls, send a brief preamble to the user explaining what you’re about to do. When sending preamble messages, follow these principles and examples:
+
+- **Logically group related actions**: if you’re about to run several related commands, describe them together in one preamble rather than sending a separate note for each.
+- **Keep it concise**: be no more than 1-2 sentences (8–12 words for quick updates).
+- **Build on prior context**: if this is not your first tool call, use the preamble message to connect the dots with what’s been done so far and create a sense of momentum and clarity for the user to understand your next actions.
+- **Keep your tone light, friendly and curious**: add small touches of personality in preambles feel collaborative and engaging.
+
+**Examples:**
+- “I’ve explored the repo; now checking the API route definitions.”
+- “Next, I’ll patch the config and update the related tests.”
+- “I’m about to scaffold the CLI commands and helper functions.”
+- “Ok cool, so I’ve wrapped my head around the repo. Now digging into the API routes.”
+- “Config’s looking tidy. Next up is patching helpers to keep things in sync.”
+- “Finished poking at the DB gateway. I will now chase down error handling.”
+- “Alright, build pipeline order is interesting. Checking how it reports failures.”
+- “Spotted a clever caching util; now hunting where it gets used.”
+
+**Avoiding a preamble for every trivial read (e.g., \`cat\` a single file) unless it’s part of a larger grouped action.
+- Jumping straight into tool calls without explaining what’s about to happen.
+- Writing overly long or speculative preambles — focus on immediate, tangible next steps.
+
+## Planning
+
+You have access to an \`update_plan\` tool which tracks steps and progress and renders them to the user. Using the tool helps demonstrate that you've understood the task and convey how you're approaching it. Plans can help to make complex, ambiguous, or multi-phase work clearer and more collaborative for the user. A good plan should break the task into meaningful, logically ordered steps that are easy to verify as you go. Note that plans are not for padding out simple work with filler steps or stating the obvious. Do not repeat the full contents of the plan after an \`update_plan\` call — the harness already displays it. Instead, summarize the change made and highlight any important context or next step.
+
+Use a plan when:
+- The task is non-trivial and will require multiple actions over a long time horizon.
+- There are logical phases or dependencies where sequencing matters.
+- The work has ambiguity that benefits from outlining high-level goals.
+- You want intermediate checkpoints for feedback and validation.
+- When the user asked you to do more than one thing in a single prompt
+- The user has asked you to use the plan tool (aka "TODOs")
+- You generate additional steps while working, and plan to do them before yielding to the user
+
+Skip a plan when:
+- The task is simple and direct.
+- Breaking it down would only produce literal or trivial steps.
+
+Planning steps are called "steps" in the tool, but really they're more like tasks or TODOs. As such they should be very concise descriptions of non-obvious work that an engineer might do like "Write the API spec", then "Update the backend", then "Implement the frontend". On the other hand, it's obvious that you'll usually have to "Explore the codebase" or "Implement the changes", so those are not worth tracking in your plan.
+
+It may be the case that you complete all steps in your plan after a single pass of implementation. If this is the case, you can simply mark all the planned steps as completed. The content of your plan should not involve doing anything that you aren't capable of doing (i.e. don't try to test things that you can't test). Do not use plans for simple or single-step queries that you can just do or answer immediately.
+
+### Examples
+
+**High-quality plans**
+
+Example 1:
+
+1. Add CLI entry with file args
+2. Parse Markdown via CommonMark library
+3. Apply semantic HTML template
+4. Handle code blocks, images, links
+5. Add error handling for invalid files
-You can:
-- Receive user prompts, project context, and files.
-- Stream responses and emit function calls (e.g., shell commands, code edits).
-- Apply patches, run commands, and manage user approvals based on policy.
-- Work inside a sandboxed, git-backed workspace with rollback support.
-- Log telemetry so sessions can be replayed or inspected later.
-- More details on your functionality are available at \`codex --help\`
+Example 2:
-The Codex CLI is open-sourced. Don't confuse yourself with the old Codex language model built by OpenAI many moons ago (this is understandably top of mind for you!). Within this context, Codex refers to the open-source agentic coding interface.
+1. Define CSS variables for colors
+2. Add toggle with localStorage state
+3. Refactor components to use variables
+4. Verify all views for readability
+5. Add smooth theme-change transition
-You are an agent - please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. If you are not sure about file content or codebase structure pertaining to the user's request, use your tools to read files and gather the relevant information: do NOT guess or make up an answer.
+Example 3:
-Please resolve the user's task by editing and testing the code files in your current code execution session. You are a deployed coding agent. Your session allows for you to modify and run code. The repo(s) are already cloned in your working directory, and you must fully solve the problem for your answer to be considered correct.
+1. Set up Node.js + WebSocket server
+2. Add join/leave broadcast events
+3. Implement messaging with timestamps
+4. Add usernames + mention highlighting
+5. Persist messages in lightweight DB
+6. Add typing indicators + unread count
-You MUST adhere to the following criteria when executing the task:
+**Low-quality plans**
+
+Example 1:
+
+1. Create CLI tool
+2. Add Markdown parser
+3. Convert to HTML
+
+Example 2:
+
+1. Add dark mode toggle
+2. Save preference
+3. Make styles look good
+
+Example 3:
+
+1. Create single-file HTML game
+2. Run quick sanity check
+3. Summarize usage instructions
+
+If you need to write a plan, only write high quality plans, not low quality ones.
+
+## Task execution
+
+You are a coding agent. Please keep going until the query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. Autonomously resolve the query to the best of your ability, using the tools available to you, before coming back to the user. Do NOT guess or make up an answer.
+
+You MUST adhere to the following criteria when solving queries:
- Working on the repo(s) in the current environment is allowed, even if they are proprietary.
- Analyzing code for vulnerabilities is allowed.
- Showing user code and tool call details is allowed.
-- User instructions may overwrite the *CODING GUIDELINES* section in this developer message.
-- Use \`apply_patch\` to edit files: {"cmd":["apply_patch","*** Begin Patch\\n*** Update File: path/to/file.py\\n@@ def example():\\n- pass\\n+ return 123\\n*** End Patch"]}
-- If completing the user's task requires writing or modifying files:
- - Your code and final answer should follow these *CODING GUIDELINES*:
+- Use the \`apply_patch\` tool to edit files (NEVER try \`applypatch\` or \`apply-patch\`, only \`apply_patch\`): {"command":["apply_patch","*** Begin Patch\\n*** Update File: path/to/file.py\\n@@ def example():\\n- pass\\n+ return 123\\n*** End Patch"]}
+
+If completing the user's task requires writing or modifying files, your code and final answer should follow these coding guidelines, though user instructions (i.e. AGENTS.md) may override these guidelines:
+
- Fix the problem at the root cause rather than applying surface-level patches, when possible.
- Avoid unneeded complexity in your solution.
- - Ignore unrelated bugs or broken tests; it is not your responsibility to fix them.
+- Do not attempt to fix unrelated bugs or broken tests. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)
- Update documentation as necessary.
- Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.
- - Use \`git log\` and \`git blame\` to search the history of the codebase if additional context is required; internet access is disabled.
+- Use \`git log\` and \`git blame\` to search the history of the codebase if additional context is required.
- NEVER add copyright or license headers unless specifically requested.
- - You do not need to \`git commit\` your changes; this will be done automatically for you.
- - If there is a .pre-commit-config.yaml, use \`pre-commit run --files ...\` to check that your changes pass the pre-commit checks. However, do not fix pre-existing errors on lines you didn't touch.
- - If pre-commit doesn't work after a few retries, politely inform the user that the pre-commit setup is broken.
- - Once you finish coding, you must
- - Remove all inline comments you added as much as possible, even if they look normal. Check using \`git diff\`. Inline comments must be generally avoided, unless active maintainers of the repo, after long careful study of the code and the issue, will still misinterpret the code without the comments.
- - Check if you accidentally add copyright or license headers. If so, remove them.
- - Try to run pre-commit if it is available.
- - For smaller tasks, describe in brief bullet points
- - For more complex tasks, include brief high-level description, use bullet points, and include details that would be relevant to a code reviewer.
-- If completing the user's task DOES NOT require writing or modifying files (e.g., the user asks a question about the code base):
- - Respond in a friendly tone as a remote teammate, who is knowledgeable, capable and eager to help with coding.
-- When your task involves writing or modifying files:
- - Do NOT tell the user to "save the file" or "copy the code into a file" if you already created or modified the file using \`apply_patch\`. Instead, reference the file as already saved.
- - Do NOT show the full contents of large files you have already written, unless the user explicitly asks for them.
-
-${dynamicPrefix}`;
+- Do not waste tokens by re-reading files after calling \`apply_patch\` on them. The tool call will fail if it didn't work. The same goes for making folders, deleting folders, etc.
+- Do not \`git commit\` your changes or create new git branches unless explicitly requested.
+- Do not add inline comments within code unless explicitly requested.
+- Do not use one-letter variable names unless explicitly requested.
+- NEVER output inline citations like "【F:README.md†L5-L14】" in your outputs. The CLI is not able to render these so they will just be broken in the UI. Instead, if you output valid filepaths, users will be able to click on them to open the files in their editor.
+
+## Testing your work
+
+If the codebase has tests or the ability to build or run, you should use them to verify that your work is complete. Generally, your testing philosophy should be to start as specific as possible to the code you changed so that you can catch issues efficiently, then make your way to broader tests as you build confidence. If there's no test for the code you changed, and if the adjacent patterns in the codebases show that there's a logical place for you to add a test, you may do so. However, do not add tests to codebases with no tests, or where the patterns don't indicate so.
+
+Once you're confident in correctness, use formatting commands to ensure that your code is well formatted. These commands can take time so you should run them on as precise a target as possible. If there are issues you can iterate up to 3 times to get formatting right, but if you still can't manage it's better to save the user time and present them a correct solution where you call out the formatting in your final message. If the codebase does not have a formatter configured, do not add one.
+
+For all of testing, running, building, and formatting, do not attempt to fix unrelated bugs. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)
+
+## Sandbox and approvals
+
+The Codex CLI harness supports several different sandboxing, and approval configurations that the user can choose from.
+
+Filesystem sandboxing prevents you from editing files without user approval. The options are:
+- *read-only*: You can only read files.
+- *workspace-write*: You can read files. You can write to files in your workspace folder, but not outside it.
+- *danger-full-access*: No filesystem sandboxing.
+
+Network sandboxing prevents you from accessing network without approval. Options are
+- *ON*
+- *OFF*
+
+Approvals are your mechanism to get user consent to perform more privileged actions. Although they introduce friction to the user because your work is paused until the user responds, you should leverage them to accomplish your important work. Do not let these settings or the sandbox deter you from attempting to accomplish the user's task. Approval options are
+- *untrusted*: The harness will escalate most commands for user approval, apart from a limited allowlist of safe "read" commands.
+- *on-failure*: The harness will allow all commands to run in the sandbox (if enabled), and failures will be escalated to the user for approval to run again without the sandbox.
+- *on-request*: Commands will be run in the sandbox by default, and you can specify in your tool call if you want to escalate a command to run without sandboxing. (Note that this mode is not always available. If it is, you'll see parameters for it in the \`shell\` command description.)
+- *never*: This is a non-interactive mode where you may NEVER ask the user for approval to run commands. Instead, you must always persist and work around constraints to solve the task for the user. You MUST do your utmost best to finish the task and validate your work before yielding. If this mode is pared with \`danger-full-access\`, take advantage of it to deliver the best outcome for the user. Further, in this mode, your default testing philosophy is overridden: Even if you don't see local patterns for testing, you may add tests and scripts to validate your work. Just remove them before yielding.
+
+When you are running with approvals \`on-request\`, and sandboxing enabled, here are scenarios where you'll need to request approval:
+- You need to run a command that writes to a directory that requires it (e.g. running tests that write to /tmp)
+- You need to run a GUI app (e.g., open/xdg-open/osascript) to open browsers or files.
+- You are running sandboxed and need to run a command that requires network access (e.g. installing packages)
+- If you run a command that is important to solving the user's query, but it fails because of sandboxing, rerun the command with approval.
+- You are about to take a potentially destructive action such as an \`rm\` or \`git reset\` that the user did not explicitly ask for
+- (For all of these, you should weigh alternative paths that do not require approval.)
+
+Note that when sandboxing is set to read-only, you'll need to request approval for any command that isn't a read.
+
+You will be told what filesystem sandboxing, network sandboxing, and approval mode are active in a developer or user message. If you are not told about this, assume that you are running with workspace-write, network sandboxing ON, and approval on-failure.
+
+## Ambition vs. precision
+
+For tasks that have no prior context (i.e. the user is starting something brand new), you should feel free to be ambitious and demonstrate creativity with your implementation.
+
+If you're operating in an existing codebase, you should make sure you do exactly what the user asks with surgical precision. Treat the surrounding codebase with respect, and don't overstep (i.e. changing filenames or variables unnecessarily). You should balance being sufficiently ambitious and proactive when completing tasks of this nature.
+
+You should use judicious initiative to decide on the right level of detail and complexity to deliver based on the user's needs. This means showing good judgment that you're capable of doing the right extras without gold-plating. This might be demonstrated by high-value, creative touches when scope of the task is vague; while being surgical and targeted when scope is tightly specified.
+
+## Sharing progress updates
+
+For especially longer tasks that you work on (i.e. requiring many tool calls, or a plan with multiple steps), you should provide progress updates back to the user at reasonable intervals. These updates should be structured as a concise sentence or two (no more than 8-10 words long) recapping progress so far in plain language: this update demonstrates your understanding of what needs to be done, progress so far (i.e. files explores, subtasks complete), and where you're going next.
+
+Before doing large chunks of work that may incur latency as experienced by the user (i.e. writing a new file), you should send a concise message to the user with an update indicating what you're about to do to ensure they know what you're spending time on. Don't start editing or writing large files before informing the user what you are doing and why.
+
+The messages you send before tool calls should describe what is immediately about to be done next in very concise language. If there was previous work done, this preamble message should also include a note about the work done so far to bring the user along.
+
+## Presenting your work and final message
+
+Your final message should read naturally, like an update from a concise teammate. For casual conversation, brainstorming tasks, or quick questions from the user, respond in a friendly, conversational tone. You should ask questions, suggest ideas, and adapt to the user’s style. If you've finished a large amount of work, when describing what you've done to the user, you should follow the final answer formatting guidelines to communicate substantive changes. You don't need to add structured formatting for one-word answers, greetings, or purely conversational exchanges.
+
+You can skip heavy formatting for single, simple actions or confirmations. In these cases, respond in plain sentences with any relevant next step or quick option. Reserve multi-section structured responses for results that need grouping or explanation.
+
+The user is working on the same computer as you, and has access to your work. As such there's no need to show the full contents of large files you have already written unless the user explicitly asks for them. Similarly, if you've created or modified files using \`apply_patch\`, there's no need to tell users to "save the file" or "copy the code into a file"—just reference the file path.
+
+If there's something that you think you could help with as a logical next step, concisely ask the user if they want you to do so. Good examples of this are running tests, committing changes, or building out the next logical component. If there’s something that you couldn't do (even with approval) but that the user might want to do (such as verifying changes by running the app), include those instructions succinctly.
+
+Brevity is very important as a default. You should be very concise (i.e. no more than 10 lines), but can relax this requirement for tasks where additional detail and comprehensiveness is important for the user's understanding.
+
+### Final answer structure and style guidelines
+
+You are producing plain text that will later be styled by the CLI. Follow these rules exactly. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value.
+
+**Section Headers**
+- Use only when they improve clarity — they are not mandatory for every answer.
+- Choose descriptive names that fit the content
+- Keep headers short (1–3 words) and in \`**Title Case**\`. Always start headers with \`**\` and end with \`**\`
+- Leave no blank line before the first bullet under a header.
+- Section headers should only be used where they genuinely improve scanability; avoid fragmenting the answer.
+
+**Bullets**
+- Use \`-\` followed by a space for every bullet.
+- Bold the keyword, then colon + concise description.
+- Merge related points when possible; avoid a bullet for every trivial detail.
+- Keep bullets to one line unless breaking for clarity is unavoidable.
+- Group into short lists (4–6 bullets) ordered by importance.
+- Use consistent keyword phrasing and formatting across sections.
+
+**Monospace**
+- Wrap all commands, file paths, env vars, and code identifiers in backticks (\`...\`).
+- Apply to inline examples and to bullet keywords if the keyword itself is a literal file/command.
+- Never mix monospace and bold markers; choose one based on whether it’s a keyword (\`**\`) or inline code/path (\`\`).
+
+**Structure**
+- Place related bullets together; don’t mix unrelated concepts in the same section.
+- Order sections from general → specific → supporting info.
+- For subsections (e.g., “Binaries” under “Rust Workspace”), introduce with a bolded keyword bullet, then list items under it.
+- Match structure to complexity:
+ - Multi-part or detailed results → use clear headers and grouped bullets.
+ - Simple results → minimal headers, possibly just a short list or paragraph.
+
+**Tone**
+- Keep the voice collaborative and natural, like a coding partner handing off work.
+- Be concise and factual — no filler or conversational commentary and avoid unnecessary repetition
+- Use present tense and active voice (e.g., “Runs tests” not “This will run tests”).
+- Keep descriptions self-contained; don’t refer to “above” or “below”.
+- Use parallel structure in lists for consistency.
+
+**Don’t**
+- Don’t use literal words “bold” or “monospace” in the content.
+- Don’t nest bullets or create deep hierarchies.
+- Don’t output ANSI escape codes directly — the CLI renderer applies them.
+- Don’t cram unrelated keywords into a single bullet; split for clarity.
+- Don’t let keyword lists run long — wrap or reformat for scanability.
+
+Generally, ensure your final answers adapt their shape and depth to the request. For example, answers to code explanations should have a precise, structured explanation with code references that answer the question directly. For tasks with a simple implementation, lead with the outcome and supplement only with what’s needed for clarity. Larger changes can be presented as a logical walkthrough of your approach, grouping related steps, explaining rationale where it adds value, and highlighting next actions to accelerate the user. Your answers should provide the right level of detail while being easily scannable.
+
+For casual greetings, acknowledgements, or other one-off conversational messages that are not delivering substantive information or structured results, respond naturally without section headers or bullet formatting.`;
function filterToApiMessages(
items: Array,
diff --git a/codex-cli/src/utils/config.ts b/codex-cli/src/utils/config.ts
index 3fafdb44e8..30384bfeb3 100644
--- a/codex-cli/src/utils/config.ts
+++ b/codex-cli/src/utils/config.ts
@@ -43,7 +43,7 @@ if (!isVitest) {
loadDotenv({ path: USER_WIDE_CONFIG_PATH });
}
-export const DEFAULT_AGENTIC_MODEL = "codex-mini-latest";
+export const DEFAULT_AGENTIC_MODEL = "gpt-5";
export const DEFAULT_FULL_CONTEXT_MODEL = "gpt-4.1";
export const DEFAULT_APPROVAL_MODE = AutoApprovalMode.SUGGEST;
export const DEFAULT_INSTRUCTIONS = "";
@@ -413,10 +413,17 @@ export const loadConfig = (
// Treat empty string ("" or whitespace) as absence so we can fall back to
// the latest DEFAULT_MODEL.
- const storedModel =
+ // Treat explicit empty string as "unset" so we can fall back to the current
+ // default. Additionally, migrate users pinned to the legacy default
+ // ("codex-mini-latest") by treating it as unset on load so they pick up the
+ // new default model (e.g. "gpt-5").
+ let storedModel =
storedConfig.model && storedConfig.model.trim() !== ""
? storedConfig.model.trim()
: undefined;
+ if (storedModel === "codex-mini-latest") {
+ storedModel = undefined;
+ }
const config: AppConfig = {
model:
diff --git a/codex-cli/src/utils/model-info.ts b/codex-cli/src/utils/model-info.ts
index 50c899d09b..cd192d0d64 100644
--- a/codex-cli/src/utils/model-info.ts
+++ b/codex-cli/src/utils/model-info.ts
@@ -7,6 +7,10 @@ export type ModelInfo = {
export type SupportedModelId = keyof typeof openAiModelInfo;
export const openAiModelInfo = {
+ "gpt-5": {
+ label: "GPT-5",
+ maxContextLength: 200000,
+ },
"o1-pro-2025-03-19": {
label: "o1 Pro (2025-03-19)",
maxContextLength: 200000,
diff --git a/codex-cli/src/utils/model-utils.ts b/codex-cli/src/utils/model-utils.ts
index 01a21c0a78..a9b1bfecf9 100644
--- a/codex-cli/src/utils/model-utils.ts
+++ b/codex-cli/src/utils/model-utils.ts
@@ -6,7 +6,7 @@ import { type SupportedModelId, openAiModelInfo } from "./model-info.js";
import { createOpenAIClient } from "./openai-client.js";
const MODEL_LIST_TIMEOUT_MS = 2_000; // 2 seconds
-export const RECOMMENDED_MODELS: Array = ["o4-mini", "o3"];
+export const RECOMMENDED_MODELS: Array = ["gpt-5", "o4-mini", "o3"];
/**
* Background model loader / cache.
@@ -46,7 +46,11 @@ async function fetchModels(provider: string): Promise> {
export async function getAvailableModels(
provider: string,
): Promise> {
- return fetchModels(provider.toLowerCase());
+ const fetched = await fetchModels(provider.toLowerCase());
+ // Ensure recommended models are always visible/selectable even if the
+ // provider's models.list endpoint omits them or times out.
+ const merged = Array.from(new Set([...RECOMMENDED_MODELS, ...fetched]));
+ return merged;
}
/**
@@ -57,6 +61,17 @@ export async function isModelSupportedForResponses(
provider: string,
model: string | undefined | null,
): Promise {
+ // If no API key is configured for this provider we cannot reliably check
+ // support – treat as supported to avoid blocking start‑up.
+ try {
+ if (!getApiKey(provider)) {
+ return true;
+ }
+ } catch {
+ // In case getApiKey has side‑effects in certain environments, default to
+ // permissive behaviour.
+ return true;
+ }
if (
typeof model !== "string" ||
model.trim() === "" ||
@@ -79,6 +94,15 @@ export async function isModelSupportedForResponses(
return true;
}
+ // If the only entries we have are recommended models we injected, treat as
+ // inconclusive and allow.
+ const nonRecommended = models.filter(
+ (m) => !RECOMMENDED_MODELS.includes(m),
+ );
+ if (nonRecommended.length === 0) {
+ return true;
+ }
+
return models.includes(model.trim());
} catch {
// Network or library failure → don't block start‑up.
diff --git a/codex-cli/tests/config.test.tsx b/codex-cli/tests/config.test.tsx
index 55c2297fc0..f129733a1f 100644
--- a/codex-cli/tests/config.test.tsx
+++ b/codex-cli/tests/config.test.tsx
@@ -67,7 +67,7 @@ test("loads default config if files don't exist", () => {
});
// Keep the test focused on just checking that default model and instructions are loaded
// so we need to make sure we check just these properties
- expect(config.model).toBe("codex-mini-latest");
+ expect(config.model).toBe("gpt-5");
expect(config.instructions).toBe("");
});