# Hacking Subagents Into Codex CLI — Brian John, BetterUp

Brian John, BetterUp

AI Engineer Code 2025

[Talk page](https://ai.engineer/talks/5eJqXtevlXg-hacking-subagents-into-codex-cli) · [Video](https://www.youtube.com/watch?v=5eJqXtevlXg)

## Hacking Subagents into Codex CLI

Brian John builds a small wrapper around child Codex processes to preserve delegation workflows, isolate context, and reuse approvals without disabling the sandbox.

Familiarity with command-line coding agents, subprocesses, filesystem permissions, and basic Python will help you follow the implementation.

### How do you take your subagent workflow with you?

[0:12](https://www.youtube.com/watch?v=5eJqXtevlXg&t=12s)

How do you move between coding tools without giving up the delegation workflow that makes them useful? Brian John approaches that problem as a principal full stack engineer responsible for AI enablement in BetterUp’s R&D organization: helping people work faster and produce higher-quality results. At the time of the talk, he had spent more than eight years at BetterUp, which he describes as using AI from its beginning. Its mission—helping people live with purpose, clarity, and passion—also frames his invitation to engineers interested in working with LLMs.

Claude Code is his daily driver, and subagents are a regular part of his work. But those workflows create a dependency: switching tools can mean losing the ability to delegate in the same way. Codex CLI’s models look appealing to him, and he wants to use them without being locked into either one tool or one model family.

**The main benefit is context isolation.** The parent gives a subagent a problem; the child spends its own tokens investigating it and returns only the answer. The intermediate work does not fill the parent’s context window. John credits Dex Horthy’s context-engineering talk with changing how he works, particularly in large codebases. Delegation is therefore more than assigning a role: it controls how much working material the main agent has to carry forward.

![Slide titled “But…why?” lists vendor lock-in to Claude Code, context management, and “You’re absolutely right!” above a thumbnail for “Advanced Context Engineering for Agents.”](https://ai.engineer/api/talk-essay-media/253be770e28407ca02a7f5e82165b876e89a50b3bcd5e74081a79c81ec6486b1)

Motivations for subagents, with a reference to Dexter Horthy’s context engineering talk.

### A subagent is another Codex process

[2:36](https://www.youtube.com/watch?v=5eJqXtevlXg&t=156s)

The implementation starts with a small observation: a subagent can be another instance of the main agent. There is no need to build a separate agent runtime. The parent Codex session can invoke a wrapper that starts a child through `codex exec`.

The complete execution loop has four steps:

1. The parent calls the wrapper with a delegated task.
2. The wrapper selects the agent definition, builds its prompt, and launches child Codex.
3. The child performs the task and writes its final answer into a file.
4. The wrapper reads that file and prints its contents to **stdout**, where the parent receives the result.

The answer file is the handoff between child and wrapper; stdout is the handoff between wrapper and parent. The design is small, but John’s first attempts immediately run into sandbox errors.

![Design flowchart connects Parent Codex Session, agent-exec CLI, Child Codex CLI, and the wrapper’s return path back to the parent.](https://ai.engineer/api/talk-essay-media/cac4c57bac4fded6af5d7fe1356a869777d225a4e477608c15cfd83c460d26e3)

The parent session launches a wrapper, which runs child Codex and returns its file output through stdout.

### Getting nested permissions right

[3:36](https://www.youtube.com/watch?v=5eJqXtevlXg&t=216s)

John does not solve those errors by disabling permission checks. The hard part is finding the minimum permissions that let the nested process work. In his setup, the parent needs at least `--sandbox workspace-write` to run the Codex command. The child then encounters another boundary: the OpenAI credentials in the user’s home directory sit outside the workspace accessible under the parent’s sandbox.

| Component | Requirement in the demonstration | Purpose |
|---|---|---|
| Parent Codex | `--sandbox workspace-write` | Permit the demonstrated child-launch workflow |
| Child Codex | `--sandbox workspace-write` | Write the answer file |
| Credentials | An accessible workspace location | Avoid depending on blocked home-directory access |
| Rollout recorder | Disabled | Avoid logging writes outside the workspace |

The child’s own settings cannot make the parent’s filesystem restrictions disappear. John therefore also disables the **rollout recorder**, the logging mechanism whose filesystem access causes trouble inside the enclosing sandbox.

Before proceeding, he evaluates the arrangement using Meta’s [Agents Rule of Two](https://ai.meta.com/blog/practical-ai-agent-security/). The framework examines three properties: processing untrusted input, accessing sensitive systems or private data, and changing state or communicating externally. Its security boundary depends on restricting at least one of these properties; allowing all three together calls for supervision.

John assumes his particular workflow does not process untrusted input. It does access private data through a proprietary codebase, and it can both change state and communicate externally. He considers the state changes in his environment relatively low risk and says the external communication is limited to OpenAI’s API endpoint. That is a conditional assessment of his system: **lower risk does not mean no risk**, and a different input source or set of accessible systems changes the assessment.

### Teaching the parent how to delegate

[6:14](https://www.youtube.com/watch?v=5eJqXtevlXg&t=374s)

A working wrapper is not enough: the parent needs to know it exists. The repository’s [invocation instructions in `AGENTS.md`](https://github.com/betterup/codex-cli-subagents/blob/main/AGENTS.md) supply three parts of the contract:

- **How:** map a request for a named subagent to the wrapper invocation.
- **When:** delegate when the user asks, or when the parent judges delegation useful.
- **What:** list the available subagents and their responsibilities.

This turns a natural-language request to use a subagent into a concrete action the parent can perform.

John then opens the small [BetterUp Codex CLI Subagent Demo](https://github.com/betterup/codex-cli-subagents). Its agent definitions contain a name, a reasoning-effort setting, and a prompt, much like Claude Code’s subagent definitions. He describes choosing lighter, medium, or higher reasoning according to the work. The two toy agents make that distinction easy to see: one counts words, while the other writes supplied text to a file, a task that needs little reasoning.

John describes the [command wrapper](https://github.com/betterup/codex-cli-subagents/blob/main/bin/agent-exec) as 72 lines. It accepts the inputs, calls the Python [`AgentExecutor`](https://github.com/betterup/codex-cli-subagents/blob/main/src/agent_executor.py), and prints the returned answer to stdout. The executor owns the process details: child permissions, reasoning effort, and rollout-recorder settings. Keeping those details together leaves the outer command focused on input and output.

### Change the input files, keep the command

[9:05](https://www.youtube.com/watch?v=5eJqXtevlXg&t=545s)

The invocation contract has an unusual detail: the parent writes the agent name into `agent.txt` and the user’s query into `query.txt` before running the wrapper. Passing both values as command-line arguments would be more obvious, but it would change the command on every request.

In the permission system John demonstrates, an exactly unchanged command can retain approval, while changing its arguments prompts for approval again. Moving variable data into files lets different tasks use the same invocation. The following Python example prepares a word-count request through that file interface:

```python
from pathlib import Path
import subprocess

Path("agent.txt").write_text("word-counter\n", encoding="utf-8")
Path("query.txt").write_text(
    "Count the words in this text: Small wrappers preserve useful workflows.\n",
    encoding="utf-8",
)

subprocess.run(
    ["timeout", "600", "bin/agent-exec"],
    check=True,
)
```

The sentence can change without changing `timeout 600 bin/agent-exec`. This separates the command being approved from the task data it will read.

The reusable approval is consequently approval to invoke the wrapper with changing file contents, not approval of one immutable query. Bypassing permission checks would remove the repeated prompts too, but that is not the operating mode John chooses.

### Preparing a Codex home inside the workspace

[10:09](https://www.youtube.com/watch?v=5eJqXtevlXg&t=609s)

A second wrapper prepares the parent session. It copies Codex home files from the user’s home directory into a workspace subdirectory so the nested process can access them. John describes this as syncing the files, pointing `CODEX_HOME` at the new location, and launching Codex. In the inspected repository, those responsibilities are split: [`bin/codex`](https://github.com/betterup/codex-cli-subagents/blob/main/bin/codex) copies the files into `tmp/codex-home`, while `AgentExecutor` sets `CODEX_HOME` for the child. The accessible copy resolves the earlier credential-location problem.

The launch shown uses `--full-auto`. John associates it with workspace-write permissions but does not recall its precise approval policy. These flags and approval behaviors belong to the historical demonstration: the current CLI reference marks `--full-auto` deprecated, and current Codex supports native parallel subagents. The wrapper walkthrough explains how this setup worked without treating its historical limitations as current requirements.

![Terminal editor shows a loop copying files and directories, credential-sync status messages, and the final exec codex command with --full-auto.](https://ai.engineer/api/talk-essay-media/94b04a07f233447b271dde5bd93d06d46baae22279e191bd647930b99b27caaf)

Launch script copies Codex home entries into the workspace location and runs Codex with --full-auto.

### From the first approval to a verified file

[10:45](https://www.youtube.com/watch?v=5eJqXtevlXg&t=645s)

With the prepared session running, John asks Codex to use the word-counter subagent. The parent recognizes that it needs the agent-execution wrapper, writes the agent name and query into their files, and requests permission to run the command. John chooses the option to approve it without asking again for that command. This first invocation establishes the approval that the next task will reuse.

The demonstrated workflow runs serially: the parent waits while the child does its work. John finds it slower than his Claude Code workflow and interprets Codex as better suited to hands-off, unattended work, while Claude Code feels more iterative to him. He accepts that tradeoff for his usage. The child’s result then appears on stdout, and the parent turns it into the answer shown to the user.

The second request uses the file-writer subagent. Codex writes a new agent name and query into the same input files and invokes the same command. This time there is no permission prompt. The task has changed, but the approved command has not.

The command uses `timeout 600`, giving the outer invocation ten minutes. John reports that large-codebase tasks can take ten minutes and sometimes as long as twenty minutes. That motivates allowing more time for substantial repository work. There is also an implementation detail to account for: `AgentExecutor` passes its own 600-second timeout to `subprocess.run`, so increasing only the outer timeout would leave the internal limit in place.

John reports that the easy file-writing example took about 40 seconds. These durations are observations from his usage and demonstration, rather than controlled comparisons across models or repositories. He finishes by checking that the requested file was written—the concrete output matters beyond the parent’s success message.

The recording closes with pointers to the open-source code and BetterUp, plus email and X direct messages for questions. The proof of concept ends at a useful boundary: two different delegated tasks, one reusable wrapper approval, and a file checked after creation.

## Resources

- [Codex CLI Subagent Demo](https://github.com/betterup/codex-cli-subagents) — BetterUp's proof of concept with word-counter and file-writer agents, Python execution code, and launch scripts.
- [Agents Rule of Two: A Practical Approach to AI Agent Security](https://ai.meta.com/blog/practical-ai-agent-security/) — Meta's framework for limiting combinations of untrusted input, sensitive access, and external actions in autonomous agents.
- [Advanced Context Engineering for Coding Agents](https://www.humanlayer.dev/blog/advanced-context-engineering) — Dex Horthy explains context isolation, intentional compaction, and research, planning, and implementation workflows.
- [Native Codex subagents](https://learn.chatgpt.com/docs/agent-configuration/subagents) — Current documentation for parallel subagents, custom agent configuration, and orchestration in Codex.

## Slides

### Hacking Subagents into Codex CLI

Brian John of BetterUp introduces his talk on hacking subagents into Codex CLI.

[0:00](https://www.youtube.com/watch?v=5eJqXtevlXg&t=0s) [Title slide naming Brian John of BetterUp.](https://assets.ai.engineer/sites/aiecode2025/sha256/23186ee837672844385cea0a3a9d05719dbd07a0fa7d843def05e4a55998d52e.webp)

Hacking Subagents into
Codex CLI

Brian John, BetterUp

### About Me

Brian John is a principal full stack engineer at BetterUp, where he helps R&D teams use AI to work faster and improve quality.

[0:09](https://www.youtube.com/watch?v=5eJqXtevlXg&t=9s) [Brian John's role, AI enablement focus, and company, BetterUp.](https://assets.ai.engineer/sites/aiecode2025/sha256/0047a1a06c0bc91acbe7720a866dd7fd42e29a00bbb6d9040d8336c0f7a1c137.webp)

About Me

• Title: Principal Full Stack Engineer
• Current Focus: AI Enablement for R&D
• Company: BetterUp (Awesome place to work - let’s talk!)

BetterUp

### But...why?

John cites Claude Code lock-in and context management: subagents can work in their own context and return only the answer to the main agent. He also calls out the familiar “You’re absolutely right!” response.

[1:58](https://www.youtube.com/watch?v=5eJqXtevlXg&t=118s) [Reasons include vendor lock-in and context management.](https://assets.ai.engineer/sites/aiecode2025/sha256/017e6970eec701d3d5628a2bb184402509eaaec092ee87da06585fc5cbec299b.webp)

But...why?

• Vendor Lock-in to Claude Code
• Context Management
• You’re absolutely right!

### Advanced Context Engineering for Agents

Brian John credits Dexter Horthy’s talk with changing how he works with AI; he found its workflows especially effective on large codebases.

[2:04](https://www.youtube.com/watch?v=5eJqXtevlXg&t=124s) [Title card for Dexter Horthy's talk at Context Engineering SF, alongside a photograph of the speaker.](https://assets.ai.engineer/sites/aiecode2025/sha256/4127fc939f53c09c5ac7e8653bb72bbea07f6494e7335b564955c913a7f9b78b.webp)

CONTEXT ENGINEERING SF
August 20th, 2025

Advanced Context Engineering for Agents
Dexter Horthy

Y Combinator   Chroma   mastra

Interface text:
14

### Minimum Required Permissions

The parent needs workspace-write to run Codex. The child needs access to the parent’s credentials, workspace-write for the wrapper’s file, and a disabled rollout recorder because the parent sandbox blocks access.

[3:57](https://www.youtube.com/watch?v=5eJqXtevlXg&t=237s) [Slide listing parent and child sandbox requirements for running subagents.](https://assets.ai.engineer/sites/aiecode2025/sha256/d098bded749937652947f689276212fac362bde0fc9b6466d057528a4d0e794e.webp)

Minimum Required Permissions

• Parent:
  ◦ Minimum: --sandbox workspace-write (to be able to run codex)
  ◦ If you like to live dangerously: --dangerously-bypass-approvals-and-sandbox
• Child:
  ◦ Access to parent’s OpenAI credentials (parent sandbox prevents access to ~/.codex/)
  ◦ --sandbox workspace-write (write to /tmp/<agent>.md)
  ◦ Disable Rollout recorder (parent sandbox prevents access)

### Agents Rule of Two

The diagram marks sensitive data access combined with external actions as lower risk when an agent does not process untrustworthy inputs. John cautions that lower risk still carries risk.

[4:56](https://www.youtube.com/watch?v=5eJqXtevlXg&t=296s) [Security slide with a three-circle diagram of untrusted inputs, sensitive data, and external actions.](https://assets.ai.engineer/sites/aiecode2025/sha256/ab37955f2a9f413a52ace2d9742927ccba7ff6c6febecc2cbbf6b01a8e50d824.webp)

Obligatory Security Message

Agents Rule of 2

Choose Two

A
Process untrustworthy inputs
Externally authored data may contain prompt injection attacks that turn an agent malicious.

Lower Risk
Lower Risk
Danger

B
Access to sensitive systems or private data
This includes private user data, company secrets, production settings and configs, source code, and other sensitive data.

C
Change state or communicate externally
Overwrite or change state through write actions, or transmitting data to a threat actor through web requests or tool calls.

Lower Risk

[6:03](https://www.youtube.com/watch?v=5eJqXtevlXg&t=363s) [Security slide with a warning over the Rule of Two diagram: lower risk does not mean no risk.](https://assets.ai.engineer/sites/aiecode2025/sha256/9a0b6bdcbbfb3c8b8a1b06171d4981fcfc10748804428dd6ce282f49bd487c10.webp)

Obligatory Security Message

Agents Rule of 2

Choose Two

A
Process untrustworthy inputs
Externally authored data may contain prompt injection attacks that turn an agent malicious.

Lower risk does not mean no risk!

Danger

B
Access to sensitive systems or private data
This includes private user data, company secrets, production settings and configs, source code, and other sensitive data.

C
Change state or communicate externally
Overwrite or change state through write actions, or transmitting data to a threat actor through web requests or tool calls.

Lower Risk

### AGENTS.md

The AGENTS.md example tells Codex how to invoke subagents through a wrapper script and when to use them: on request or when helpful.

[6:16](https://www.youtube.com/watch?v=5eJqXtevlXg&t=376s) [Slide showing example instructions for invoking subagents and deciding when to use them.](https://assets.ai.engineer/sites/aiecode2025/sha256/e1498758ee1b4a82180673f960cf27ac21aba5dafd1a87a244fc8eeb6d8bad7c.webp)

AGENTS.md

# Available Subagents

This document describes the subagents available to you in this workspace. To invoke one, write the agent name to `tmp/agent-exec/agent.txt`, the query to `tmp/agent-exec/query.txt`, then run `timeout 600 bin/agent-exec`.

## When to Use Subagents

You should use subagents in these situations:
- When the user explicitly requests it: If the user says "use the word-counter subagent" or "use the file-writer subagent", invoke that specific agent
- When you think it would be helpful: Feel free to use any subagent proactively whenever you believe it would help accomplish the task

### Available Subagents

...

### Repository Listing

Brian John lists the proof-of-concept repository and starts typing a command to inspect its agents directory.

[7:21](https://www.youtube.com/watch?v=5eJqXtevlXg&t=441s) [Terminal displaying the contents of a subagent example repository.](https://assets.ai.engineer/sites/aiecode2025/sha256/1e10c0ef706b39ad12f7f1c79c65dd990b3a2cb60ed65e60f14a56d2558dc27e.webp)

ls
agents  bin  notes  README.md  tmp
AGENTS.md  LICENSE  pyproject.toml  src  venv

ls ag

Interface text:
9: zsh
brianjohn@caldigit-thunderbolt-dock  ~/p/codex-cli-subagents  main
[11:42:49]
brianjohn@caldigit-thunderbolt-dock  ~/p/codex-cli-subagents  main
[11:42:49]
0:zsh*
load averages: 3.96 4.27 4.19

### Word-counter agent

Brian opens a toy word-counter agent. Its light reasoning setting and prompt request a total count, the three most frequent words with case-insensitive counts, and the original text in triple backticks.

[7:27](https://www.youtube.com/watch?v=5eJqXtevlXg&t=447s) [Terminal lists two example agent files and opens the word-counter definition.](https://assets.ai.engineer/sites/aiecode2025/sha256/8bb9c09258c925c68e7016da0fd1c38b212e6ea0385468bbf8e348731bb1d4c3.webp)

❯ ls
agents  bin  notes  README.md  tmp
AGENTS.md  LICENSE  pyproject.toml  src  venv

❯ ls agents
file-writer.md  word-counter.md

❯ vim agents/word-counter.md

Interface text:
9: zsh
brianjohn@caldigit-thunderbolt-dock  ~/p/codex-cli-subagents  main
[11:42:49] [11:42:55] [11:43:00]
0:zsh*  load averages: 3.96 4.27 4.19

[7:33](https://www.youtube.com/watch?v=5eJqXtevlXg&t=453s) [Editor showing the word-counter agent’s configuration and response requirements.](https://assets.ai.engineer/sites/aiecode2025/sha256/4cf012aa693737da37d814dd258208196ac68def54e847362130defd2298bdc5.webp)

---
name: word-counter
reasoning_effort: light
---

You count words. Given any text, return:
- total word count
- three most frequent words (case-insensitive) with counts
- the original text wrapped in triple backticks

Format your response clearly with headers and proper markdown formatting.

Interface text:
9: zsh
agents/word-counter.md  3,1  All
0:zsh*  load averages: 3.96 4.25 4.18

### Agent files in the terminal

After inspecting the word-counter definition, Brian returns to the terminal and begins opening the file-writer agent. Both files appear in the agents directory.

[7:56](https://www.youtube.com/watch?v=5eJqXtevlXg&t=476s) [Terminal listing the project and agent files, with a command being typed.](https://assets.ai.engineer/sites/aiecode2025/sha256/435d662b0e0fcf1983ce62d9dae6c428f948cef290fcae6ceea650eff9648668.webp)

ls
agents       bin       notes          README.md  tmp
AGENTS.md    LICENSE   pyproject.toml src        venv

ls agents
file-writer.md  word-counter.md

vim agents/word-counter.md
>>> elapsed time 24s

vim agents/f

Interface text:
9: zsh
brianjohn@caldigit-thunderbolt-dock  ~/p/codex-cli-subagents  main
[11:42:49] [11:42:55] [11:43:00] [11:43:24]
0:zsh*
load averages: 3.96 4.25 4.18

### File-writer agent

The file-writer agent uses light reasoning to write supplied content to a file. Its prompt specifies the input format and asks for the path and first five lines after writing.

[7:59](https://www.youtube.com/watch?v=5eJqXtevlXg&t=479s) [Editor showing the file-writer agent’s input format and response requirements.](https://assets.ai.engineer/sites/aiecode2025/sha256/294d376797474a0072754260d691a145f7b4aa5d1cf69d60774306c6c05d9865.webp)

---
name: file-writer
reasoning_effort: light
---

You create or update files. When given a filename and content (separated by a newline), write the content to the file (overwriting if it exists).

The input format is:
```
filename.txt
content goes here
more content
```

After writing, respond with:
- confirmation that the file was written
- the absolute path to the file
- the first 5 lines of the file wrapped in triple backticks

Assume relative paths are relative to the current working directory.

Interface text:
9: zsh
agents/file-writer.md
1,1
All
0:zsh*
load averages: 3.96 4.25 4.18

### Subagent wrapper setup

The wrapper reads agent inputs, calls AgentExecutor, and returns the agent’s output to standard output so the main agent can see it.

[8:16](https://www.youtube.com/watch?v=5eJqXtevlXg&t=496s) [Editor showing the beginning of a Python wrapper for subagent execution.](https://assets.ai.engineer/sites/aiecode2025/sha256/f2026d6b41a52810e1d1d4d96b84b6d8f0734532d0f9b36824cef20b6aec4a7f.webp)

#!/usr/bin/env python3
"""CLI wrapper for Codex sub-agent execution."""

import sys
from pathlib import Path

project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root / "src"))

venv_site_packages = project_root / "venv" / "lib"
if venv_site_packages.exists():
    for path in venv_site_packages.glob("python*/site-packages"):
        sys.path.insert(0, str(path))

from agent_executor import AgentExecutor

INPUT_DIR = project_root / "tmp" / "agent-exec"
AGENT_FILE = INPUT_DIR / "agent.txt"
QUERY_FILE = INPUT_DIR / "query.txt"


def _load_inputs() -> tuple[str, str]:
    if len(sys.argv) > 1:
        print(
            "Usage:\n"
            "  echo <agent> > tmp/agent-exec/agent.txt\n"

Interface text:
9: zsh
bin/agent-exec
1,1
Top
0:zsh*
load averages: 4.04 4.17 4.15

### Subagent wrapper execution

The wrapper loads the agent and input, checks that the agent definition exists, and runs AgentExecutor. It prints the result to standard output so the main agent can read it.

[8:28](https://www.youtube.com/watch?v=5eJqXtevlXg&t=508s) [Editor showing the wrapper’s main function calling the agent executor and printing its output.](https://assets.ai.engineer/sites/aiecode2025/sha256/c51a24f0b1315592668c0061f1e000e3b19386d52a1b4e9fb094c41c11669135.webp)

def main():
    INPUT_DIR.mkdir(parents=True, exist_ok=True)
    agent_name, user_input = _load_inputs()

    agent_path = Path(__file__).parent.parent / "agents" / f"{agent_name}.md"

    if not agent_path.exists():
        print(f"Error: Agent '{agent_name}' not found", file=sys.stderr)
        print(f"Expected: {agent_path}", file=sys.stderr)
        sys.exit(1)

    try:
        executor = AgentExecutor(str(agent_path))
        result = executor.run(user_input)

        print(result["content"])

    except Exception as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()

Interface text:
9: zsh
bin/agent-exec
69,0-1
Bot
0:zsh*
load averages: 4.31 4.22 4.17

### Agent executor command and output path

The executor launches a child Codex agent with workspace-write permissions and optional reasoning effort, disables the rollout recorder, and names its temporary output file using the agent name, process ID, and timestamp.

[8:52](https://www.youtube.com/watch?v=5eJqXtevlXg&t=532s) [Editor showing command arguments, reasoning-effort configuration, and the beginning of an output-path function.](https://assets.ai.engineer/sites/aiecode2025/sha256/251dfdaf594bd8761c62f954598cda33f38aa1db4069b9944a2fdc81952e9411.webp)

            "codex",
            "--config", "features.rollout_recorder=false",
            "exec",
            "--output-last-message", output_file,
            "--sandbox", "workspace-write",
        ]

        if reasoning_effort := self.config.get("reasoning_effort"):
            argv.extend(["--config", f"reasoning_effort={reasoning_effort}"])

        argv.append(prompt)

        return argv

    def _generate_output_path(self) -> str:
        """Generate unique output file path.

        Returns:
            Path string in /tmp/ with timestamp and PID
        """
        timestamp = time.strftime("%Y%m%d%H%M%S", time.gmtime())
        agent_name = self.config.get("name", "agent").replace(" ", "-").lower()
        pid = os.getpid()

        return os.path.join(
            tempfile.gettempdir(),

Interface text:
9: zsh
src/agent_executor.py
147,1
98%
0:zsh*
load averages: 4.75 4.32 4.21

[8:55](https://www.youtube.com/watch?v=5eJqXtevlXg&t=535s) [Code generates a temporary output filename using the agent name, process ID, and timestamp.](https://assets.ai.engineer/sites/aiecode2025/sha256/99f8726dadfca86e713ee5c3abc38213bb8769b4b61de21d7ab87bb94606201d.webp)

            "exec",
            "--output-last-message", output_file,
            "--sandbox", "workspace-write",
        ]

        if reasoning_effort := self.config.get("reasoning_effort"):
            argv.extend(["--config", f"reasoning_effort={reasoning_effort}"])

        argv.append(prompt)

        return argv

    def _generate_output_path(self) -> str:
        """Generate unique output file path.

        Returns:
            Path string in /tmp/ with timestamp and PID
        """
        timestamp = time.strftime("%Y%m%d%H%M%S", time.gmtime())
        agent_name = self.config.get("name", "agent").replace(" ", "-").lower()
        pid = os.getpid()

        return os.path.join(
            tempfile.gettempdir(),
            f"{agent_name}-{pid}-{timestamp}.md"
        )

Interface text:
9: zsh
src/agent_executor.py
171,1
Bot
0:zsh*
load averages: 4.75 4.32 4.21

### Subagent instructions

AGENTS.md tells Codex to write the agent name and query to files before running a fixed command. Brian says keeping the command unchanged avoids repeated permission approvals for different arguments.

[9:03](https://www.youtube.com/watch?v=5eJqXtevlXg&t=543s) [An AGENTS.md file lists two subagents and explains how to invoke them.](https://assets.ai.engineer/sites/aiecode2025/sha256/337558be1d6ecb9282349294e9c9b7716b990afca0f31f79be329dfe5c11ff12.webp)

# Available Subagents

This document describes the subagents available to you in this workspace. To invoke one, write the agent name to `tmp/agent-exec/agent.txt`, the query to `tmp/agent-exec/query.txt`, then run `timeout 600 bin/agent-exec`.

## When to Use Subagents

You should use subagents in these situations:
- When the user explicitly requests it: If the user says "use the word-counter subagent" or "use the file-writer subagent", invoke that specific agent
- When you think it would be helpful: Feel free to use any subagent proactively whenever you believe it would help accomplish the task

### Available Subagents

#### word-counter
Analyzes text to provide word count statistics and frequency analysis.

#### file-writer
Creates or updates files with specified content.

## How to Invoke

echo word-counter > tmp/agent-exec/agent.txt

Interface text:
9: zsh
AGENTS.md  4,0-1  Top
0:zsh*  load averages: 4.72 4.38 4.24

### Project terminal

The terminal shows the project files and recent edits to the subagent launcher, executor, and AGENTS.md. John then turns to the Codex wrapper.

[10:03](https://www.youtube.com/watch?v=5eJqXtevlXg&t=603s) [A terminal lists project files and recent editor commands.](https://assets.ai.engineer/sites/aiecode2025/sha256/5b79e1af289c83f88bfe0b4a4b3e61c3d9e7407c8542bd5fd4211033a84f4c14.webp)

brianjohn@caldigit-thunderbolt-dock ~/p/codex-cli-subagents main
❯ ls [11:44:16]
agents       bin       notes           README.md  tmp
AGENTS.md    LICENSE   pyproject.toml  src        venv

brianjohn@caldigit-thunderbolt-dock ~/p/codex-cli-subagents main
❯ vim bin/agent-exec [11:44:29]
>>> elapsed time 25s

brianjohn@caldigit-thunderbolt-dock ~/p/codex-cli-subagents main
❯ vim src/agent_executor.py [11:44:58]
>>> elapsed time 17s

brianjohn@caldigit-thunderbolt-dock ~/p/codex-cli-subagents main
❯ vim AGENTS.md [11:45:20]
>>> elapsed time 1m0s

brianjohn@caldigit-thunderbolt-dock ~/p/codex-cli-subagents main
❯ vim bin/cr [11:46:20]

Interface text:
9: zsh
0:zsh*  load averages: 4.29 4.30 4.21

### Codex wrapper setup

The wrapper creates a project-local Codex home and copies entries from ~/.codex into it, replacing existing copies so Codex can access them from the workspace.

[10:13](https://www.youtube.com/watch?v=5eJqXtevlXg&t=613s) [A shell script sets up a workspace directory and copies Codex home files into it.](https://assets.ai.engineer/sites/aiecode2025/sha256/a8cc15749bcddea8eebc38fa7a7b261770d8b4847518060466fd83e9533aad1e.webp)

#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

CODEX_HOME_WORKSPACE="$PROJECT_ROOT/tmp/codex-home"
mkdir -p "$CODEX_HOME_WORKSPACE"

if [ -d "$HOME/.codex" ]; then
    echo "Syncing Codex credentials to workspace..." >&2

    for entry in "$HOME/.codex"/*; do
        basename=$(basename "$entry")
        dest="$CODEX_HOME_WORKSPACE/$basename"

        if [ -e "$dest" ]; then
            rm -rf "$dest"
        fi

        if [ -d "$entry" ]; then
            cp -R "$entry" "$dest"
        else
            cp "$entry" "$dest"
        fi
    done

Interface text:
9: zsh
bin/codex
12,0-1 Top
0:zsh*
load averages: 4.23 4.29 4.20

### Codex wrapper launch

The wrapper copies Codex home files into a workspace directory, replacing existing entries, then launches Codex in --full-auto mode.

[10:25](https://www.youtube.com/watch?v=5eJqXtevlXg&t=625s) [The lower portion of the wrapper script reports synchronization and launches Codex in full-auto mode.](https://assets.ai.engineer/sites/aiecode2025/sha256/bdce37517aef7973e2b628177228d6759a513b81d75a7076a0a63a1ee7738f54.webp)

    for entry in "$HOME/.codex"/*; do
        basename=$(basename "$entry")
        dest="$CODEX_HOME_WORKSPACE/$basename"

        if [ -e "$dest" ]; then
            rm -rf "$dest"
        fi

        if [ -d "$entry" ]; then
            cp -R "$entry" "$dest"
        else
            cp "$entry" "$dest"
        fi
    done

    echo "Credentials synced to $CODEX_HOME_WORKSPACE" >&2
else
    echo "Warning: ~/.codex not found. Run 'codex login' first." >&2
fi

echo "Launching Codex with parent agent configuration..." >&2
echo "" >&2

exec codex \
  --full-auto

Interface text:
9: zsh
bin/codex
35,0-1
Bot
0:zsh*
load averages: 3.75 4.17 4.17

### Running the word-counter subagent

After launching Codex, Brian asks the word-counter subagent to analyze a tongue twister. Codex writes the agent name and query to files, then starts agent-exec.

[10:47](https://www.youtube.com/watch?v=5eJqXtevlXg&t=647s) [A terminal shows the Codex startup screen after the wrapper runs.](https://assets.ai.engineer/sites/aiecode2025/sha256/a7a77bc07bc135993937056f65d0db07ea95061092d9bee863de0465c3829034.webp)

❯ vim bin/codex
>>> elapsed time 32s

❯ bin/codex
Syncing Codex credentials to workspace...
Credentials synced to /Users/brianjohn/projects/codex-cli-subagents/tmp/codex-home
Launching Codex with parent agent configuration...

>_ OpenAI Codex (v0.55.0)

model:     gpt-5-codex    /model to change
directory: ~/projects/codex-cli-subagents

To get started, describe a task or try one of these commands:

/init - create an AGENTS.md file with instructions for Codex
/status - show current session configuration
/approvals - choose what Codex can do without approval
/model - choose what model and reasoning effort to use
/review - review any changes and find issues

❯ Implement {feature}

Interface text:
9: zsh
[11:46:29]
brianjohn@caldigit-thunderbolt-dock ~/p/codex-cli-subagents main
[11:47:04]
100% context left · ? for shortcuts
0:zsh*  load averages: 4.17 4.25 4.19

[11:09](https://www.youtube.com/watch?v=5eJqXtevlXg&t=669s) [Codex writes the subagent name and sample query to files and begins running the agent.](https://assets.ai.engineer/sites/aiecode2025/sha256/2f6d10dae81470fd5d296fe32fa6595c30b7fbd846bd163b75a8166c906aa773.webp)

/init - create an AGENTS.md file with instructions for Codex
/status - show current session configuration
/approvals - choose what Codex can do without approval
/model - choose what model and reasoning effort to use
/review - review any changes and find issues

Use the word-counter subagent to analyze this text: "How much wood would a woodchuck chuck if a woodchuck could chuck wood"

Heads up, you've used over 75% of your weekly limit. Run /status for a breakdown.

Ran echo word-counter > tmp/agent-exec/agent.txt
  (no output)

Ran cat <<'EOF' > tmp/agent-exec/query.txt
  How much wood would a woodchuck
  chuck if a woodchuck could chuck wood
  … +1 lines
  (no output)

Running agent-exec with escalated permissions (15s · esc to interrupt)

❯ Implement {feature}

Interface text:
9: zsh
100% context left · ? for shortcuts
0:zsh*  load averages: 4.47 4.31 4.22

### Approve subagent execution

Codex asks permission to run agent-exec with network access. John highlights the option to stop asking for this command on later subagent runs.

[11:14](https://www.youtube.com/watch?v=5eJqXtevlXg&t=674s) [Codex requests permission to run the subagent, with the option to stop asking for this command highlighted.](https://assets.ai.engineer/sites/aiecode2025/sha256/c2015e1b3e5e29b797d6ffb24e0f3749a720b0595c8fc0baaf707d9cf557c675.webp)

chuck if a woodchuck could chuck wood"

Heads up, you've used over 75% of your weekly limit. Run /status for a breakdown.

Ran echo word-counter > tmp/agent-exec/agent.txt
  (no output)

Ran cat <<'EOF' > tmp/agent-exec/query.txt
  How much wood would a woodchuck
  chuck if a woodchuck could chuck wood
  … +1 lines
  (no output)

Running timeout 600 bin/agent-exec

Would you like to run the following command?

Reason: Subagent requires network access to run word-counter analysis

$ timeout 600 bin/agent-exec

1. Yes, proceed
2. Yes, and don't ask again for this command
3. No, and tell Codex what to do differently esc

Press enter to confirm or esc to cancel

Interface text:
9: zsh
0:zsh*
load averages: 4.29 4.28 4.21

### Running the word-counter subagent

After session approval, Codex runs the word-counter and returns a 13-word result. Brian John notes that execution is serial; a file-writer request is entered next.

[11:24](https://www.youtube.com/watch?v=5eJqXtevlXg&t=684s) [Codex confirms approval for the command during the session and shows the subagent running.](https://assets.ai.engineer/sites/aiecode2025/sha256/331cf2f9ac6b425a39cfb4a04dd2d81121c367c5dc88a8bbb446954526471a27.webp)

chuck if a woodchuck could chuck wood"

Ran echo word-counter > tmp/agent-exec/agent.txt
  (no output)

Ran cat <<'EOF' > tmp/agent-exec/query.txt
  How much wood would a woodchuck
  chuck if a woodchuck could chuck wood
  … +1 lines
  (no output)

You approved codex to run timeout 600 bin/agent-exec every time this session
Running timeout 600 bin/agent-exec
Running agent-exec with escalated permissions (26s · esc to interrupt)

Interface text:
9: zsh
Heads up, you've used over 75% of your weekly limit. Run /status for a breakdown.
Implement {feature}
100% context left · ? for shortcuts
0:zsh*
load averages: 3.84 4.18 4.17

[11:40](https://www.youtube.com/watch?v=5eJqXtevlXg&t=700s) [Terminal shows a 13-word count result and a file-writer request being entered.](https://assets.ai.engineer/sites/aiecode2025/sha256/e484c1af029443b449c2a4507f3968e1af3ea89cec4c6d23c39e33a17be6e918.webp)

(no output)

Ran cat <<'EOF' > tmp/agent-exec/query.txt
  How much wood would a woodchuck
  chuck if a woodchuck could chuck wood
  … +1 lines
  (no output)

You approved codex to run timeout 600 bin/agent-exec every time this session

Ran timeout 600 bin/agent-exec
  ## Word Count
  - Total words: 13
  … +10 lines
  chuck if a woodchuck could chuck wood
  ```

Worked for 30s

Word-counter reports 13 total words. Top words: a, chuck, and wood with 2 occurrences each (tied with woodchuck). Original text analyzed matches what you provided.

Use the file-writer subagent to make a notes/test.txt file that says "File-writer subagent was here"

Interface text:
9: zsh
100% context left
0:zsh*
load averages: 4.00 4.21 4.18

### File-writer subagent demonstration

Codex writes the agent name and file request to separate files, then runs agent-exec with a 600-second timeout. The file-writer reports creating notes/test.txt with the requested text.

[12:31](https://www.youtube.com/watch?v=5eJqXtevlXg&t=751s) [Terminal shows a file-writer request, its prepared query, and the agent execution running.](https://assets.ai.engineer/sites/aiecode2025/sha256/0a5a5fa3937b01c3bbb8f6334966317a68c47c384bd885c7271bdcd761b14d97.webp)

Worked for 30s

Word-counter reports 13 total words. Top words: a, chuck, and wood with 2 occurrences each (tied with woodchuck). Original text analyzed matches what you provided.

Use the file-writer subagent to make a notes/test.txt file that says "File-writer subagent was here"

Ran echo file-writer > tmp/agent-exec/agent.txt
  (no output)

Ran cat <<'EOF' > tmp/agent-exec/query.txt
  Create file notes/test.txt containing exactly:
  File-writer subagent was here
  … +1 lines
  (no output)

Running timeout 600 bin/agent-exec

Preparing to run agent-exec with elevated permissions (37s · esc to interrupt)

Interface text:
9: zsh
Implement {feature}
100% context left · ? for shortcuts
0:zsh*
load averages: 4.17 4.20 4.18

[12:56](https://www.youtube.com/watch?v=5eJqXtevlXg&t=776s) [Terminal shows a file-writer subagent completing a request to create a text file.](https://assets.ai.engineer/sites/aiecode2025/sha256/a0b783ae3ed6f7fa62ea43a29ad32bb7e2bc23be1c2cf7a1854980a02211b8e6.webp)

Ran echo file-writer > tmp/agent-exec/agent.txt
  (no output)

Ran cat <<'EOF' > tmp/agent-exec/query.txt
  Create file notes/test.txt containing exactly:
  File-writer subagent was here
  … +1 lines
  (no output)

Ran timeout 600 bin/agent-exec
  - Wrote file `notes/test.txt`.
  - Absolute path: `/Users/brianjohn/projects/codex-cli-subagents/notes/test.txt`.
  … +2 lines
  File-writer subagent was here

Worked for 39s

Created notes/test.txt with “File-writer subagent was here” via the file-writer subagent. Let me know if you need more edits or additional files.

Interface text:
9: zsh
Implement {feature}
100% context left · ? for shortcuts
0:zsh*
load averages: 4.17 4.20 4.18

### Closing slide

Brian John closes with the project repository and BetterUp website.

[13:07](https://www.youtube.com/watch?v=5eJqXtevlXg&t=787s) [Closing slide lists the project repository and presenter contact options above a BetterUp logo.](https://assets.ai.engineer/sites/aiecode2025/sha256/1f58ba31de9ee1776968ea73c3cb494de72e07265517cace491440d895aff4c1.webp)

That’s it!

• https://github.com/betterup/codex-cli-subagents

• https://betterup.com
• [redacted]
• [redacted] on X

BetterUp

## Full transcript

[0:02](https://www.youtube.com/watch?v=5eJqXtevlXg&t=2s) Hi, everybody. My name is Brian John, and I'm excited today to talk to you about hacking subagents into Codex CLI. So who am I?

[0:12](https://www.youtube.com/watch?v=5eJqXtevlXg&t=12s) I'm a principal full stack engineer. My current focus at work is AI enablement for R&D, so think helping our R&D team members get their work done faster and with higher quality using AI.

[0:25](https://www.youtube.com/watch?v=5eJqXtevlXg&t=25s) The company I work for is BetterUp. It's an awesome place to work. We've been using AI since the very beginning. I've been there for over eight years now, which is longer than any place I've ever worked before.

[0:36](https://www.youtube.com/watch?v=5eJqXtevlXg&t=36s) And our mission is to help people everywhere live their lives with better purpose, clarity, and passion. If that sounds interesting to you, and you work on-- wanna work on cool stuff with LLMs,

[0:47](https://www.youtube.com/watch?v=5eJqXtevlXg&t=47s) please hit me up. I'll have my contact info in the last slide.

[0:52](https://www.youtube.com/watch?v=5eJqXtevlXg&t=52s) So why would we wanna hack subagents into Codex CLI?

[0:59](https://www.youtube.com/watch?v=5eJqXtevlXg&t=59s) Well, I've been using Claude Code as my daily driver since the very beginning.

[1:04](https://www.youtube.com/watch?v=5eJqXtevlXg&t=64s) It's a great tool. It's got tons of bells and whistles. It's got great models,

[1:10](https://www.youtube.com/watch?v=5eJqXtevlXg&t=70s) and I use subagents all the time. But I don't wanna be locked into one tool, and I really don't wanna be locked into one model family.

[1:19](https://www.youtube.com/watch?v=5eJqXtevlXg&t=79s) I wanted to be able to use other tools, particularly Codex CLI, because the models look really good,

[1:27](https://www.youtube.com/watch?v=5eJqXtevlXg&t=87s) and I wanna be able to still use subagents with them so that I can use my workflows with other tools.

[1:35](https://www.youtube.com/watch?v=5eJqXtevlXg&t=95s) Context management. So as you all know, subagents are amazing for context management. The main agent can give a problem to a subagent. It can go off, do its work, use its tokens, and pass just the answer back to the main agent.

[1:51](https://www.youtube.com/watch?v=5eJqXtevlXg&t=111s) And all that context that got used up by the subagent doesn't end up in your main context window, which is incredible. [chuckles]

[2:01](https://www.youtube.com/watch?v=5eJqXtevlXg&t=121s) And I don't think I have to say any more about this one. We've all seen this way too many times, and it gets annoying. And I have to give credit where credit is due.

[2:09](https://www.youtube.com/watch?v=5eJqXtevlXg&t=129s) This talk by Dex Horthy changed the way that I work with AI.

[2:16](https://www.youtube.com/watch?v=5eJqXtevlXg&t=136s) The workflows he proposes here I found to be really effective, especially in working with large code bases. I'd recommend you check out this talk. He's also talking at AI Engineer Code this year, and I recommend you check out that one too, `cause I'm sure it's gonna be great.

[2:36](https://www.youtube.com/watch?v=5eJqXtevlXg&t=156s) All right. So let's talk about design. At the end of the day, a subagent is really simple. It's just another instance of the main agent. So our design can also be really simple.

[2:49](https://www.youtube.com/watch?v=5eJqXtevlXg&t=169s) In this case, we're gonna have our parent Codex session. We're gonna have it run a script. It's just gonna be a wrapper script that's gonna kinda take care of, like, figuring out what agent to run.

[3:00](https://www.youtube.com/watch?v=5eJqXtevlXg&t=180s) It's gonna build the prompt, et cetera. And it's gonna kick off codex exec, so that child Codex is gonna run as the subagent. It's gonna respond to the prompt.

[3:09](https://www.youtube.com/watch?v=5eJqXtevlXg&t=189s) It's gonna do its work, and it's gonna write its answer into a file. And then our wrapper script is gonna read that file, and it's gonna print that result to standard out and give it back to the parent Cod- Codex session.

[3:22](https://www.youtube.com/watch?v=5eJqXtevlXg&t=202s) Pretty straightforward. Well, this is simple, so it should be easy, right? Well, that's what I thought too. And I started to get all these errors from Codex when I tried it.

[3:36](https://www.youtube.com/watch?v=5eJqXtevlXg&t=216s) Codex's sandbox really seems to not wanna let you do this. Now, you can of course run it with dangerously skip permissions or whatever. I don't do that.

[3:47](https://www.youtube.com/watch?v=5eJqXtevlXg&t=227s) But to get it to work with a normal set of permissions actually was really, really hard, and I banged my head against the wall a long time trying to get this to work.

[3:59](https://www.youtube.com/watch?v=5eJqXtevlXg&t=239s) So figuring out the minimum required permissions is probably the hardest part about this, getting the combination just right. On the parent, you need at least --sandbox workspace-write to be able to run the Codex command.

[4:12](https://www.youtube.com/watch?v=5eJqXtevlXg&t=252s) You can always run that dangerously whatever, whatever command if you want. Again, I don't really do that. The child process is a little bit trickier. The sandbox prevents its access to the OpenAI credentials in your home directory since it's outside of the workspace.

[4:30](https://www.youtube.com/watch?v=5eJqXtevlXg&t=270s) The... You need at least --sandbox workspace-write again so that it can write the file that the, uh, wrapper script is gonna read. And you need to, to disable this thing called the rollout recorder,

[4:44](https://www.youtube.com/watch?v=5eJqXtevlXg&t=284s) which is like a logging thing. The-- Just because the parent sandbox, again, it prevents file system access to any subcommands that are outside of the workspace.

[5:00](https://www.youtube.com/watch?v=5eJqXtevlXg&t=300s) All right. Before we go any further, I have to give a quick note about security.

[5:06](https://www.youtube.com/watch?v=5eJqXtevlXg&t=306s) Meta recently wrote a great paper called "The Agent's Rule of Two" that I think explains this really, really well. And what it says is there's three things you need to care about with your agent when it comes to security:

[5:17](https://www.youtube.com/watch?v=5eJqXtevlXg&t=317s) whether it's processing untrustworthy input, whether it has access to sensitive systems or private data, and whether it can change state or communicate externally.

[5:27](https://www.youtube.com/watch?v=5eJqXtevlXg&t=327s) In our case, we're not processing untrustworthy inputs. We do have access to sensitive systems or private data because we're probably working with a proprietary code base.

[5:39](https://www.youtube.com/watch?v=5eJqXtevlXg&t=339s) And it can change state, and it also can, can communicate externally. Now, the state that it can change is really kinda dependent on your system. In my case, it's really not very high risk, and the communication it does externally is just to OpenAI's API endpoint.

[5:56](https://www.youtube.com/watch?v=5eJqXtevlXg&t=356s) So again, not a major risk, I would say, so that puts us in the lower risk category. But importantly, lower risk does not mean no risk. So your mileage may vary here You need to make your own determination on if this is something you feel comfortable with.

[6:14](https://www.youtube.com/watch?v=5eJqXtevlXg&t=374s) And with that, let's move forward. All right, so to get Codex to be able to use subagents with this wrapper script and everything, we have to tell it how to run them.

[6:26](https://www.youtube.com/watch?v=5eJqXtevlXg&t=386s) So in our AGENTS.md, we're gonna have just a little bit of information here that tells Codex, "Hey, when I say use the whatever subagent, go and actually, like, run this script and, you know, with these commands or whatever," and that's how you do it.

[6:47](https://www.youtube.com/watch?v=5eJqXtevlXg&t=407s) Also, we have to tell it when to run subagents. So that would be, you know, when the user asks or just when you think it'd be helpful. And then we wanna tell it what subagents are available and what they do.

[7:04](https://www.youtube.com/watch?v=5eJqXtevlXg&t=424s) All right. With that, let's do a quick demo.

[7:10](https://www.youtube.com/watch?v=5eJqXtevlXg&t=430s) I've put together a really quick and small proof of concept repository. It's open source, so you can go and take a look at it yourself. I'll have the URL at the end of the talk.

[7:21](https://www.youtube.com/watch?v=5eJqXtevlXg&t=441s) Let's just take a look at what's in here.

[7:24](https://www.youtube.com/watch?v=5eJqXtevlXg&t=444s) So first of all, let's take a look at our agents.

[7:28](https://www.youtube.com/watch?v=5eJqXtevlXg&t=448s) I just created a couple of toy agents here. Let's go take a look at them. They're defined.

[7:35](https://www.youtube.com/watch?v=5eJqXtevlXg&t=455s) You can see here each agent has a name. It also has a reasoning effort. So depending on what kind of work it's doing, you can give it a light, medium, you can give it a high reasoning effort, whatever you think is appropriate.

[7:49](https://www.youtube.com/watch?v=5eJqXtevlXg&t=469s) Then you just give it, you know, the prompt for the agent, so very similar to kinda how Claude Code subagents work. In this case, it's just counting words. You know, this other one is a file writer agent.

[8:00](https://www.youtube.com/watch?v=5eJqXtevlXg&t=480s) Just gonna take some text and put it in a file. Don't need much reasoning for that.

[8:07](https://www.youtube.com/watch?v=5eJqXtevlXg&t=487s) All right. So now let's look at our wrapper script.

[8:15](https://www.youtube.com/watch?v=5eJqXtevlXg&t=495s) It's really small, only 72 lines. Basically just takes in the inputs.

[8:24](https://www.youtube.com/watch?v=5eJqXtevlXg&t=504s) It's gonna call this AgentExecutor Python class, which I'll show in just a minute, also very small, and it's gonna return that, uh,

[8:33](https://www.youtube.com/watch?v=5eJqXtevlXg&t=513s) the agent's output to standard out so that the main agent can see it. Let's look at that AgentExecutor class.

[8:42](https://www.youtube.com/watch?v=5eJqXtevlXg&t=522s) Not gonna go through this whole thing. Again, it's pretty small. Basically just kicks off the child subagent with the proper permissions and with the right reasoning effort,

[8:53](https://www.youtube.com/watch?v=5eJqXtevlXg&t=533s) and it disables the rollout recorder, all that kind of stuff. Just does all that for you, so pretty handy. One thing that I think I didn't cover, if you look at AGENTS.md,

[9:05](https://www.youtube.com/watch?v=5eJqXtevlXg&t=545s) is, it's kind of important here, is this part. So when we're telling Codex how to invoke the subagent, we're gonna have it write the agent name to a file, we're gonna have it write the user's query to a file, and then we're gonna have it run this command.

[9:22](https://www.youtube.com/watch?v=5eJqXtevlXg&t=562s) You know, another alternative to this would be to actually pass the agent name and the query as command arguments. The reason why we don't wanna do that is because of Codex's permissioning system.

[9:36](https://www.youtube.com/watch?v=5eJqXtevlXg&t=576s) As long as the command looks exactly the same,

[9:39](https://www.youtube.com/watch?v=5eJqXtevlXg&t=579s) you only have to grant permission once. But if you have different arguments to the command, you have to approve it every time.

[9:48](https://www.youtube.com/watch?v=5eJqXtevlXg&t=588s) So it gets really annoying if you have to approve every time the C- Codex wants to call a subagent.

[9:57](https://www.youtube.com/watch?v=5eJqXtevlXg&t=597s) So in this case, we make the command look exactly the same. Codex is just gonna run it.

[10:03](https://www.youtube.com/watch?v=5eJqXtevlXg&t=603s) Now, if you run, again, with dangerously skip permissions or whatever, you don't have to worry about this.

[10:09](https://www.youtube.com/watch?v=5eJqXtevlXg&t=609s) But all right, let's go in. Oh, then we've got this also is wrapper script around Codex, so let's take a look at that real quick. Super simple. Uh, what it does is it takes the Codex home files from your home directory, it's gonna sync them into a subdirectory so it has access to them, and it's gonna set

[10:25](https://www.youtube.com/watch?v=5eJqXtevlXg&t=625s) CODEX_HOME to that directory, then it's just gonna launch Codex. In this case, I'm launching it in --full-auto mode, which is just, like, shorthand for workspace-write plus, I think, approval on a request or something like that.

[10:37](https://www.youtube.com/watch?v=5eJqXtevlXg&t=637s) I can't remember which one. Um, but pretty straightforward. Not much going on here. Really not much code.

[10:45](https://www.youtube.com/watch?v=5eJqXtevlXg&t=645s) All right, let's go ahead and launch this.

[10:50](https://www.youtube.com/watch?v=5eJqXtevlXg&t=650s) Okay. Now let's just give it just a quick

[10:55](https://www.youtube.com/watch?v=5eJqXtevlXg&t=655s) query. I'm gonna tell it to use its word counter subagent,

[10:59](https://www.youtube.com/watch?v=5eJqXtevlXg&t=659s) have it go off and do that. You're gonna see it

[11:06](https://www.youtube.com/watch?v=5eJqXtevlXg&t=666s) figure out that it needs to run this AgentExec. It's gonna go ahead and put the name of the agent in a file, it's gonna put the query in a file, then it's gonna ask me for permissions to run it, and it's really important here that I say yes and don't ask again for this command.

[11:20](https://www.youtube.com/watch?v=5eJqXtevlXg&t=680s) That way, it's not gonna ask me every time it has to run a subagent.

[11:26](https://www.youtube.com/watch?v=5eJqXtevlXg&t=686s) You'll notice that it's running everything in serial here. Codex does not have the ability to run things asynchronously like Claude does, so this is slower. And Codex in general, if you've used it, I think you'd find it's slower overall than Ch- than Claude Code, but I think that's really kind of intentional.

[11:47](https://www.youtube.com/watch?v=5eJqXtevlXg&t=707s) Seems like Codex is really kind of meant to be more of, like, a hands-off unattended type of a tool versus Claude Code is meant to be more kind of iterative.

[11:56](https://www.youtube.com/watch?v=5eJqXtevlXg&t=716s) And so, you know, I think that's actually okay. I found this okay for me the way that I've used Codex. All right. So we can see we got that result back, printed to standard out here, and then

[12:09](https://www.youtube.com/watch?v=5eJqXtevlXg&t=729s) Codex just gave us back the answer. So let's just do one more with this file writer subagent.

[12:18](https://www.youtube.com/watch?v=5eJqXtevlXg&t=738s) Again, it's gonna do the same thing. It's gonna write that agent name into a file. It's gonna write the query into a file. Then it's gonna call that same command.

[12:29](https://www.youtube.com/watch?v=5eJqXtevlXg&t=749s) It will not ask for permissions this time.

[12:34](https://www.youtube.com/watch?v=5eJqXtevlXg&t=754s) Oh, and we're using the timeout 600 here because some of these agents can actually take a long time to run. If you're having to do a big task that's gonna have it look across a whole code base and you have a large code base, it can take up to 10 minutes.

[12:48](https://www.youtube.com/watch?v=5eJqXtevlXg&t=768s) I've actually seen them take longer, up to 20 minutes sometimes, so you might even want a longer timeout here. This is what I've set for this example. In this case, this is a pretty easy one, so it only took about 40 seconds.

[13:01](https://www.youtube.com/watch?v=5eJqXtevlXg&t=781s) All right, so it wrote the file. Just go ahead and verify that.

[13:06](https://www.youtube.com/watch?v=5eJqXtevlXg&t=786s) All right. All right. That's all I have. The-- You can find the code at that URL.

[13:14](https://www.youtube.com/watch?v=5eJqXtevlXg&t=794s) You can find BetterUp at betterup.com. If you have any questions for me, you can use my email address, or you can DM me on X. I don't post anything on X, so really no reason to follow me, but go ahead if you want.

[13:28](https://www.youtube.com/watch?v=5eJqXtevlXg&t=808s) And I hope this was helpful for you. And again, if BetterUp sounds like an interesting place to you, please hit me up. Have a great day.
