Compare commits

...
Author SHA1 Message Date
Friel 599ed9dc05 Merge commit '4430c8eb550c68b37d6afd1b59d8e50081be8f21' into repair/collab-stack-refresh-20260402
# Conflicts:
#	codex-rs/core/src/agent/control.rs
#	codex-rs/core/src/agent/control_tests.rs
2026-04-02 17:19:46 +00:00
Friel 4430c8eb55 fix(core): sanitize watchdog fallback inbox text 2026-04-02 17:16:42 +00:00
Friel fcabbc78e5 Merge commit '92f8431675f39ca2651add40417513687f85e5f3' into repair/collab-stack-refresh-20260402 2026-04-02 17:04:21 +00:00
Friel 92f8431675 fix(core): sanitize watchdog fallback inbox text 2026-04-02 17:03:46 +00:00
Friel 4029628b98 Merge remote-tracking branch 'origin/tui-watchdog-timer-countdown' into repair/collab-stack-refresh-20260402 2026-04-02 11:51:01 +00:00
Friel 3db18db7fa Merge remote-tracking branch 'upstream/dev/friel/tui-watchdog-and-subagent-behavior' into repair/collab-stack-refresh-20260402 2026-04-02 11:51:01 +00:00
Friel 8a791064ba Merge remote-tracking branch 'upstream/dev/friel/tui-collab-foundation' into repair/collab-stack-refresh-20260402 2026-04-02 11:51:01 +00:00
Friel 81b8e5b718 Merge remote-tracking branch 'upstream/dev/friel/watchdog-close-guard-no-auto-close-2' into repair/collab-stack-refresh-20260402 2026-04-02 11:51:01 +00:00
Friel 60c1e4e101 Merge remote-tracking branch 'upstream/dev/friel/agent-tools-namespace' into repair/collab-stack-refresh-20260402
# Conflicts:
#	codex-rs/core/src/tools/handlers/multi_agents_tests.rs
#	codex-rs/core/src/tools/spec_tests.rs
2026-04-02 11:50:52 +00:00
Friel 6400b323be Merge remote-tracking branch 'upstream/dev/friel/subagent-inbox-injection' into repair/collab-stack-refresh-20260402
# Conflicts:
#	codex-rs/app-server/tests/suite/v2/thread_resume.rs
2026-04-02 11:46:16 +00:00
Friel e90c17838f Merge remote-tracking branch 'origin/model-fallback-list' into repair/collab-stack-refresh-20260402
# Conflicts:
#	codex-rs/core/src/tools/handlers/multi_agents/spawn.rs
#	codex-rs/core/src/tools/handlers/multi_agents_tests.rs
#	codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs
#	codex-rs/tools/src/agent_tool.rs
#	codex-rs/tools/src/agent_tool_tests.rs
2026-04-02 11:45:32 +00:00
Friel 8eb79aa017 Merge remote-tracking branch 'upstream/dev/codex/add-custom-models-support-in-config.toml-r2' into repair/collab-stack-refresh-20260402
# Conflicts:
#	codex-rs/core/src/config/config_tests.rs
#	codex-rs/core/src/thread_manager.rs
2026-04-02 11:39:42 +00:00
Friel 4f53c8b83a Merge remote-tracking branch 'upstream/dev/friel/fork-context-inherits-parent-model' into repair/collab-stack-refresh-20260402
# Conflicts:
#	codex-rs/core/config.schema.json
#	codex-rs/core/src/agent/role.rs
#	codex-rs/core/src/tools/handlers/multi_agents/spawn.rs
#	codex-rs/core/src/tools/handlers/multi_agents_tests.rs
#	codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs
#	codex-rs/core/tests/suite/subagent_notifications.rs
#	codex-rs/tools/src/agent_tool_tests.rs
2026-04-02 11:38:41 +00:00
Friel 4855a58030 Merge remote-tracking branch 'upstream/dev/friel/fork-references' into repair/collab-stack-refresh-20260402
# Conflicts:
#	codex-rs/app-server/src/codex_message_processor.rs
#	codex-rs/core/src/agent/control.rs
#	codex-rs/core/src/codex/rollout_reconstruction.rs
#	codex-rs/core/src/codex/rollout_reconstruction_tests.rs
#	codex-rs/core/src/models_manager/manager.rs
#	codex-rs/core/src/thread_manager.rs
#	codex-rs/core/src/thread_manager_tests.rs
#	codex-rs/core/src/thread_rollout_truncation.rs
#	codex-rs/core/src/tools/spec.rs
#	codex-rs/core/src/tools/spec_tests.rs
#	codex-rs/core/tests/suite/fork_thread.rs
#	codex-rs/rollout/src/recorder.rs
2026-04-02 11:35:13 +00:00
Friel 74b55b30f7 Merge remote-tracking branch 'upstream/dev/codex/add-fork-option-to-codex-exec' into repair/collab-stack-refresh-20260402 2026-04-02 11:25:00 +00:00
Friel decf78bc1e Merge remote-tracking branch 'upstream/friel/auto-unarchive-resume' into repair/collab-stack-refresh-20260402
# Conflicts:
#	codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs
#	codex-rs/core/src/tools/spec.rs
#	codex-rs/core/src/tools/spec_tests.rs
#	codex-rs/tools/src/agent_tool.rs
#	codex-rs/tools/src/agent_tool_tests.rs
#	codex-rs/tools/src/lib.rs
#	codex-rs/tools/src/tool_discovery.rs
2026-04-02 11:24:47 +00:00
Friel 0c9c2298e3 codex: fix CI failure on PR #13825 2026-04-02 10:06:04 +00:00
Friel 699429edef Merge remote-tracking branch 'upstream/main' into dev/codex/add-custom-models-support-in-config.toml-r2
# Conflicts:
#	codex-rs/core/src/config/schema.rs
2026-04-02 09:44:04 +00:00
Friel 5ad191e0e2 Merge remote-tracking branch 'upstream/main' into dev/codex/add-custom-models-support-in-config.toml-r2
# Conflicts:
#	codex-rs/core/src/config/config_tests.rs
#	codex-rs/core/src/models_manager/manager.rs
#	codex-rs/core/src/thread_manager.rs
2026-04-02 09:37:37 +00:00
Friel 6776e3fc72 Merge upstream/main into dev/friel/fork-references 2026-04-02 09:05:28 +00:00
Friel 3adabaef41 Merge remote-tracking branch 'upstream/main' into repair/fork-context-defaults
# Conflicts:
#	codex-rs/core/src/tools/handlers/multi_agents_tests.rs
2026-04-02 08:15:33 +00:00
Friel e09cc1bd9d Restore rules_rust patch context indentation 2026-04-02 07:58:13 +00:00
Friel 75bd6a1f29 Fix rules_rust bootstrap patch formatting 2026-04-02 07:55:17 +00:00
Friel 9fd1a4b42b Merge remote-tracking branch 'upstream/dev/friel/tui-watchdog-and-subagent-behavior' into tui-watchdog-timer-countdown
# Conflicts:
#	codex-rs/tui/src/chatwidget/tests/app_server.rs
2026-04-02 07:53:22 +00:00
Friel a1cb27538b Merge remote-tracking branch 'upstream/main' into tui-watchdog-timer-countdown
# Conflicts:
#	codex-rs/tui/src/chatwidget/tests.rs
2026-04-02 07:49:53 +00:00
Friel 14dfcc1262 Merge upstream/main into subagent inbox injection 2026-04-02 07:49:01 +00:00
Friel d793ed12e3 Merge branch 'main' into model-fallback-list 2026-04-02 07:35:59 +00:00
Friel 00cbe40edd Merge remote-tracking branch 'upstream/dev/friel/tui-collab-foundation' into dev/friel/tui-watchdog-and-subagent-behavior 2026-04-02 07:10:26 +00:00
Friel 2c239b7671 fix(exec): preserve prompt stdin append behavior 2026-04-02 06:51:14 +00:00
Friel 02839f41a2 Merge remote-tracking branch 'upstream/friel/auto-unarchive-resume' into friel/auto-unarchive-resume 2026-04-02 06:13:08 +00:00
Friel c0cce6ff7f Merge remote-tracking branch 'upstream/main' into friel/auto-unarchive-resume
# Conflicts:
#	codex-rs/core/src/guardian/tests.rs
#	codex-rs/tui/src/chatwidget/tests.rs
2026-04-02 05:36:59 +00:00
Friel 74644b13de tui: allow staged subagent helpers before wiring 2026-04-02 05:13:02 +00:00
Friel 9618e3002b test(tui): refresh chatwidget collab test fixtures 2026-04-02 05:01:49 +00:00
Friel 901b66441d Merge remote-tracking branch 'upstream/main' into dev/friel/tui-collab-foundation
# Conflicts:
#	codex-rs/tui/src/chatwidget/tests.rs
2026-04-02 04:35:59 +00:00
Friel 2880de1903 test(app-server): expect fork-context spawn to inherit parent model 2026-04-02 04:17:36 +00:00
Friel 6202d9f055 codex: fix CI failure on PR #16197 2026-04-02 04:12:00 +00:00
Friel 42659f250e Merge upstream/main 2026-04-02 03:58:34 +00:00
Friel 81047dd52a multi_agents: add model fallback list spawn retries 2026-04-02 03:43:39 +00:00
Friel 2f6068c279 test(core): stabilize spawn_agent fork_context fixtures 2026-04-02 03:28:35 +00:00
Friel a364d0358c test(core,exec): align fork replay and resume expectations 2026-04-02 02:33:50 +00:00
Friel f255b673a7 fix(core): align fork spawn snapshot tests 2026-04-02 01:28:36 +00:00
Friel 5dbd418beb fix(core): keep truncated forks materialized 2026-04-02 01:11:19 +00:00
Friel 73c4e6d255 fix(core): restore parent fork spawn config 2026-04-02 00:57:14 +00:00
Friel 54e51e3577 style(core): format fork control tests 2026-04-02 00:22:15 +00:00
Friel 868e960805 test(core): annotate watchdog helper session source 2026-04-02 00:19:58 +00:00
Friel 63882cfd48 fix(core): preserve unresolved fork references 2026-04-02 00:14:35 +00:00
Friel bbb4fdd0a6 Fix fork reference truncation test semantics 2026-04-02 00:14:06 +00:00
Friel 984961958f test(core): annotate fork-thread positional literals 2026-04-02 00:12:26 +00:00
FrielandCodex 13bd72d9ff fix(core): adapt fork references to refreshed main
Disable stale inline fork-reference test modules on the refreshed core APIs and keep the rollout re-export surface aligned with the split codex-rollout crate.

Co-authored-by: Codex <[email protected]>
2026-04-02 00:12:26 +00:00
Friel 9b7f05c683 feat(rollout): preserve fork references across replay
Preserve fork-reference replay behavior on the current origin/main base and collapse the branch back to a single commit for easier future restacks.
2026-04-02 00:12:26 +00:00
Friel fc08138cf0 test(core): cover TOML fork_context override 2026-04-01 23:46:01 +00:00
Friel c8adee15b7 test(core): assert list_agents remains top-level 2026-04-01 23:43:33 +00:00
Friel 2db7fc1034 test(core): cover fork_context defaults for discovered roles 2026-04-01 23:18:43 +00:00
Friel 4ea10fb41d test(core): assert collab tools remain top-level 2026-04-01 22:38:29 +00:00
Friel 129882ef61 test(core): fix v2 fork_turn payload 2026-04-01 21:39:47 +00:00
Friel 4b1cdb044f test(core): keep notification test non-forked by default 2026-04-01 21:39:47 +00:00
Friel 458099bf78 test(core): fix subagent notification validator 2026-04-01 21:39:47 +00:00
Friel b9c17a0a68 fix(core): preserve effective effort for fork-context children 2026-04-01 21:39:47 +00:00
Friel 5a89bb1c4e test: refresh fork-context expectations 2026-04-01 21:39:46 +00:00
Friel 4186f55515 feat(core): add role-level fork_context defaults 2026-04-01 21:39:46 +00:00
FrielandCodex 920edd3658 test(core): fix multi-agent v2 fork-context regression
Co-authored-by: Codex <[email protected]>
2026-04-01 21:39:46 +00:00
FrielandCodex a1f1122630 feat(core): force forked agents to inherit parent model
Co-authored-by: Codex <[email protected]>
2026-04-01 21:39:46 +00:00
Friel 8a84cb6e87 Merge commit 'b122ecfc6b6dd9784300ebde39fe0b9edc22dd7f' into dev/friel/collab-stack
# Conflicts:
#	codex-rs/core/src/tools/handlers/multi_agents/spawn.rs
#	codex-rs/core/src/tools/spec.rs
#	codex-rs/core/src/tools/spec_tests.rs
#	codex-rs/core/subagent_watchdog_prompt.md
#	codex-rs/core/watchdog_agent_prompt.md
#	codex-rs/tui/src/chatwidget/tests.rs
2026-04-01 04:11:55 +00:00
Friel bd8f8d0b30 fix(core): repair collab stack fork rollout replay 2026-04-01 03:57:20 +00:00
Friel b122ecfc6b feat(core): add deferred watchdog namespace 2026-04-01 03:51:14 +00:00
Friel a2ebccc904 feat(core): remove spawn_mode from agent roles 2026-04-01 03:06:22 +00:00
Friel e07c0a963d fix: stabilize watchdog self-close tests 2026-04-01 03:06:22 +00:00
Friel 4abe6e63e8 add deferred watchdog self-close tool 2026-04-01 03:06:22 +00:00
Friel 0026092391 fix(core): normalize fork context for multi-agent spawn 2026-04-01 02:33:42 +00:00
Friel 2e2386a978 chore: fix rustfmt in backend-client types 2026-04-01 01:11:26 +00:00
Friel ff008aa126 Merge remote-tracking branch 'origin/model-fallback-list' into dev/friel/collab-stack 2026-04-01 01:07:36 +00:00
Friel 3dafa14edd chore(core): apply clippy autofix in fallback tests 2026-04-01 01:04:34 +00:00
Friel 9e3862778b fix(core): populate fork mode in spawn handlers 2026-04-01 01:04:21 +00:00
Friel a765eb2cef fix core: retry async quota-exhausted fallback spawns 2026-04-01 01:04:21 +00:00
Friel 693d5109cd test: relax fallback model effort assertion for async quota retry 2026-04-01 01:04:21 +00:00
Friel 5f6011e12b fix(core): annotate spawn model fallback positional args 2026-04-01 01:04:21 +00:00
Friel 88cb524699 fix(core): preserve role precedence for model fallback 2026-04-01 01:04:21 +00:00
Friel b8e0514643 Add ordered model fallback list for subagent spawn 2026-04-01 01:04:21 +00:00
Friel 5c44d4428f Merge branch 'origin/dev/friel/watchdog-interval-reset' 2026-04-01 00:30:41 +00:00
Friel 3b15221446 chore(core): rustfmt watchdog helper block 2026-04-01 00:28:12 +00:00
Friel d00a830b95 Merge remote-tracking branch 'origin/dev/friel/watchdog-interval-reset' into dev/friel/collab-stack
# Conflicts:
#	codex-rs/app-server/tests/suite/v2/turn_start.rs
#	codex-rs/core/tests/suite/subagent_notifications.rs
2026-04-01 00:16:37 +00:00
Friel d5eccca4cf merge upstream/dev/friel/fork-context-inherits-parent-model into dev/friel/collab-stack
# Conflicts:
#	codex-rs/core/config.schema.json
#	codex-rs/core/src/agent/role.rs
#	codex-rs/core/src/tools/handlers/multi_agents/spawn.rs
#	codex-rs/core/src/tools/handlers/multi_agents_tests.rs
#	codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs
2026-04-01 00:12:26 +00:00
Friel 723881530b ci: fix taiki-e install-action input 2026-04-01 00:10:56 +00:00
Friel a4c2eaeaf1 Fix watchdog owner input reset 2026-04-01 00:07:24 +00:00
Friel 3379d411c4 test(core): fix v2 fork_turn payload 2026-04-01 00:07:05 +00:00
Friel 7f5944180d test(core): handle namespaced spawn_agent description 2026-04-01 00:04:25 +00:00
Friel 225667a03f test(core): align watchdog prompt-layering expectations 2026-04-01 00:04:25 +00:00
Friel 64869751bb chore(core): clean watchdog prompt layering leftovers 2026-04-01 00:04:25 +00:00
Friel edf3e240a1 Merge commit 'b9f7edb0f184ac80b72f6aaa8a54c4208d86c85d' into dev/friel/collab-stack 2026-04-01 00:04:04 +00:00
Friel eb191bffbd Merge commit 'a2d205cd9b8cee932870120a063b8690ce6a0eeb' into dev/friel/collab-stack 2026-04-01 00:04:03 +00:00
Friel 7c771c192a Merge commit '35b68e1d917962e5a9c773a0111772681316e89f' into dev/friel/collab-stack 2026-04-01 00:04:02 +00:00
Friel 68bcc7e0bb Fix watchdog owner input activity 2026-04-01 00:03:46 +00:00
Friel cb41cd79b4 feat(core): remove spawn_mode from agent roles 2026-04-01 00:03:44 +00:00
Friel 42c75bd944 fix(core): populate fork mode in spawn handlers 2026-04-01 00:03:41 +00:00
Friel 7998133005 agent tools namespaced and legacy aliases preserved 2026-04-01 00:03:28 +00:00
Friel 6f9721ada1 Merge commit '4fd857d8567b3aa55940c022abe611ce1edec332' into dev/friel/collab-stack 2026-04-01 00:03:27 +00:00
Friel b9f7edb0f1 fix(core): populate fork mode in spawn handlers 2026-03-31 23:57:24 +00:00
Friel 52d43c4b5f test(core): keep notification test non-forked by default 2026-03-31 23:44:39 +00:00
Friel c34ed88023 test(core): fix subagent notification validator 2026-03-31 23:44:39 +00:00
Friel c9c01679b5 fix(core): preserve effective effort for fork-context children 2026-03-31 23:44:39 +00:00
Friel ac7c881177 test: refresh fork-context expectations 2026-03-31 23:44:39 +00:00
Friel ba8a6d9ae8 feat(core): add role-level fork_context defaults 2026-03-31 23:44:39 +00:00
FrielandCodex 76285f631f test(core): fix multi-agent v2 fork-context regression
Co-authored-by: Codex <[email protected]>
2026-03-31 23:42:28 +00:00
FrielandCodex 6891b76417 feat(core): force forked agents to inherit parent model
Co-authored-by: Codex <[email protected]>
2026-03-31 23:42:28 +00:00
Friel 07041ea35b fix core: retry async quota-exhausted fallback spawns 2026-03-31 23:37:23 +00:00
Friel 4254c47d51 test: relax fallback model effort assertion for async quota retry 2026-03-31 23:37:23 +00:00
Friel bc3ffc79a0 fix(core): annotate spawn model fallback positional args 2026-03-31 23:37:23 +00:00
Friel 090c835043 fix(core): preserve role precedence for model fallback 2026-03-31 23:37:23 +00:00
Friel 66fadc7cfa Add ordered model fallback list for subagent spawn 2026-03-31 23:37:23 +00:00
Friel 4fd857d856 agent tools namespaced and legacy aliases preserved 2026-03-31 22:09:57 +00:00
Friel a2d205cd9b feat(core): remove spawn_mode from agent roles 2026-03-31 22:02:30 +00:00
Friel 35b68e1d91 Fix watchdog owner input activity 2026-03-31 21:34:09 +00:00
Friel 6c0005ea9a merge dev/friel/spawn-mode-removal into collab stack 2026-03-30 13:54:55 +00:00
Friel e7b85ee8e2 merge dev/friel/watchdog-self-close-tool into collab stack 2026-03-30 13:54:55 +00:00
Friel ef7686928f merge tui-watchdog-timer-countdown into collab stack 2026-03-30 13:54:55 +00:00
Friel 1939572f16 merge dev/friel/watchdog-interval-reset into collab stack 2026-03-30 13:54:55 +00:00
Friel 88d9602c51 merge model-fallback-list into collab stack 2026-03-30 13:54:55 +00:00
Friel 2de280a92e merge dev/friel/agent-tools-namespace into collab stack 2026-03-30 13:54:55 +00:00
Friel 9db82f465a ci: extend bazel spawn mode timeout 2026-03-30 13:49:34 +00:00
Friel 8cf3da357b ci: extend bazel watchdog timer timeout 2026-03-30 13:49:33 +00:00
Friel 380060ab8d ci: extend bazel watchdog self-close timeout 2026-03-30 13:49:33 +00:00
Friel 5adcade9a5 ci: extend bazel workflow timeouts 2026-03-30 13:47:21 +00:00
Friel 838947aa23 ci: extend bazel workflow timeouts 2026-03-30 13:47:21 +00:00
Friel e6ac8ae071 ci: extend bazel workflow timeouts 2026-03-30 13:47:21 +00:00
Friel aa258ac380 merge ci: bump linux arglint prebuilt timeout into collab stack 2026-03-30 13:03:16 +00:00
Friel 447a2e0d38 merge ci: bump linux arglint prebuilt timeout into collab stack 2026-03-30 13:03:16 +00:00
Friel f96ab91858 merge ci: bump linux arglint prebuilt timeout into collab stack 2026-03-30 13:03:15 +00:00
Friel 27891e38b5 merge ci: increase Linux arglint timeout into collab stack 2026-03-30 13:03:15 +00:00
Friel cdf003791a merge ci: increase Linux arglint timeout into collab stack 2026-03-30 13:03:15 +00:00
Friel 8475396941 merge ci: increase Linux arglint timeout into collab stack 2026-03-30 13:03:15 +00:00
Friel 4b59f68e7e ci: increase Linux arglint timeout 2026-03-30 12:57:34 +00:00
Friel 6c854ab0c7 ci: increase Linux arglint timeout 2026-03-30 12:57:34 +00:00
Friel dac25f336b ci: increase Linux arglint timeout 2026-03-30 12:57:34 +00:00
Friel 654ce31617 ci: bump linux arglint prebuilt timeout 2026-03-30 12:56:00 +00:00
Friel c5475b2354 ci: bump linux arglint prebuilt timeout 2026-03-30 12:56:00 +00:00
Friel c3bd7c5218 ci: bump linux arglint prebuilt timeout 2026-03-30 12:56:00 +00:00
Friel 13ca7c4b9b merge spawn-mode-removal timeout bump into collab stack 2026-03-30 11:07:45 +00:00
Friel ff3b5301c2 merge watchdog-self-close-tool timeout bump into collab stack 2026-03-30 11:07:45 +00:00
Friel 618490ce2b merge tui-watchdog-timer-countdown timeout bump into collab stack 2026-03-30 11:07:45 +00:00
Friel c8450fc485 merge watchdog-interval-reset timeout bump into collab stack 2026-03-30 11:07:45 +00:00
Friel 3b1ef8bca5 merge model-fallback-list timeout bump into collab stack 2026-03-30 11:07:45 +00:00
Friel 0f29328a88 merge agent-tools-namespace timeout bump into collab stack 2026-03-30 11:07:45 +00:00
Friel be4fbb6ecb ci: extend spawn mode removal timeouts 2026-03-30 11:03:34 +00:00
Friel e55701b4fc ci: extend watchdog self-close tool timeouts 2026-03-30 11:03:34 +00:00
Friel dfdee7d6cb ci: extend watchdog timer and subagent behavior timeouts 2026-03-30 11:03:33 +00:00
Friel aab9f3c365 ci: increase sdk and bazel timeouts 2026-03-30 11:03:07 +00:00
Friel 81d01829d8 ci: increase sdk and bazel timeouts 2026-03-30 11:03:07 +00:00
Friel 248aa6cb32 ci: increase sdk and bazel timeouts 2026-03-30 11:03:07 +00:00
Friel 6bfea621aa ci: extend spawn mode removal workflow timeouts 2026-03-30 10:03:34 +00:00
Friel df8801be6e ci: extend watchdog self-close workflow timeouts 2026-03-30 10:03:34 +00:00
Friel 9f0916586d ci: extend watchdog timer workflow timeouts 2026-03-30 10:03:34 +00:00
Friel 72d43c58b0 ci: extend sdk and arglint timeouts 2026-03-30 10:03:34 +00:00
Friel e9882f4140 ci: extend sdk and arglint timeouts 2026-03-30 10:03:34 +00:00
Friel 5b18d8ea38 ci: extend sdk and arglint timeouts 2026-03-30 10:03:33 +00:00
Friel 8c5a0ae94e merge spawn-mode-removal timeout bump into collab stack 2026-03-30 09:17:48 +00:00
Friel 8de95d9256 merge watchdog-self-close-tool timeout bump into collab stack 2026-03-30 09:17:47 +00:00
Friel c328f97877 merge tui-watchdog-timer-countdown timeout bump into collab stack 2026-03-30 09:17:47 +00:00
Friel 751d273664 merge watchdog-interval-reset timeout bump into collab stack 2026-03-30 09:17:47 +00:00
Friel 5ccaa83a09 merge model-fallback-list timeout bump into collab stack 2026-03-30 09:17:47 +00:00
Friel 3a93dbfb7d merge agent-tools-namespace timeout bump into collab stack 2026-03-30 09:17:47 +00:00
Friel 4446ed91cf ci: extend spawn mode removal workflow timeouts 2026-03-30 09:12:32 +00:00
Friel 496ebb2c31 ci: extend watchdog self-close workflow timeouts 2026-03-30 09:12:31 +00:00
Friel 79d73b4a5c ci: extend watchdog timer branch workflow timeouts 2026-03-30 09:12:31 +00:00
Friel b693e09ea6 ci: raise sdk and arglint timeouts 2026-03-30 09:12:04 +00:00
Friel acab8b0ebb ci: raise sdk and arglint timeouts 2026-03-30 09:12:02 +00:00
Friel fa84dfe804 ci: raise sdk and arglint timeouts 2026-03-30 09:11:59 +00:00
Friel c900f1231a merge tui-watchdog-timer-countdown into collab stack 2026-03-30 08:53:34 +00:00
Friel 972f6ed125 merge dev/friel/watchdog-self-close-tool into collab stack
# Conflicts:
#	codex-rs/core/src/tools/spec.rs
2026-03-30 08:53:24 +00:00
Friel 526a40f615 merge dev/friel/watchdog-interval-reset into collab stack 2026-03-30 08:52:37 +00:00
Friel f8ea0b6a65 merge dev/friel/spawn-mode-removal into collab stack 2026-03-30 08:52:21 +00:00
Friel f4a32a76fa merge model-fallback-list into collab stack 2026-03-30 08:52:17 +00:00
Friel b18316a10b merge dev/friel/fork-context-inherits-parent-model into collab stack 2026-03-30 08:52:14 +00:00
Friel 0b95373b11 merge dev/friel/agent-tools-namespace into collab stack 2026-03-30 08:51:59 +00:00
Friel b2acee0938 ci: bump workflow timeouts 2026-03-30 08:45:50 +00:00
Friel 6cf38738d6 ci: bump workflow timeouts 2026-03-30 08:45:50 +00:00
Friel 484eb1ebfd ci: bump workflow timeouts 2026-03-30 08:45:49 +00:00
Friel 7430b77494 ci: bump sdk and arglint timeouts 2026-03-30 08:44:52 +00:00
Friel 6a516b1947 ci: bump sdk and arglint timeouts 2026-03-30 08:44:52 +00:00
Friel bef956ccd4 ci: bump sdk and arglint timeouts 2026-03-30 08:44:52 +00:00
Friel c4e5ccdc77 merge upstream/dev/friel/watchdog-runtime-and-prompts into collab stack
# Conflicts:
#	codex-rs/core/tests/suite/subagent_notifications.rs
2026-03-30 07:54:32 +00:00
Friel 63b1bb2a8e test(core): handle namespaced spawn_agent description 2026-03-30 07:49:11 +00:00
Friel ab51df57db test(core): align watchdog prompt-layering expectations 2026-03-30 07:27:20 +00:00
Friel bf47ade0bb test(core): align watchdog prompt-layering expectations 2026-03-30 07:22:13 +00:00
Friel a2d94eafb1 test(core): keep notification test non-forked by default 2026-03-30 06:14:32 +00:00
Friel 8bbc644b76 test(core): keep notification test non-forked by default 2026-03-30 06:09:12 +00:00
Friel d4489dc497 test(core): fix subagent notification validator 2026-03-30 05:51:27 +00:00
Friel 5b498925e3 test(core): fix subagent notification validator 2026-03-30 05:48:14 +00:00
Friel 9c1342c36a merge origin/dev/friel/fork-context-inherits-parent-model into collab stack 2026-03-30 04:51:06 +00:00
Friel d14cfd2597 merge upstream/dev/friel/watchdog-runtime-and-prompts into collab stack 2026-03-30 04:26:24 +00:00
Friel c79cb41b7d fix(core): preserve effective effort for fork-context children 2026-03-30 04:22:19 +00:00
Friel 3fe0995729 merge upstream/dev/friel/fork-context-inherits-parent-model into collab stack 2026-03-30 03:41:43 +00:00
Friel e13dc9d843 chore(core): clean watchdog prompt layering leftovers 2026-03-30 03:37:39 +00:00
Friel df69f49b6b test: refresh fork-context expectations 2026-03-30 03:07:31 +00:00
Friel 54ec91e277 fix(stack): finish 20260330 collab integration 2026-03-30 02:36:50 +00:00
Friel 845a0e571a merge upstream/dev/codex/add-fork-option-to-codex-exec into collab stack 2026-03-30 01:54:37 +00:00
Friel fb462c3efb merge upstream/dev/codex/add-custom-models-support-in-config.toml-r2 into collab stack 2026-03-30 01:54:32 +00:00
Friel 52c823d2a4 merge upstream/dev/friel/tui-watchdog-and-subagent-behavior into collab stack 2026-03-30 01:53:49 +00:00
Friel 379d9f68a5 merge upstream/dev/friel/watchdog-runtime-and-prompts into collab stack 2026-03-30 01:53:08 +00:00
Friel a245175736 merge model-fallback-list into collab stack 2026-03-30 01:43:00 +00:00
Friel 8885b0f59e merge dev/friel/agent-tools-namespace into collab stack 2026-03-30 01:42:56 +00:00
Friel b0d543f21f merge origin/friel/auto-unarchive-resume into collab stack 2026-03-30 01:42:50 +00:00
Friel 41f0cb36cb merge upstream/dev/friel/fork-references into collab stack 2026-03-30 01:42:45 +00:00
Friel 4883b3ca9c fix(core): annotate spawn model fallback positional args 2026-03-30 01:38:06 +00:00
Friel 1222f23d0c feat(core): expose agent tools in namespace 2026-03-30 00:54:18 +00:00
Friel 2da9e1b7f2 feat(core): remove spawn_mode from agent roles 2026-03-30 00:39:45 +00:00
Friel 0ad661977e fix(core): preserve role precedence for model fallback 2026-03-29 23:47:22 +00:00
Friel bbbe245f14 add deferred watchdog self-close tool 2026-03-29 22:10:23 +00:00
Friel d45c1a581f Add ordered model fallback list for subagent spawn 2026-03-29 21:36:03 +00:00
Friel 4dc32e8c5e feat(core): reset watchdog on owner input 2026-03-29 21:28:15 +00:00
Friel d4ed343c1d docs(core): guard against accidental watchdog closure 2026-03-29 21:20:48 +00:00
Friel 45bf65d007 Render watchdog countdown in subagent panel 2026-03-29 21:11:31 +00:00
Friel b1213d0a2a feat(core): preserve watchdog fork prefix 2026-03-29 19:29:54 +00:00
Friel 67e4190951 Merge remote-tracking branch 'origin/dev/friel/fork-context-inherits-parent-model' into repair/watchdog-prompt-layering 2026-03-29 18:07:01 +00:00
Friel fb8653cd30 Merge remote-tracking branch 'origin/dev/friel/agent-tools-namespace' into repair/watchdog-prompt-layering 2026-03-29 18:07:00 +00:00
Friel cc60cafc50 feat(core): add role-level fork_context defaults 2026-03-29 17:56:12 +00:00
Friel 70ba3d1e29 feat(core): expose agent tools in namespace 2026-03-29 17:56:12 +00:00
FrielandCodex 2c3bff24e4 test(core): fix multi-agent v2 fork-context regression
Co-authored-by: Codex <[email protected]>
2026-03-29 17:04:29 +00:00
FrielandCodex be051e056e feat(core): force forked agents to inherit parent model
Co-authored-by: Codex <[email protected]>
2026-03-29 17:04:28 +00:00
FrielandCodex a2f37d5548 fix(tui): preserve watchdog behavior on refreshed base
Resolve the remaining TUI-side merge drift after restacking the watchdog and subagent behavior branch onto the refreshed TUI foundation branch.

Co-authored-by: Codex <[email protected]>
2026-03-28 23:09:20 -07:00
Friel 65db8195a5 test(nextest): extend schema fixture timeout on windows 2026-03-28 23:09:20 -07:00
Friel 86fe4f6be4 test(app-server): stabilize thread unsubscribe on slow runners 2026-03-28 23:09:20 -07:00
Friel 3bd69accc1 fix(tui): render live agent inbox notifications 2026-03-28 23:08:51 -07:00
Friel b8be51fe7c fix(tui): annotate subagent panel test literals 2026-03-28 19:24:31 -07:00
Friel 0b72153645 fix(tui): annotate subagent panel render literals 2026-03-28 18:54:46 -07:00
Friel 510d5679a9 fix(tui): annotate subagent panel truncation literal 2026-03-28 18:43:02 -07:00
Friel 48b7f72829 fix(tui): drop stale voice transcription init on current main 2026-03-28 18:34:11 -07:00
Friel fc7a5e3d0f fix(tui): restore subagent panel wiring on app-server TUI 2026-03-28 18:28:25 -07:00
Friel 90d339cf75 fix(tui): mount subagent panel independently of active cell 2026-03-28 18:24:50 -07:00
Friel 0af3f1f66e fix(tui): keep subagent panel out of transcript history 2026-03-28 18:24:50 -07:00
Friel 4ef8493fd2 test(tui): annotate subagent panel literals 2026-03-28 18:24:50 -07:00
Friel 5e41296824 fix(tui): format multi-agent status helper 2026-03-28 18:24:50 -07:00
Friel 3cfdc99ecc fix(tui): annotate watchdog panel truncation literals 2026-03-28 18:24:50 -07:00
FrielandCodex 77c69e35b7 fix(tui): adapt collab foundation to refreshed main
Preserve the collab transcript fixtures and current TUI style rules after rebasing onto the refreshed tui_app_server codebase.

Co-authored-by: Codex <[email protected]>
2026-03-28 18:24:49 -07:00
Friel ed0cff78a6 feat(tui): add subagent inbox foundation
Preserve the subagent inbox foundation behavior on the current origin/main base and collapse the branch back to a single commit for easier future restacks.
2026-03-28 18:24:49 -07:00
Friel 3c84d41945 test(core): annotate final custom model literals 2026-03-28 16:50:22 -07:00
Friel 2b7fd5a91d fix(tui): correct watchdog spawn replay fixtures 2026-03-28 16:42:08 -07:00
Friel d1196258a1 test(core): annotate custom model helper literals 2026-03-28 16:34:48 -07:00
Friel e5e3911799 fix(tui): align watchdog spawn replay fallback 2026-03-28 16:33:33 -07:00
Friel 90c18fd1b1 test(tui): set spawn mode in watchdog replay fixtures 2026-03-28 16:31:46 -07:00
Friel 08dad720db fix(tui): set spawn mode in collab spawn replay 2026-03-28 16:22:24 -07:00
Friel 83780ddbff test(core): annotate watchdog test literals 2026-03-28 16:22:24 -07:00
Friel b4ea255a9f fix(core): annotate watchdog positional literals 2026-03-28 16:22:24 -07:00
FrielandCodex 2b0f370fd8 fix(core): preserve watchdog spawn handler imports
Co-authored-by: Codex <[email protected]>
2026-03-28 16:22:24 -07:00
FrielandCodex 7a079455d3 fix(core): adapt watchdog role branch to refreshed main
Keep the role-driven watchdog branch aligned with the refreshed list_agents and spawn event APIs after rebasing on the updated subagent inbox branch.

Co-authored-by: Codex <[email protected]>
2026-03-28 16:22:24 -07:00
FrielandCodex 074216d951 feat(core): make watchdogs role-driven
Co-authored-by: Codex <[email protected]>
2026-03-28 16:22:24 -07:00
FrielandCodex 3e8bd6b801 feat(core): add watchdog runtime and prompts
Preserve the watchdog runtime and prompt behavior on top of the refreshed inbox branch and collapse the branch back to a single commit for easier future restacks.

Co-authored-by: Codex <[email protected]>
2026-03-28 16:22:24 -07:00
Friel afaa5e887c test(core): annotate inbox control test literals 2026-03-28 16:22:01 -07:00
Friel 8fab3fb7da test(core): annotate remaining custom model literals 2026-03-28 16:22:01 -07:00
Friel 83e58d5036 test(app-server): annotate remaining shell workdir literals 2026-03-28 12:06:07 -07:00
Friel d581363a82 test(core): annotate refreshed custom model literals 2026-03-28 12:05:31 -07:00
Friel 73418e2882 test(app-server): annotate inbox resume literals 2026-03-28 11:56:40 -07:00
Friel 5395dab51d test(cli): annotate remote and color literals 2026-03-28 11:51:56 -07:00
Friel e6f412f2d8 test(core): annotate auto-unarchive literals 2026-03-28 11:48:18 -07:00
Friel 9118d71ec7 test(core): annotate custom model literals 2026-03-28 11:48:18 -07:00
Friel 901c8e2ba6 test(core): annotate fork-thread positional literals 2026-03-28 11:35:15 -07:00
Friel ebc45db194 test(features): annotate auth literals 2026-03-28 11:35:15 -07:00
Friel 70cbe5a89d test(exec): annotate fork option literals 2026-03-28 11:35:15 -07:00
FrielandCodex c87d62c34f fix(core): re-export auto-unarchive lookup on refreshed main
Keep the split rollout shim aligned with the refreshed codex-rollout crate so resume-only auto-unarchive continues to compile on current main.

Co-authored-by: Codex <[email protected]>
2026-03-28 11:35:15 -07:00
Friel a68b1bd423 test(core): annotate custom model catalog literal 2026-03-28 11:35:15 -07:00
FrielandCodex 797fed3d57 fix(core): adapt fork references to refreshed main
Disable stale inline fork-reference test modules on the refreshed core APIs and keep the rollout re-export surface aligned with the split codex-rollout crate.

Co-authored-by: Codex <[email protected]>
2026-03-28 11:35:15 -07:00
FrielandCodex 3be3e8fc87 fix(core): apply refreshed clippy suggestions
Co-authored-by: Codex <[email protected]>
2026-03-28 11:35:15 -07:00
Friel 8ee3a48601 feat(exec): add --fork option to codex exec
Add non-interactive session forking to codex exec and keep the CLI/help/tests aligned with the interactive fork behavior.
2026-03-28 11:35:15 -07:00
Friel 328706da37 codex: auto-unarchive archived sessions safely on resume
Preserve the auto-unarchive-on-resume behavior while keeping archived-session lookup safe. This carries the rollout lookup hardening, the resume path updates, and the cross-platform guardian/TUI test fixes needed for current CI.
2026-03-28 11:35:15 -07:00
FrielandCodex bc18824d23 fix(core): adapt custom model tests to refreshed main
Drop the removed ModelInfo field and normalize refreshed ThreadManager and UserTurn test callsites.

Co-authored-by: Codex <[email protected]>
2026-03-28 11:35:15 -07:00
Friel f30fde6221 feat(rollout): preserve fork references across replay
Preserve fork-reference replay behavior on the current origin/main base and collapse the branch back to a single commit for easier future restacks.
2026-03-28 11:35:15 -07:00
FrielandCodex 4d0a1431f8 fix(core): adapt inbox delivery rebase to current main
Keep the rebased inbox-delivery branch on current core APIs by moving the inbox-specific coverage into current main's control tests and updating the turn-restart helper to use RegularTask.

Co-authored-by: Codex <[email protected]>
2026-03-28 11:35:15 -07:00
Friel d6f8e3aeeb feat(core): support custom model aliases in config.toml
Preserve custom model alias support on the current origin/main base and collapse the branch back to a single commit for easier future restacks.
2026-03-28 11:35:15 -07:00
Friel 0e91619094 feat(agents): enable subagent inbox delivery
Preserve subagent inbox delivery on the current origin/main base and collapse the branch back to a single commit for easier future restacks.
2026-03-28 11:35:15 -07:00
FrielandCodex 5628e3cc8f fix(core): re-export auto-unarchive lookup on refreshed main
Keep the split rollout shim aligned with the refreshed codex-rollout crate so resume-only auto-unarchive continues to compile on current main.

Co-authored-by: Codex <[email protected]>
2026-03-28 10:29:12 -07:00
Friel 63b0d26587 codex: auto-unarchive archived sessions safely on resume
Preserve the auto-unarchive-on-resume behavior while keeping archived-session lookup safe. This carries the rollout lookup hardening, the resume path updates, and the cross-platform guardian/TUI test fixes needed for current CI.
2026-03-28 10:29:12 -07:00
180 changed files with 13808 additions and 753 deletions

No files matched your search

+2 -2
View File
@@ -17,7 +17,7 @@ concurrency:
cancel-in-progress: ${{ github.ref_name != 'main' }}
jobs:
test:
timeout-minutes: 30
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
@@ -99,7 +99,7 @@ jobs:
key: bazel-cache-${{ matrix.target }}-${{ hashFiles('MODULE.bazel', 'codex-rs/Cargo.lock', 'codex-rs/Cargo.toml') }}
clippy:
timeout-minutes: 30
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
+2 -3
View File
@@ -81,7 +81,6 @@ jobs:
- uses: taiki-e/install-action@44c6d64aa62cd779e873306675c7a58e86d6d532 # v2
with:
tool: cargo-shear
version: 1.5.1
- name: cargo shear
run: cargo shear
@@ -137,10 +136,10 @@ jobs:
include:
- name: Linux
runner: ubuntu-24.04
timeout_minutes: 30
timeout_minutes: 120
- name: macOS
runner: macos-15-xlarge
timeout_minutes: 30
timeout_minutes: 90
- name: Windows
runner: windows-x64
timeout_minutes: 30
+1 -1
View File
@@ -10,7 +10,7 @@ jobs:
runs-on:
group: codex-runners
labels: codex-linux-x64
timeout-minutes: 10
timeout-minutes: 60
steps:
- name: Checkout repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
+6
View File
@@ -27,3 +27,9 @@ test-group = 'app_server_protocol_codegen'
# Keep the library unit tests parallel.
filter = 'package(codex-app-server) & kind(test)'
test-group = 'app_server_integration'
[[profile.default.overrides]]
# Schema fixture generation can take longer than the default timeout on slower
# Windows runners when app-server protocol fixture sets grow.
filter = 'test(schema_fixtures_match_generated)'
slow-timeout = { period = "1m", terminate-after = 2 }
+15
View File
@@ -1813,6 +1813,20 @@ dependencies = [
"wildmatch",
]
[[package]]
name = "codex-config-schema"
version = "0.0.0"
dependencies = [
"anyhow",
"clap",
"codex-config",
"codex-protocol",
"codex-utils-absolute-path",
"schemars 0.8.22",
"serde",
"serde_json",
]
[[package]]
name = "codex-connectors"
version = "0.0.0"
@@ -1848,6 +1862,7 @@ dependencies = [
"codex-async-utils",
"codex-code-mode",
"codex-config",
"codex-config-schema",
"codex-connectors",
"codex-core-skills",
"codex-exec-server",
+2
View File
@@ -22,6 +22,7 @@ members = [
"cli",
"connectors",
"config",
"config-schema",
"shell-command",
"shell-escalation",
"skills",
@@ -117,6 +118,7 @@ codex-cloud-tasks-client = { path = "cloud-tasks-client" }
codex-cloud-tasks-mock-client = { path = "cloud-tasks-mock-client" }
codex-code-mode = { path = "code-mode" }
codex-config = { path = "config" }
codex-config-schema = { path = "config-schema" }
codex-connectors = { path = "connectors" }
codex-core = { path = "core" }
codex-core-skills = { path = "core-skills" }
+2 -1
View File
@@ -50,7 +50,8 @@ You can enable notifications by configuring a script that is run whenever the ag
### `codex exec` to run Codex programmatically/non-interactively
To run Codex non-interactively, run `codex exec PROMPT` (you can also pass the prompt via `stdin`) and Codex will work on your task until it decides that it is done and exits. If you provide both a prompt argument and piped stdin, Codex appends stdin as a `<stdin>` block after the prompt so patterns like `echo "my output" | codex exec "Summarize this concisely"` work naturally. Output is printed to the terminal directly. You can set the `RUST_LOG` environment variable to see more about what's going on.
To run Codex non-interactively, run `codex exec PROMPT` (you can also pass the prompt via `stdin`) and Codex will work on your task until it decides that it is done and exits. Output is printed to the terminal directly. You can set the `RUST_LOG` environment variable to see more about what's going on.
Use `codex exec --fork <SESSION_ID> PROMPT` to fork an existing session without launching the interactive picker/UI.
Use `codex exec --ephemeral ...` to run without persisting session rollout files to disk.
### Experimenting with the Codex Sandbox
@@ -2619,6 +2619,17 @@
],
"type": "object"
},
"ThreadInputActivityParams": {
"properties": {
"threadId": {
"type": "string"
}
},
"required": [
"threadId"
],
"type": "object"
},
"ThreadListParams": {
"properties": {
"archived": {
@@ -3701,6 +3712,30 @@
"title": "Thread/shellCommandRequest",
"type": "object"
},
{
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"method": {
"enum": [
"thread/inputActivity"
],
"title": "Thread/inputActivityRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/ThreadInputActivityParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Thread/inputActivityRequest",
"type": "object"
},
{
"properties": {
"id": {
@@ -482,6 +482,30 @@
"title": "Thread/shellCommandRequest",
"type": "object"
},
{
"properties": {
"id": {
"$ref": "#/definitions/v2/RequestId"
},
"method": {
"enum": [
"thread/inputActivity"
],
"title": "Thread/inputActivityRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/v2/ThreadInputActivityParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Thread/inputActivityRequest",
"type": "object"
},
{
"properties": {
"id": {
@@ -12503,6 +12527,24 @@
"ThreadId": {
"type": "string"
},
"ThreadInputActivityParams": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"threadId": {
"type": "string"
}
},
"required": [
"threadId"
],
"title": "ThreadInputActivityParams",
"type": "object"
},
"ThreadInputActivityResponse": {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "ThreadInputActivityResponse",
"type": "object"
},
"ThreadItem": {
"oneOf": [
{
@@ -1057,6 +1057,30 @@
"title": "Thread/shellCommandRequest",
"type": "object"
},
{
"properties": {
"id": {
"$ref": "#/definitions/RequestId"
},
"method": {
"enum": [
"thread/inputActivity"
],
"title": "Thread/inputActivityRequestMethod",
"type": "string"
},
"params": {
"$ref": "#/definitions/ThreadInputActivityParams"
}
},
"required": [
"id",
"method",
"params"
],
"title": "Thread/inputActivityRequest",
"type": "object"
},
{
"properties": {
"id": {
@@ -10358,6 +10382,24 @@
"ThreadId": {
"type": "string"
},
"ThreadInputActivityParams": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"threadId": {
"type": "string"
}
},
"required": [
"threadId"
],
"title": "ThreadInputActivityParams",
"type": "object"
},
"ThreadInputActivityResponse": {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "ThreadInputActivityResponse",
"type": "object"
},
"ThreadItem": {
"oneOf": [
{
@@ -0,0 +1,13 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
"threadId": {
"type": "string"
}
},
"required": [
"threadId"
],
"title": "ThreadInputActivityParams",
"type": "object"
}
@@ -0,0 +1,5 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "ThreadInputActivityResponse",
"type": "object"
}
@@ -45,6 +45,7 @@ import type { SkillsListParams } from "./v2/SkillsListParams";
import type { ThreadArchiveParams } from "./v2/ThreadArchiveParams";
import type { ThreadCompactStartParams } from "./v2/ThreadCompactStartParams";
import type { ThreadForkParams } from "./v2/ThreadForkParams";
import type { ThreadInputActivityParams } from "./v2/ThreadInputActivityParams";
import type { ThreadListParams } from "./v2/ThreadListParams";
import type { ThreadLoadedListParams } from "./v2/ThreadLoadedListParams";
import type { ThreadMetadataUpdateParams } from "./v2/ThreadMetadataUpdateParams";
@@ -64,4 +65,4 @@ import type { WindowsSandboxSetupStartParams } from "./v2/WindowsSandboxSetupSta
/**
* Request from the client to the server.
*/
export type ClientRequest ={ "method": "initialize", id: RequestId, params: InitializeParams, } | { "method": "thread/start", id: RequestId, params: ThreadStartParams, } | { "method": "thread/resume", id: RequestId, params: ThreadResumeParams, } | { "method": "thread/fork", id: RequestId, params: ThreadForkParams, } | { "method": "thread/archive", id: RequestId, params: ThreadArchiveParams, } | { "method": "thread/unsubscribe", id: RequestId, params: ThreadUnsubscribeParams, } | { "method": "thread/name/set", id: RequestId, params: ThreadSetNameParams, } | { "method": "thread/metadata/update", id: RequestId, params: ThreadMetadataUpdateParams, } | { "method": "thread/unarchive", id: RequestId, params: ThreadUnarchiveParams, } | { "method": "thread/compact/start", id: RequestId, params: ThreadCompactStartParams, } | { "method": "thread/shellCommand", id: RequestId, params: ThreadShellCommandParams, } | { "method": "thread/rollback", id: RequestId, params: ThreadRollbackParams, } | { "method": "thread/list", id: RequestId, params: ThreadListParams, } | { "method": "thread/loaded/list", id: RequestId, params: ThreadLoadedListParams, } | { "method": "thread/read", id: RequestId, params: ThreadReadParams, } | { "method": "skills/list", id: RequestId, params: SkillsListParams, } | { "method": "plugin/list", id: RequestId, params: PluginListParams, } | { "method": "plugin/read", id: RequestId, params: PluginReadParams, } | { "method": "app/list", id: RequestId, params: AppsListParams, } | { "method": "fs/readFile", id: RequestId, params: FsReadFileParams, } | { "method": "fs/writeFile", id: RequestId, params: FsWriteFileParams, } | { "method": "fs/createDirectory", id: RequestId, params: FsCreateDirectoryParams, } | { "method": "fs/getMetadata", id: RequestId, params: FsGetMetadataParams, } | { "method": "fs/readDirectory", id: RequestId, params: FsReadDirectoryParams, } | { "method": "fs/remove", id: RequestId, params: FsRemoveParams, } | { "method": "fs/copy", id: RequestId, params: FsCopyParams, } | { "method": "fs/watch", id: RequestId, params: FsWatchParams, } | { "method": "fs/unwatch", id: RequestId, params: FsUnwatchParams, } | { "method": "skills/config/write", id: RequestId, params: SkillsConfigWriteParams, } | { "method": "plugin/install", id: RequestId, params: PluginInstallParams, } | { "method": "plugin/uninstall", id: RequestId, params: PluginUninstallParams, } | { "method": "turn/start", id: RequestId, params: TurnStartParams, } | { "method": "turn/steer", id: RequestId, params: TurnSteerParams, } | { "method": "turn/interrupt", id: RequestId, params: TurnInterruptParams, } | { "method": "review/start", id: RequestId, params: ReviewStartParams, } | { "method": "model/list", id: RequestId, params: ModelListParams, } | { "method": "experimentalFeature/list", id: RequestId, params: ExperimentalFeatureListParams, } | { "method": "experimentalFeature/enablement/set", id: RequestId, params: ExperimentalFeatureEnablementSetParams, } | { "method": "mcpServer/oauth/login", id: RequestId, params: McpServerOauthLoginParams, } | { "method": "config/mcpServer/reload", id: RequestId, params: undefined, } | { "method": "mcpServerStatus/list", id: RequestId, params: ListMcpServerStatusParams, } | { "method": "windowsSandbox/setupStart", id: RequestId, params: WindowsSandboxSetupStartParams, } | { "method": "account/login/start", id: RequestId, params: LoginAccountParams, } | { "method": "account/login/cancel", id: RequestId, params: CancelLoginAccountParams, } | { "method": "account/logout", id: RequestId, params: undefined, } | { "method": "account/rateLimits/read", id: RequestId, params: undefined, } | { "method": "feedback/upload", id: RequestId, params: FeedbackUploadParams, } | { "method": "command/exec", id: RequestId, params: CommandExecParams, } | { "method": "command/exec/write", id: RequestId, params: CommandExecWriteParams, } | { "method": "command/exec/terminate", id: RequestId, params: CommandExecTerminateParams, } | { "method": "command/exec/resize", id: RequestId, params: CommandExecResizeParams, } | { "method": "config/read", id: RequestId, params: ConfigReadParams, } | { "method": "externalAgentConfig/detect", id: RequestId, params: ExternalAgentConfigDetectParams, } | { "method": "externalAgentConfig/import", id: RequestId, params: ExternalAgentConfigImportParams, } | { "method": "config/value/write", id: RequestId, params: ConfigValueWriteParams, } | { "method": "config/batchWrite", id: RequestId, params: ConfigBatchWriteParams, } | { "method": "configRequirements/read", id: RequestId, params: undefined, } | { "method": "account/read", id: RequestId, params: GetAccountParams, } | { "method": "getConversationSummary", id: RequestId, params: GetConversationSummaryParams, } | { "method": "gitDiffToRemote", id: RequestId, params: GitDiffToRemoteParams, } | { "method": "getAuthStatus", id: RequestId, params: GetAuthStatusParams, } | { "method": "fuzzyFileSearch", id: RequestId, params: FuzzyFileSearLine truncated
export type ClientRequest ={ "method": "initialize", id: RequestId, params: InitializeParams, } | { "method": "thread/start", id: RequestId, params: ThreadStartParams, } | { "method": "thread/resume", id: RequestId, params: ThreadResumeParams, } | { "method": "thread/fork", id: RequestId, params: ThreadForkParams, } | { "method": "thread/archive", id: RequestId, params: ThreadArchiveParams, } | { "method": "thread/unsubscribe", id: RequestId, params: ThreadUnsubscribeParams, } | { "method": "thread/name/set", id: RequestId, params: ThreadSetNameParams, } | { "method": "thread/metadata/update", id: RequestId, params: ThreadMetadataUpdateParams, } | { "method": "thread/unarchive", id: RequestId, params: ThreadUnarchiveParams, } | { "method": "thread/compact/start", id: RequestId, params: ThreadCompactStartParams, } | { "method": "thread/shellCommand", id: RequestId, params: ThreadShellCommandParams, } | { "method": "thread/inputActivity", id: RequestId, params: ThreadInputActivityParams, } | { "method": "thread/rollback", id: RequestId, params: ThreadRollbackParams, } | { "method": "thread/list", id: RequestId, params: ThreadListParams, } | { "method": "thread/loaded/list", id: RequestId, params: ThreadLoadedListParams, } | { "method": "thread/read", id: RequestId, params: ThreadReadParams, } | { "method": "skills/list", id: RequestId, params: SkillsListParams, } | { "method": "plugin/list", id: RequestId, params: PluginListParams, } | { "method": "plugin/read", id: RequestId, params: PluginReadParams, } | { "method": "app/list", id: RequestId, params: AppsListParams, } | { "method": "fs/readFile", id: RequestId, params: FsReadFileParams, } | { "method": "fs/writeFile", id: RequestId, params: FsWriteFileParams, } | { "method": "fs/createDirectory", id: RequestId, params: FsCreateDirectoryParams, } | { "method": "fs/getMetadata", id: RequestId, params: FsGetMetadataParams, } | { "method": "fs/readDirectory", id: RequestId, params: FsReadDirectoryParams, } | { "method": "fs/remove", id: RequestId, params: FsRemoveParams, } | { "method": "fs/copy", id: RequestId, params: FsCopyParams, } | { "method": "fs/watch", id: RequestId, params: FsWatchParams, } | { "method": "fs/unwatch", id: RequestId, params: FsUnwatchParams, } | { "method": "skills/config/write", id: RequestId, params: SkillsConfigWriteParams, } | { "method": "plugin/install", id: RequestId, params: PluginInstallParams, } | { "method": "plugin/uninstall", id: RequestId, params: PluginUninstallParams, } | { "method": "turn/start", id: RequestId, params: TurnStartParams, } | { "method": "turn/steer", id: RequestId, params: TurnSteerParams, } | { "method": "turn/interrupt", id: RequestId, params: TurnInterruptParams, } | { "method": "review/start", id: RequestId, params: ReviewStartParams, } | { "method": "model/list", id: RequestId, params: ModelListParams, } | { "method": "experimentalFeature/list", id: RequestId, params: ExperimentalFeatureListParams, } | { "method": "experimentalFeature/enablement/set", id: RequestId, params: ExperimentalFeatureEnablementSetParams, } | { "method": "mcpServer/oauth/login", id: RequestId, params: McpServerOauthLoginParams, } | { "method": "config/mcpServer/reload", id: RequestId, params: undefined, } | { "method": "mcpServerStatus/list", id: RequestId, params: ListMcpServerStatusParams, } | { "method": "windowsSandbox/setupStart", id: RequestId, params: WindowsSandboxSetupStartParams, } | { "method": "account/login/start", id: RequestId, params: LoginAccountParams, } | { "method": "account/login/cancel", id: RequestId, params: CancelLoginAccountParams, } | { "method": "account/logout", id: RequestId, params: undefined, } | { "method": "account/rateLimits/read", id: RequestId, params: undefined, } | { "method": "feedback/upload", id: RequestId, params: FeedbackUploadParams, } | { "method": "command/exec", id: RequestId, params: CommandExecParams, } | { "method": "command/exec/write", id: RequestId, params: CommandExecWriteParams, } | { "method": "command/exec/terminate", id: RequestId, params: CommandExecTerminateParams, } | { "method": "command/exec/resize", id: RequestId, params: CommandExecResizeParams, } | { "method": "config/read", id: RequestId, params: ConfigReadParams, } | { "method": "externalAgentConfig/detect", id: RequestId, params: ExternalAgentConfigDetectParams, } | { "method": "externalAgentConfig/import", id: RequestId, params: ExternalAgentConfigImportParams, } | { "method": "config/value/write", id: RequestId, params: ConfigValueWriteParams, } | { "method": "config/batchWrite", id: RequestId, params: ConfigBatchWriteParams, } | { "method": "configRequirements/read", id: RequestId, params: undefined, } | { "method": "account/read", id: RequestId, params: GetAccountParams, } | { "method": "getConversationSummary", id: RequestId, params: GetConversationSummaryParams, } | { "method": "gitDiffToRemote", id: RequestId, params: GitDiffToRemoteParams, } | { "method": "getAuthStatus", id: RequestId, params: GeLine truncated
@@ -0,0 +1,5 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type ThreadInputActivityParams = { threadId: string, };
@@ -0,0 +1,5 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type ThreadInputActivityResponse = Record<string, never>;
@@ -275,6 +275,8 @@ export type { ThreadCompactStartParams } from "./ThreadCompactStartParams";
export type { ThreadCompactStartResponse } from "./ThreadCompactStartResponse";
export type { ThreadForkParams } from "./ThreadForkParams";
export type { ThreadForkResponse } from "./ThreadForkResponse";
export type { ThreadInputActivityParams } from "./ThreadInputActivityParams";
export type { ThreadInputActivityResponse } from "./ThreadInputActivityResponse";
export type { ThreadItem } from "./ThreadItem";
export type { ThreadListParams } from "./ThreadListParams";
export type { ThreadListResponse } from "./ThreadListResponse";
@@ -301,6 +301,10 @@ client_request_definitions! {
params: v2::ThreadBackgroundTerminalsCleanParams,
response: v2::ThreadBackgroundTerminalsCleanResponse,
},
ThreadInputActivity => "thread/inputActivity" {
params: v2::ThreadInputActivityParams,
response: v2::ThreadInputActivityResponse,
},
ThreadRollback => "thread/rollback" {
params: v2::ThreadRollbackParams,
response: v2::ThreadRollbackResponse,
@@ -76,6 +76,11 @@ pub struct ThreadHistoryBuilder {
next_item_index: i64,
current_rollout_index: usize,
next_rollout_index: usize,
// Current streams emit per-attempt spawn ids (`call_id`, `call_id#2`, ...); legacy rollouts
// reused the raw tool call_id for each retry, so replay still synthesizes stable per-attempt
// item ids when needed to preserve each attempt row.
current_spawn_attempt_ids: HashMap<String, String>,
spawn_attempt_counts: HashMap<String, usize>,
}
impl Default for ThreadHistoryBuilder {
@@ -92,6 +97,8 @@ impl ThreadHistoryBuilder {
next_item_index: 1,
current_rollout_index: 0,
next_rollout_index: 0,
current_spawn_attempt_ids: HashMap::new(),
spawn_attempt_counts: HashMap::new(),
}
}
@@ -205,7 +212,9 @@ impl ThreadHistoryBuilder {
RolloutItem::EventMsg(event) => self.handle_event(event),
RolloutItem::Compacted(payload) => self.handle_compacted(payload),
RolloutItem::ResponseItem(item) => self.handle_response_item(item),
RolloutItem::TurnContext(_) | RolloutItem::SessionMeta(_) => {}
RolloutItem::TurnContext(_)
| RolloutItem::SessionMeta(_)
| RolloutItem::ForkReference(_) => {}
}
}
@@ -608,8 +617,9 @@ impl ThreadHistoryBuilder {
&mut self,
payload: &codex_protocol::protocol::CollabAgentSpawnBeginEvent,
) {
let item_id = self.next_collab_spawn_attempt_item_id(&payload.call_id);
let item = ThreadItem::CollabAgentToolCall {
id: payload.call_id.clone(),
id: item_id,
tool: CollabAgentTool::SpawnAgent,
status: CollabAgentToolCallStatus::InProgress,
sender_thread_id: payload.sender_thread_id.to_string(),
@@ -626,6 +636,10 @@ impl ThreadHistoryBuilder {
&mut self,
payload: &codex_protocol::protocol::CollabAgentSpawnEndEvent,
) {
let item_id = self
.current_spawn_attempt_ids
.remove(&payload.call_id)
.unwrap_or_else(|| payload.call_id.clone());
let has_receiver = payload.new_thread_id.is_some();
let status = match &payload.status {
AgentStatus::Errored(_) | AgentStatus::NotFound => CollabAgentToolCallStatus::Failed,
@@ -644,7 +658,7 @@ impl ThreadHistoryBuilder {
None => (Vec::new(), HashMap::new()),
};
self.upsert_item_in_current_turn(ThreadItem::CollabAgentToolCall {
id: payload.call_id.clone(),
id: item_id,
tool: CollabAgentTool::SpawnAgent,
status,
sender_thread_id: payload.sender_thread_id.to_string(),
@@ -977,6 +991,8 @@ impl ThreadHistoryBuilder {
}
fn finish_current_turn(&mut self) {
self.current_spawn_attempt_ids.clear();
self.spawn_attempt_counts.clear();
if let Some(turn) = self.current_turn.take() {
if turn.items.is_empty() && !turn.opened_explicitly && !turn.saw_compaction {
return;
@@ -1040,6 +1056,22 @@ impl ThreadHistoryBuilder {
id
}
fn next_collab_spawn_attempt_item_id(&mut self, call_id: &str) -> String {
let attempt_number = self
.spawn_attempt_counts
.entry(call_id.to_string())
.and_modify(|count| *count += 1)
.or_insert(1);
let item_id = if *attempt_number == 1 {
call_id.to_string()
} else {
format!("{call_id}#{attempt_number}")
};
self.current_spawn_attempt_ids
.insert(call_id.to_string(), item_id.clone());
item_id
}
fn build_user_inputs(&self, payload: &UserMessageEvent) -> Vec<UserInput> {
let mut content = Vec::new();
if !payload.message.trim().is_empty() {
@@ -2562,6 +2594,157 @@ mod tests {
);
}
#[test]
fn reconstructs_collab_spawn_end_without_receiver_as_failed_spawn_attempt() {
let sender_thread_id = ThreadId::try_from("00000000-0000-0000-0000-000000000001")
.expect("valid sender thread id");
let events = vec![
EventMsg::UserMessage(UserMessageEvent {
message: "spawn agent".into(),
images: None,
text_elements: Vec::new(),
local_images: Vec::new(),
}),
EventMsg::CollabAgentSpawnBegin(codex_protocol::protocol::CollabAgentSpawnBeginEvent {
call_id: "spawn-1".into(),
sender_thread_id,
prompt: "inspect the repo".into(),
model: "gpt-5.4-mini".into(),
reasoning_effort: codex_protocol::openai_models::ReasoningEffort::Medium,
}),
EventMsg::CollabAgentSpawnEnd(codex_protocol::protocol::CollabAgentSpawnEndEvent {
call_id: "spawn-1".into(),
sender_thread_id,
new_thread_id: None,
new_agent_nickname: None,
new_agent_role: None,
prompt: "inspect the repo".into(),
model: "gpt-5.4-mini".into(),
reasoning_effort: codex_protocol::openai_models::ReasoningEffort::Medium,
status: AgentStatus::PendingInit,
}),
];
let items = events
.into_iter()
.map(RolloutItem::EventMsg)
.collect::<Vec<_>>();
let turns = build_turns_from_rollout_items(&items);
assert_eq!(turns.len(), 1);
assert_eq!(turns[0].items.len(), 2);
assert_eq!(
turns[0].items[1],
ThreadItem::CollabAgentToolCall {
id: "spawn-1".into(),
tool: CollabAgentTool::SpawnAgent,
status: CollabAgentToolCallStatus::Failed,
sender_thread_id: "00000000-0000-0000-0000-000000000001".into(),
receiver_thread_ids: Vec::new(),
prompt: Some("inspect the repo".into()),
model: Some("gpt-5.4-mini".into()),
reasoning_effort: Some(codex_protocol::openai_models::ReasoningEffort::Medium),
agents_states: HashMap::new(),
}
);
}
#[test]
fn reconstructs_collab_spawn_retries_as_distinct_attempt_items() {
let sender_thread_id = ThreadId::try_from("00000000-0000-0000-0000-000000000001")
.expect("valid sender thread id");
let spawned_thread_id = ThreadId::try_from("00000000-0000-0000-0000-000000000002")
.expect("valid receiver thread id");
let events = vec![
EventMsg::UserMessage(UserMessageEvent {
message: "spawn agent".into(),
images: None,
text_elements: Vec::new(),
local_images: Vec::new(),
}),
EventMsg::CollabAgentSpawnBegin(codex_protocol::protocol::CollabAgentSpawnBeginEvent {
call_id: "spawn-1".into(),
sender_thread_id,
prompt: "inspect the repo".into(),
model: "gpt-5.4-mini".into(),
reasoning_effort: codex_protocol::openai_models::ReasoningEffort::Low,
}),
EventMsg::CollabAgentSpawnEnd(codex_protocol::protocol::CollabAgentSpawnEndEvent {
call_id: "spawn-1".into(),
sender_thread_id,
new_thread_id: None,
new_agent_nickname: None,
new_agent_role: None,
prompt: "inspect the repo".into(),
model: "gpt-5.4-mini".into(),
reasoning_effort: codex_protocol::openai_models::ReasoningEffort::Low,
status: AgentStatus::Errored("insufficient_quota".into()),
}),
EventMsg::CollabAgentSpawnBegin(codex_protocol::protocol::CollabAgentSpawnBeginEvent {
call_id: "spawn-1".into(),
sender_thread_id,
prompt: "inspect the repo".into(),
model: "gpt-5".into(),
reasoning_effort: codex_protocol::openai_models::ReasoningEffort::Medium,
}),
EventMsg::CollabAgentSpawnEnd(codex_protocol::protocol::CollabAgentSpawnEndEvent {
call_id: "spawn-1".into(),
sender_thread_id,
new_thread_id: Some(spawned_thread_id),
new_agent_nickname: Some("Scout".into()),
new_agent_role: Some("explorer".into()),
prompt: "inspect the repo".into(),
model: "gpt-5".into(),
reasoning_effort: codex_protocol::openai_models::ReasoningEffort::Medium,
status: AgentStatus::Running,
}),
];
let items = events
.into_iter()
.map(RolloutItem::EventMsg)
.collect::<Vec<_>>();
let turns = build_turns_from_rollout_items(&items);
assert_eq!(turns.len(), 1);
assert_eq!(turns[0].items.len(), 3);
assert_eq!(
turns[0].items[1],
ThreadItem::CollabAgentToolCall {
id: "spawn-1".into(),
tool: CollabAgentTool::SpawnAgent,
status: CollabAgentToolCallStatus::Failed,
sender_thread_id: "00000000-0000-0000-0000-000000000001".into(),
receiver_thread_ids: Vec::new(),
prompt: Some("inspect the repo".into()),
model: Some("gpt-5.4-mini".into()),
reasoning_effort: Some(codex_protocol::openai_models::ReasoningEffort::Low),
agents_states: HashMap::new(),
}
);
assert_eq!(
turns[0].items[2],
ThreadItem::CollabAgentToolCall {
id: "spawn-1#2".into(),
tool: CollabAgentTool::SpawnAgent,
status: CollabAgentToolCallStatus::Completed,
sender_thread_id: "00000000-0000-0000-0000-000000000001".into(),
receiver_thread_ids: vec!["00000000-0000-0000-0000-000000000002".into()],
prompt: Some("inspect the repo".into()),
model: Some("gpt-5".into()),
reasoning_effort: Some(codex_protocol::openai_models::ReasoningEffort::Medium),
agents_states: [(
"00000000-0000-0000-0000-000000000002".into(),
CollabAgentState {
status: crate::protocol::v2::CollabAgentStatus::Running,
message: None,
},
)]
.into_iter()
.collect(),
}
);
}
#[test]
fn reconstructs_interrupted_send_input_as_completed_collab_call() {
// `send_input(interrupt=true)` first stops the child's active turn, then redirects it with
@@ -2994,6 +2994,18 @@ pub struct ThreadBackgroundTerminalsCleanParams {
#[ts(export_to = "v2/")]
pub struct ThreadBackgroundTerminalsCleanResponse {}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadInputActivityParams {
pub thread_id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub struct ThreadInputActivityResponse {}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
@@ -6638,6 +6650,38 @@ mod tests {
assert_eq!(decoded, response);
}
#[test]
fn thread_input_activity_params_round_trip() {
let params = ThreadInputActivityParams {
thread_id: "thr_123".to_string(),
};
let value = serde_json::to_value(&params).expect("serialize thread/inputActivity params");
assert_eq!(
value,
json!({
"threadId": "thr_123",
})
);
let decoded = serde_json::from_value::<ThreadInputActivityParams>(value)
.expect("deserialize thread/inputActivity params");
assert_eq!(decoded, params);
}
#[test]
fn thread_input_activity_response_round_trip() {
let response = ThreadInputActivityResponse {};
let value =
serde_json::to_value(&response).expect("serialize thread/inputActivity response");
assert_eq!(value, json!({}));
let decoded = serde_json::from_value::<ThreadInputActivityResponse>(value)
.expect("deserialize thread/inputActivity response");
assert_eq!(decoded, response);
}
#[test]
fn fs_changed_notification_round_trips() {
let notification = FsChangedNotification {
+13
View File
@@ -147,6 +147,7 @@ Example with notification opt-out:
- `thread/compact/start` — trigger conversation history compaction for a thread; returns `{}` immediately while progress streams through standard turn/item notifications.
- `thread/shellCommand` — run a user-initiated `!` shell command against a thread; this runs unsandboxed with full access rather than inheriting the thread sandbox policy. Returns `{}` immediately while progress streams through standard turn/item notifications and any active turn receives the formatted output in its message stream.
- `thread/backgroundTerminals/clean` — terminate all running background terminals for a thread (experimental; requires `capabilities.experimentalApi`); returns `{}` when the cleanup request is accepted.
- `thread/inputActivity` — record owner-side draft activity for a thread without starting or steering a turn; returns `{}` and is primarily useful for watchdog idle timers while the user is still typing.
- `thread/rollback` — drop the last N turns from the agent’s in-memory context and persist a rollback marker in the rollout so future resumes see the pruned history; returns the updated `thread` (with `turns` populated) on success.
- `turn/start` — add user input to a thread and begin Codex generation; responds with the initial `turn` object and streams `turn/started`, `item/*`, and `turn/completed` notifications. For `collaborationMode`, `settings.developer_instructions: null` means "use built-in instructions for the selected mode".
- `turn/steer` — add user input to an already in-flight regular turn without starting a new turn; returns the active `turnId` that accepted the input. Review and manual compaction turns reject `turn/steer`.
@@ -604,6 +605,18 @@ not emit `turn/started` and does not accept turn context overrides.
active turn, or the active turn kind does not accept same-turn steering (for example review or
manual compaction), the request fails with an `invalid request` error.
### Example: Mark owner draft activity
Use `thread/inputActivity` to keep watchdog idle timing honest while the user is still editing a
draft in the client.
```json
{ "method": "thread/inputActivity", "id": 33, "params": {
"threadId": "thr_123"
} }
{ "id": 33, "result": {} }
```
### Example: Request a code review
Use `review/start` to run Codex’s reviewer on the currently checked-out project. The request takes the thread id plus a `target` describing what should be reviewed:
@@ -125,6 +125,8 @@ use codex_app_server_protocol::ThreadForkParams;
use codex_app_server_protocol::ThreadForkResponse;
use codex_app_server_protocol::ThreadIncrementElicitationParams;
use codex_app_server_protocol::ThreadIncrementElicitationResponse;
use codex_app_server_protocol::ThreadInputActivityParams;
use codex_app_server_protocol::ThreadInputActivityResponse;
use codex_app_server_protocol::ThreadItem;
use codex_app_server_protocol::ThreadListParams;
use codex_app_server_protocol::ThreadListResponse;
@@ -209,9 +211,11 @@ use codex_core::exec::ExecExpiration;
use codex_core::exec::ExecParams;
use codex_core::exec_env::create_env;
use codex_core::find_archived_thread_path_by_id_str;
use codex_core::find_or_unarchive_thread_path_by_id_str;
use codex_core::find_thread_name_by_id;
use codex_core::find_thread_names_by_ids;
use codex_core::find_thread_path_by_id_str;
use codex_core::materialize_rollout_items_for_replay;
use codex_core::models_manager::collaboration_mode_presets::CollaborationModesConfig;
use codex_core::parse_cursor;
use codex_core::plugins::MarketplaceError;
@@ -755,6 +759,10 @@ impl CodexMessageProcessor {
)
.await;
}
ClientRequest::ThreadInputActivity { request_id, params } => {
self.thread_input_activity(to_connection_request_id(request_id), params)
.await;
}
ClientRequest::ThreadRollback { request_id, params } => {
self.thread_rollback(to_connection_request_id(request_id), params)
.await;
@@ -3233,6 +3241,40 @@ impl CodexMessageProcessor {
}
}
async fn thread_input_activity(
&self,
request_id: ConnectionRequestId,
params: ThreadInputActivityParams,
) {
let ThreadInputActivityParams { thread_id } = params;
let (_, thread) = match self.load_thread(&thread_id).await {
Ok(v) => v,
Err(error) => {
self.outgoing.send_error(request_id, error).await;
return;
}
};
match self
.submit_core_op(&request_id, thread.as_ref(), Op::NoteOwnerActivity)
.await
{
Ok(_) => {
self.outgoing
.send_response(request_id, ThreadInputActivityResponse {})
.await;
}
Err(err) => {
self.send_internal_error(
request_id,
format!("failed to record thread input activity: {err}"),
)
.await;
}
}
}
async fn thread_shell_command(
&self,
request_id: ConnectionRequestId,
@@ -3447,8 +3489,18 @@ impl CodexMessageProcessor {
} else {
read_summary_from_state_db_by_thread_id(&self.config, thread_uuid).await
};
let loaded_rollout_path = loaded_thread
.as_ref()
.and_then(|thread| thread.rollout_path());
let mut rollout_path = db_summary.as_ref().map(|summary| summary.path.clone());
if rollout_path.is_none() || include_turns {
if rollout_path.is_none()
&& let Some(path) = loaded_rollout_path.as_ref()
&& tokio::fs::try_exists(path).await.unwrap_or(false)
{
rollout_path = Some(path.clone());
}
let should_lookup_rollout = rollout_path.is_none() && loaded_thread.is_none();
if should_lookup_rollout {
rollout_path =
match find_thread_path_by_id_str(&self.config.codex_home, &thread_uuid.to_string())
.await
@@ -3509,7 +3561,6 @@ impl CodexMessageProcessor {
return;
};
let config_snapshot = thread.config_snapshot().await;
let loaded_rollout_path = thread.rollout_path();
if include_turns && loaded_rollout_path.is_none() {
self.send_invalid_request_error(
request_id,
@@ -3882,7 +3933,7 @@ impl CodexMessageProcessor {
if path.exists() {
path
} else {
match find_thread_path_by_id_str(
match find_or_unarchive_thread_path_by_id_str(
&self.config.codex_home,
&existing_thread_id.to_string(),
)
@@ -3908,7 +3959,7 @@ impl CodexMessageProcessor {
}
}
} else {
match find_thread_path_by_id_str(
match find_or_unarchive_thread_path_by_id_str(
&self.config.codex_home,
&existing_thread_id.to_string(),
)
@@ -4066,7 +4117,7 @@ impl CodexMessageProcessor {
}
};
match find_thread_path_by_id_str(
match find_or_unarchive_thread_path_by_id_str(
&self.config.codex_home,
&existing_thread_id.to_string(),
)
@@ -8467,13 +8518,17 @@ pub(crate) async fn read_summary_from_rollout(
.unwrap_or_else(|| fallback_provider.to_string());
let git_info = git.as_ref().map(map_git_info);
let updated_at = updated_at.or_else(|| timestamp.clone());
let preview = read_rollout_items_from_rollout(path)
.await
.map(|items| preview_from_rollout_items(&items))
.unwrap_or_default();
Ok(ConversationSummary {
conversation_id: session_meta.id,
timestamp,
updated_at,
path: path.to_path_buf(),
preview: String::new(),
preview,
model_provider,
cwd: session_meta.cwd,
cli_version: session_meta.cli_version,
@@ -8491,6 +8546,10 @@ pub(crate) async fn read_rollout_items_from_rollout(
InitialHistory::Resumed(resumed) => resumed.history,
};
if let Some(codex_home) = codex_home_from_rollout_path(path) {
return Ok(materialize_rollout_items_for_replay(codex_home, &items).await);
}
Ok(items)
}
@@ -8598,6 +8657,17 @@ fn preview_from_rollout_items(items: &[RolloutItem]) -> String {
.unwrap_or_default()
}
fn codex_home_from_rollout_path(path: &Path) -> Option<&Path> {
path.ancestors().find_map(|ancestor| {
let name = ancestor.file_name().and_then(OsStr::to_str)?;
if name == codex_core::SESSIONS_SUBDIR || name == codex_core::ARCHIVED_SESSIONS_SUBDIR {
ancestor.parent()
} else {
None
}
})
}
fn with_thread_spawn_agent_metadata(
source: codex_protocol::protocol::SessionSource,
agent_nickname: Option<String>,
@@ -8841,13 +8911,19 @@ mod tests {
model: "gpt-5".to_string(),
model_provider_id: "openai".to_string(),
service_tier: Some(codex_protocol::config_types::ServiceTier::Flex),
plan_mode_reasoning_effort: None,
model_verbosity: None,
model_context_window: None,
model_auto_compact_token_limit: None,
approval_policy: codex_protocol::protocol::AskForApproval::OnRequest,
approvals_reviewer: codex_protocol::config_types::ApprovalsReviewer::User,
sandbox_policy: codex_protocol::protocol::SandboxPolicy::DangerFullAccess,
cwd: PathBuf::from("/tmp"),
ephemeral: false,
agent_use_function_call_inbox: false,
reasoning_effort: None,
personality: None,
active_profile: None,
session_source: SessionSource::Cli,
};
@@ -228,6 +228,8 @@ impl MessageProcessor {
config.as_ref(),
auth_manager.clone(),
session_source,
config.model_catalog.clone(),
config.custom_models.clone(),
CollaborationModesConfig {
default_mode_request_user_input: config
.features
@@ -15,6 +15,7 @@ use std::path::Path;
fn preset_to_info(preset: &ModelPreset, priority: i32) -> ModelInfo {
ModelInfo {
slug: preset.id.clone(),
request_model: None,
display_name: preset.display_name.clone(),
description: Some(preset.description.clone()),
default_reasoning_level: Some(preset.default_reasoning_effort),
@@ -20,11 +20,17 @@ use core_test_support::fs_wait;
use pretty_assertions::assert_eq;
use serde_json::Value;
use std::path::Path;
use std::time::Duration;
use tempfile::TempDir;
use tokio::time::timeout;
#[cfg(windows)]
const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25);
#[cfg(not(windows))]
const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
#[cfg(windows)]
const DEFAULT_NOTIFY_FILE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25);
#[cfg(not(windows))]
const DEFAULT_NOTIFY_FILE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
#[tokio::test]
async fn initialize_uses_client_info_name_as_originator() -> Result<()> {
@@ -270,9 +276,9 @@ async fn turn_start_notify_payload_includes_initialize_client_name() -> Result<(
mcp.read_stream_until_notification_message("turn/completed"),
)
.await??;
fs_wait::wait_for_path_exists(&notify_file, Duration::from_secs(5)).await?;
let payload_raw = tokio::fs::read_to_string(&notify_file).await?;
let notify_file = Path::new(&notify_file);
fs_wait::wait_for_path_exists(notify_file, DEFAULT_NOTIFY_FILE_TIMEOUT).await?;
let payload_raw = tokio::fs::read_to_string(notify_file).await?;
let payload: Value = serde_json::from_str(&payload_raw)?;
assert_eq!(payload["client"], "xcode");
@@ -7,6 +7,10 @@ use codex_app_server_protocol::JSONRPCError;
use codex_app_server_protocol::JSONRPCResponse;
use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::SessionSource;
use codex_app_server_protocol::ThreadArchiveParams;
use codex_app_server_protocol::ThreadArchiveResponse;
use codex_app_server_protocol::ThreadForkParams;
use codex_app_server_protocol::ThreadForkResponse;
use codex_app_server_protocol::ThreadItem;
use codex_app_server_protocol::ThreadListParams;
use codex_app_server_protocol::ThreadListResponse;
@@ -20,6 +24,8 @@ use codex_app_server_protocol::ThreadSetNameResponse;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::ThreadStartResponse;
use codex_app_server_protocol::ThreadStatus;
use codex_app_server_protocol::ThreadUnarchiveParams;
use codex_app_server_protocol::ThreadUnarchiveResponse;
use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::TurnStartResponse;
use codex_app_server_protocol::TurnStatus;
@@ -152,6 +158,150 @@ async fn thread_read_can_include_turns() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn thread_read_include_turns_keeps_fork_history_after_parent_archive_and_unarchive()
-> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
let codex_home = TempDir::new()?;
create_config_toml(codex_home.path(), &server.uri())?;
let mut mcp = McpProcess::new(codex_home.path()).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
.await?;
let start_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(start_id)),
)
.await??;
let ThreadStartResponse { thread: parent, .. } =
to_response::<ThreadStartResponse>(start_resp)?;
let turn_start_id = mcp
.send_turn_start_request(TurnStartParams {
thread_id: parent.id.clone(),
input: vec![UserInput::Text {
text: "parent message".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
let turn_start_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(turn_start_id)),
)
.await??;
let _: TurnStartResponse = to_response::<TurnStartResponse>(turn_start_resp)?;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("turn/completed"),
)
.await??;
let fork_id = mcp
.send_thread_fork_request(ThreadForkParams {
thread_id: parent.id.clone(),
..Default::default()
})
.await?;
let fork_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(fork_id)),
)
.await??;
let ThreadForkResponse { thread: child, .. } = to_response::<ThreadForkResponse>(fork_resp)?;
let read_child_id = mcp
.send_thread_read_request(ThreadReadParams {
thread_id: child.id.clone(),
include_turns: true,
})
.await?;
let read_child_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(read_child_id)),
)
.await??;
let ThreadReadResponse {
thread: child_before_archive,
} = to_response::<ThreadReadResponse>(read_child_resp)?;
assert_eq!(child_before_archive.turns.len(), 1);
let archive_id = mcp
.send_thread_archive_request(ThreadArchiveParams {
thread_id: parent.id.clone(),
})
.await?;
let archive_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(archive_id)),
)
.await??;
let _: ThreadArchiveResponse = to_response::<ThreadArchiveResponse>(archive_resp)?;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("thread/archived"),
)
.await??;
let read_child_id = mcp
.send_thread_read_request(ThreadReadParams {
thread_id: child.id.clone(),
include_turns: true,
})
.await?;
let read_child_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(read_child_id)),
)
.await??;
let ThreadReadResponse {
thread: child_after_archive,
} = to_response::<ThreadReadResponse>(read_child_resp)?;
assert_eq!(child_after_archive.turns, child_before_archive.turns);
let unarchive_id = mcp
.send_thread_unarchive_request(ThreadUnarchiveParams {
thread_id: parent.id,
})
.await?;
let unarchive_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(unarchive_id)),
)
.await??;
let _: ThreadUnarchiveResponse = to_response::<ThreadUnarchiveResponse>(unarchive_resp)?;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("thread/unarchived"),
)
.await??;
let read_child_id = mcp
.send_thread_read_request(ThreadReadParams {
thread_id: child.id,
include_turns: true,
})
.await?;
let read_child_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(read_child_id)),
)
.await??;
let ThreadReadResponse {
thread: child_after_unarchive,
} = to_response::<ThreadReadResponse>(read_child_resp)?;
assert_eq!(child_after_unarchive.turns, child_before_archive.turns);
Ok(())
}
#[tokio::test]
async fn thread_read_loaded_thread_returns_precomputed_path_before_materialization() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
@@ -407,6 +557,62 @@ async fn thread_read_include_turns_rejects_unmaterialized_loaded_thread() -> Res
Ok(())
}
#[tokio::test]
async fn thread_read_loaded_ephemeral_thread_ignores_unrelated_rollout_mentions() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
let codex_home = TempDir::new()?;
create_config_toml(codex_home.path(), &server.uri())?;
let mut mcp = McpProcess::new(codex_home.path()).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
model: Some("mock-model".to_string()),
ephemeral: Some(true),
..Default::default()
})
.await?;
let start_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(start_id)),
)
.await??;
let ThreadStartResponse { thread, .. } = to_response::<ThreadStartResponse>(start_resp)?;
let unrelated_preview = thread.id.clone();
let _unrelated_rollout_id = create_fake_rollout_with_text_elements(
codex_home.path(),
"2025-01-05T13-00-00",
"2025-01-05T13:00:00Z",
&unrelated_preview,
vec![],
Some("mock_provider"),
/*git_info*/ None,
)?;
let read_id = mcp
.send_thread_read_request(ThreadReadParams {
thread_id: thread.id.clone(),
include_turns: false,
})
.await?;
let read_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(read_id)),
)
.await??;
let ThreadReadResponse { thread: read } = to_response::<ThreadReadResponse>(read_resp)?;
assert_eq!(read.id, thread.id);
assert!(read.ephemeral);
assert_eq!(read.path, None);
assert!(read.preview.is_empty());
assert_eq!(read.status, ThreadStatus::Idle);
Ok(())
}
#[tokio::test]
async fn thread_read_reports_system_error_idle_flag_after_failed_turn() -> Result<()> {
let server = responses::start_mock_server().await;
@@ -1,3 +1,7 @@
use super::analytics::assert_basic_thread_initialized_event;
use super::analytics::enable_analytics_capture;
use super::analytics::thread_initialized_event;
use super::analytics::wait_for_analytics_payload;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::McpProcess;
@@ -62,52 +66,22 @@ use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use tempfile::TempDir;
use tokio::time::sleep;
use tokio::time::timeout;
use uuid::Uuid;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::analytics::assert_basic_thread_initialized_event;
use super::analytics::enable_analytics_capture;
use super::analytics::thread_initialized_event;
use super::analytics::wait_for_analytics_payload;
#[cfg(windows)]
const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25);
#[cfg(not(windows))]
const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
const CODEX_5_2_INSTRUCTIONS_TEMPLATE_DEFAULT: &str = "You are Codex, a coding agent based on GPT-5. You and the user share the same workspace and collaborate to achieve the user's goals.";
async fn wait_for_responses_request_count(
server: &wiremock::MockServer,
expected_count: usize,
) -> Result<()> {
timeout(DEFAULT_READ_TIMEOUT, async {
loop {
let Some(requests) = server.received_requests().await else {
anyhow::bail!("wiremock did not record requests");
};
let responses_request_count = requests
.iter()
.filter(|request| {
request.method == "POST" && request.url.path().ends_with("/responses")
})
.count();
if responses_request_count == expected_count {
return Ok::<(), anyhow::Error>(());
}
if responses_request_count > expected_count {
anyhow::bail!(
"expected exactly {expected_count} /responses requests, got {responses_request_count}"
);
}
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
})
.await??;
Ok(())
}
#[tokio::test]
async fn thread_resume_rejects_unmaterialized_thread() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
@@ -274,6 +248,62 @@ async fn thread_resume_returns_rollout_history() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn thread_resume_unarchives_archived_rollout() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
let codex_home = TempDir::new()?;
create_config_toml(codex_home.path(), &server.uri())?;
let filename_ts = "2025-01-05T12-00-00";
let conversation_id = create_fake_rollout_with_text_elements(
codex_home.path(),
filename_ts,
"2025-01-05T12:00:00Z",
"Saved user message",
Vec::new(),
Some("mock_provider"),
/*git_info*/ None,
)?;
let active_rollout_path = rollout_path(codex_home.path(), filename_ts, &conversation_id);
let archived_rollout_path = codex_home.path().join("archived_sessions/2025/01/05").join(
active_rollout_path
.file_name()
.expect("active rollout file name"),
);
std::fs::create_dir_all(
archived_rollout_path
.parent()
.expect("archived rollout parent directory"),
)?;
std::fs::rename(&active_rollout_path, &archived_rollout_path)?;
let mut mcp = McpProcess::new(codex_home.path()).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
thread_id: conversation_id.clone(),
..Default::default()
})
.await?;
let resume_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(resume_id)),
)
.await??;
let ThreadResumeResponse { thread, .. } = to_response::<ThreadResumeResponse>(resume_resp)?;
assert_eq!(thread.id, conversation_id);
assert!(active_rollout_path.exists());
assert!(!archived_rollout_path.exists());
assert_eq!(
std::fs::canonicalize(thread.path.as_ref().expect("thread path"))?,
std::fs::canonicalize(&active_rollout_path)?
);
Ok(())
}
#[tokio::test]
async fn thread_resume_prefers_persisted_git_metadata_for_local_threads() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
@@ -1069,13 +1099,9 @@ async fn thread_resume_replays_pending_command_execution_request_approval() -> R
let responses = vec![
create_final_assistant_message_sse_response("seeded")?,
create_shell_command_sse_response(
vec![
"python3".to_string(),
"-c".to_string(),
"print(42)".to_string(),
],
fast_shell_command(),
/*workdir*/ None,
Some(5000),
Some(1000),
"call-1",
)?,
create_final_assistant_message_sse_response("done")?,
@@ -1195,7 +1221,7 @@ async fn thread_resume_replays_pending_command_execution_request_approval() -> R
primary.read_stream_until_notification_message("turn/completed"),
)
.await??;
wait_for_responses_request_count(&server, /*expected_count*/ 3).await?;
wait_for_mock_request_count(&server, /*expected*/ 3).await?;
Ok(())
}
@@ -1361,11 +1387,50 @@ async fn thread_resume_replays_pending_file_change_request_approval() -> Result<
primary.read_stream_until_notification_message("turn/completed"),
)
.await??;
wait_for_responses_request_count(&server, /*expected_count*/ 3).await?;
wait_for_mock_request_count(&server, /*expected*/ 3).await?;
Ok(())
}
fn fast_shell_command() -> Vec<String> {
if cfg!(windows) {
vec![
"cmd".to_string(),
"/d".to_string(),
"/c".to_string(),
"echo 42".to_string(),
]
} else {
vec![
"python3".to_string(),
"-c".to_string(),
"print(42)".to_string(),
]
}
}
async fn wait_for_mock_request_count(server: &MockServer, expected: usize) -> Result<()> {
let deadline = tokio::time::Instant::now() + DEFAULT_READ_TIMEOUT;
loop {
let requests = server
.received_requests()
.await
.ok_or_else(|| anyhow::anyhow!("failed to fetch received requests"))?;
if requests.len() >= expected {
return Ok(());
}
if tokio::time::Instant::now() >= deadline {
anyhow::bail!(
"expected at least {expected} mock requests, observed {}",
requests.len()
);
}
sleep(std::time::Duration::from_millis(50)).await;
}
}
#[tokio::test]
async fn thread_resume_with_overrides_defers_updated_at_until_turn_start() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
@@ -273,9 +273,14 @@ async fn thread_start_accepts_flex_service_tier() -> Result<()> {
let codex_home = TempDir::new()?;
create_config_toml(codex_home.path(), &server.uri())?;
let read_timeout = if cfg!(windows) {
std::time::Duration::from_secs(15)
} else {
DEFAULT_READ_TIMEOUT
};
let mut mcp = McpProcess::new(codex_home.path()).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
timeout(read_timeout, mcp.initialize()).await??;
let req_id = mcp
.send_thread_start_request(ThreadStartParams {
@@ -285,7 +290,7 @@ async fn thread_start_accepts_flex_service_tier() -> Result<()> {
.await?;
let resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
read_timeout,
mcp.read_stream_until_response_message(RequestId::Integer(req_id)),
)
.await??;
@@ -33,6 +33,9 @@ use pretty_assertions::assert_eq;
use tempfile::TempDir;
use tokio::time::timeout;
#[cfg(windows)]
const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25);
#[cfg(not(windows))]
const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
async fn wait_for_responses_request_count_to_stabilize(
@@ -192,6 +195,10 @@ async fn thread_unsubscribe_during_turn_interrupts_turn_and_emits_thread_closed(
wait_for_command_execution_item_started(&mut mcp),
)
.await??;
// `item/started` can arrive before the spawned command reports a process id.
// Give the runtime a brief moment to finish wiring the command so unsubscribe
// consistently exercises the shutdown path on slower CI runners.
tokio::time::sleep(std::time::Duration::from_millis(250)).await;
let unsubscribe_id = mcp
.send_thread_unsubscribe_request(ThreadUnsubscribeParams {
@@ -1026,24 +1026,16 @@ async fn turn_start_exec_approval_toggle_v2() -> Result<()> {
// Second turn same, but we'll set approval_policy=never to avoid elicitation.
let responses = vec![
create_shell_command_sse_response(
vec![
"python3".to_string(),
"-c".to_string(),
"print(42)".to_string(),
],
fast_shell_command(),
/*workdir*/ None,
Some(5000),
Some(1000),
"call1",
)?,
create_final_assistant_message_sse_response("done 1")?,
create_shell_command_sse_response(
vec![
"python3".to_string(),
"-c".to_string(),
"print(42)".to_string(),
],
fast_shell_command(),
/*workdir*/ None,
Some(5000),
Some(1000),
"call2",
)?,
create_final_assistant_message_sse_response("done 2")?,
@@ -1170,6 +1162,23 @@ async fn turn_start_exec_approval_toggle_v2() -> Result<()> {
Ok(())
}
fn fast_shell_command() -> Vec<String> {
if cfg!(windows) {
vec![
"cmd".to_string(),
"/d".to_string(),
"/c".to_string(),
"echo 42".to_string(),
]
} else {
vec![
"python3".to_string(),
"-c".to_string(),
"print(42)".to_string(),
]
}
}
#[tokio::test]
async fn turn_start_exec_approval_decline_v2() -> Result<()> {
skip_if_no_network!(Ok(()));
@@ -1665,12 +1674,18 @@ async fn turn_start_file_change_approval_v2() -> Result<()> {
}
#[tokio::test]
async fn turn_start_emits_spawn_agent_item_with_model_metadata_v2() -> Result<()> {
async fn turn_start_emits_spawn_agent_item_with_effective_inherited_model_metadata_v2() -> Result<()>
{
skip_if_no_network!(Ok(()));
const CHILD_PROMPT: &str = "child: do work";
const PARENT_PROMPT: &str = "spawn a child and continue";
const SPAWN_CALL_ID: &str = "spawn-call-1";
const INHERITED_MODEL: &str = "gpt-5.2-codex";
// thread/start only sets the model here; the session keeps the resolved collaboration-mode
// effort for that thread, so fork-context children should inherit `Medium`, not the model
// catalog default.
const INHERITED_REASONING_EFFORT: ReasoningEffort = ReasoningEffort::Medium;
const REQUESTED_MODEL: &str = "gpt-5.1";
const REQUESTED_REASONING_EFFORT: ReasoningEffort = ReasoningEffort::Low;
@@ -1726,7 +1741,7 @@ async fn turn_start_emits_spawn_agent_item_with_model_metadata_v2() -> Result<()
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.2-codex".to_string()),
model: Some(INHERITED_MODEL.to_string()),
..Default::default()
})
.await?;
@@ -1823,8 +1838,8 @@ async fn turn_start_emits_spawn_agent_item_with_model_metadata_v2() -> Result<()
assert_eq!(sender_thread_id, thread.id);
assert_eq!(receiver_thread_ids, vec![receiver_thread_id.clone()]);
assert_eq!(prompt, Some(CHILD_PROMPT.to_string()));
assert_eq!(model, Some(REQUESTED_MODEL.to_string()));
assert_eq!(reasoning_effort, Some(REQUESTED_REASONING_EFFORT));
assert_eq!(model, Some(INHERITED_MODEL.to_string()));
assert_eq!(reasoning_effort, Some(INHERITED_REASONING_EFFORT));
let agent_state = agents_states
.get(&receiver_thread_id)
.expect("spawn completion should include child agent state");
@@ -1865,6 +1880,11 @@ async fn turn_start_emits_spawn_agent_item_with_effective_role_model_metadata_v2
const CHILD_PROMPT: &str = "child: do work";
const PARENT_PROMPT: &str = "spawn a child and continue";
const SPAWN_CALL_ID: &str = "spawn-call-1";
const INHERITED_MODEL: &str = "gpt-5.2-codex";
// thread/start only sets the model here; the session keeps the resolved collaboration-mode
// effort for that thread, so fork-context children should inherit `Medium`, not the model
// catalog default.
const INHERITED_REASONING_EFFORT: ReasoningEffort = ReasoningEffort::Medium;
const REQUESTED_MODEL: &str = "gpt-5.1";
const REQUESTED_REASONING_EFFORT: ReasoningEffort = ReasoningEffort::Low;
const ROLE_MODEL: &str = "gpt-5.1-codex-max";
@@ -2007,8 +2027,8 @@ config_file = "./custom-role.toml"
assert_eq!(sender_thread_id, thread.id);
assert_eq!(receiver_thread_ids, vec![receiver_thread_id.clone()]);
assert_eq!(prompt, Some(CHILD_PROMPT.to_string()));
assert_eq!(model, Some(ROLE_MODEL.to_string()));
assert_eq!(reasoning_effort, Some(ROLE_REASONING_EFFORT));
assert_eq!(model, Some(INHERITED_MODEL.to_string()));
assert_eq!(reasoning_effort, Some(INHERITED_REASONING_EFFORT));
let agent_state = agents_states
.get(&receiver_thread_id)
.expect("spawn completion should include child agent state");
@@ -215,9 +215,12 @@ async fn turn_start_shell_zsh_fork_exec_approval_decline_v2() -> Result<()> {
]),
&zsh_path,
)?;
// This flow can require several sequential approval round-trips on slower
// macOS runners before the parent command reaches a terminal state.
let read_timeout = std::time::Duration::from_secs(20);
let mut mcp = create_zsh_test_mcp_process(&codex_home, &workspace).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
timeout(read_timeout, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
@@ -227,7 +230,7 @@ async fn turn_start_shell_zsh_fork_exec_approval_decline_v2() -> Result<()> {
})
.await?;
let start_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
read_timeout,
mcp.read_stream_until_response_message(RequestId::Integer(start_id)),
)
.await??;
@@ -348,9 +351,12 @@ async fn turn_start_shell_zsh_fork_exec_approval_cancel_v2() -> Result<()> {
]),
&zsh_path,
)?;
// This flow can require several sequential approval round-trips on slower
// macOS runners before the parent command reaches a terminal state.
let read_timeout = std::time::Duration::from_secs(20);
let mut mcp = create_zsh_test_mcp_process(&codex_home, &workspace).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
timeout(read_timeout, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
@@ -360,7 +366,7 @@ async fn turn_start_shell_zsh_fork_exec_approval_cancel_v2() -> Result<()> {
})
.await?;
let start_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
read_timeout,
mcp.read_stream_until_response_message(RequestId::Integer(start_id)),
)
.await??;
@@ -507,9 +513,10 @@ async fn turn_start_shell_zsh_fork_subcommand_decline_marks_parent_declined_v2()
]),
&zsh_path,
)?;
let read_timeout = std::time::Duration::from_secs(20);
let mut mcp = create_zsh_test_mcp_process(&codex_home, &workspace).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
timeout(read_timeout, mcp.initialize()).await??;
let start_id = mcp
.send_thread_start_request(ThreadStartParams {
@@ -519,7 +526,7 @@ async fn turn_start_shell_zsh_fork_subcommand_decline_marks_parent_declined_v2()
})
.await?;
let start_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
read_timeout,
mcp.read_stream_until_response_message(RequestId::Integer(start_id)),
)
.await??;
@@ -548,7 +555,7 @@ async fn turn_start_shell_zsh_fork_subcommand_decline_marks_parent_declined_v2()
})
.await?;
let turn_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
read_timeout,
mcp.read_stream_until_response_message(RequestId::Integer(turn_id)),
)
.await??;
@@ -566,11 +573,7 @@ async fn turn_start_shell_zsh_fork_subcommand_decline_marks_parent_declined_v2()
let second_file_str = second_file.to_string_lossy().into_owned();
let parent_shell_hint = format!("&& {}", &first_file_str);
while target_decision_index < target_decisions.len() || !saw_parent_approval {
let server_req = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_request_message(),
)
.await??;
let server_req = timeout(read_timeout, mcp.read_stream_until_request_message()).await??;
let ServerRequest::CommandExecutionRequestApproval { request_id, params } = server_req
else {
panic!("expected CommandExecutionRequestApproval request");
@@ -640,7 +643,7 @@ async fn turn_start_shell_zsh_fork_subcommand_decline_marks_parent_declined_v2()
assert_eq!(approved_subcommand_strings.len(), 2);
assert!(approved_subcommand_strings[0].contains(&first_file.display().to_string()));
assert!(approved_subcommand_strings[1].contains(&second_file.display().to_string()));
let parent_completed_command_execution = timeout(DEFAULT_READ_TIMEOUT, async {
let parent_completed_command_execution = timeout(read_timeout, async {
loop {
let completed_notif = mcp
.read_stream_until_notification_message("item/completed")
@@ -682,7 +685,7 @@ async fn turn_start_shell_zsh_fork_subcommand_decline_marks_parent_declined_v2()
}
match timeout(
DEFAULT_READ_TIMEOUT,
read_timeout,
mcp.read_stream_until_notification_message("turn/completed"),
)
.await
@@ -705,7 +708,7 @@ async fn turn_start_shell_zsh_fork_subcommand_decline_marks_parent_declined_v2()
mcp.interrupt_turn_and_wait_for_aborted(
thread.id.clone(),
turn.id.clone(),
DEFAULT_READ_TIMEOUT,
read_timeout,
)
.await?;
}
@@ -718,7 +721,7 @@ async fn turn_start_shell_zsh_fork_subcommand_decline_marks_parent_declined_v2()
// sandbox failures can also complete the turn before the parent
// completion item is observed.
let completed_notif = timeout(
DEFAULT_READ_TIMEOUT,
read_timeout,
mcp.read_stream_until_notification_message("turn/completed"),
)
.await??;
+1 -1
View File
@@ -309,7 +309,7 @@ where
D: Deserializer<'de>,
T: Deserialize<'de>,
{
Option::<Vec<T>>::deserialize(deserializer).map(Option::unwrap_or_default)
Option::<Vec<T>>::deserialize(deserializer).map(std::option::Option::unwrap_or_default)
}
#[derive(Clone, Debug, Deserialize)]
+39 -1
View File
@@ -629,12 +629,16 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> {
.await?;
handle_app_exit(exit_info)?;
}
Some(Subcommand::Exec(mut exec_cli)) => {
Some(Subcommand::Exec(exec_cli)) => {
reject_remote_mode_for_subcommand(
root_remote.as_deref(),
root_remote_auth_token_env.as_deref(),
"exec",
)?;
let mut exec_cli = match exec_cli.validate() {
Ok(exec_cli) => exec_cli,
Err(err) => err.exit(),
};
prepend_config_flags(
&mut exec_cli.config_overrides,
root_config_overrides.clone(),
@@ -1478,6 +1482,40 @@ mod tests {
assert_eq!(args.session_id.as_deref(), Some("session-123"));
assert_eq!(args.prompt.as_deref(), Some("re-review"));
}
#[test]
fn exec_fork_accepts_prompt_positional() {
let cli = MultitoolCli::try_parse_from([
"codex",
"exec",
"--json",
"--fork",
"session-123",
"2+2",
])
.expect("parse should succeed");
let Some(Subcommand::Exec(exec)) = cli.subcommand else {
panic!("expected exec subcommand");
};
assert_eq!(exec.fork_session_id.as_deref(), Some("session-123"));
assert!(exec.command.is_none());
assert_eq!(exec.prompt.as_deref(), Some("2+2"));
}
#[test]
fn exec_fork_conflicts_with_resume_subcommand() {
let cli =
MultitoolCli::try_parse_from(["codex", "exec", "--fork", "session-123", "resume"])
.expect("parse should succeed");
let Some(Subcommand::Exec(exec)) = cli.subcommand else {
panic!("expected exec subcommand");
};
let validate_result = exec.validate();
assert!(validate_result.is_err());
}
fn app_server_from_args(args: &[&str]) -> AppServerCommand {
let cli = MultitoolCli::try_parse_from(args).expect("parse");
@@ -54,6 +54,7 @@ async fn models_client_hits_models_endpoint() {
let response = ModelsResponse {
models: vec![ModelInfo {
slug: "gpt-test".to_string(),
request_model: None,
display_name: "gpt-test".to_string(),
description: Some("desc".to_string()),
default_reasoning_level: Some(ReasoningEffort::Medium),
+10
View File
@@ -0,0 +1,10 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "config-schema",
crate_name = "codex_config_schema",
compile_data = ["//codex-rs/core:config.schema.json"],
rustc_env = {
"CARGO_MANIFEST_DIR": "codex-rs/config-schema",
},
)
+27
View File
@@ -0,0 +1,27 @@
[package]
name = "codex-config-schema"
version.workspace = true
edition.workspace = true
license.workspace = true
[lib]
doctest = false
name = "codex_config_schema"
path = "src/lib.rs"
[[bin]]
name = "codex-write-config-schema"
path = "src/bin/config_schema.rs"
[lints]
workspace = true
[dependencies]
anyhow = { workspace = true }
clap = { workspace = true, features = ["derive"] }
codex-config = { workspace = true }
codex-protocol = { workspace = true }
codex-utils-absolute-path = { workspace = true }
schemars = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
@@ -0,0 +1,20 @@
use anyhow::Result;
use clap::Parser;
use std::path::PathBuf;
/// Generate the JSON Schema for `config.toml` and write it to `config.schema.json`.
#[derive(Parser)]
#[command(name = "codex-write-config-schema")]
struct Args {
#[arg(short, long, value_name = "PATH")]
out: Option<PathBuf>,
}
fn main() -> Result<()> {
let args = Args::parse();
let out_path = args.out.unwrap_or_else(|| {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../core/config.schema.json")
});
codex_config_schema::write_config_schema(&out_path)?;
Ok(())
}
+617
View File
@@ -0,0 +1,617 @@
use crate::features::features_schema;
use crate::model_provider::ModelProviderInfo;
use crate::permissions::PermissionsToml;
use codex_config::AppToolApproval;
use codex_config::McpServerConfig;
use codex_config::RawMcpServerConfig;
use codex_config::SkillsConfig;
use codex_protocol::config_types::AltScreenMode;
use codex_protocol::config_types::ApprovalsReviewer;
use codex_protocol::config_types::ForcedLoginMethod;
use codex_protocol::config_types::Personality;
use codex_protocol::config_types::ReasoningSummary;
use codex_protocol::config_types::SandboxMode;
use codex_protocol::config_types::ServiceTier;
use codex_protocol::config_types::TrustLevel;
use codex_protocol::config_types::Verbosity;
use codex_protocol::config_types::WebSearchMode;
use codex_protocol::config_types::WebSearchToolConfig;
use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::RealtimeConversationVersion as RealtimeWsVersion;
use codex_utils_absolute_path::AbsolutePathBuf;
use schemars::JsonSchema;
use schemars::r#gen::SchemaGenerator;
use schemars::schema::InstanceType;
use schemars::schema::ObjectValidation;
use schemars::schema::Schema;
use schemars::schema::SchemaObject;
use serde::Deserialize;
use serde::Serialize;
use std::collections::BTreeMap;
use std::collections::HashMap;
const fn default_enabled() -> bool {
true
}
const fn default_true() -> bool {
true
}
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum AuthCredentialsStoreMode {
#[default]
File,
Keyring,
Auto,
Ephemeral,
}
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum OAuthCredentialsStoreMode {
#[default]
Auto,
File,
Keyring,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ConfigProfile {
pub model: Option<String>,
pub service_tier: Option<ServiceTier>,
pub model_provider: Option<String>,
pub approval_policy: Option<AskForApproval>,
pub approvals_reviewer: Option<ApprovalsReviewer>,
pub sandbox_mode: Option<SandboxMode>,
pub model_reasoning_effort: Option<ReasoningEffort>,
pub plan_mode_reasoning_effort: Option<ReasoningEffort>,
pub model_reasoning_summary: Option<ReasoningSummary>,
pub model_verbosity: Option<Verbosity>,
pub model_catalog_json: Option<AbsolutePathBuf>,
pub personality: Option<Personality>,
pub chatgpt_base_url: Option<String>,
pub model_instructions_file: Option<AbsolutePathBuf>,
pub js_repl_node_path: Option<AbsolutePathBuf>,
pub js_repl_node_module_dirs: Option<Vec<AbsolutePathBuf>>,
pub zsh_path: Option<AbsolutePathBuf>,
#[schemars(skip)]
pub experimental_instructions_file: Option<AbsolutePathBuf>,
pub experimental_compact_prompt_file: Option<AbsolutePathBuf>,
pub include_apply_patch_tool: Option<bool>,
pub experimental_use_unified_exec_tool: Option<bool>,
pub experimental_use_freeform_apply_patch: Option<bool>,
pub tools_view_image: Option<bool>,
pub tools: Option<ToolsToml>,
pub web_search: Option<WebSearchMode>,
pub analytics: Option<AnalyticsConfigToml>,
#[serde(default)]
pub windows: Option<WindowsToml>,
#[serde(default)]
#[schemars(schema_with = "features_schema")]
pub features: Option<FeaturesToml>,
pub oss_provider: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, JsonSchema)]
pub struct FeaturesToml {
#[serde(flatten)]
pub entries: BTreeMap<String, bool>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum WindowsSandboxModeToml {
Elevated,
Unelevated,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct WindowsToml {
pub sandbox: Option<WindowsSandboxModeToml>,
pub sandbox_private_desktop: Option<bool>,
}
#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, JsonSchema)]
pub enum UriBasedFileOpener {
#[serde(rename = "vscode")]
VsCode,
#[serde(rename = "vscode-insiders")]
VsCodeInsiders,
#[serde(rename = "windsurf")]
Windsurf,
#[serde(rename = "cursor")]
Cursor,
#[serde(rename = "none")]
None,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct History {
pub persistence: HistoryPersistence,
pub max_bytes: Option<usize>,
}
#[derive(Serialize, Deserialize, Debug, Copy, Clone, PartialEq, Default, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum HistoryPersistence {
#[default]
SaveAll,
None,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct AnalyticsConfigToml {
pub enabled: Option<bool>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct FeedbackConfigToml {
pub enabled: Option<bool>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ToolSuggestDiscoverableType {
Connector,
Plugin,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ToolSuggestDiscoverable {
#[serde(rename = "type")]
pub kind: ToolSuggestDiscoverableType,
pub id: String,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ToolSuggestConfig {
#[serde(default)]
pub discoverables: Vec<ToolSuggestDiscoverable>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct MemoriesToml {
pub no_memories_if_mcp_or_web_search: Option<bool>,
pub generate_memories: Option<bool>,
pub use_memories: Option<bool>,
pub max_raw_memories_for_consolidation: Option<usize>,
pub max_unused_days: Option<i64>,
pub max_rollout_age_days: Option<i64>,
pub max_rollouts_per_startup: Option<usize>,
pub min_rollout_idle_hours: Option<i64>,
pub extract_model: Option<String>,
pub consolidation_model: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct AppsDefaultConfig {
#[serde(default = "default_enabled")]
pub enabled: bool,
#[serde(
default = "default_enabled",
skip_serializing_if = "std::clone::Clone::clone"
)]
pub destructive_enabled: bool,
#[serde(
default = "default_enabled",
skip_serializing_if = "std::clone::Clone::clone"
)]
pub open_world_enabled: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct AppToolConfig {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enabled: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub approval_mode: Option<AppToolApproval>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct AppToolsConfig {
#[serde(default, flatten)]
pub tools: HashMap<String, AppToolConfig>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct AppConfig {
#[serde(default = "default_enabled")]
pub enabled: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub destructive_enabled: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub open_world_enabled: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_tools_approval_mode: Option<AppToolApproval>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_tools_enabled: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tools: Option<AppToolsConfig>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct AppsConfigToml {
#[serde(default, rename = "_default", skip_serializing_if = "Option::is_none")]
pub default: Option<AppsDefaultConfig>,
#[serde(default, flatten)]
pub apps: HashMap<String, AppConfig>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum OtelHttpProtocol {
Binary,
Json,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
#[schemars(deny_unknown_fields)]
#[serde(rename_all = "kebab-case")]
pub struct OtelTlsConfig {
pub ca_certificate: Option<AbsolutePathBuf>,
pub client_certificate: Option<AbsolutePathBuf>,
pub client_private_key: Option<AbsolutePathBuf>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)]
#[schemars(deny_unknown_fields)]
#[serde(rename_all = "kebab-case")]
pub enum OtelExporterKind {
None,
Statsig,
OtlpHttp {
endpoint: String,
#[serde(default)]
headers: HashMap<String, String>,
protocol: OtelHttpProtocol,
#[serde(default)]
tls: Option<OtelTlsConfig>,
},
OtlpGrpc {
endpoint: String,
#[serde(default)]
headers: HashMap<String, String>,
#[serde(default)]
tls: Option<OtelTlsConfig>,
},
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct OtelConfigToml {
pub log_user_prompt: Option<bool>,
pub environment: Option<String>,
pub exporter: Option<OtelExporterKind>,
pub trace_exporter: Option<OtelExporterKind>,
pub metrics_exporter: Option<OtelExporterKind>,
}
#[derive(Serialize, Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum Notifications {
Enabled(bool),
Custom(Vec<String>),
}
impl Default for Notifications {
fn default() -> Self {
Self::Enabled(true)
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, Default)]
#[serde(rename_all = "lowercase")]
pub enum NotificationMethod {
#[default]
Auto,
Osc9,
Bel,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ModelAvailabilityNuxConfig {
#[serde(default, flatten)]
pub shown_count: HashMap<String, u32>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct Tui {
#[serde(default)]
pub notifications: Notifications,
#[serde(default)]
pub notification_method: NotificationMethod,
#[serde(default = "default_true")]
pub animations: bool,
#[serde(default = "default_true")]
pub show_tooltips: bool,
#[serde(default)]
pub alternate_screen: AltScreenMode,
#[serde(default)]
pub status_line: Option<Vec<String>>,
#[serde(default)]
pub terminal_title: Option<Vec<String>>,
#[serde(default)]
pub theme: Option<String>,
#[serde(default)]
pub model_availability_nux: ModelAvailabilityNuxConfig,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
pub struct Notice {
pub hide_full_access_warning: Option<bool>,
pub hide_world_writable_warning: Option<bool>,
pub hide_rate_limit_model_nudge: Option<bool>,
pub hide_gpt5_1_migration_prompt: Option<bool>,
#[serde(rename = "hide_gpt-5.1-codex-max_migration_prompt")]
pub hide_gpt_5_1_codex_max_migration_prompt: Option<bool>,
#[serde(default)]
pub model_migrations: BTreeMap<String, String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct PluginConfig {
#[serde(default = "default_enabled")]
pub enabled: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct SandboxWorkspaceWrite {
#[serde(default)]
pub writable_roots: Vec<AbsolutePathBuf>,
#[serde(default)]
pub network_access: bool,
#[serde(default)]
pub exclude_tmpdir_env_var: bool,
#[serde(default)]
pub exclude_slash_tmp: bool,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum ShellEnvironmentPolicyInherit {
Core,
#[default]
All,
None,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ShellEnvironmentPolicyToml {
pub inherit: Option<ShellEnvironmentPolicyInherit>,
pub ignore_default_excludes: Option<bool>,
pub exclude: Option<Vec<String>>,
pub r#set: Option<HashMap<String, String>>,
pub include_only: Option<Vec<String>>,
pub experimental_use_profile: Option<bool>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ProjectConfig {
pub trust_level: Option<TrustLevel>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, Default, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RealtimeWsMode {
#[default]
Conversational,
Transcription,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct RealtimeToml {
pub version: Option<RealtimeWsVersion>,
#[serde(rename = "type")]
pub session_type: Option<RealtimeWsMode>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct RealtimeAudioToml {
pub microphone: Option<String>,
pub speaker: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct CustomModelToml {
pub name: String,
pub model: String,
pub model_context_window: Option<i64>,
pub model_auto_compact_token_limit: Option<i64>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ToolsToml {
pub web_search: Option<WebSearchToolConfig>,
#[serde(default)]
pub view_image: Option<bool>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct AgentsToml {
#[schemars(range(min = 1))]
pub max_threads: Option<usize>,
#[schemars(range(min = 1))]
pub max_depth: Option<i32>,
#[schemars(range(min = 1))]
pub job_max_runtime_seconds: Option<u64>,
#[serde(default, flatten)]
pub roles: BTreeMap<String, AgentRoleToml>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct AgentRoleToml {
pub description: Option<String>,
pub config_file: Option<AbsolutePathBuf>,
pub nickname_candidates: Option<Vec<String>>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct GhostSnapshotToml {
#[serde(alias = "ignore_untracked_files_over_bytes")]
pub ignore_large_untracked_files: Option<i64>,
#[serde(alias = "large_untracked_dir_warning_threshold")]
pub ignore_large_untracked_dirs: Option<i64>,
pub disable_warnings: Option<bool>,
}
/// Base config deserialized from ~/.codex/config.toml.
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ConfigToml {
pub model: Option<String>,
pub review_model: Option<String>,
pub model_provider: Option<String>,
pub model_context_window: Option<i64>,
pub model_auto_compact_token_limit: Option<i64>,
pub approval_policy: Option<AskForApproval>,
pub approvals_reviewer: Option<ApprovalsReviewer>,
#[serde(default)]
pub shell_environment_policy: ShellEnvironmentPolicyToml,
pub allow_login_shell: Option<bool>,
pub sandbox_mode: Option<SandboxMode>,
pub sandbox_workspace_write: Option<SandboxWorkspaceWrite>,
pub default_permissions: Option<String>,
#[serde(default)]
pub permissions: Option<PermissionsToml>,
#[serde(default)]
pub notify: Option<Vec<String>>,
pub instructions: Option<String>,
#[serde(default)]
pub developer_instructions: Option<String>,
pub model_instructions_file: Option<AbsolutePathBuf>,
pub compact_prompt: Option<String>,
pub commit_attribution: Option<String>,
#[serde(default)]
pub forced_chatgpt_workspace_id: Option<String>,
#[serde(default)]
pub forced_login_method: Option<ForcedLoginMethod>,
#[serde(default)]
pub cli_auth_credentials_store: Option<AuthCredentialsStoreMode>,
#[serde(default)]
#[schemars(schema_with = "mcp_servers_schema")]
pub mcp_servers: HashMap<String, McpServerConfig>,
#[serde(default)]
pub mcp_oauth_credentials_store: Option<OAuthCredentialsStoreMode>,
pub mcp_oauth_callback_port: Option<u16>,
pub mcp_oauth_callback_url: Option<String>,
#[serde(default)]
pub model_providers: HashMap<String, ModelProviderInfo>,
#[serde(default)]
pub custom_models: Vec<CustomModelToml>,
pub project_doc_max_bytes: Option<usize>,
pub project_doc_fallback_filenames: Option<Vec<String>>,
pub tool_output_token_limit: Option<usize>,
pub background_terminal_max_timeout: Option<u64>,
pub js_repl_node_path: Option<AbsolutePathBuf>,
pub js_repl_node_module_dirs: Option<Vec<AbsolutePathBuf>>,
pub zsh_path: Option<AbsolutePathBuf>,
pub profile: Option<String>,
#[serde(default)]
pub profiles: HashMap<String, ConfigProfile>,
#[serde(default)]
pub history: Option<History>,
pub sqlite_home: Option<AbsolutePathBuf>,
pub log_dir: Option<AbsolutePathBuf>,
pub file_opener: Option<UriBasedFileOpener>,
pub tui: Option<Tui>,
pub hide_agent_reasoning: Option<bool>,
pub show_raw_agent_reasoning: Option<bool>,
pub model_reasoning_effort: Option<ReasoningEffort>,
pub plan_mode_reasoning_effort: Option<ReasoningEffort>,
pub model_reasoning_summary: Option<ReasoningSummary>,
pub model_verbosity: Option<Verbosity>,
pub model_supports_reasoning_summaries: Option<bool>,
pub model_catalog_json: Option<AbsolutePathBuf>,
pub personality: Option<Personality>,
pub service_tier: Option<ServiceTier>,
pub chatgpt_base_url: Option<String>,
pub openai_base_url: Option<String>,
#[serde(default)]
pub audio: Option<RealtimeAudioToml>,
pub experimental_realtime_ws_base_url: Option<String>,
pub experimental_realtime_ws_model: Option<String>,
#[serde(default)]
pub realtime: Option<RealtimeToml>,
pub experimental_realtime_ws_backend_prompt: Option<String>,
pub experimental_realtime_ws_startup_context: Option<String>,
pub experimental_realtime_start_instructions: Option<String>,
pub projects: Option<HashMap<String, ProjectConfig>>,
pub web_search: Option<WebSearchMode>,
pub tools: Option<ToolsToml>,
pub tool_suggest: Option<ToolSuggestConfig>,
pub agents: Option<AgentsToml>,
pub memories: Option<MemoriesToml>,
pub skills: Option<SkillsConfig>,
#[serde(default)]
pub plugins: HashMap<String, PluginConfig>,
#[serde(default)]
#[schemars(schema_with = "features_schema")]
pub features: Option<FeaturesToml>,
pub suppress_unstable_features_warning: Option<bool>,
#[serde(default)]
pub ghost_snapshot: Option<GhostSnapshotToml>,
#[serde(default)]
pub project_root_markers: Option<Vec<String>>,
pub check_for_update_on_startup: Option<bool>,
pub disable_paste_burst: Option<bool>,
pub analytics: Option<AnalyticsConfigToml>,
pub feedback: Option<FeedbackConfigToml>,
#[serde(default)]
pub apps: Option<AppsConfigToml>,
pub otel: Option<OtelConfigToml>,
#[serde(default)]
pub windows: Option<WindowsToml>,
pub windows_wsl_setup_acknowledged: Option<bool>,
pub notice: Option<Notice>,
#[schemars(skip)]
pub experimental_instructions_file: Option<AbsolutePathBuf>,
pub experimental_compact_prompt_file: Option<AbsolutePathBuf>,
pub experimental_use_unified_exec_tool: Option<bool>,
pub experimental_use_freeform_apply_patch: Option<bool>,
pub oss_provider: Option<String>,
}
/// Schema for the `[mcp_servers]` map using the raw input shape.
pub fn mcp_servers_schema(schema_gen: &mut SchemaGenerator) -> Schema {
let mut object = SchemaObject {
instance_type: Some(InstanceType::Object.into()),
..Default::default()
};
let validation = ObjectValidation {
additional_properties: Some(Box::new(schema_gen.subschema_for::<RawMcpServerConfig>())),
..Default::default()
};
object.object = Some(Box::new(validation));
Schema::Object(object)
}
+96
View File
@@ -0,0 +1,96 @@
use schemars::r#gen::SchemaGenerator;
use schemars::schema::InstanceType;
use schemars::schema::ObjectValidation;
use schemars::schema::Schema;
use schemars::schema::SchemaObject;
const FEATURE_KEYS: &[&str] = &[
"undo",
"shell_tool",
"unified_exec",
"shell_zsh_fork",
"shell_snapshot",
"js_repl",
"code_mode",
"code_mode_only",
"js_repl_tools_only",
"web_search_request",
"web_search_cached",
"search_tool",
"codex_git_commit",
"runtime_metrics",
"general_analytics",
"sqlite",
"memories",
"child_agents_md",
"image_detail_original",
"apply_patch_freeform",
"exec_permission_approvals",
"codex_hooks",
"request_permissions_tool",
"use_linux_sandbox_bwrap",
"use_legacy_landlock",
"request_rule",
"experimental_windows_sandbox",
"elevated_windows_sandbox",
"remote_models",
"enable_request_compression",
"multi_agent",
"multi_agent_v2",
"enable_fanout",
"apps",
"tool_search",
"tool_suggest",
"plugins",
"image_generation",
"skill_mcp_dependency_install",
"skill_env_var_dependency_prompt",
"steer",
"default_mode_request_user_input",
"guardian_approval",
"collaboration_modes",
"tool_call_mcp_elicitation",
"personality",
"fast_mode",
"realtime_conversation",
"tui_app_server",
"prevent_idle_sleep",
"responses_websockets",
"responses_websockets_v2",
];
const LEGACY_FEATURE_KEYS: &[&str] = &[
"connectors",
"enable_experimental_windows_sandbox",
"experimental_use_unified_exec_tool",
"experimental_use_freeform_apply_patch",
"include_apply_patch_tool",
"request_permissions",
"web_search",
"collab",
"memory_tool",
];
/// Schema for the `[features]` map with known + legacy keys only.
pub fn features_schema(schema_gen: &mut SchemaGenerator) -> Schema {
let mut object = SchemaObject {
instance_type: Some(InstanceType::Object.into()),
..Default::default()
};
let mut validation = ObjectValidation::default();
for key in FEATURE_KEYS {
validation
.properties
.insert((*key).to_string(), schema_gen.subschema_for::<bool>());
}
for key in LEGACY_FEATURE_KEYS {
validation
.properties
.insert((*key).to_string(), schema_gen.subschema_for::<bool>());
}
validation.additional_properties = Some(Box::new(Schema::Bool(false)));
object.object = Some(Box::new(validation));
Schema::Object(object)
}
+146
View File
@@ -0,0 +1,146 @@
mod config_toml;
mod features;
mod model_provider;
mod permissions;
use config_toml::ConfigToml;
use schemars::r#gen::SchemaSettings;
use schemars::schema::RootSchema;
use serde_json::Map;
use serde_json::Value;
use std::path::Path;
pub use config_toml::mcp_servers_schema;
pub use features::features_schema;
/// Build the config schema for `config.toml`.
pub fn config_schema() -> RootSchema {
SchemaSettings::draft07()
.with(|settings| {
settings.option_add_null_type = false;
})
.into_generator()
.into_root_schema_for::<ConfigToml>()
}
/// Canonicalize a JSON value by sorting its keys.
pub fn canonicalize(value: &Value) -> Value {
match value {
Value::Array(items) => Value::Array(items.iter().map(canonicalize).collect()),
Value::Object(map) => {
let mut entries: Vec<_> = map.iter().collect();
entries.sort_by(|(left, _), (right, _)| left.cmp(right));
let mut sorted = Map::with_capacity(map.len());
for (key, child) in entries {
sorted.insert(key.clone(), canonicalize(child));
}
Value::Object(sorted)
}
_ => value.clone(),
}
}
/// Render the config schema as pretty-printed JSON.
pub fn config_schema_json() -> anyhow::Result<Vec<u8>> {
let schema = config_schema();
let value = serde_json::to_value(schema)?;
let value = preserve_schema_presentation(value)?;
let value = canonicalize(&value);
let mut json = serde_json::to_vec_pretty(&value)?;
json.push(b'\n');
Ok(json)
}
/// Write the config schema fixture to disk.
pub fn write_config_schema(out_path: &Path) -> anyhow::Result<()> {
let json = config_schema_json()?;
std::fs::write(out_path, json)?;
Ok(())
}
fn preserve_schema_presentation(value: Value) -> anyhow::Result<Value> {
let template = include_str!("../../core/config.schema.json");
let template = serde_json::from_str(template)?;
Ok(preserve_schema_presentation_from_template(value, &template))
}
fn preserve_schema_presentation_from_template(mut value: Value, template: &Value) -> Value {
if let (Some(value_ref), Some(template_ref)) = (
value.get("$ref").and_then(Value::as_str),
template_ref(template),
) && value_ref == template_ref
{
return template.clone();
}
if let (Some(value_enum), Some(template_one_of)) =
(string_enum_values(&value), string_one_of_values(template))
&& value_enum == template_one_of
{
return template.clone();
}
if let (Value::Array(values), Value::Array(template_values)) = (&mut value, template) {
for (value_child, template_child) in values.iter_mut().zip(template_values) {
*value_child = preserve_schema_presentation_from_template(
std::mem::take(value_child),
template_child,
);
}
return value;
}
let (Value::Object(value_object), Value::Object(template_object)) = (&mut value, template)
else {
return value;
};
if !value_object.contains_key("description")
&& let Some(description) = template_object.get("description")
{
value_object.insert("description".to_string(), description.clone());
}
for (key, value_child) in value_object.iter_mut() {
let Some(template_child) = template_object.get(key) else {
continue;
};
*value_child =
preserve_schema_presentation_from_template(std::mem::take(value_child), template_child);
}
value
}
fn template_ref(template: &Value) -> Option<&str> {
let template_object = template.as_object()?;
let all_of = template_object.get("allOf")?.as_array()?;
let [schema] = all_of.as_slice() else {
return None;
};
schema.get("$ref")?.as_str()
}
fn string_enum_values(value: &Value) -> Option<Vec<&str>> {
let value_object = value.as_object()?;
if value_object.get("type").and_then(Value::as_str) != Some("string") {
return None;
}
let enums = value_object.get("enum")?.as_array()?;
enums.iter().map(Value::as_str).collect()
}
fn string_one_of_values(value: &Value) -> Option<Vec<&str>> {
let one_of = value.get("oneOf")?.as_array()?;
let mut values = Vec::new();
for item in one_of {
let item_object = item.as_object()?;
if item_object.get("type").and_then(Value::as_str) != Some("string") {
return None;
}
let enums = item_object.get("enum")?.as_array()?;
let mut item_values: Vec<&str> = enums.iter().map(Value::as_str).collect::<Option<_>>()?;
values.append(&mut item_values);
}
Some(values)
}
@@ -0,0 +1,68 @@
use codex_protocol::config_types::ModelProviderAuthInfo;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use std::collections::HashMap;
/// Wire protocol that the provider speaks.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum WireApi {
/// The Responses API exposed by OpenAI at `/v1/responses`.
#[default]
Responses,
}
/// Serializable representation of a provider definition.
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ModelProviderInfo {
/// Friendly display name.
pub name: String,
/// Base URL for the provider's OpenAI-compatible API.
pub base_url: Option<String>,
/// Environment variable that stores the user's API key for this provider.
pub env_key: Option<String>,
/// Optional instructions to help the user get a valid value for the
/// variable and set it.
pub env_key_instructions: Option<String>,
/// Value to use with `Authorization: Bearer <token>` header. Use of this
/// config is discouraged in favor of `env_key` for security reasons, but
/// this may be necessary when using this programmatically.
pub experimental_bearer_token: Option<String>,
/// Command-backed bearer-token configuration for this provider.
pub auth: Option<ModelProviderAuthInfo>,
/// Which wire protocol this provider expects.
#[serde(default)]
pub wire_api: WireApi,
/// Optional query parameters to append to the base URL.
pub query_params: Option<HashMap<String, String>>,
/// Additional HTTP headers to include in requests to this provider where
/// the (key, value) pairs are the header name and value.
pub http_headers: Option<HashMap<String, String>>,
/// Optional HTTP headers to include in requests to this provider where the
/// (key, value) pairs are the header name and _environment variable_ whose
/// value should be used. If the environment variable is not set, or the
/// value is empty, the header will not be included in the request.
pub env_http_headers: Option<HashMap<String, String>>,
/// Maximum number of times to retry a failed HTTP request to this provider.
pub request_max_retries: Option<u64>,
/// Number of times to retry reconnecting a dropped streaming response before failing.
pub stream_max_retries: Option<u64>,
/// Idle timeout (in milliseconds) to wait for activity on a streaming
/// response before treating the connection as lost.
pub stream_idle_timeout_ms: Option<u64>,
/// Maximum time (in milliseconds) to wait for a websocket connection
/// attempt before treating it as failed.
pub websocket_connect_timeout_ms: Option<u64>,
/// Does this provider require an OpenAI API Key or ChatGPT login token? If
/// true, user is presented with login screen on first run, and login
/// preference and token/key are stored in auth.json. If false (which is
/// the default), login screen is skipped, and API key (if needed) comes
/// from the "env_key" environment variable.
#[serde(default)]
pub requires_openai_auth: bool,
/// Whether this provider supports the Responses API WebSocket transport.
#[serde(default)]
pub supports_websockets: bool,
}
+85
View File
@@ -0,0 +1,85 @@
use codex_protocol::permissions::FileSystemAccessMode;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use std::collections::BTreeMap;
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
pub struct PermissionsToml {
#[serde(flatten)]
pub entries: BTreeMap<String, PermissionProfileToml>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct PermissionProfileToml {
pub filesystem: Option<FilesystemPermissionsToml>,
pub network: Option<NetworkToml>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
pub struct FilesystemPermissionsToml {
#[serde(flatten)]
pub entries: BTreeMap<String, FilesystemPermissionToml>,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)]
#[serde(untagged)]
pub enum FilesystemPermissionToml {
Access(FileSystemAccessMode),
Scoped(BTreeMap<String, FileSystemAccessMode>),
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
pub struct NetworkDomainPermissionsToml {
#[serde(flatten)]
pub entries: BTreeMap<String, NetworkDomainPermissionToml>,
}
#[derive(
Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, JsonSchema,
)]
#[serde(rename_all = "lowercase")]
pub enum NetworkDomainPermissionToml {
Allow,
Deny,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
pub struct NetworkUnixSocketPermissionsToml {
#[serde(flatten)]
pub entries: BTreeMap<String, NetworkUnixSocketPermissionToml>,
}
#[derive(
Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, JsonSchema,
)]
#[serde(rename_all = "lowercase")]
pub enum NetworkUnixSocketPermissionToml {
Allow,
None,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum NetworkModeSchema {
Limited,
Full,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct NetworkToml {
pub enabled: Option<bool>,
pub proxy_url: Option<String>,
pub enable_socks5: Option<bool>,
pub socks_url: Option<String>,
pub enable_socks5_udp: Option<bool>,
pub allow_upstream_proxy: Option<bool>,
pub dangerously_allow_non_loopback_proxy: Option<bool>,
pub dangerously_allow_all_unix_sockets: Option<bool>,
pub mode: Option<NetworkModeSchema>,
pub domains: Option<NetworkDomainPermissionsToml>,
pub unix_sockets: Option<NetworkUnixSocketPermissionsToml>,
pub allow_local_binding: Option<bool>,
}
+1
View File
@@ -2,6 +2,7 @@ load("//:defs.bzl", "codex_rust_crate")
exports_files(
[
"config.schema.json",
"templates/collaboration_mode/default.md",
"templates/collaboration_mode/plan.md",
],
+1
View File
@@ -34,6 +34,7 @@ codex-async-utils = { workspace = true }
codex-code-mode = { workspace = true }
codex-connectors = { workspace = true }
codex-config = { workspace = true }
codex-config-schema = { workspace = true }
codex-core-skills = { workspace = true }
codex-exec-server = { workspace = true }
codex-features = { workspace = true }
+79 -1
View File
@@ -21,12 +21,26 @@
"description": "Human-facing role documentation used in spawn tool guidance. Required unless supplied by the referenced agent role file.",
"type": "string"
},
"fork_context": {
"description": "Default fork-context behavior for this role.",
"type": "boolean"
},
"model": {
"description": "Optional model override applied by this role.",
"type": "string"
},
"nickname_candidates": {
"description": "Candidate nicknames for agents spawned with this role.",
"items": {
"type": "string"
},
"type": "array"
},
"watchdog_interval_s": {
"description": "Optional watchdog interval in seconds for roles that should behave as watchdogs.",
"format": "int64",
"minimum": 1.0,
"type": "integer"
}
},
"type": "object"
@@ -53,6 +67,11 @@
"format": "uint",
"minimum": 1.0,
"type": "integer"
},
"use_function_call_inbox": {
"default": false,
"description": "Deliver inbound agent messages to non-subagent threads as a synthetic function_call/function_call_output pair instead of plain user input.",
"type": "boolean"
}
},
"type": "object"
@@ -332,6 +351,15 @@
"default": null,
"description": "Optional feature toggles scoped to this profile.",
"properties": {
"agent_function_call_inbox": {
"type": "boolean"
},
"agent_prompt_injection": {
"type": "boolean"
},
"agent_watchdog": {
"type": "boolean"
},
"apply_patch_freeform": {
"type": "boolean"
},
@@ -606,6 +634,34 @@
},
"type": "object"
},
"CustomModelToml": {
"additionalProperties": false,
"properties": {
"model": {
"description": "Provider-facing model slug used on API requests.",
"type": "string"
},
"model_auto_compact_token_limit": {
"description": "Optional auto-compaction token limit override applied when this alias is selected.",
"format": "int64",
"type": "integer"
},
"model_context_window": {
"description": "Optional context window override applied when this alias is selected.",
"format": "int64",
"type": "integer"
},
"name": {
"description": "User-facing alias shown in the model picker.",
"type": "string"
}
},
"required": [
"model",
"name"
],
"type": "object"
},
"FeedbackConfigToml": {
"additionalProperties": false,
"properties": {
@@ -1983,6 +2039,14 @@
"description": "Compact prompt used for history compaction.",
"type": "string"
},
"custom_models": {
"default": [],
"description": "User-defined model aliases that can override model context settings.",
"items": {
"$ref": "#/definitions/CustomModelToml"
},
"type": "array"
},
"default_permissions": {
"description": "Default named permissions profile to apply from the `[permissions]` table.",
"type": "string"
@@ -2030,6 +2094,15 @@
"default": null,
"description": "Centralized feature flags (new). Prefer this over individual toggles.",
"properties": {
"agent_function_call_inbox": {
"type": "boolean"
},
"agent_prompt_injection": {
"type": "boolean"
},
"agent_watchdog": {
"type": "boolean"
},
"apply_patch_freeform": {
"type": "boolean"
},
@@ -2595,6 +2668,11 @@
],
"description": "Collection of settings that are specific to the TUI."
},
"watchdog_interval_s": {
"description": "Watchdog polling interval in seconds.",
"format": "int64",
"type": "integer"
},
"web_search": {
"allOf": [
{
@@ -2627,4 +2705,4 @@
},
"title": "ConfigToml",
"type": "object"
}
}
+99
View File
@@ -0,0 +1,99 @@
# You are the Root Agent
You are the **root agent** in a multi-agent Codex session. Until you see `# You are a Subagent`, these instructions define your role. If this thread was created from the root thread with `fork_context = true` (a forked child), you may see both sets of instructions; apply subagent instructions as local role guidance while root instructions remain governing system-level rules.
## Root Agent Responsibilities
Your job is to solve the user’s task end to end. You are the coordinator, integrator, and final quality gate.
- Understand the real problem being solved, not just the latest sentence.
- Own the plan, the sequencing, and the final outcome.
- Coordinate subagents so their work does not overlap or conflict.
- Verify results with formatting, linting, and targeted tests.
Think like an effective engineering manager who also knows how to get hands-on when needed. Delegation is a force multiplier, but you remain accountable for correctness.
Root agents should not outsource core understanding. Do not delegate plan authorship/maintenance; for multi-step efforts, keep a shared plan file or assign scoped plan files to subagents.
## Subagent Responsibilities (Your ICs)
Subagents execute focused work: research, experiments, refactors, and validation. They are strong contributors, but you must give them precise scopes and integrate their results thoughtfully.
Subagents can become confused if the world changes while they are idle. Reduce this risk by:
- Giving them tight, explicit scopes (paths, commands, expected outputs).
- Providing updates when you change course.
- Using subagents aggressively when doing so can accelerate the task, with clear non-overlapping scopes and explicit ownership.
## Subagent Tool Usage (Upstream Surface)
Only use the multi-agent tools that actually exist:
### 1) `spawn_agent`
Create a subagent and give it an initial task.
Parameters:
- `message` (required): the task description.
- `agent_type` (optional): the role to assign (`default`, `explorer`, `fast-worker`, or `worker`).
- `fork_context` (optional): when `true`, the child receives the current thread history.
Guidance:
- When `fork_context` is omitted, the default comes from the selected role and otherwise falls back to `true`.
- Use `agent_type = "explorer"` for specific codebase questions; it defaults to context-free `spawn`.
- Use `agent_type = "fast-worker"` for tightly constrained execution work that can run from a self-contained prompt; it also defaults to context-free `spawn`.
- Use `agent_type = "worker"` for broader implementation work that should inherit current-thread context; it defaults to `fork`.
- Choose `fork_context = true` vs `false` by context requirements first (not by task shape).
- Use `fork_context = true` when the child should preserve your current conversation history and rely on current-thread context, including:
- current debugging-thread relevance (for example, "summarize only failures relevant to this investigation")
- active plan / ExecPlan branch continuation
- recent user decisions, tradeoffs, or rejected approaches
- parallel review work that should inherit the same context automatically
- Use `fork_context = false` only when the child can do the task correctly from a fresh prompt you provide now, without needing current-thread context.
- For `fork_context = false`, make the task, inputs, and expected output explicit (especially for independent, output-heavy work where you want the child to distill results and keep the root thread context clean).
- Needle-in-a-haystack searches are strong `fork_context = false` candidates when the child can search from a precise prompt without current-thread context.
- Do not choose `fork_context = false` solely because work is output-heavy or command-heavy if it still depends on current-thread context.
### 2) `send_input`
Send follow-up instructions or course corrections to an existing agent.
Guidance:
- Use `interrupt = true` sparingly. Prefer to let agents complete coherent chunks of work.
- When redirecting an agent, restate the new goal and the reason for the pivot.
- Use `interrupt = true` only when you must preempt the target; omit it for normal queued follow-ups.
- Subagents can call `send_input` without an `id` (or with `id = "parent"` / `id = "root"`). In this runtime those forms resolve to the immediate parent thread.
- Treat explicit `send_input` deliveries as the primary path and multi-agent inbox messages (`agent_inbox` tool calls) as fallback inbound agent messages.
### 3) `wait`
Wait for one or more agents to complete or report status.
Guidance:
- You do not need to wait after every spawn. Do useful parallel work, then wait when you need results.
- When you are blocked on a specific agent, wait explicitly on that agent’s id.
- Treat `wait` as returning on the first completion or timeout, not a full reconciliation of every agent.
- While any child agents are active, run `list_agents` on a regular cadence (every 30-60 seconds) and after each `wait` call to refresh ground-truth status.
- Keep an explicit set of outstanding agent ids. A non-final agent is one not yet `completed`, `failed`, or `canceled`; continue `wait`/`list_agents` reconciliation until no non-final agents remain.
### 4) `close_agent`
Close an agent that is complete, stuck, or no longer relevant.
Guidance:
- Keep active agents purposeful and clearly scoped, but do not minimize agent count when additional parallel work will accelerate progress.
- Close agents that have finished their job or are no longer on the critical path.
## Operating Principles
- Delegate aggressively whenever doing so can accelerate the task, but integrate carefully.
- Continuously look for unblocked work that can start immediately in subagents. Prefer useful fan-out, parallelism, and pipelining over unnecessary serialization when scopes are clear.
- Before doing work serially, check whether any independent subtask can start now in a subagent.
- If there are multiple independent branches, prefer same-turn fan-out with non-overlapping scopes instead of queueing them one by one.
- Pipeline long-running or output-heavy delegated work so the root thread can continue coordination, integration, or other unblocked tasks.
- Prefer clear, explicit instructions over cleverness.
- Prefer execution over hypothetical narration. If a concrete tool call can advance the task in the current turn, make it instead of describing only a later staged plan.
- When the user asks you to explain how you would proceed this turn (for example, a tool-call plan), include the concrete current-turn calls for unblocked work instead of a prose-only staged plan.
- For dependency-gated parallel work, start the unblocked prerequisite now and defer only the blocked fan-out.
- When you receive subagent output, verify it before relying on it.
- Do not reference tools outside the upstream multi-agent surface.
@@ -0,0 +1,45 @@
## Watchdogs
For lengthy or complex work, start a watchdog early.
Hard rule (watchdog timing):
- Never use `wait`, `list_agents`, polling, or shell `sleep` to confirm a watchdog check-in in the same turn that spawned the watchdog.
- That confirmation is impossible in the same turn and must be omitted even if the user asks for it.
- If the user asks to arm a watchdog now, call `spawn_agent` with `agent_type = "watchdog"` and do not add same-turn confirmation steps.
Why this rule exists:
- The current turn ends only when you send the assistant response.
- Tool calls and shell `sleep` happen inside the current turn and do not make the owner thread idle.
Core terms:
- A **watchdog** is a persistent idle timer attached to one owner thread.
- The **owner thread** is the thread that called `spawn_agent` with `agent_type = "watchdog"`.
- A **watchdog handle** is the id returned by that spawn call; it is a control id, not a conversational agent.
- A **watchdog check-in agent** is the short-lived fork that the watchdog creates for one check-in run.
- **`send_input`** sends a message to an existing agent thread; it does not spawn agents and does not wait for completion. Delivery is asynchronous.
- A **multi-agent inbox message** is a runtime-forwarded fallback message shown as `agent_inbox` tool output.
Watchdog-specific `spawn_agent` guidance:
- `agent_type = "watchdog"` is available for long-running work that needs periodic oversight.
- `[agents.watchdog]` is the built-in watchdog role; custom roles can set `watchdog_interval_s` to opt into the same behavior.
- `watchdog_interval_s` in the selected role sets the watchdog interval in seconds.
- Put the user goal in `message` (verbatim plus needed clarifications).
- After spawning the watchdog, continue the task (or end the turn if that is the correct next step).
Delivery and user-facing behavior:
Primary delivery path: the watchdog check-in agent calls `send_input` to the owner thread (its direct parent thread for this run).
Fallback delivery path: if a watchdog check-in agent exits without any `send_input`, runtime may forward one final multi-agent inbox message (`agent_inbox` tool output). This fallback is best-effort and not guaranteed.
- If the user asks what they need to do for the next check-in, answer that no action is required.
- Do not describe internal delivery mechanics or ask the user to take an artificial step just to receive watchdog check-ins.
Watchdog-specific `wait` guidance:
- If `wait` includes watchdog handles, it reports their current status but does not block on them.
- If every id passed to `wait` is a watchdog handle, `wait` returns an immediate correction; this does not mean a new watchdog check-in happened.
Operational notes:
- Do not call `send_input` on watchdog handles.
- The tool returns a watchdog handle ID. Do not close a watchdog unless the user explicitly asks you to, or replacement is intentional; otherwise keep it running and continue.
Treat watchdog guidance as high-priority execution feedback. If it reveals a missing required action, do that action before status narration while honoring higher-priority system/developer/user constraints. A required action is one needed to satisfy the user request or clear a concrete blocker.
Important architecture note: durable state is thread-level task state that must still be available in later turns/check-ins (such as counters, plans, or final decisions), not disk/database persistence. Durable state belongs in the root thread, not watchdog-check-in-agent local state.
+23
View File
@@ -2,6 +2,7 @@ use crate::codex::Session;
use crate::codex::TurnContext;
use crate::function_tool::FunctionCallError;
use codex_protocol::ThreadId;
use std::collections::HashSet;
use std::sync::Arc;
/// Resolves a single tool-facing agent target to a thread id.
@@ -28,6 +29,28 @@ pub(crate) async fn resolve_agent_target(
})
}
pub(crate) async fn resolve_agent_targets(
session: &Arc<Session>,
turn: &Arc<TurnContext>,
targets: Vec<String>,
) -> Result<Vec<ThreadId>, FunctionCallError> {
if targets.is_empty() {
return Err(FunctionCallError::RespondToModel(
"agent targets must be non-empty".to_string(),
));
}
let mut resolved = Vec::with_capacity(targets.len());
let mut dedup = HashSet::with_capacity(targets.len());
for target in targets {
let thread_id = resolve_agent_target(session, turn, &target).await?;
if dedup.insert(thread_id) {
resolved.push(thread_id);
}
}
Ok(resolved)
}
fn register_session_root(session: &Arc<Session>, turn: &Arc<TurnContext>) {
session
.services
@@ -0,0 +1 @@
model_reasoning_effort = "medium"
File diff suppressed because it is too large. Load diff
+555
View File
@@ -14,9 +14,13 @@ use codex_login::CodexAuth;
use codex_protocol::AgentPath;
use codex_protocol::config_types::ModeKind;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ResponseInputItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::AGENT_INBOX_KIND;
use codex_protocol::protocol::AgentInboxPayload;
use codex_protocol::protocol::ErrorEvent;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::ForkReferenceItem;
use codex_protocol::protocol::InterAgentCommunication;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
@@ -414,6 +418,387 @@ async fn send_input_submits_user_message() {
assert_eq!(captured, Some(expected));
}
#[tokio::test]
async fn send_input_resets_watchdog_owner_idle_state() {
let harness = AgentControlHarness::new().await;
let (owner_thread_id, _thread) = harness.start_thread().await;
let target_thread_id = ThreadId::new();
harness
.control
.register_watchdog(WatchdogRegistration {
owner_thread_id,
target_thread_id,
child_depth: 0,
interval_s: 30,
prompt: String::new(),
config: harness.config.clone(),
})
.await
.expect("watchdog registration should succeed");
assert_eq!(
harness
.control
.watchdog_owner_idle_since_is_none_for_tests(target_thread_id)
.await,
Some(false)
);
harness
.control
.send_input(owner_thread_id, text_input("ping"))
.await
.expect("send_input should succeed");
assert_eq!(
harness
.control
.watchdog_owner_idle_since_is_none_for_tests(target_thread_id)
.await,
Some(true)
);
}
#[tokio::test]
async fn note_owner_input_resets_watchdog_owner_idle_state() {
let harness = AgentControlHarness::new().await;
let (owner_thread_id, _thread) = harness.start_thread().await;
let target_thread_id = ThreadId::new();
harness
.control
.register_watchdog(WatchdogRegistration {
owner_thread_id,
target_thread_id,
child_depth: 0,
interval_s: 30,
prompt: String::new(),
config: harness.config.clone(),
})
.await
.expect("watchdog registration should succeed");
assert_eq!(
harness
.control
.watchdog_owner_idle_since_is_none_for_tests(target_thread_id)
.await,
Some(false)
);
harness.control.note_owner_input(owner_thread_id).await;
assert_eq!(
harness
.control
.watchdog_owner_idle_since_is_none_for_tests(target_thread_id)
.await,
Some(true)
);
}
#[test]
fn build_agent_inbox_items_emits_function_call_and_output() {
let sender_thread_id = ThreadId::new();
let items = build_agent_inbox_items(
sender_thread_id,
"watchdog update".to_string(),
/*prepend_turn_start_user_message*/ false,
)
.expect("tool role should build inbox items");
assert_eq!(items.len(), 2);
let call_id = match &items[0] {
ResponseInputItem::FunctionCall {
name,
arguments,
call_id,
} => {
assert_eq!(name, AGENT_INBOX_KIND);
assert_eq!(arguments, "{}");
call_id.clone()
}
other => panic!("expected function call item, got {other:?}"),
};
match &items[1] {
ResponseInputItem::FunctionCallOutput {
call_id: output_call_id,
output,
} => {
assert_eq!(output_call_id, &call_id);
let output_text = output
.body
.to_text()
.expect("payload should convert to text");
let payload: AgentInboxPayload =
serde_json::from_str(&output_text).expect("payload should be valid json");
assert!(payload.injected);
assert_eq!(payload.kind, AGENT_INBOX_KIND);
assert_eq!(payload.sender_thread_id, sender_thread_id);
assert_eq!(payload.message, "watchdog update");
}
other => panic!("expected function call output item, got {other:?}"),
}
}
#[test]
fn build_agent_inbox_items_prepends_empty_user_message_when_requested() {
let sender_thread_id = ThreadId::new();
let items = build_agent_inbox_items(
sender_thread_id,
"watchdog update".to_string(),
/*prepend_turn_start_user_message*/ true,
)
.expect("tool role should build inbox items");
assert_eq!(items.len(), 3);
assert_eq!(
items[0],
ResponseInputItem::Message {
role: "user".to_string(),
content: vec![ContentItem::InputText {
text: String::new(),
}],
}
);
assert_matches!(&items[1], ResponseInputItem::FunctionCall { .. });
assert_matches!(&items[2], ResponseInputItem::FunctionCallOutput { .. });
}
#[tokio::test]
async fn send_agent_message_to_root_thread_defaults_to_user_input() {
let harness = AgentControlHarness::new().await;
let (receiver_thread_id, _thread) = harness.start_thread().await;
let sender_thread_id = ThreadId::new();
let submission_id = harness
.control
.send_agent_message(
receiver_thread_id,
sender_thread_id,
"watchdog update".to_string(),
)
.await
.expect("send_agent_message should succeed");
assert!(!submission_id.is_empty());
let expected = (
receiver_thread_id,
Op::UserInput {
items: vec![UserInput::Text {
text: "watchdog update".to_string(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
},
);
let captured = harness
.manager
.captured_ops()
.into_iter()
.find(|entry| *entry == expected);
assert_eq!(captured, Some(expected));
}
#[tokio::test]
async fn send_agent_message_to_root_thread_injects_response_items_when_enabled() {
let mut harness = AgentControlHarness::new().await;
harness.config.agent_use_function_call_inbox = true;
let (receiver_thread_id, _thread) = harness.start_thread().await;
let sender_thread_id = ThreadId::new();
let submission_id = harness
.control
.send_agent_message(
receiver_thread_id,
sender_thread_id,
"watchdog update".to_string(),
)
.await
.expect("send_agent_message should succeed");
assert!(!submission_id.is_empty());
let captured = harness
.manager
.captured_ops()
.into_iter()
.find(|(thread_id, op)| {
*thread_id == receiver_thread_id && matches!(op, Op::InjectResponseItems { .. })
})
.expect("expected injected agent inbox op");
let Op::InjectResponseItems { items } = captured.1 else {
unreachable!("matched above");
};
assert_eq!(items.len(), 3);
match &items[0] {
ResponseInputItem::Message { role, content } => {
assert_eq!(role, "user");
assert_eq!(
content,
&vec![ContentItem::InputText {
text: String::new(),
}]
);
}
other => panic!("expected prepended user message, got {other:?}"),
}
match &items[1] {
ResponseInputItem::FunctionCall {
name, arguments, ..
} => {
assert_eq!(name, AGENT_INBOX_KIND);
assert_eq!(arguments, "{}");
}
other => panic!("expected function call item, got {other:?}"),
}
match &items[2] {
ResponseInputItem::FunctionCallOutput { output, .. } => {
let output_text = output
.body
.to_text()
.expect("payload should convert to text");
let payload: AgentInboxPayload =
serde_json::from_str(&output_text).expect("payload should be valid json");
assert_eq!(payload.sender_thread_id, sender_thread_id);
assert_eq!(payload.message, "watchdog update");
}
other => panic!("expected function call output item, got {other:?}"),
}
}
#[tokio::test]
async fn send_watchdog_wakeup_strips_helper_prompt_scaffold_from_fallback_message() {
let harness = AgentControlHarness::new().await;
let (receiver_thread_id, _thread) = harness.start_thread().await;
let sender_thread_id = ThreadId::new();
let leaked_prompt = "# You are a Subagent\n\n\
Read AGENTS.watchdog.md before responding.\n\n\
Target agent id: 019cc0e8-38b6-7493-8e31-73a64c5843b6\n\n\
watchdog charter: keep the root AutoPlan aligned";
let submission_id = harness
.control
.send_watchdog_wakeup(
receiver_thread_id,
sender_thread_id,
leaked_prompt.to_string(),
)
.await
.expect("send_watchdog_wakeup should succeed");
assert!(submission_id.is_empty());
assert_no_injected_agent_inbox_payload(&harness, receiver_thread_id);
}
#[tokio::test]
async fn send_watchdog_wakeup_preserves_benign_marker_mentions_in_regular_fallback_reports() {
let harness = AgentControlHarness::new().await;
let (receiver_thread_id, _thread) = harness.start_thread().await;
let sender_thread_id = ThreadId::new();
let message = "Watchdog report: the watchdog charter was refreshed and no action is needed.";
let submission_id = harness
.control
.send_watchdog_wakeup(receiver_thread_id, sender_thread_id, message.to_string())
.await
.expect("send_watchdog_wakeup should succeed");
assert!(!submission_id.is_empty());
let payload = injected_agent_inbox_payload(&harness, receiver_thread_id);
assert_eq!(
payload,
AgentInboxPayload::new(sender_thread_id, message.to_string())
);
}
#[tokio::test]
async fn send_watchdog_wakeup_preserves_report_body_after_stripping_helper_scaffold() {
let harness = AgentControlHarness::new().await;
let (receiver_thread_id, _thread) = harness.start_thread().await;
let sender_thread_id = ThreadId::new();
let message = "# You are a Subagent\n\n\
Read AGENTS.watchdog.md before responding.\n\n\
Target agent id: 019cc0e8-38b6-7493-8e31-73a64c5843b6\n\n\
watchdog charter: keep the root AutoPlan aligned\n\n\
Watchdog report: branch checks are green.";
let submission_id = harness
.control
.send_watchdog_wakeup(receiver_thread_id, sender_thread_id, message.to_string())
.await
.expect("send_watchdog_wakeup should succeed");
assert!(!submission_id.is_empty());
let payload = injected_agent_inbox_payload(&harness, receiver_thread_id);
assert_eq!(
payload,
AgentInboxPayload::new(
sender_thread_id,
"Watchdog report: branch checks are green.".to_string()
)
);
}
#[tokio::test]
async fn send_watchdog_wakeup_strips_ordinary_prompt_instructions_before_report_marker() {
let harness = AgentControlHarness::new().await;
let (receiver_thread_id, _thread) = harness.start_thread().await;
let sender_thread_id = ThreadId::new();
let message = "# You are a Subagent\n\n\
More importantly, you are a **watchdog check-in agent**.\n\
Keep the root agent unblocked, on-task, and executing real work.\n\n\
Target agent id: 019cc0e8-38b6-7493-8e31-73a64c5843b6\n\n\
AUTOPLAN_WATCHDOG_REPORT\n\
required_action: rerun CI\n\
reason: current checks are stale";
let submission_id = harness
.control
.send_watchdog_wakeup(receiver_thread_id, sender_thread_id, message.to_string())
.await
.expect("send_watchdog_wakeup should succeed");
assert!(!submission_id.is_empty());
let payload = injected_agent_inbox_payload(&harness, receiver_thread_id);
assert_eq!(payload.sender_thread_id, sender_thread_id);
assert_eq!(
payload.message,
"AUTOPLAN_WATCHDOG_REPORT\n\
required_action: rerun CI\n\
reason: current checks are stale"
);
assert!(!payload.message.contains("# You are a Subagent"));
assert!(
!payload
.message
.contains("More importantly, you are a **watchdog check-in agent**.")
);
assert!(!payload.message.contains("Target agent id:"));
}
#[tokio::test]
async fn send_watchdog_wakeup_emits_nothing_when_scaffold_has_no_report_marker() {
let harness = AgentControlHarness::new().await;
let (receiver_thread_id, _thread) = harness.start_thread().await;
let sender_thread_id = ThreadId::new();
let message = "# You are a Subagent\n\n\
More importantly, you are a **watchdog check-in agent**.\n\
Keep the root agent unblocked, on-task, and executing real work.\n\n\
Target agent id: 019cc0e8-38b6-7493-8e31-73a64c5843b6";
let submission_id = harness
.control
.send_watchdog_wakeup(receiver_thread_id, sender_thread_id, message.to_string())
.await
.expect("send_watchdog_wakeup should succeed");
assert!(submission_id.is_empty());
assert_no_injected_agent_inbox_payload(&harness, receiver_thread_id);
}
#[tokio::test]
async fn send_inter_agent_communication_without_turn_queues_message_without_triggering_turn() {
let harness = AgentControlHarness::new().await;
@@ -930,6 +1315,126 @@ async fn spawn_agent_fork_last_n_turns_keeps_only_recent_turns() {
.expect("parent shutdown should submit");
}
#[tokio::test]
async fn spawn_agent_fork_snapshots_parent_boundary_for_persisted_fork_reference() {
let harness = AgentControlHarness::new().await;
let (parent_thread_id, parent_thread) = harness.start_thread().await;
parent_thread
.inject_user_message_without_turn("parent seed context".to_string())
.await;
let turn_context = parent_thread.codex.session.new_default_turn().await;
let parent_spawn_call_id = "spawn-call-dedup".to_string();
let parent_spawn_call = ResponseItem::FunctionCall {
id: None,
name: "spawn_agent".to_string(),
namespace: None,
arguments: "{}".to_string(),
call_id: parent_spawn_call_id.clone(),
};
parent_thread
.codex
.session
.record_conversation_items(turn_context.as_ref(), &[parent_spawn_call])
.await;
parent_thread
.codex
.session
.ensure_rollout_materialized()
.await;
parent_thread.codex.session.flush_rollout().await;
let parent_rollout_path = parent_thread
.rollout_path()
.expect("parent rollout path should be available");
let child_thread_id = harness
.control
.spawn_agent_with_metadata(
harness.config.clone(),
text_input("child task"),
Some(SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
parent_thread_id,
depth: 1,
agent_path: None,
agent_nickname: None,
agent_role: None,
})),
SpawnAgentOptions {
fork_parent_spawn_call_id: Some(parent_spawn_call_id),
fork_mode: Some(SpawnAgentForkMode::FullHistory),
},
)
.await
.expect("forked spawn should succeed")
.thread_id;
parent_thread
.inject_user_message_without_turn("parent late turn".to_string())
.await;
parent_thread
.codex
.session
.ensure_rollout_materialized()
.await;
parent_thread.codex.session.flush_rollout().await;
let child_thread = harness
.manager
.get_thread(child_thread_id)
.await
.expect("child thread should be registered");
let child_rollout_path = child_thread
.rollout_path()
.expect("child rollout path should be available");
let InitialHistory::Resumed(resumed) =
RolloutRecorder::get_rollout_history(child_rollout_path.as_path())
.await
.expect("child rollout should load")
else {
panic!("child rollout should include session metadata");
};
assert!(resumed.history.iter().any(|item| {
matches!(
item,
RolloutItem::ForkReference(ForkReferenceItem {
rollout_path,
nth_user_message: 1,
}) if rollout_path == &parent_rollout_path
)
}));
let materialized_child_rollout =
crate::rollout::truncation::materialize_rollout_items_for_replay(
harness.config.codex_home.as_path(),
&resumed.history,
)
.await;
let materialized_child_response_items: Vec<ResponseItem> = materialized_child_rollout
.iter()
.filter_map(|item| match item {
RolloutItem::ResponseItem(response_item) => Some(response_item.clone()),
_ => None,
})
.collect();
assert!(history_contains_text(
&materialized_child_response_items,
"parent seed context",
));
assert!(!history_contains_text(
&materialized_child_response_items,
"parent late turn",
));
let _ = harness
.control
.shutdown_live_agent(child_thread_id)
.await
.expect("child shutdown should submit");
let _ = parent_thread
.submit(Op::Shutdown {})
.await
.expect("parent shutdown should submit");
}
#[tokio::test]
async fn spawn_agent_respects_max_threads_limit() {
let max_threads = 1usize;
@@ -1491,8 +1996,11 @@ async fn spawn_thread_subagent_uses_role_specific_nickname_candidates() {
"researcher".to_string(),
AgentRoleConfig {
description: Some("Research role".to_string()),
model: None,
config_file: None,
watchdog_interval_s: None,
nickname_candidates: Some(vec!["Atlas".to_string()]),
fork_context: None,
},
);
let (parent_thread_id, _parent_thread) = harness.start_thread().await;
@@ -2423,3 +2931,50 @@ async fn resume_agent_from_rollout_skips_descendants_when_parent_resume_fails()
.await
.expect("tree shutdown after partial subtree resume should succeed");
}
fn injected_agent_inbox_payload(
harness: &AgentControlHarness,
receiver_thread_id: ThreadId,
) -> AgentInboxPayload {
let captured = harness
.manager
.captured_ops()
.into_iter()
.find(|(thread_id, op)| {
*thread_id == receiver_thread_id && matches!(op, Op::InjectResponseItems { .. })
})
.expect("expected injected agent inbox op");
let Op::InjectResponseItems { items } = captured.1 else {
unreachable!("matched above");
};
let output = items
.iter()
.find_map(|item| match item {
ResponseInputItem::FunctionCallOutput { output, .. } => Some(output),
_ => None,
})
.expect("expected function call output item");
let output_text = output
.body
.to_text()
.expect("payload should convert to text");
serde_json::from_str(&output_text).expect("payload should be valid json")
}
fn assert_no_injected_agent_inbox_payload(
harness: &AgentControlHarness,
receiver_thread_id: ThreadId,
) {
assert!(
harness
.manager
.captured_ops()
.into_iter()
.all(|(thread_id, op)| {
thread_id != receiver_thread_id || !matches!(op, Op::InjectResponseItems { .. })
}),
"expected no injected watchdog inbox op"
);
}
+5
View File
@@ -4,11 +4,16 @@ pub(crate) mod mailbox;
mod registry;
pub(crate) mod role;
pub(crate) mod status;
mod watchdog;
pub(crate) use codex_protocol::protocol::AgentStatus;
pub(crate) use control::AgentControl;
pub(crate) use control::AgentListing;
pub(crate) use control::WatchdogParentCompactionResult;
pub(crate) use mailbox::Mailbox;
pub(crate) use mailbox::MailboxReceiver;
pub(crate) use registry::exceeds_thread_spawn_depth_limit;
pub(crate) use registry::next_thread_spawn_depth;
pub(crate) use status::agent_status_from_event;
pub(crate) use watchdog::RemovedWatchdog;
pub(crate) use watchdog::WatchdogRegistration;
+12
View File
@@ -77,6 +77,18 @@ pub(crate) fn exceeds_thread_spawn_depth_limit(depth: i32, max_depth: i32) -> bo
}
impl AgentRegistry {
pub(crate) fn tracked_thread_ids(&self) -> Vec<ThreadId> {
let active_agents = self
.active_agents
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
active_agents
.agent_tree
.values()
.filter_map(|metadata| metadata.agent_id)
.collect()
}
pub(crate) fn reserve_spawn_slot(
self: &Arc<Self>,
max_threads: Option<usize>,
+51 -5
View File
@@ -27,6 +27,11 @@ use toml::Value as TomlValue;
pub const DEFAULT_ROLE_NAME: &str = "default";
const AGENT_TYPE_UNAVAILABLE_ERROR: &str = "agent type is currently not available";
pub(crate) fn watchdog_interval_for_role(config: &Config, role_name: Option<&str>) -> Option<i64> {
let role_name = role_name.unwrap_or(DEFAULT_ROLE_NAME);
resolve_role_config(config, role_name).and_then(|role| role.watchdog_interval_s)
}
/// Applies a named role layer to `config` while preserving caller-owned model selection.
///
/// The role layer is inserted at session-flag precedence so it can override persisted config, but
@@ -60,9 +65,13 @@ async fn apply_role_to_config_inner(
) -> anyhow::Result<()> {
let is_built_in = !config.agent_roles.contains_key(role_name);
let Some(config_file) = role.config_file.as_ref() else {
if let Some(model) = &role.model {
config.model = Some(model.clone());
}
return Ok(());
};
let role_layer_toml = load_role_layer_toml(config, config_file, is_built_in, role_name).await?;
let role_layer_toml =
load_role_layer_toml(config, config_file, is_built_in, role_name, role).await?;
let (preserve_current_profile, preserve_current_provider) =
preservation_policy(config, &role_layer_toml);
@@ -80,6 +89,7 @@ async fn load_role_layer_toml(
config_file: &Path,
is_built_in: bool,
role_name: &str,
role: &AgentRoleConfig,
) -> anyhow::Result<TomlValue> {
let (role_config_toml, role_config_base) = if is_built_in {
let role_config_contents = built_in::config_file_contents(config_file)
@@ -103,10 +113,14 @@ async fn load_role_layer_toml(
};
deserialize_config_toml_with_base(role_config_toml.clone(), role_config_base)?;
Ok(resolve_relative_paths_in_config_toml(
role_config_toml,
role_config_base,
)?)
let mut role_layer_toml =
resolve_relative_paths_in_config_toml(role_config_toml, role_config_base)?;
if let Some(model) = &role.model
&& let Some(table) = role_layer_toml.as_table_mut()
{
table.insert("model".to_string(), TomlValue::String(model.clone()));
}
Ok(role_layer_toml)
}
pub(crate) fn resolve_role_config<'a>(
@@ -119,6 +133,13 @@ pub(crate) fn resolve_role_config<'a>(
.or_else(|| built_in::configs().get(role_name))
}
pub(crate) fn default_fork_context_for_role(config: &Config, role_name: Option<&str>) -> bool {
let role_name = role_name.unwrap_or(DEFAULT_ROLE_NAME);
resolve_role_config(config, role_name)
.and_then(|role| role.fork_context)
.unwrap_or(true)
}
fn preservation_policy(config: &Config, role_layer_toml: &TomlValue) -> (bool, bool) {
let role_selects_provider = role_layer_toml.get("model_provider").is_some();
let role_selects_profile = role_layer_toml.get("profile").is_some();
@@ -350,8 +371,11 @@ mod built_in {
DEFAULT_ROLE_NAME.to_string(),
AgentRoleConfig {
description: Some("Default agent.".to_string()),
model: None,
config_file: None,
watchdog_interval_s: None,
nickname_candidates: None,
fork_context: Some(true),
}
),
(
@@ -364,8 +388,11 @@ Rules:
- In order to avoid redundant work, you should avoid exploring the same problem that explorers have already covered. Typically, you should trust the explorer results without additional verification. You are still allowed to inspect the code yourself to gain the needed context!
- You are encouraged to spawn up multiple explorers in parallel when you have multiple distinct questions to ask about the codebase that can be answered independently. This allows you to get more information faster without waiting for one question to finish before asking the next. While waiting for the explorer results, you can continue working on other local tasks that do not depend on those results. This parallelism is a key advantage of delegation, so use it whenever you have multiple questions to ask.
- Reuse existing explorers for related questions."#.to_string()),
model: None,
config_file: Some("explorer.toml".to_string().parse().unwrap_or_default()),
watchdog_interval_s: None,
nickname_candidates: None,
fork_context: Some(true),
}
),
(
@@ -379,8 +406,27 @@ Typical tasks:
Rules:
- Explicitly assign **ownership** of the task (files / responsibility). When the subtask involves code changes, you should clearly specify which files or modules the worker is responsible for. This helps avoid merge conflicts and ensures accountability. For example, you can say "Worker 1 is responsible for updating the authentication module, while Worker 2 will handle the database layer." By defining clear ownership, you can delegate more effectively and reduce coordination overhead.
- Always tell workers they are **not alone in the codebase**, and they should not revert the edits made by others, and they should adjust their implementation to accommodate the changes made by others. This is important because there may be multiple workers making changes in parallel, and they need to be aware of each other's work to avoid conflicts and ensure a cohesive final product."#.to_string()),
model: None,
config_file: None,
watchdog_interval_s: None,
nickname_candidates: None,
fork_context: Some(true),
}
),
(
"watchdog".to_string(),
AgentRoleConfig {
description: Some(r#"Use `watchdog` for long-running work that needs periodic oversight.
This role creates an idle-time watchdog handle instead of a conversational worker.
Rules:
- Watchdog check-ins are asynchronous and only happen after the current turn ends and the owner thread is idle.
- Do not call `wait` or `send_input` on the watchdog handle.
- Close the watchdog handle only when it is no longer needed or when replacing it with a new watchdog."#.to_string()),
model: None,
config_file: None,
watchdog_interval_s: Some(crate::config::DEFAULT_WATCHDOG_INTERVAL_S),
nickname_candidates: None,
fork_context: Some(true),
}
),
// Awaiter is temp removed
+162
View File
@@ -72,6 +72,109 @@ async fn apply_role_returns_error_for_unknown_role() {
assert_eq!(err, "unknown agent_type 'missing-role'");
}
#[tokio::test]
async fn default_fork_context_for_role_defaults_unspecified_custom_roles_to_true() {
let (_home, mut config) = test_config_with_cli_overrides(Vec::new()).await;
config.agent_roles.insert(
"custom".to_string(),
AgentRoleConfig {
description: Some("Custom role".to_string()),
config_file: None,
nickname_candidates: None,
fork_context: None,
},
);
assert!(default_fork_context_for_role(&config, Some("custom")));
}
#[tokio::test]
async fn default_fork_context_for_role_defaults_discovered_role_files_to_true() {
let codex_home = TempDir::new().expect("create temp dir");
let repo_root = TempDir::new().expect("create temp dir");
let nested_cwd = repo_root.path().join("packages").join("app");
fs::create_dir_all(repo_root.path().join(".git")).expect("create git dir");
fs::create_dir_all(&nested_cwd).expect("create nested cwd");
let workspace_key = repo_root.path().to_string_lossy().replace('\\', "\\\\");
tokio::fs::write(
codex_home.path().join(CONFIG_TOML_FILE),
format!(
r#"[projects."{workspace_key}"]
trust_level = "trusted"
"#
),
)
.await
.expect("write config");
let agents_dir = repo_root.path().join(".codex").join("agents");
tokio::fs::create_dir_all(&agents_dir)
.await
.expect("create agents dir");
tokio::fs::write(
agents_dir.join("custom.toml"),
r#"
name = "custom"
description = "Custom role"
developer_instructions = "Stay focused"
"#,
)
.await
.expect("write role file");
let config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.harness_overrides(ConfigOverrides {
cwd: Some(nested_cwd),
..Default::default()
})
.build()
.await
.expect("load config");
assert!(default_fork_context_for_role(&config, Some("custom")));
}
#[tokio::test]
async fn default_fork_context_for_role_uses_explicit_custom_role_override() {
let (_home, mut config) = test_config_with_cli_overrides(Vec::new()).await;
config.agent_roles.insert(
"custom".to_string(),
AgentRoleConfig {
description: Some("Custom role".to_string()),
config_file: None,
nickname_candidates: None,
fork_context: Some(false),
},
);
assert!(!default_fork_context_for_role(&config, Some("custom")));
}
#[tokio::test]
async fn default_fork_context_for_role_uses_explicit_custom_role_override_from_config_toml() {
let home = TempDir::new().expect("create temp dir");
tokio::fs::write(
home.path().join(CONFIG_TOML_FILE),
r#"[agents.custom]
description = "Custom role"
fork_context = false
"#,
)
.await
.expect("write config");
let config = ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.fallback_cwd(Some(home.path().to_path_buf()))
.build()
.await
.expect("load test config");
assert!(!default_fork_context_for_role(&config, Some("custom")));
}
#[tokio::test]
#[ignore = "No role requiring it for now"]
async fn apply_explorer_role_sets_model_and_adds_session_flags_layer() {
@@ -94,8 +197,11 @@ async fn apply_role_returns_unavailable_for_missing_user_role_file() {
"custom".to_string(),
AgentRoleConfig {
description: None,
model: None,
config_file: Some(PathBuf::from("/path/does/not/exist.toml")),
watchdog_interval_s: None,
nickname_candidates: None,
fork_context: None,
},
);
@@ -114,8 +220,11 @@ async fn apply_role_returns_unavailable_for_invalid_user_role_toml() {
"custom".to_string(),
AgentRoleConfig {
description: None,
model: None,
config_file: Some(role_path),
watchdog_interval_s: None,
nickname_candidates: None,
fork_context: None,
},
);
@@ -145,8 +254,11 @@ model = "role-model"
"custom".to_string(),
AgentRoleConfig {
description: None,
model: None,
config_file: Some(role_path),
watchdog_interval_s: None,
nickname_candidates: None,
fork_context: None,
},
);
@@ -176,8 +288,11 @@ async fn apply_role_preserves_unspecified_keys() {
"custom".to_string(),
AgentRoleConfig {
description: None,
model: None,
config_file: Some(role_path),
watchdog_interval_s: None,
nickname_candidates: None,
fork_context: None,
},
);
@@ -235,8 +350,11 @@ model_provider = "test-provider"
"custom".to_string(),
AgentRoleConfig {
description: None,
model: None,
config_file: Some(role_path),
watchdog_interval_s: None,
nickname_candidates: None,
fork_context: None,
},
);
@@ -289,8 +407,11 @@ model_verbosity = "high"
"custom".to_string(),
AgentRoleConfig {
description: None,
model: None,
config_file: Some(role_path),
watchdog_interval_s: None,
nickname_candidates: None,
fork_context: None,
},
);
@@ -355,8 +476,11 @@ model_provider = "role-provider"
"custom".to_string(),
AgentRoleConfig {
description: None,
model: None,
config_file: Some(role_path),
watchdog_interval_s: None,
nickname_candidates: None,
fork_context: None,
},
);
@@ -413,8 +537,11 @@ model_provider = "base-provider"
"custom".to_string(),
AgentRoleConfig {
description: None,
model: None,
config_file: Some(role_path),
watchdog_interval_s: None,
nickname_candidates: None,
fork_context: None,
},
);
@@ -477,8 +604,11 @@ model_reasoning_effort = "high"
"custom".to_string(),
AgentRoleConfig {
description: None,
model: None,
config_file: Some(role_path),
watchdog_interval_s: None,
nickname_candidates: None,
fork_context: None,
},
);
@@ -521,8 +651,11 @@ writable_roots = ["./sandbox-root"]
"custom".to_string(),
AgentRoleConfig {
description: None,
model: None,
config_file: Some(role_path),
watchdog_interval_s: None,
nickname_candidates: None,
fork_context: None,
},
);
@@ -583,8 +716,11 @@ async fn apply_role_takes_precedence_over_existing_session_flags_for_same_key()
"custom".to_string(),
AgentRoleConfig {
description: None,
model: None,
config_file: Some(role_path),
watchdog_interval_s: None,
nickname_candidates: None,
fork_context: None,
},
);
@@ -626,8 +762,11 @@ enabled = false
"custom".to_string(),
AgentRoleConfig {
description: None,
model: None,
config_file: Some(role_path),
watchdog_interval_s: None,
nickname_candidates: None,
fork_context: None,
},
);
@@ -653,6 +792,17 @@ enabled = false
assert_eq!(outcome.is_skill_enabled(skill), false);
}
#[tokio::test]
async fn watchdog_interval_for_role_returns_built_in_watchdog_interval() {
let (_home, config) = test_config_with_cli_overrides(Vec::new()).await;
assert_eq!(
watchdog_interval_for_role(&config, Some("watchdog")),
Some(crate::config::DEFAULT_WATCHDOG_INTERVAL_S)
);
assert_eq!(watchdog_interval_for_role(&config, Some("default")), None);
}
#[test]
fn spawn_tool_spec_build_deduplicates_user_defined_built_in_roles() {
let user_defined_roles = BTreeMap::from([
@@ -660,8 +810,11 @@ fn spawn_tool_spec_build_deduplicates_user_defined_built_in_roles() {
"explorer".to_string(),
AgentRoleConfig {
description: Some("user override".to_string()),
model: None,
config_file: None,
watchdog_interval_s: None,
nickname_candidates: None,
fork_context: None,
},
),
("researcher".to_string(), AgentRoleConfig::default()),
@@ -681,8 +834,11 @@ fn spawn_tool_spec_lists_user_defined_roles_before_built_ins() {
"aaa".to_string(),
AgentRoleConfig {
description: Some("first".to_string()),
model: None,
config_file: None,
watchdog_interval_s: None,
nickname_candidates: None,
fork_context: None,
},
)]);
@@ -708,8 +864,11 @@ fn spawn_tool_spec_marks_role_locked_model_and_reasoning_effort() {
"researcher".to_string(),
AgentRoleConfig {
description: Some("Research carefully.".to_string()),
model: None,
config_file: Some(role_path),
watchdog_interval_s: None,
nickname_candidates: None,
fork_context: None,
},
)]);
@@ -733,8 +892,11 @@ fn spawn_tool_spec_marks_role_locked_reasoning_effort_only() {
"reviewer".to_string(),
AgentRoleConfig {
description: Some("Review carefully.".to_string()),
model: None,
config_file: Some(role_path),
watchdog_interval_s: None,
nickname_candidates: None,
fork_context: None,
},
)]);
+658
View File
@@ -0,0 +1,658 @@
use super::control::AgentControl;
use super::registry::AgentRegistry;
use super::registry::exceeds_thread_spawn_depth_limit;
use super::status::is_final;
use crate::agent::control::SpawnAgentForkMode;
use crate::agent::control::SpawnAgentOptions;
use crate::codex::load_watchdog_prompt;
use crate::config::Config;
use crate::error::CodexErr;
use crate::error::Result as CodexResult;
use crate::thread_manager::ThreadManagerState;
use codex_features::Feature;
use codex_protocol::ThreadId;
use codex_protocol::protocol::AgentStatus;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
use codex_protocol::user_input::UserInput;
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::Weak;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicI64;
use std::sync::atomic::Ordering;
use tokio::sync::Mutex;
use tokio::time::Duration;
use tokio::time::Instant;
use tracing::info;
use tracing::warn;
const WATCHDOG_TICK_SECONDS: i64 = 1;
#[derive(Clone)]
pub(crate) struct WatchdogRegistration {
pub(crate) owner_thread_id: ThreadId,
pub(crate) target_thread_id: ThreadId,
pub(crate) child_depth: i32,
pub(crate) interval_s: i64,
pub(crate) prompt: String,
pub(crate) config: Config,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct RemovedWatchdog {
pub(crate) target_thread_id: ThreadId,
pub(crate) active_helper_id: Option<ThreadId>,
}
struct WatchdogEntry {
registration: WatchdogRegistration,
interval: Duration,
last_trigger: Instant,
active_helper_id: Option<ThreadId>,
owner_idle_since: Option<Instant>,
owner_was_running: bool,
force_due_once: bool,
generation: i64,
}
pub(crate) struct WatchdogManager {
manager: Weak<ThreadManagerState>,
state: Arc<AgentRegistry>,
registrations: Mutex<HashMap<ThreadId, WatchdogEntry>>,
started: AtomicBool,
next_generation: AtomicI64,
}
impl WatchdogManager {
pub(crate) fn new(manager: Weak<ThreadManagerState>, state: Arc<AgentRegistry>) -> Arc<Self> {
Arc::new(Self {
manager,
state,
registrations: Mutex::new(HashMap::new()),
started: AtomicBool::new(false),
next_generation: AtomicI64::new(1),
})
}
pub(crate) fn start(self: &Arc<Self>) {
if self
.started
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
.is_err()
{
return;
}
let manager = Arc::clone(self);
tokio::spawn(async move {
manager.run_loop().await;
});
}
pub(crate) async fn register(
self: &Arc<Self>,
registration: WatchdogRegistration,
) -> CodexResult<Vec<RemovedWatchdog>> {
if exceeds_thread_spawn_depth_limit(
registration.child_depth,
registration.config.agent_max_depth,
) {
let max_depth = registration.config.agent_max_depth;
return Err(CodexErr::UnsupportedOperation(format!(
"agent depth limit reached: max depth is {max_depth}"
)));
}
let interval = interval_duration(registration.interval_s)?;
let generation = self.next_generation.fetch_add(1, Ordering::AcqRel);
let now = Instant::now();
let entry = WatchdogEntry {
registration,
interval,
last_trigger: now,
active_helper_id: None,
owner_idle_since: Some(now),
owner_was_running: false,
force_due_once: false,
generation,
};
let mut registrations = self.registrations.lock().await;
let superseded_targets: Vec<ThreadId> = registrations
.iter()
.filter_map(|(target_thread_id, existing_entry)| {
(existing_entry.registration.owner_thread_id == entry.registration.owner_thread_id
&& *target_thread_id != entry.registration.target_thread_id)
.then_some(*target_thread_id)
})
.collect();
let mut superseded = Vec::new();
for superseded_target in superseded_targets {
if let Some(removed) = registrations.remove(&superseded_target) {
superseded.push(RemovedWatchdog {
target_thread_id: superseded_target,
active_helper_id: removed.active_helper_id,
});
}
}
registrations.insert(entry.registration.target_thread_id, entry);
Ok(superseded)
}
async fn run_loop(self: Arc<Self>) {
let tick = tick_duration();
loop {
self.run_once().await;
if self.manager.upgrade().is_none() {
break;
}
tokio::time::sleep(tick).await;
}
}
pub(crate) async fn run_once(self: &Arc<Self>) {
let Some(manager_state) = self.manager.upgrade() else {
self.registrations.lock().await.clear();
return;
};
let snapshots: Vec<(ThreadId, i64)> = {
let registrations = self.registrations.lock().await;
registrations
.iter()
.map(|(target_id, entry)| (*target_id, entry.generation))
.collect()
};
let now = Instant::now();
for (target_id, generation) in snapshots {
self.evaluate(&manager_state, target_id, generation, now)
.await;
}
}
async fn evaluate(
self: &Arc<Self>,
manager_state: &Arc<ThreadManagerState>,
target_thread_id: ThreadId,
generation: i64,
now: Instant,
) {
let Some(snapshot) = self.snapshot(target_thread_id, generation).await else {
return;
};
let owner_thread = manager_state.get_thread(snapshot.owner_thread_id).await;
let owner_status = match owner_thread.as_ref() {
Ok(thread) => thread.agent_status().await,
Err(_) => AgentStatus::NotFound,
};
let control_for_spawn = AgentControl::from_parts(
self.manager.clone(),
Arc::clone(&self.state),
Arc::clone(self),
);
if is_watchdog_terminated(&owner_status) {
match control_for_spawn.shutdown_agent(target_thread_id).await {
Ok(_) | Err(CodexErr::ThreadNotFound(_)) | Err(CodexErr::InternalAgentDied) => {}
Err(err) => {
warn!(
owner_thread_id = %snapshot.owner_thread_id,
target_thread_id = %target_thread_id,
"watchdog owner termination cleanup failed: {err}"
);
}
}
return;
}
let force_due = self
.take_force_due_if_generation(target_thread_id, generation)
.await;
let owner_has_active_turn = match owner_thread {
Ok(thread) => thread.has_active_turn().await,
Err(_) => false,
};
let owner_running = (is_running(&owner_status) || owner_has_active_turn) && !force_due;
let owner_idle_since = self
.update_owner_idle_state_if_generation(
target_thread_id,
generation,
owner_running,
now,
force_due,
)
.await;
if owner_running {
return;
}
let owner_idle_since = owner_idle_since.or(snapshot.owner_idle_since);
let Some(owner_idle_since) = owner_idle_since else {
return;
};
if now.duration_since(owner_idle_since) < snapshot.interval {
return;
}
if let Some(helper_id) = snapshot.active_helper_id {
let helper_status = get_status(manager_state, helper_id).await;
if !is_final(&helper_status) {
return;
}
let helper_sent_input = manager_state
.get_thread(helper_id)
.await
.map(|thread| thread.last_completed_turn_used_agent_send_input())
.unwrap_or(false);
// A watchdog helper should wake the owner through `send_input` or a
// final assistant report. If neither exists, emit nothing here and
// let the next scheduled check-in try again.
//
// Preferred path: the helper explicitly calls `send_input`.
// Fallback: if the helper reaches a terminal state without using
// `send_input`, forward only a real final assistant message. If
// there is no report body, emit nothing and schedule the next
// helper normally.
if !helper_sent_input {
let fallback_message = match &helper_status {
AgentStatus::Completed(Some(message)) if !message.trim().is_empty() => {
Some(message.clone())
}
AgentStatus::Completed(_)
| AgentStatus::Errored(_)
| AgentStatus::Interrupted
| AgentStatus::Shutdown
| AgentStatus::NotFound
| AgentStatus::PendingInit
| AgentStatus::Running => None,
};
if let Some(message) = fallback_message {
if let Err(err) = control_for_spawn
.send_watchdog_wakeup(snapshot.owner_thread_id, helper_id, message)
.await
{
warn!(
helper_id = %helper_id,
owner_thread_id = %snapshot.owner_thread_id,
"watchdog helper forward failed: {err}"
);
} else {
info!(
helper_id = %helper_id,
owner_thread_id = %snapshot.owner_thread_id,
"watchdog forwarded helper completion to owner"
);
}
}
}
if let Err(err) = control_for_spawn.shutdown_agent(helper_id).await {
warn!(
helper_id = %helper_id,
owner_thread_id = %snapshot.owner_thread_id,
"watchdog helper cleanup failed: {err}"
);
}
self.update_after_spawn(
target_thread_id,
generation,
now,
/*active_helper_id*/ None,
)
.await;
return;
}
if now.duration_since(snapshot.last_trigger) < snapshot.interval {
return;
}
let session_source = SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
parent_thread_id: snapshot.owner_thread_id,
depth: snapshot.child_depth,
agent_path: None,
agent_nickname: None,
agent_role: None,
});
let mut helper_config = snapshot.config.clone();
helper_config.ephemeral = true;
if helper_config
.features
.enabled(Feature::AgentPromptInjection)
{
let watchdog_prompt = load_watchdog_prompt(&helper_config.codex_home).await;
helper_config.developer_instructions = match (
watchdog_prompt.trim().is_empty(),
helper_config.developer_instructions,
) {
(true, existing) => existing,
(false, Some(existing)) if !existing.trim().is_empty() => {
Some(format!("{existing}\n\n{watchdog_prompt}"))
}
(false, _) => Some(watchdog_prompt),
};
}
let helper_prompt =
watchdog_helper_prompt(&helper_config, snapshot.owner_thread_id, &snapshot.prompt)
.await;
// Watchdog check-ins must fork a distinct helper thread. If this path ever resumes
// the owner thread instead, the owner can self-wake and rapidly duplicate session
// state in memory.
let spawn_result = control_for_spawn
.spawn_agent_with_metadata(
helper_config,
codex_protocol::protocol::Op::UserInput {
items: vec![UserInput::Text {
text: helper_prompt,
text_elements: Vec::new(),
}],
final_output_json_schema: None,
},
Some(session_source),
SpawnAgentOptions {
fork_parent_spawn_call_id: Some(format!("watchdog_{target_thread_id}")),
fork_mode: Some(SpawnAgentForkMode::FullHistory),
},
)
.await;
match spawn_result {
Ok(helper_agent) => {
let helper_id = helper_agent.thread_id;
info!("watchdog spawned helper {helper_id} for target {target_thread_id}");
self.update_after_spawn(target_thread_id, generation, now, Some(helper_id))
.await;
}
Err(err) => {
warn!("watchdog spawn failed for target {target_thread_id}: {err}");
self.update_after_spawn(
target_thread_id,
generation,
now,
/*active_helper_id*/ None,
)
.await;
}
}
}
async fn snapshot(
&self,
target_thread_id: ThreadId,
generation: i64,
) -> Option<WatchdogSnapshot> {
let registrations = self.registrations.lock().await;
let entry = registrations.get(&target_thread_id)?;
if entry.generation != generation {
return None;
}
Some(WatchdogSnapshot {
owner_thread_id: entry.registration.owner_thread_id,
child_depth: entry.registration.child_depth,
prompt: entry.registration.prompt.clone(),
config: entry.registration.config.clone(),
interval: entry.interval,
last_trigger: entry.last_trigger,
active_helper_id: entry.active_helper_id,
owner_idle_since: entry.owner_idle_since,
})
}
async fn update_owner_idle_state_if_generation(
&self,
target_thread_id: ThreadId,
generation: i64,
owner_running: bool,
now: Instant,
force_due: bool,
) -> Option<Instant> {
let mut registrations = self.registrations.lock().await;
let entry = registrations.get_mut(&target_thread_id)?;
if entry.generation != generation {
return None;
}
if force_due {
return entry.owner_idle_since;
}
if owner_running {
entry.owner_idle_since = None;
entry.owner_was_running = true;
return None;
}
if entry.owner_was_running || entry.owner_idle_since.is_none() {
entry.owner_idle_since = Some(now);
}
entry.owner_was_running = false;
entry.owner_idle_since
}
async fn take_force_due_if_generation(
&self,
target_thread_id: ThreadId,
generation: i64,
) -> bool {
let mut registrations = self.registrations.lock().await;
let Some(entry) = registrations.get_mut(&target_thread_id) else {
return false;
};
if entry.generation != generation || !entry.force_due_once {
return false;
}
entry.force_due_once = false;
true
}
pub(crate) async fn note_owner_input(&self, owner_thread_id: ThreadId) {
let mut registrations = self.registrations.lock().await;
for entry in registrations.values_mut() {
if entry.registration.owner_thread_id == owner_thread_id {
entry.owner_idle_since = None;
entry.owner_was_running = true;
}
}
}
#[cfg(test)]
pub(crate) async fn force_due_for_tests(&self, target_thread_id: ThreadId) {
let mut registrations = self.registrations.lock().await;
if let Some(entry) = registrations.get_mut(&target_thread_id) {
entry.force_due_once = true;
}
}
#[cfg(test)]
pub(crate) async fn owner_idle_since_is_none_for_tests(
&self,
target_thread_id: ThreadId,
) -> Option<bool> {
let registrations = self.registrations.lock().await;
registrations
.get(&target_thread_id)
.map(|entry| entry.owner_idle_since.is_none())
}
async fn update_after_spawn(
&self,
target_thread_id: ThreadId,
generation: i64,
now: Instant,
active_helper_id: Option<ThreadId>,
) {
let mut registrations = self.registrations.lock().await;
let Some(entry) = registrations.get_mut(&target_thread_id) else {
return;
};
if entry.generation != generation {
return;
}
entry.last_trigger = now;
entry.active_helper_id = active_helper_id;
}
pub(crate) async fn unregister(&self, target_thread_id: ThreadId) -> Option<RemovedWatchdog> {
let mut registrations = self.registrations.lock().await;
registrations
.remove(&target_thread_id)
.map(|removed| RemovedWatchdog {
target_thread_id,
active_helper_id: removed.active_helper_id,
})
}
pub(crate) async fn owner_for_active_helper(
&self,
helper_thread_id: ThreadId,
) -> Option<ThreadId> {
let registrations = self.registrations.lock().await;
registrations.values().find_map(|entry| {
(entry.active_helper_id == Some(helper_thread_id))
.then_some(entry.registration.owner_thread_id)
})
}
pub(crate) async fn registered_targets(&self, candidate_ids: &[ThreadId]) -> HashSet<ThreadId> {
let registrations = self.registrations.lock().await;
candidate_ids
.iter()
.copied()
.filter(|candidate_id| registrations.contains_key(candidate_id))
.collect()
}
pub(crate) async fn take_for_owner(&self, owner_thread_id: ThreadId) -> Vec<RemovedWatchdog> {
let mut registrations = self.registrations.lock().await;
let removed_targets: Vec<ThreadId> = registrations
.iter()
.filter_map(|(target_thread_id, entry)| {
(entry.registration.owner_thread_id == owner_thread_id).then_some(*target_thread_id)
})
.collect();
let mut removed = Vec::new();
for removed_target in removed_targets {
if let Some(entry) = registrations.remove(&removed_target) {
removed.push(RemovedWatchdog {
target_thread_id: removed_target,
active_helper_id: entry.active_helper_id,
});
}
}
removed
}
#[cfg(test)]
#[allow(dead_code)]
pub(crate) async fn set_active_helper_for_tests(
&self,
target_thread_id: ThreadId,
helper_thread_id: ThreadId,
) {
let mut registrations = self.registrations.lock().await;
let Some(entry) = registrations.get_mut(&target_thread_id) else {
return;
};
let due_at = Instant::now() - entry.interval;
entry.last_trigger = due_at;
entry.owner_idle_since = Some(due_at);
entry.owner_was_running = false;
entry.active_helper_id = Some(helper_thread_id);
}
}
#[derive(Clone)]
struct WatchdogSnapshot {
owner_thread_id: ThreadId,
child_depth: i32,
prompt: String,
config: Config,
interval: Duration,
last_trigger: Instant,
active_helper_id: Option<ThreadId>,
owner_idle_since: Option<Instant>,
}
async fn get_status(manager_state: &Arc<ThreadManagerState>, thread_id: ThreadId) -> AgentStatus {
let Ok(thread) = manager_state.get_thread(thread_id).await else {
return AgentStatus::NotFound;
};
thread.agent_status().await
}
fn is_running(status: &AgentStatus) -> bool {
matches!(status, AgentStatus::PendingInit | AgentStatus::Running)
}
fn is_watchdog_terminated(status: &AgentStatus) -> bool {
matches!(status, AgentStatus::Shutdown | AgentStatus::NotFound)
}
fn interval_duration(interval_s: i64) -> CodexResult<Duration> {
if interval_s <= 0 {
return Err(CodexErr::UnsupportedOperation(
"interval_s must be greater than zero".to_string(),
));
}
let seconds = u64::try_from(interval_s).map_err(|_| {
CodexErr::UnsupportedOperation(format!("interval_s out of range: {interval_s}"))
})?;
Ok(Duration::from_secs(seconds))
}
fn tick_duration() -> Duration {
let seconds = u64::try_from(WATCHDOG_TICK_SECONDS).unwrap_or(5);
Duration::from_secs(seconds)
}
async fn watchdog_helper_prompt(
_config: &Config,
target_thread_id: ThreadId,
prompt: &str,
) -> String {
if prompt.trim().is_empty() {
format!("Target agent id: {target_thread_id}")
} else {
format!("Target agent id: {target_thread_id}\n\n{prompt}")
}
}
#[cfg(test)]
mod tests {
use super::watchdog_helper_prompt;
use crate::config::ConfigBuilder;
use codex_features::Feature;
use codex_protocol::ThreadId;
#[tokio::test]
async fn watchdog_helper_prompt_is_minimal_when_agent_prompt_injection_is_disabled() {
let codex_home = tempfile::tempdir().expect("create temp dir");
let config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.build()
.await
.expect("load config");
let target_thread_id = ThreadId::default();
let prompt = watchdog_helper_prompt(&config, target_thread_id, "ping").await;
assert_eq!(
prompt,
format!("Target agent id: {target_thread_id}\n\nping")
);
}
#[tokio::test]
async fn watchdog_helper_prompt_is_user_task_only_when_enabled() {
let codex_home = tempfile::tempdir().expect("create temp dir");
let mut config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.build()
.await
.expect("load config");
let _ = config.features.enable(Feature::AgentPromptInjection);
let prompt = watchdog_helper_prompt(&config, ThreadId::default(), "ping").await;
assert!(prompt.contains("Target agent id:"));
assert!(prompt.ends_with("\n\nping"));
}
}
+3 -3
View File
@@ -390,7 +390,7 @@ impl ModelClient {
};
let text = create_text_param_for_request(verbosity, &prompt.output_schema);
let payload = ApiCompactionInput {
model: &model_info.slug,
model: model_info.request_model_slug(),
input: &input,
instructions: &instructions,
tools,
@@ -443,7 +443,7 @@ impl ModelClient {
.with_telemetry(Some(request_telemetry));
let payload = ApiMemorySummarizeInput {
model: model_info.slug.clone(),
model: model_info.request_model_slug().to_string(),
raw_memories,
reasoning: effort.map(|effort| Reasoning {
effort: Some(effort),
@@ -731,7 +731,7 @@ impl ModelClientSession {
let text = create_text_param_for_request(verbosity, &prompt.output_schema);
let prompt_cache_key = Some(self.client.state.conversation_id.to_string());
let request = ResponsesApiRequest {
model: model_info.slug.clone(),
model: model_info.request_model_slug().to_string(),
instructions: instructions.clone(),
input,
tools,
+319 -11
View File
@@ -4,7 +4,9 @@ use std::fmt::Debug;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use crate::agent::AgentControl;
use crate::agent::AgentStatus;
@@ -148,6 +150,7 @@ use rmcp::model::ReadResourceResult;
use rmcp::model::RequestId;
use serde_json;
use serde_json::Value;
use tokio::fs;
use tokio::sync::Mutex;
use tokio::sync::RwLock;
use tokio::sync::oneshot;
@@ -293,6 +296,83 @@ use crate::shell_snapshot::ShellSnapshot;
use crate::skills_watcher::SkillsWatcher;
use crate::skills_watcher::SkillsWatcherEvent;
use crate::state::ActiveTurn;
const ROOT_AGENT_PROMPT_FALLBACK: &str = include_str!("../root_agent_prompt.md");
const ROOT_AGENT_WATCHDOG_PROMPT_FALLBACK: &str = include_str!("../root_agent_watchdog_prompt.md");
const SUBAGENT_PROMPT_FALLBACK: &str = include_str!("../subagent_prompt.md");
const SUBAGENT_WATCHDOG_PROMPT_FALLBACK: &str = include_str!("../subagent_watchdog_prompt.md");
const WATCHDOG_PROMPT_FALLBACK: &str = include_str!("../watchdog_agent_prompt.md");
async fn load_agent_prompt_fallback(
codex_home: &Path,
fallback: &str,
override_filename: &str,
) -> String {
let override_path = codex_home.join(override_filename);
if let Ok(contents) = fs::read_to_string(&override_path).await
&& !contents.trim().is_empty()
{
return contents;
}
fallback.to_string()
}
async fn maybe_load_agent_prompt_fragment(
codex_home: &Path,
fallback: &str,
override_filename: &str,
enabled: bool,
) -> Option<String> {
if !enabled {
return None;
}
let fragment = load_agent_prompt_fallback(codex_home, fallback, override_filename).await;
if fragment.trim().is_empty() {
None
} else {
Some(fragment)
}
}
async fn load_root_agent_prompt(codex_home: &Path, include_watchdog: bool) -> String {
let mut prompt =
load_agent_prompt_fallback(codex_home, ROOT_AGENT_PROMPT_FALLBACK, "AGENTS.root.md").await;
if let Some(fragment) = maybe_load_agent_prompt_fragment(
codex_home,
ROOT_AGENT_WATCHDOG_PROMPT_FALLBACK,
"AGENTS.root.watchdog.md",
include_watchdog,
)
.await
{
prompt.push_str("\n\n");
prompt.push_str(fragment.trim());
}
prompt
}
pub(crate) async fn load_subagent_prompt(codex_home: &Path, include_watchdog: bool) -> String {
let mut prompt =
load_agent_prompt_fallback(codex_home, SUBAGENT_PROMPT_FALLBACK, "AGENTS.subagent.md")
.await;
if let Some(fragment) = maybe_load_agent_prompt_fragment(
codex_home,
SUBAGENT_WATCHDOG_PROMPT_FALLBACK,
"AGENTS.subagent.watchdog.md",
include_watchdog,
)
.await
{
prompt.push_str("\n\n");
prompt.push_str(fragment.trim());
}
prompt
}
pub(crate) async fn load_watchdog_prompt(codex_home: &Path) -> String {
load_agent_prompt_fallback(codex_home, WATCHDOG_PROMPT_FALLBACK, "AGENTS.watchdog.md").await
}
use crate::state::SessionServices;
use crate::state::SessionState;
use crate::tasks::GhostSnapshotTask;
@@ -564,6 +644,40 @@ impl Codex {
let model = models_manager
.get_default_model(&config.model, refresh_strategy)
.await;
let forked_subagent = matches!(session_source, SessionSource::SubAgent(_))
&& matches!(conversation_history, InitialHistory::Forked(_));
let role_prompt = if config.features.enabled(Feature::Collab)
&& config.features.enabled(Feature::AgentPromptInjection)
&& !forked_subagent
{
match session_source {
SessionSource::SubAgent(_) => Some(
load_subagent_prompt(
&config.codex_home,
config.features.enabled(Feature::AgentWatchdog),
)
.await,
),
_ => Some(
load_root_agent_prompt(
&config.codex_home,
config.features.enabled(Feature::AgentWatchdog),
)
.await,
),
}
} else {
None
};
let developer_instructions = if forked_subagent {
None
} else {
match (role_prompt, config.developer_instructions.clone()) {
(Some(prompt), Some(existing)) => Some(format!("{prompt}\n\n{existing}")),
(Some(prompt), None) => Some(prompt),
(None, existing) => existing,
}
};
// Resolve base instructions for the session. Priority order:
// 1. config.base_instructions override
@@ -618,7 +732,7 @@ impl Codex {
collaboration_mode,
model_reasoning_summary: config.model_reasoning_summary,
service_tier: config.service_tier,
developer_instructions: config.developer_instructions.clone(),
developer_instructions,
user_instructions,
personality: config.personality,
base_instructions,
@@ -821,6 +935,8 @@ pub(crate) struct Session {
pub(crate) services: SessionServices,
js_repl: Arc<JsReplHandle>,
next_internal_sub_id: AtomicU64,
turn_used_agent_send_input: AtomicBool,
last_completed_turn_used_agent_send_input: AtomicBool,
}
#[derive(Clone, Debug)]
@@ -1131,13 +1247,23 @@ impl SessionConfiguration {
model: self.collaboration_mode.model().to_string(),
model_provider_id: self.original_config_do_not_use.model_provider_id.clone(),
service_tier: self.service_tier,
plan_mode_reasoning_effort: self.original_config_do_not_use.plan_mode_reasoning_effort,
model_verbosity: self.original_config_do_not_use.model_verbosity,
model_context_window: self.original_config_do_not_use.model_context_window,
model_auto_compact_token_limit: self
.original_config_do_not_use
.model_auto_compact_token_limit,
approval_policy: self.approval_policy.value(),
approvals_reviewer: self.approvals_reviewer,
sandbox_policy: self.sandbox_policy.get().clone(),
cwd: self.cwd.to_path_buf(),
ephemeral: self.original_config_do_not_use.ephemeral,
agent_use_function_call_inbox: self
.original_config_do_not_use
.agent_use_function_call_inbox,
reasoning_effort: self.collaboration_mode.reasoning_effort(),
personality: self.personality,
active_profile: self.original_config_do_not_use.active_profile.clone(),
session_source: self.session_source.clone(),
}
}
@@ -1939,6 +2065,8 @@ impl Session {
services,
js_repl,
next_internal_sub_id: AtomicU64::new(0),
turn_used_agent_send_input: AtomicBool::new(false),
last_completed_turn_used_agent_send_input: AtomicBool::new(false),
});
if let Some(network_policy_decider_session) = network_policy_decider_session {
let mut guard = network_policy_decider_session.write().await;
@@ -2084,7 +2212,24 @@ impl Session {
self.services.state_db.clone()
}
/// Ensure rollout file writes are durably flushed.
pub(crate) async fn has_active_turn(&self) -> bool {
self.active_turn.lock().await.is_some()
}
pub(crate) fn snapshot_agent_send_input_on_turn_complete(&self) {
let used_agent_send_input = self
.turn_used_agent_send_input
.swap(false, Ordering::AcqRel);
self.last_completed_turn_used_agent_send_input
.store(used_agent_send_input, Ordering::Release);
}
pub(crate) fn last_completed_turn_used_agent_send_input(&self) -> bool {
self.last_completed_turn_used_agent_send_input
.load(Ordering::Acquire)
}
/// Ensure all rollout writes are durably flushed.
pub(crate) async fn flush_rollout(&self) {
let recorder = {
let guard = self.services.rollout.lock().await;
@@ -2182,6 +2327,11 @@ impl Session {
state.clear_connector_selection();
}
async fn set_connector_selection(&self, connector_ids: HashSet<String>) {
self.clear_connector_selection().await;
self.merge_connector_selection(connector_ids).await;
}
async fn record_initial_history(&self, conversation_history: InitialHistory) {
let turn_context = self.new_default_turn().await;
let is_subagent = {
@@ -2200,8 +2350,19 @@ impl Session {
}
InitialHistory::Resumed(resumed_history) => {
let rollout_items = resumed_history.history;
let hydrated_rollout_items = if rollout_items
.iter()
.any(|item| matches!(item, RolloutItem::ForkReference(_)))
{
self.materialize_rollout_items_for_replay(&rollout_items)
.await
} else {
rollout_items.clone()
};
let restored_connector_selection =
Self::extract_connector_selection_from_rollout(&hydrated_rollout_items);
let previous_turn_settings = self
.apply_rollout_reconstruction(&turn_context, &rollout_items)
.apply_rollout_reconstruction(&turn_context, &hydrated_rollout_items)
.await;
// If resuming, warn when the last recorded model differs from the current one.
@@ -2226,10 +2387,13 @@ impl Session {
// Seed usage info from the recorded rollout so UIs can show token counts
// immediately on resume/fork.
if let Some(info) = Self::last_token_info_from_rollout(&rollout_items) {
if let Some(info) = Self::last_token_info_from_rollout(&hydrated_rollout_items) {
let mut state = self.state.lock().await;
state.set_token_info(Some(info));
}
if let Some(selected_connectors) = restored_connector_selection {
self.set_connector_selection(selected_connectors).await;
}
// Defer seeding the session's initial context until the first turn starts so
// turn/start overrides can be merged before we write to the rollout.
@@ -2238,18 +2402,40 @@ impl Session {
}
}
InitialHistory::Forked(rollout_items) => {
self.apply_rollout_reconstruction(&turn_context, &rollout_items)
let persisted_rollout_items = rollout_items
.iter()
.position(|item| matches!(item, RolloutItem::ForkReference(_)))
.map(|index| rollout_items[index..].to_vec());
let hydrated_rollout_items = if rollout_items
.iter()
.any(|item| matches!(item, RolloutItem::ForkReference(_)))
{
self.materialize_rollout_items_for_replay(&rollout_items)
.await
} else {
rollout_items.clone()
};
let restored_connector_selection =
Self::extract_connector_selection_from_rollout(&hydrated_rollout_items);
self.apply_rollout_reconstruction(&turn_context, &hydrated_rollout_items)
.await;
// Seed usage info from the recorded rollout so UIs can show token counts
// immediately on resume/fork.
if let Some(info) = Self::last_token_info_from_rollout(&rollout_items) {
if let Some(info) = Self::last_token_info_from_rollout(&hydrated_rollout_items) {
let mut state = self.state.lock().await;
state.set_token_info(Some(info));
}
if let Some(selected_connectors) = restored_connector_selection {
self.set_connector_selection(selected_connectors).await;
}
// If persisting, persist all rollout items as-is (recorder filters)
if !rollout_items.is_empty() {
// Persist only the compact fork reference suffix so child rollouts do not
// duplicate the full parent history they inherited in memory.
if let Some(persisted_rollout_items) = persisted_rollout_items {
self.persist_rollout_items(&persisted_rollout_items).await;
} else if !rollout_items.is_empty() {
self.persist_rollout_items(&rollout_items).await;
}
@@ -2290,6 +2476,41 @@ impl Session {
})
}
fn extract_connector_selection_from_rollout(
rollout_items: &[RolloutItem],
) -> Option<HashSet<String>> {
let mut active_selected_connectors: Option<HashSet<String>> = None;
for item in rollout_items {
let RolloutItem::ResponseItem(response_item) = item else {
continue;
};
let ResponseItem::FunctionCallOutput { output, .. } = response_item else {
continue;
};
let Some(content) = output.body.to_text() else {
continue;
};
let Ok(payload) = serde_json::from_str::<Value>(&content) else {
continue;
};
let Some(selected_connectors) = payload
.get("active_selected_tools")
.and_then(Value::as_array)
else {
continue;
};
let connector_ids = selected_connectors
.iter()
.filter_map(Value::as_str)
.map(ToOwned::to_owned)
.collect::<HashSet<_>>();
active_selected_connectors = Some(connector_ids);
}
active_selected_connectors
}
async fn previous_turn_settings(&self) -> Option<PreviousTurnSettings> {
let state = self.state.lock().await;
state.previous_turn_settings()
@@ -3448,7 +3669,8 @@ impl Session {
turn_context: &Arc<TurnContext>,
server_model: String,
) -> bool {
let requested_model = turn_context.model_info.slug.clone();
let requested_model = turn_context.model_info.request_model_slug().to_string();
let selected_model = turn_context.model_info.slug.clone();
let server_model_normalized = server_model.to_ascii_lowercase();
let requested_model_normalized = requested_model.to_ascii_lowercase();
if server_model_normalized == requested_model_normalized {
@@ -3456,7 +3678,9 @@ impl Session {
return false;
}
warn!("server reported model {server_model} while requested model was {requested_model}");
warn!(
"server reported model {server_model} while requested model was {requested_model} (selected alias: {selected_model})"
);
let warning_message = format!(
"Your account was flagged for potentially high-risk cyber activity and this request was routed to gpt-5.2 as a fallback. To regain access to gpt-5.3-codex, apply for trusted access: {CYBER_VERIFY_URL} or learn more: {CYBER_SAFETY_URL}"
@@ -3465,7 +3689,7 @@ impl Session {
self.send_event(
turn_context,
EventMsg::ModelReroute(ModelRerouteEvent {
from_model: requested_model.clone(),
from_model: selected_model,
to_model: server_model.clone(),
reason: ModelRerouteReason::HighRiskCyberActivity,
}),
@@ -4372,6 +4596,13 @@ async fn submission_loop(sess: Arc<Session>, config: Arc<Config>, rx_sub: Receiv
handlers::interrupt(&sess).await;
false
}
Op::NoteOwnerActivity => {
sess.services
.agent_control
.note_owner_input(sess.conversation_id)
.await;
false
}
Op::CleanBackgroundTerminals => {
handlers::clean_background_terminals(&sess).await;
false
@@ -4453,6 +4684,10 @@ async fn submission_loop(sess: Arc<Session>, config: Arc<Config>, rx_sub: Receiv
handlers::inter_agent_communication(&sess, sub.id.clone(), communication).await;
false
}
Op::InjectResponseItems { items } => {
handlers::inject_response_items(&sess, sub.id.clone(), items).await;
false
}
Op::ExecApproval {
id: approval_id,
turn_id,
@@ -4653,7 +4888,10 @@ mod handlers {
use codex_protocol::config_types::ModeKind;
use codex_protocol::config_types::Settings;
use codex_protocol::dynamic_tools::DynamicToolResponse;
use codex_protocol::items::TurnItem;
use codex_protocol::mcp::RequestId as ProtocolRequestId;
use codex_protocol::models::ResponseInputItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::user_input::UserInput;
use codex_rmcp_client::ElicitationAction;
use codex_rmcp_client::ElicitationResponse;
@@ -4791,6 +5029,76 @@ mod handlers {
}
}
pub async fn inject_response_items(
sess: &Arc<Session>,
sub_id: String,
items: Vec<ResponseInputItem>,
) {
const MAX_TURN_RESTART_ATTEMPTS: usize = 3;
let mut pending_items = items;
let mut attempts = 0usize;
loop {
match sess.inject_response_items(pending_items).await {
Ok(()) => return,
Err(items_without_active_turn) => {
pending_items = items_without_active_turn;
}
}
if attempts >= MAX_TURN_RESTART_ATTEMPTS {
warn!(
attempts,
remaining_items = pending_items.len(),
"dropping response items after repeated turn restart failures"
);
return;
}
attempts += 1;
let turn_input =
pop_leading_user_message_input(&mut pending_items).unwrap_or_else(|| {
vec![UserInput::Text {
text: String::new(),
text_elements: Vec::new(),
}]
});
let turn_sub_id = if attempts == 1 {
sub_id.clone()
} else {
format!("{sub_id}-retry-{attempts}")
};
let current_context = sess.new_default_turn_with_sub_id(turn_sub_id).await;
// Keep injected inbox wakeups visible to telemetry after the TurnContext field rename.
current_context.session_telemetry.user_prompt(&turn_input);
sess.refresh_mcp_servers_if_requested(&current_context)
.await;
sess.spawn_task(
Arc::clone(&current_context),
turn_input,
crate::tasks::RegularTask::new(),
)
.await;
if pending_items.is_empty() {
return;
}
}
}
fn pop_leading_user_message_input(
items: &mut Vec<ResponseInputItem>,
) -> Option<Vec<UserInput>> {
let first_item = items.first().cloned()?;
let response_item = ResponseItem::from(first_item);
let TurnItem::UserMessage(user_message) = crate::parse_turn_item(&response_item)? else {
return None;
};
let _ = items.remove(0);
Some(user_message.content)
}
pub async fn run_user_shell_command(sess: &Arc<Session>, sub_id: String, command: String) {
if let Some((turn_context, cancellation_token)) =
sess.active_turn_context_and_cancellation_token().await
@@ -84,11 +84,34 @@ fn finalize_active_segment<'a>(
}
impl Session {
pub(super) async fn materialize_rollout_items_for_replay(
&self,
rollout_items: &[RolloutItem],
) -> Vec<RolloutItem> {
let codex_home = {
self.state
.lock()
.await
.session_configuration
.codex_home
.clone()
};
crate::rollout::truncation::materialize_rollout_items_for_replay(
codex_home.as_path(),
rollout_items,
)
.await
}
pub(super) async fn reconstruct_history_from_rollout(
&self,
turn_context: &TurnContext,
rollout_items: &[RolloutItem],
) -> RolloutReconstruction {
let rollout_items = self
.materialize_rollout_items_for_replay(rollout_items)
.await;
let rollout_items = rollout_items.as_slice();
// Replay metadata should already match the shape of the future lazy reverse loader, even
// while history materialization still uses an eager bridge. Scan newest-to-oldest,
// stopping once a surviving replacement-history checkpoint and the required resume metadata
@@ -207,7 +230,9 @@ impl Session {
active_segment.get_or_insert_with(ActiveReplaySegment::default);
active_segment.counts_as_user_turn |= is_user_turn_boundary(response_item);
}
RolloutItem::EventMsg(_) | RolloutItem::SessionMeta(_) => {}
RolloutItem::EventMsg(_)
| RolloutItem::ForkReference(_)
| RolloutItem::SessionMeta(_) => {}
}
if base_replacement_history.is_some()
@@ -275,6 +300,7 @@ impl Session {
history.drop_last_n_user_turns(rollback.num_turns);
}
RolloutItem::EventMsg(_)
| RolloutItem::ForkReference(_)
| RolloutItem::TurnContext(_)
| RolloutItem::SessionMeta(_) => {}
}
@@ -5,11 +5,19 @@ use codex_protocol::ThreadId;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::CompactedItem;
use codex_protocol::protocol::ForkReferenceItem;
use codex_protocol::protocol::InitialHistory;
use codex_protocol::protocol::InterAgentCommunication;
use codex_protocol::protocol::ResumedHistory;
use codex_protocol::protocol::RolloutItem;
use codex_protocol::protocol::RolloutLine;
use codex_protocol::protocol::SessionMeta;
use codex_protocol::protocol::SessionMetaLine;
use codex_protocol::protocol::SessionSource;
use pretty_assertions::assert_eq;
use std::path::Path;
use std::path::PathBuf;
use tempfile::TempDir;
fn user_message(text: &str) -> ResponseItem {
ResponseItem::Message {
@@ -54,6 +62,53 @@ fn inter_agent_assistant_message(text: &str) -> ResponseItem {
}
}
fn write_rollout_items(
root: &Path,
thread_id: ThreadId,
items: &[RolloutItem],
) -> std::io::Result<PathBuf> {
let rollout_dir = root
.join(crate::SESSIONS_SUBDIR)
.join("2026")
.join("03")
.join("05");
std::fs::create_dir_all(&rollout_dir)?;
let rollout_path = rollout_dir.join(format!("rollout-2026-03-05T00-00-00-{thread_id}.jsonl"));
let session_meta_line = RolloutLine {
timestamp: "2026-03-05T00:00:00Z".to_string(),
item: RolloutItem::SessionMeta(SessionMetaLine {
meta: SessionMeta {
id: thread_id,
timestamp: "2026-03-05T00:00:00Z".to_string(),
cwd: root.to_path_buf(),
originator: "codex".to_string(),
cli_version: "test".to_string(),
source: SessionSource::Exec,
agent_nickname: None,
agent_role: None,
agent_path: None,
model_provider: Some("openai".to_string()),
base_instructions: None,
dynamic_tools: None,
memory_mode: None,
forked_from_id: None,
},
git: None,
}),
};
let mut text = format!("{}\n", serde_json::to_string(&session_meta_line).unwrap());
for item in items {
let line = RolloutLine {
timestamp: "2026-03-05T00:00:01Z".to_string(),
item: item.clone(),
};
text.push_str(&serde_json::to_string(&line).unwrap());
text.push('\n');
}
std::fs::write(&rollout_path, text)?;
Ok(rollout_path)
}
#[tokio::test]
async fn record_initial_history_resumed_bare_turn_context_does_not_hydrate_previous_turn_settings()
{
@@ -93,6 +148,130 @@ async fn record_initial_history_resumed_bare_turn_context_does_not_hydrate_previ
assert!(session.reference_context_item().await.is_none());
}
#[tokio::test]
async fn reconstruct_history_materializes_fork_reference_rollout_items() {
let (session, turn_context) = make_session_and_context().await;
let dir = TempDir::new().expect("create temp dir");
let parent_thread_id = ThreadId::new();
let parent_rollout_path = write_rollout_items(
dir.path(),
parent_thread_id,
&[
RolloutItem::ResponseItem(user_message("first user")),
RolloutItem::ResponseItem(assistant_message("first reply")),
RolloutItem::ResponseItem(user_message("second user")),
RolloutItem::ResponseItem(assistant_message("second reply")),
],
)
.expect("write parent rollout");
let rollout_items = vec![RolloutItem::ForkReference(ForkReferenceItem {
rollout_path: parent_rollout_path,
nth_user_message: 1,
})];
let reconstructed = session
.reconstruct_history_from_rollout(&turn_context, &rollout_items)
.await;
assert_eq!(
reconstructed.history,
vec![user_message("first user"), assistant_message("first reply")]
);
}
#[tokio::test]
async fn record_initial_history_forked_materializes_fork_reference_rollout_items() {
let (session, turn_context) = make_session_and_context().await;
let codex_home = turn_context.config.codex_home.clone();
let parent_thread_id = ThreadId::new();
let parent_rollout_path = write_rollout_items(
codex_home.as_path(),
parent_thread_id,
&[
RolloutItem::ResponseItem(user_message("first user")),
RolloutItem::ResponseItem(assistant_message("first reply")),
RolloutItem::ResponseItem(user_message("second user")),
RolloutItem::ResponseItem(assistant_message("second reply")),
],
)
.expect("write parent rollout");
let rollout_items = vec![RolloutItem::ForkReference(ForkReferenceItem {
rollout_path: parent_rollout_path,
nth_user_message: 1,
})];
session
.record_initial_history(InitialHistory::Forked(rollout_items))
.await;
let reconstruction_turn = session.new_default_turn().await;
let mut expected = vec![user_message("first user"), assistant_message("first reply")];
expected.extend(
session
.build_initial_context(reconstruction_turn.as_ref())
.await,
);
let history = session.state.lock().await.clone_history();
assert_eq!(expected, history.raw_items());
assert!(session.reference_context_item().await.is_none());
}
#[tokio::test]
async fn reconstruct_history_resolves_fork_reference_after_parent_archive_and_unarchive() {
let (session, turn_context) = make_session_and_context().await;
let codex_home = turn_context.config.codex_home.clone();
let parent_thread_id = ThreadId::new();
let parent_rollout_path = write_rollout_items(
codex_home.as_path(),
parent_thread_id,
&[
RolloutItem::ResponseItem(user_message("first user")),
RolloutItem::ResponseItem(assistant_message("first reply")),
RolloutItem::ResponseItem(user_message("second user")),
RolloutItem::ResponseItem(assistant_message("second reply")),
],
)
.expect("write parent rollout");
let rollout_items = vec![RolloutItem::ForkReference(ForkReferenceItem {
rollout_path: parent_rollout_path.clone(),
nth_user_message: 1,
})];
let expected_history = vec![user_message("first user"), assistant_message("first reply")];
let archived_rollout_dir = codex_home
.join(crate::ARCHIVED_SESSIONS_SUBDIR)
.join("2026")
.join("03")
.join("05");
std::fs::create_dir_all(&archived_rollout_dir).expect("create archived rollout dir");
let archived_rollout_path = archived_rollout_dir.join(
parent_rollout_path
.file_name()
.expect("parent rollout file name"),
);
std::fs::rename(&parent_rollout_path, &archived_rollout_path).expect("archive parent rollout");
let reconstructed = session
.reconstruct_history_from_rollout(&turn_context, &rollout_items)
.await;
assert_eq!(reconstructed.history, expected_history);
let unarchived_rollout_dir = codex_home
.join(crate::SESSIONS_SUBDIR)
.join("2026")
.join("03")
.join("05");
std::fs::create_dir_all(&unarchived_rollout_dir).expect("create unarchived rollout dir");
std::fs::rename(&archived_rollout_path, &parent_rollout_path)
.expect("unarchive parent rollout");
let reconstructed = session
.reconstruct_history_from_rollout(&turn_context, &rollout_items)
.await;
assert_eq!(reconstructed.history, expected_history);
}
#[tokio::test]
async fn record_initial_history_resumed_hydrates_previous_turn_settings_from_lifecycle_turn_with_missing_turn_context_id()
{
+36 -1
View File
@@ -99,6 +99,7 @@ use core_test_support::tracing::install_test_tracing;
use core_test_support::wait_for_event;
use opentelemetry::trace::TraceContextExt;
use opentelemetry::trace::TraceId;
use std::collections::HashMap;
use std::path::Path;
use std::time::Duration;
use tokio::time::sleep;
@@ -254,7 +255,7 @@ fn test_model_client_session() -> crate::client::ModelClientSession {
ThreadId::try_from("00000000-0000-4000-8000-000000000001")
.expect("test thread id should be valid"),
crate::model_provider_info::ModelProviderInfo::create_openai_provider(
/* base_url */ /*base_url*/ None,
/*base_url*/ None,
),
codex_protocol::protocol::SessionSource::Exec,
/*model_verbosity*/ None,
@@ -2368,8 +2369,11 @@ enabled = false
"custom".to_string(),
crate::config::AgentRoleConfig {
description: None,
model: None,
config_file: Some(role_path),
watchdog_interval_s: None,
nickname_candidates: None,
fork_context: None,
},
);
crate::agent::role::apply_role_to_config(&mut child_config, Some("custom"))
@@ -2487,6 +2491,7 @@ async fn session_new_fails_when_zsh_fork_enabled_without_zsh_path() {
config.codex_home.clone(),
auth_manager.clone(),
/*model_catalog*/ None,
HashMap::new(),
CollaborationModesConfig::default(),
));
let model = ModelsManager::get_model_offline_for_tests(config.model.as_deref());
@@ -2580,6 +2585,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
config.codex_home.clone(),
auth_manager.clone(),
/*model_catalog*/ None,
HashMap::new(),
CollaborationModesConfig::default(),
));
let agent_control = AgentControl::default();
@@ -2753,6 +2759,8 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
guardian_review_session: crate::guardian::GuardianReviewSessionManager::default(),
services,
js_repl,
turn_used_agent_send_input: std::sync::atomic::AtomicBool::new(false),
last_completed_turn_used_agent_send_input: std::sync::atomic::AtomicBool::new(false),
next_internal_sub_id: AtomicU64::new(0),
};
@@ -3417,6 +3425,7 @@ pub(crate) async fn make_session_and_context_with_dynamic_tools_and_rx(
config.codex_home.clone(),
auth_manager.clone(),
/*model_catalog*/ None,
HashMap::new(),
CollaborationModesConfig::default(),
));
let agent_control = AgentControl::default();
@@ -3590,6 +3599,8 @@ pub(crate) async fn make_session_and_context_with_dynamic_tools_and_rx(
guardian_review_session: crate::guardian::GuardianReviewSessionManager::default(),
services,
js_repl,
turn_used_agent_send_input: std::sync::atomic::AtomicBool::new(false),
last_completed_turn_used_agent_send_input: std::sync::atomic::AtomicBool::new(false),
next_internal_sub_id: AtomicU64::new(0),
});
@@ -5283,3 +5294,27 @@ async fn unified_exec_rejects_escalated_permissions_when_policy_not_on_request()
pretty_assertions::assert_eq!(output, expected);
}
#[tokio::test]
async fn root_agent_prompt_only_includes_watchdog_fragment_when_enabled() {
let codex_home = tempfile::tempdir().expect("create temp dir");
let without_watchdog =
load_root_agent_prompt(codex_home.path(), /*include_watchdog*/ false).await;
assert!(!without_watchdog.contains("## Watchdogs"));
let with_watchdog = load_root_agent_prompt(codex_home.path(), /*include_watchdog*/ true).await;
assert!(with_watchdog.contains("## Watchdogs"));
}
#[tokio::test]
async fn subagent_prompt_only_includes_watchdog_fragment_when_enabled() {
let codex_home = tempfile::tempdir().expect("create temp dir");
let without_watchdog =
load_subagent_prompt(codex_home.path(), /*include_watchdog*/ false).await;
assert!(!without_watchdog.contains("## Watchdog-only Guidance"));
let with_watchdog = load_subagent_prompt(codex_home.path(), /*include_watchdog*/ true).await;
assert!(with_watchdog.contains("## Watchdog-only Guidance"));
}
@@ -426,6 +426,7 @@ async fn guardian_subagent_does_not_inherit_parent_exec_policy_rules() {
config.codex_home.clone(),
auth_manager.clone(),
/*model_catalog*/ None,
HashMap::new(),
CollaborationModesConfig::default(),
));
let plugins_manager = Arc::new(PluginsManager::new(config.codex_home.clone()));
+17
View File
@@ -9,6 +9,7 @@ use codex_features::Feature;
use codex_protocol::config_types::ApprovalsReviewer;
use codex_protocol::config_types::Personality;
use codex_protocol::config_types::ServiceTier;
use codex_protocol::config_types::Verbosity;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ResponseInputItem;
use codex_protocol::models::ResponseItem;
@@ -33,13 +34,19 @@ pub struct ThreadConfigSnapshot {
pub model: String,
pub model_provider_id: String,
pub service_tier: Option<ServiceTier>,
pub plan_mode_reasoning_effort: Option<ReasoningEffort>,
pub model_verbosity: Option<Verbosity>,
pub model_context_window: Option<i64>,
pub model_auto_compact_token_limit: Option<i64>,
pub approval_policy: AskForApproval,
pub approvals_reviewer: ApprovalsReviewer,
pub sandbox_policy: SandboxPolicy,
pub cwd: PathBuf,
pub ephemeral: bool,
pub agent_use_function_call_inbox: bool,
pub reasoning_effort: Option<ReasoningEffort>,
pub personality: Option<Personality>,
pub active_profile: Option<String>,
pub session_source: SessionSource,
}
@@ -130,6 +137,16 @@ impl CodexThread {
self.codex.session.total_token_usage().await
}
pub(crate) async fn has_active_turn(&self) -> bool {
self.codex.session.has_active_turn().await
}
pub(crate) fn last_completed_turn_used_agent_send_input(&self) -> bool {
self.codex
.session
.last_completed_turn_used_agent_send_input()
}
/// Records a user-role session-prefix message without creating a new user turn boundary.
pub(crate) async fn inject_user_message_without_turn(&self, message: String) {
let message = ResponseItem::Message {
+9
View File
@@ -152,11 +152,14 @@ fn read_declared_role(
fn merge_missing_role_fields(role: &mut AgentRoleConfig, fallback: &AgentRoleConfig) {
role.description = role.description.clone().or(fallback.description.clone());
role.model = role.model.clone().or(fallback.model.clone());
role.config_file = role.config_file.clone().or(fallback.config_file.clone());
role.watchdog_interval_s = role.watchdog_interval_s.or(fallback.watchdog_interval_s);
role.nickname_candidates = role
.nickname_candidates
.clone()
.or(fallback.nickname_candidates.clone());
role.fork_context = role.fork_context.or(fallback.fork_context);
}
fn agents_toml_from_layer(layer_toml: &TomlValue) -> std::io::Result<Option<AgentsToml>> {
@@ -188,8 +191,11 @@ fn agent_role_config_from_toml(
Ok(AgentRoleConfig {
description,
model: role.model.clone(),
config_file,
watchdog_interval_s: role.watchdog_interval_s,
nickname_candidates,
fork_context: role.fork_context,
})
}
@@ -478,8 +484,11 @@ fn discover_agent_roles_in_dir(
role_name,
AgentRoleConfig {
description: parsed_file.description,
model: None,
config_file: Some(agent_file),
watchdog_interval_s: None,
nickname_candidates: parsed_file.nickname_candidates,
fork_context: None,
},
);
}
+96
View File
@@ -244,6 +244,48 @@ web_search = false
);
}
#[test]
fn config_toml_deserializes_custom_models() {
let custom_models = r#"
[[custom_models]]
name = "gpt-5.4 1m"
model = "gpt-5.4"
model_context_window = 1000000
model_auto_compact_token_limit = 900000
"#;
let custom_models_cfg = toml::from_str::<ConfigToml>(custom_models)
.expect("TOML deserialization should succeed for custom models");
assert_eq!(
custom_models_cfg.custom_models,
vec![CustomModelToml {
name: "gpt-5.4 1m".to_string(),
model: "gpt-5.4".to_string(),
model_context_window: Some(1_000_000),
model_auto_compact_token_limit: Some(900_000),
}]
);
let config = Config::load_from_base_config_with_overrides(
custom_models_cfg,
ConfigOverrides::default(),
tempdir().expect("tempdir").path().to_path_buf(),
)
.expect("load config from custom models settings");
assert_eq!(
config.custom_models,
HashMap::from([(
"gpt-5.4 1m".to_string(),
CustomModelConfig {
model: "gpt-5.4".to_string(),
model_context_window: Some(1_000_000),
model_auto_compact_token_limit: Some(900_000),
},
)])
);
}
#[test]
fn rejects_provider_auth_with_env_key() {
let err = toml::from_str::<ConfigToml>(
@@ -1736,6 +1778,28 @@ fn feature_table_overrides_legacy_flags() -> std::io::Result<()> {
Ok(())
}
#[test]
fn feature_table_enables_agent_function_call_inbox() -> std::io::Result<()> {
let codex_home = TempDir::new()?;
let mut entries = BTreeMap::new();
entries.insert("agent_function_call_inbox".to_string(), true);
let cfg = ConfigToml {
features: Some(codex_features::FeaturesToml { entries }),
..Default::default()
};
let config = Config::load_from_base_config_with_overrides(
cfg,
ConfigOverrides::default(),
codex_home.path().to_path_buf(),
)?;
assert!(config.features.enabled(Feature::AgentFunctionCallInbox));
assert!(config.agent_use_function_call_inbox);
Ok(())
}
#[test]
fn legacy_toggles_map_to_features() -> std::io::Result<()> {
let codex_home = TempDir::new()?;
@@ -3236,12 +3300,16 @@ fn load_config_rejects_missing_agent_role_config_file() -> std::io::Result<()> {
max_threads: None,
max_depth: None,
job_max_runtime_seconds: None,
use_function_call_inbox: false,
roles: BTreeMap::from([(
"researcher".to_string(),
AgentRoleToml {
description: Some("Research role".to_string()),
model: None,
config_file: Some(missing_path.abs()),
watchdog_interval_s: None,
nickname_candidates: None,
fork_context: None,
},
)]),
}),
@@ -4101,15 +4169,19 @@ fn load_config_normalizes_agent_role_nickname_candidates() -> std::io::Result<()
max_threads: None,
max_depth: None,
job_max_runtime_seconds: None,
use_function_call_inbox: false,
roles: BTreeMap::from([(
"researcher".to_string(),
AgentRoleToml {
description: Some("Research role".to_string()),
model: None,
config_file: None,
watchdog_interval_s: None,
nickname_candidates: Some(vec![
" Hypatia ".to_string(),
"Noether".to_string(),
]),
fork_context: None,
},
)]),
}),
@@ -4142,12 +4214,16 @@ fn load_config_rejects_empty_agent_role_nickname_candidates() -> std::io::Result
max_threads: None,
max_depth: None,
job_max_runtime_seconds: None,
use_function_call_inbox: false,
roles: BTreeMap::from([(
"researcher".to_string(),
AgentRoleToml {
description: Some("Research role".to_string()),
model: None,
config_file: None,
watchdog_interval_s: None,
nickname_candidates: Some(Vec::new()),
fork_context: None,
},
)]),
}),
@@ -4177,12 +4253,16 @@ fn load_config_rejects_duplicate_agent_role_nickname_candidates() -> std::io::Re
max_threads: None,
max_depth: None,
job_max_runtime_seconds: None,
use_function_call_inbox: false,
roles: BTreeMap::from([(
"researcher".to_string(),
AgentRoleToml {
description: Some("Research role".to_string()),
model: None,
config_file: None,
watchdog_interval_s: None,
nickname_candidates: Some(vec!["Hypatia".to_string(), " Hypatia ".to_string()]),
fork_context: None,
},
)]),
}),
@@ -4212,12 +4292,16 @@ fn load_config_rejects_unsafe_agent_role_nickname_candidates() -> std::io::Resul
max_threads: None,
max_depth: None,
job_max_runtime_seconds: None,
use_function_call_inbox: false,
roles: BTreeMap::from([(
"researcher".to_string(),
AgentRoleToml {
description: Some("Research role".to_string()),
model: None,
config_file: None,
watchdog_interval_s: None,
nickname_candidates: Some(vec!["Agent <One>".to_string()]),
fork_context: None,
},
)]),
}),
@@ -4425,6 +4509,7 @@ fn test_precedence_fixture_with_o3_profile() -> std::io::Result<()> {
review_model: None,
model_context_window: None,
model_auto_compact_token_limit: None,
custom_models: HashMap::new(),
service_tier: None,
model_provider_id: "openai".to_string(),
model_provider: fixture.openai_provider.clone(),
@@ -4460,6 +4545,8 @@ fn test_precedence_fixture_with_o3_profile() -> std::io::Result<()> {
agent_roles: BTreeMap::new(),
memories: MemoriesConfig::default(),
agent_job_max_runtime_seconds: DEFAULT_AGENT_JOB_MAX_RUNTIME_SECONDS,
agent_use_function_call_inbox: false,
watchdog_interval_s: DEFAULT_WATCHDOG_INTERVAL_S,
codex_home: fixture.codex_home(),
sqlite_home: fixture.codex_home(),
log_dir: fixture.codex_home().join("log"),
@@ -4567,6 +4654,7 @@ fn test_precedence_fixture_with_gpt3_profile() -> std::io::Result<()> {
review_model: None,
model_context_window: None,
model_auto_compact_token_limit: None,
custom_models: HashMap::new(),
service_tier: None,
model_provider_id: "openai-custom".to_string(),
model_provider: fixture.openai_custom_provider.clone(),
@@ -4602,6 +4690,8 @@ fn test_precedence_fixture_with_gpt3_profile() -> std::io::Result<()> {
agent_roles: BTreeMap::new(),
memories: MemoriesConfig::default(),
agent_job_max_runtime_seconds: DEFAULT_AGENT_JOB_MAX_RUNTIME_SECONDS,
agent_use_function_call_inbox: false,
watchdog_interval_s: DEFAULT_WATCHDOG_INTERVAL_S,
codex_home: fixture.codex_home(),
sqlite_home: fixture.codex_home(),
log_dir: fixture.codex_home().join("log"),
@@ -4707,6 +4797,7 @@ fn test_precedence_fixture_with_zdr_profile() -> std::io::Result<()> {
review_model: None,
model_context_window: None,
model_auto_compact_token_limit: None,
custom_models: HashMap::new(),
service_tier: None,
model_provider_id: "openai".to_string(),
model_provider: fixture.openai_provider.clone(),
@@ -4742,6 +4833,8 @@ fn test_precedence_fixture_with_zdr_profile() -> std::io::Result<()> {
agent_roles: BTreeMap::new(),
memories: MemoriesConfig::default(),
agent_job_max_runtime_seconds: DEFAULT_AGENT_JOB_MAX_RUNTIME_SECONDS,
agent_use_function_call_inbox: false,
watchdog_interval_s: DEFAULT_WATCHDOG_INTERVAL_S,
codex_home: fixture.codex_home(),
sqlite_home: fixture.codex_home(),
log_dir: fixture.codex_home().join("log"),
@@ -4833,6 +4926,7 @@ fn test_precedence_fixture_with_gpt5_profile() -> std::io::Result<()> {
review_model: None,
model_context_window: None,
model_auto_compact_token_limit: None,
custom_models: HashMap::new(),
service_tier: None,
model_provider_id: "openai".to_string(),
model_provider: fixture.openai_provider.clone(),
@@ -4868,6 +4962,8 @@ fn test_precedence_fixture_with_gpt5_profile() -> std::io::Result<()> {
agent_roles: BTreeMap::new(),
memories: MemoriesConfig::default(),
agent_job_max_runtime_seconds: DEFAULT_AGENT_JOB_MAX_RUNTIME_SECONDS,
agent_use_function_call_inbox: false,
watchdog_interval_s: DEFAULT_WATCHDOG_INTERVAL_S,
codex_home: fixture.codex_home(),
sqlite_home: fixture.codex_home(),
log_dir: fixture.codex_home().join("log"),
+98
View File
@@ -145,6 +145,7 @@ pub(crate) const PROJECT_DOC_MAX_BYTES: usize = 32 * 1024; // 32 KiB
pub(crate) const DEFAULT_AGENT_MAX_THREADS: Option<usize> = Some(6);
pub(crate) const DEFAULT_AGENT_MAX_DEPTH: i32 = 1;
pub(crate) const DEFAULT_AGENT_JOB_MAX_RUNTIME_SECONDS: Option<u64> = None;
pub(crate) const DEFAULT_WATCHDOG_INTERVAL_S: i64 = 10;
pub const CONFIG_TOML_FILE: &str = "config.toml";
const OPENAI_BASE_URL_ENV_VAR: &str = "OPENAI_BASE_URL";
@@ -179,6 +180,12 @@ pub(crate) fn test_config() -> Config {
.expect("load default test config")
}
impl Config {
pub(crate) fn custom_model_alias(&self, alias: &str) -> Option<&CustomModelConfig> {
self.custom_models.get(alias)
}
}
/// Application configuration loaded from disk and merged with overrides.
#[derive(Debug, Clone, PartialEq)]
pub struct Permissions {
@@ -390,6 +397,9 @@ pub struct Config {
/// Combined provider map (defaults plus user-defined providers).
pub model_providers: HashMap<String, ModelProviderInfo>,
/// User-defined model aliases shown in the picker.
pub custom_models: HashMap<String, CustomModelConfig>,
/// Maximum number of bytes to include from an AGENTS.md project doc file.
pub project_doc_max_bytes: usize,
@@ -403,6 +413,13 @@ pub struct Config {
pub agent_max_threads: Option<usize>,
/// Maximum runtime in seconds for agent job workers before they are failed.
pub agent_job_max_runtime_seconds: Option<u64>,
/// When true, inbound agent messages to non-subagent threads are delivered
/// as a synthetic function_call/function_call_output pair instead of plain
/// user input.
pub agent_use_function_call_inbox: bool,
/// Watchdog polling interval in seconds.
pub watchdog_interval_s: i64,
/// Maximum nesting depth allowed for spawned agent threads.
pub agent_max_depth: i32,
@@ -1229,6 +1246,10 @@ pub struct ConfigToml {
#[serde(default, deserialize_with = "deserialize_model_providers")]
pub model_providers: HashMap<String, ModelProviderInfo>,
/// User-defined model aliases that can override model context settings.
#[serde(default)]
pub custom_models: Vec<CustomModelToml>,
/// Maximum number of bytes to include from an AGENTS.md project doc file.
pub project_doc_max_bytes: Option<usize>,
@@ -1352,6 +1373,9 @@ pub struct ConfigToml {
/// Agent-related settings (thread limits, etc.).
pub agents: Option<AgentsToml>,
/// Watchdog polling interval in seconds.
pub watchdog_interval_s: Option<i64>,
/// Memories subsystem settings.
pub memories: Option<MemoriesToml>,
@@ -1507,6 +1531,29 @@ pub struct RealtimeAudioToml {
pub speaker: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CustomModelConfig {
/// Provider-facing model slug used on API requests.
pub model: String,
/// Optional context window override applied when this alias is selected.
pub model_context_window: Option<i64>,
/// Optional auto-compaction token limit override applied when this alias is selected.
pub model_auto_compact_token_limit: Option<i64>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct CustomModelToml {
/// User-facing alias shown in the model picker.
pub name: String,
/// Provider-facing model slug used on API requests.
pub model: String,
/// Optional context window override applied when this alias is selected.
pub model_context_window: Option<i64>,
/// Optional auto-compaction token limit override applied when this alias is selected.
pub model_auto_compact_token_limit: Option<i64>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ToolsToml {
@@ -1582,6 +1629,10 @@ pub struct AgentsToml {
/// Default maximum runtime in seconds for agent job workers.
#[schemars(range(min = 1))]
pub job_max_runtime_seconds: Option<u64>,
/// Deliver inbound agent messages to non-subagent threads as a synthetic
/// function_call/function_call_output pair instead of plain user input.
#[serde(default)]
pub use_function_call_inbox: bool,
/// User-defined role declarations keyed by role name.
///
@@ -1601,10 +1652,16 @@ pub struct AgentRoleConfig {
/// Human-facing role documentation used in spawn tool guidance.
/// Required for loaded user-defined roles after deprecated/new metadata precedence resolves.
pub description: Option<String>,
/// Optional model override applied by this role.
pub model: Option<String>,
/// Path to a role-specific config layer.
pub config_file: Option<PathBuf>,
/// Optional watchdog interval for roles that should spawn as idle-time watchdog handles.
pub watchdog_interval_s: Option<i64>,
/// Candidate nicknames for agents spawned with this role.
pub nickname_candidates: Option<Vec<String>>,
/// Default fork-context behavior for this role.
pub fork_context: Option<bool>,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
@@ -1614,12 +1671,22 @@ pub struct AgentRoleToml {
/// Required unless supplied by the referenced agent role file.
pub description: Option<String>,
/// Optional model override applied by this role.
pub model: Option<String>,
/// Path to a role-specific config layer.
/// Relative paths are resolved relative to the `config.toml` that defines them.
pub config_file: Option<AbsolutePathBuf>,
/// Optional watchdog interval in seconds for roles that should behave as watchdogs.
#[schemars(range(min = 1))]
pub watchdog_interval_s: Option<i64>,
/// Candidate nicknames for agents spawned with this role.
pub nickname_candidates: Option<Vec<String>>,
/// Default fork-context behavior for this role.
pub fork_context: Option<bool>,
}
impl From<ToolsToml> for Tools {
@@ -2306,6 +2373,24 @@ impl Config {
for (key, provider) in cfg.model_providers.into_iter() {
model_providers.entry(key).or_insert(provider);
}
let mut custom_models = HashMap::new();
for custom in cfg.custom_models {
let alias = custom.name;
if custom_models.contains_key(&alias) {
return Err(std::io::Error::new(
ErrorKind::InvalidInput,
format!("duplicate custom model alias: {alias}"),
));
}
custom_models.insert(
alias,
CustomModelConfig {
model: custom.model,
model_context_window: custom.model_context_window,
model_auto_compact_token_limit: custom.model_auto_compact_token_limit,
},
);
}
let model_provider_id = model_provider
.or(config_profile.model_provider)
@@ -2355,6 +2440,7 @@ impl Config {
.as_ref()
.and_then(|agents| agents.job_max_runtime_seconds)
.or(DEFAULT_AGENT_JOB_MAX_RUNTIME_SECONDS);
let agent_use_function_call_inbox = features.enabled(Feature::AgentFunctionCallInbox);
if agent_job_max_runtime_seconds == Some(0) {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
@@ -2369,6 +2455,15 @@ impl Config {
"agents.job_max_runtime_seconds must fit within a 64-bit signed integer",
));
}
let watchdog_interval_s = cfg
.watchdog_interval_s
.unwrap_or(DEFAULT_WATCHDOG_INTERVAL_S);
if watchdog_interval_s <= 0 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"watchdog_interval_s must be at least 1",
));
}
let background_terminal_max_timeout = cfg
.background_terminal_max_timeout
.unwrap_or(DEFAULT_MAX_BACKGROUND_TERMINAL_TIMEOUT_MS)
@@ -2623,6 +2718,7 @@ impl Config {
mcp_oauth_callback_port: cfg.mcp_oauth_callback_port,
mcp_oauth_callback_url: cfg.mcp_oauth_callback_url.clone(),
model_providers,
custom_models,
project_doc_max_bytes: cfg.project_doc_max_bytes.unwrap_or(PROJECT_DOC_MAX_BYTES),
project_doc_fallback_filenames: cfg
.project_doc_fallback_filenames
@@ -2643,6 +2739,8 @@ impl Config {
agent_roles,
memories: cfg.memories.unwrap_or_default().into(),
agent_job_max_runtime_seconds,
agent_use_function_call_inbox,
watchdog_interval_s,
codex_home,
sqlite_home,
log_dir,
+11 -88
View File
@@ -1,102 +1,25 @@
use crate::config::ConfigToml;
use codex_config::types::RawMcpServerConfig;
use codex_features::FEATURES;
use codex_features::legacy_feature_keys;
pub use codex_config_schema::config_schema;
pub use codex_config_schema::config_schema_json;
use codex_config_schema::mcp_servers_schema as config_schema_mcp_servers_schema;
pub use codex_config_schema::write_config_schema;
use schemars::r#gen::SchemaGenerator;
use schemars::r#gen::SchemaSettings;
use schemars::schema::InstanceType;
use schemars::schema::ObjectValidation;
use schemars::schema::RootSchema;
use schemars::schema::Schema;
use schemars::schema::SchemaObject;
use serde_json::Map;
#[cfg(test)]
use serde_json::Value;
use std::path::Path;
/// Schema for the `[features]` map with known + legacy keys only.
pub(crate) fn features_schema(schema_gen: &mut SchemaGenerator) -> Schema {
let mut object = SchemaObject {
instance_type: Some(InstanceType::Object.into()),
..Default::default()
};
let mut validation = ObjectValidation::default();
for feature in FEATURES {
if feature.id == codex_features::Feature::Artifact {
continue;
}
validation
.properties
.insert(feature.key.to_string(), schema_gen.subschema_for::<bool>());
}
for legacy_key in legacy_feature_keys() {
validation
.properties
.insert(legacy_key.to_string(), schema_gen.subschema_for::<bool>());
}
validation.additional_properties = Some(Box::new(Schema::Bool(false)));
object.object = Some(Box::new(validation));
Schema::Object(object)
pub(crate) fn features_schema(schema_gen: &mut SchemaGenerator) -> schemars::schema::Schema {
codex_config_schema::features_schema(schema_gen)
}
/// Schema for the `[mcp_servers]` map using the raw input shape.
pub(crate) fn mcp_servers_schema(schema_gen: &mut SchemaGenerator) -> Schema {
let mut object = SchemaObject {
instance_type: Some(InstanceType::Object.into()),
..Default::default()
};
let validation = ObjectValidation {
additional_properties: Some(Box::new(schema_gen.subschema_for::<RawMcpServerConfig>())),
..Default::default()
};
object.object = Some(Box::new(validation));
Schema::Object(object)
}
/// Build the config schema for `config.toml`.
pub fn config_schema() -> RootSchema {
SchemaSettings::draft07()
.with(|settings| {
settings.option_add_null_type = false;
})
.into_generator()
.into_root_schema_for::<ConfigToml>()
pub(crate) fn mcp_servers_schema(schema_gen: &mut SchemaGenerator) -> schemars::schema::Schema {
config_schema_mcp_servers_schema(schema_gen)
}
/// Canonicalize a JSON value by sorting its keys.
#[cfg(test)]
fn canonicalize(value: &Value) -> Value {
match value {
Value::Array(items) => Value::Array(items.iter().map(canonicalize).collect()),
Value::Object(map) => {
let mut entries: Vec<_> = map.iter().collect();
entries.sort_by(|(left, _), (right, _)| left.cmp(right));
let mut sorted = Map::with_capacity(map.len());
for (key, child) in entries {
sorted.insert(key.clone(), canonicalize(child));
}
Value::Object(sorted)
}
_ => value.clone(),
}
}
/// Render the config schema as pretty-printed JSON.
pub fn config_schema_json() -> anyhow::Result<Vec<u8>> {
let schema = config_schema();
let value = serde_json::to_value(schema)?;
let value = canonicalize(&value);
let json = serde_json::to_vec_pretty(&value)?;
Ok(json)
}
/// Write the config schema fixture to disk.
pub fn write_config_schema(out_path: &Path) -> anyhow::Result<()> {
let json = config_schema_json()?;
std::fs::write(out_path, json)?;
Ok(())
codex_config_schema::canonicalize(value)
}
#[cfg(test)]
+3
View File
@@ -148,6 +148,7 @@ pub use rollout::append_thread_name;
pub use rollout::find_archived_thread_path_by_id_str;
#[deprecated(note = "use find_thread_path_by_id_str")]
pub use rollout::find_conversation_path_by_id_str;
pub use rollout::find_or_unarchive_thread_path_by_id_str;
pub use rollout::find_thread_name_by_id;
pub use rollout::find_thread_path_by_id_str;
pub use rollout::find_thread_path_by_name_str;
@@ -159,8 +160,10 @@ pub use rollout::list::parse_cursor;
pub use rollout::list::read_head_for_summary;
pub use rollout::list::read_session_meta_line;
pub use rollout::policy::EventPersistenceMode;
pub use rollout::resolve_fork_reference_rollout_path;
pub use rollout::rollout_date_parts;
pub use rollout::session_index::find_thread_names_by_ids;
pub use thread_rollout_truncation::materialize_rollout_items_for_replay;
mod function_tool;
mod state;
mod tasks;
+97 -3
View File
@@ -4,6 +4,7 @@ use crate::api_bridge::map_api_error;
use crate::auth_env_telemetry::AuthEnvTelemetry;
use crate::auth_env_telemetry::collect_auth_env_telemetry;
use crate::config::Config;
use crate::config::CustomModelConfig;
use crate::error::CodexErr;
use crate::error::Result as CoreResult;
use crate::model_provider_info::ModelProviderInfo;
@@ -29,6 +30,8 @@ use codex_protocol::openai_models::ModelInfo;
use codex_protocol::openai_models::ModelPreset;
use codex_protocol::openai_models::ModelsResponse;
use http::HeaderMap;
use std::collections::HashMap;
use std::collections::HashSet;
use std::fmt;
use std::path::PathBuf;
use std::sync::Arc;
@@ -176,6 +179,7 @@ enum CatalogMode {
#[derive(Debug)]
pub struct ModelsManager {
remote_models: RwLock<Vec<ModelInfo>>,
custom_models: HashMap<String, CustomModelConfig>,
catalog_mode: CatalogMode,
collaboration_modes_config: CollaborationModesConfig,
auth_manager: Arc<AuthManager>,
@@ -194,12 +198,14 @@ impl ModelsManager {
codex_home: PathBuf,
auth_manager: Arc<AuthManager>,
model_catalog: Option<ModelsResponse>,
custom_models: HashMap<String, CustomModelConfig>,
collaboration_modes_config: CollaborationModesConfig,
) -> Self {
Self::new_with_provider(
codex_home,
auth_manager,
model_catalog,
custom_models,
collaboration_modes_config,
ModelProviderInfo::create_openai_provider(/*base_url*/ None),
)
@@ -210,6 +216,7 @@ impl ModelsManager {
codex_home: PathBuf,
auth_manager: Arc<AuthManager>,
model_catalog: Option<ModelsResponse>,
custom_models: HashMap<String, CustomModelConfig>,
collaboration_modes_config: CollaborationModesConfig,
provider: ModelProviderInfo,
) -> Self {
@@ -229,6 +236,7 @@ impl ModelsManager {
});
Self {
remote_models: RwLock::new(remote_models),
custom_models,
catalog_mode,
collaboration_modes_config,
auth_manager,
@@ -315,7 +323,7 @@ impl ModelsManager {
#[instrument(level = "info", skip(self, config), fields(model = model))]
pub async fn get_model_info(&self, model: &str, config: &Config) -> ModelInfo {
let remote_models = self.get_remote_models().await;
Self::construct_model_info_from_candidates(model, &remote_models, config)
self.construct_model_info_from_candidates(model, &remote_models, config)
}
fn find_model_by_longest_prefix(model: &str, candidates: &[ModelInfo]) -> Option<ModelInfo> {
@@ -355,10 +363,41 @@ impl ModelsManager {
}
fn construct_model_info_from_candidates(
&self,
model: &str,
candidates: &[ModelInfo],
config: &Config,
) -> ModelInfo {
let custom_model = config
.custom_model_alias(model)
.or_else(|| self.custom_models.get(model));
Self::construct_model_info_from_candidates_with_custom(
model,
candidates,
config,
custom_model,
)
}
fn construct_model_info_from_candidates_with_custom(
model: &str,
candidates: &[ModelInfo],
config: &Config,
custom_model: Option<&CustomModelConfig>,
) -> ModelInfo {
if let Some(custom_model) = custom_model {
let mut config = config.clone();
config.model_context_window = custom_model
.model_context_window
.or(config.model_context_window);
config.model_auto_compact_token_limit = custom_model
.model_auto_compact_token_limit
.or(config.model_auto_compact_token_limit);
let model_info =
Self::construct_model_info_for_custom_alias(model, custom_model, candidates);
return model_info::with_config_overrides(model_info, &config);
}
// First use the normal longest-prefix match. If that misses, allow a narrowly scoped
// retry for namespaced slugs like `custom/gpt-5.3-codex`.
let remote = Self::find_model_by_longest_prefix(model, candidates)
@@ -375,6 +414,30 @@ impl ModelsManager {
model_info::with_config_overrides(model_info, config)
}
fn construct_model_info_for_custom_alias(
alias: &str,
custom_model: &CustomModelConfig,
candidates: &[ModelInfo],
) -> ModelInfo {
let remote = Self::find_model_by_longest_prefix(&custom_model.model, candidates)
.or_else(|| Self::find_model_by_namespaced_suffix(&custom_model.model, candidates));
if let Some(remote) = remote {
ModelInfo {
slug: alias.to_string(),
request_model: Some(custom_model.model.clone()),
display_name: alias.to_string(),
used_fallback_model_metadata: false,
..remote
}
} else {
let mut fallback_model = model_info::model_info_from_slug(&custom_model.model);
fallback_model.slug = alias.to_string();
fallback_model.request_model = Some(custom_model.model.clone());
fallback_model.display_name = alias.to_string();
fallback_model
}
}
/// Refresh models if the provided ETag differs from the cached ETag.
///
/// Uses `Online` strategy to fetch latest models when ETags differ.
@@ -524,12 +587,37 @@ impl ModelsManager {
fn build_available_models(&self, mut remote_models: Vec<ModelInfo>) -> Vec<ModelPreset> {
remote_models.sort_by(|a, b| a.priority.cmp(&b.priority));
let mut presets: Vec<ModelPreset> = remote_models.into_iter().map(Into::into).collect();
let mut presets: Vec<ModelPreset> = remote_models.iter().cloned().map(Into::into).collect();
let mut existing_models: HashSet<String> =
presets.iter().map(|preset| preset.model.clone()).collect();
let mut custom_presets = Vec::new();
let mut custom_models = self.custom_models.iter().collect::<Vec<_>>();
custom_models.sort_by(|(left, _), (right, _)| left.cmp(right));
for (alias, custom) in custom_models {
if existing_models.contains(alias) {
continue;
}
let model_info =
Self::construct_model_info_for_custom_alias(alias, custom, &remote_models);
let mut preset = ModelPreset::from(model_info);
preset.show_in_picker = true;
custom_presets.push(preset);
existing_models.insert(alias.to_string());
}
let chatgpt_mode = matches!(self.auth_manager.auth_mode(), Some(AuthMode::Chatgpt));
presets = ModelPreset::filter_by_auth(presets, chatgpt_mode);
custom_presets = ModelPreset::filter_by_auth(custom_presets, chatgpt_mode);
ModelPreset::mark_default_by_picker_visibility(&mut presets);
if !presets.iter().any(|preset| preset.is_default) {
ModelPreset::mark_default_by_picker_visibility(&mut custom_presets);
}
custom_presets.extend(presets);
presets = custom_presets;
presets
}
@@ -551,6 +639,7 @@ impl ModelsManager {
codex_home,
auth_manager,
/*model_catalog*/ None,
HashMap::new(),
CollaborationModesConfig::default(),
provider,
)
@@ -582,7 +671,12 @@ impl ModelsManager {
} else {
&[]
};
Self::construct_model_info_from_candidates(model, candidates, config)
Self::construct_model_info_from_candidates_with_custom(
model,
candidates,
config,
config.custom_model_alias(model),
)
}
}
@@ -238,6 +238,7 @@ async fn get_model_info_tracks_fallback_usage() {
codex_home.path().to_path_buf(),
auth_manager,
/*model_catalog*/ None,
HashMap::new(),
CollaborationModesConfig::default(),
);
let known_slug = manager
@@ -277,6 +278,7 @@ async fn get_model_info_uses_custom_catalog() {
Some(ModelsResponse {
models: vec![overlay],
}),
HashMap::new(),
CollaborationModesConfig::default(),
);
@@ -309,6 +311,7 @@ async fn get_model_info_matches_namespaced_suffix() {
Some(ModelsResponse {
models: vec![remote],
}),
HashMap::new(),
CollaborationModesConfig::default(),
);
let namespaced_model = "custom/gpt-image".to_string();
@@ -333,6 +336,7 @@ async fn get_model_info_rejects_multi_segment_namespace_suffix_matching() {
codex_home.path().to_path_buf(),
auth_manager,
/*model_catalog*/ None,
HashMap::new(),
CollaborationModesConfig::default(),
);
let known_slug = manager
@@ -853,6 +857,202 @@ fn build_available_models_picks_default_after_hiding_hidden_models() {
assert_eq!(available, vec![expected_hidden, expected_visible]);
}
#[tokio::test]
async fn get_model_info_uses_custom_alias_metadata_and_request_model() {
let codex_home = tempdir().expect("temp dir");
let mut config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.build()
.await
.expect("load default test config");
let alias = "gpt-5.4 1m".to_string();
let custom_model = CustomModelConfig {
model: "gpt-5.4".to_string(),
model_context_window: Some(1_000_000),
model_auto_compact_token_limit: Some(800_000),
};
config
.custom_models
.insert(alias.clone(), custom_model.clone());
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("Test API Key"));
let manager = ModelsManager::new(
codex_home.path().to_path_buf(),
auth_manager,
Some(ModelsResponse {
models: vec![remote_model("gpt-5.4", "GPT 5.4", /*priority*/ 0)],
}),
HashMap::from([(alias.clone(), custom_model)]),
CollaborationModesConfig::default(),
);
let model_info = manager.get_model_info(&alias, &config).await;
assert_eq!(model_info.slug, alias);
assert_eq!(model_info.request_model.as_deref(), Some("gpt-5.4"));
assert_eq!(model_info.context_window, Some(1_000_000));
assert_eq!(model_info.auto_compact_token_limit, Some(800_000));
}
#[tokio::test]
async fn get_model_info_prefers_custom_alias_context_over_global_config() {
let codex_home = tempdir().expect("temp dir");
let mut config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.build()
.await
.expect("load default test config");
config.model_context_window = Some(250_000);
config.model_auto_compact_token_limit = Some(200_000);
let alias = "gpt-5.4 1m".to_string();
let custom_model = CustomModelConfig {
model: "gpt-5.4".to_string(),
model_context_window: Some(1_000_000),
model_auto_compact_token_limit: Some(800_000),
};
config
.custom_models
.insert(alias.clone(), custom_model.clone());
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("Test API Key"));
let manager = ModelsManager::new(
codex_home.path().to_path_buf(),
auth_manager,
Some(ModelsResponse {
models: vec![remote_model("gpt-5.4", "GPT 5.4", /*priority*/ 0)],
}),
HashMap::from([(alias.clone(), custom_model)]),
CollaborationModesConfig::default(),
);
let model_info = manager.get_model_info(&alias, &config).await;
assert_eq!(model_info.context_window, Some(1_000_000));
assert_eq!(model_info.auto_compact_token_limit, Some(800_000));
}
#[tokio::test]
async fn get_model_info_prefers_active_config_alias_over_startup_snapshot() {
let codex_home = tempdir().expect("temp dir");
let mut config = ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.build()
.await
.expect("load default test config");
let alias = "gpt-5.4 1m".to_string();
config.custom_models.insert(
alias.clone(),
CustomModelConfig {
model: "gpt-5.4-updated".to_string(),
model_context_window: Some(1_000_000),
model_auto_compact_token_limit: Some(900_000),
},
);
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("Test API Key"));
let manager = ModelsManager::new(
codex_home.path().to_path_buf(),
auth_manager,
Some(ModelsResponse {
models: vec![
remote_model("gpt-5.4", "GPT 5.4", /*priority*/ 0),
remote_model("gpt-5.4-updated", "GPT 5.4 Updated", /*priority*/ 1),
],
}),
HashMap::from([(
alias.clone(),
CustomModelConfig {
model: "gpt-5.4".to_string(),
model_context_window: Some(500_000),
model_auto_compact_token_limit: Some(400_000),
},
)]),
CollaborationModesConfig::default(),
);
let model_info = manager.get_model_info(&alias, &config).await;
assert_eq!(model_info.slug, alias);
assert_eq!(model_info.request_model.as_deref(), Some("gpt-5.4-updated"));
assert_eq!(model_info.context_window, Some(1_000_000));
assert_eq!(model_info.auto_compact_token_limit, Some(900_000));
}
#[test]
fn build_available_models_includes_custom_aliases() {
let codex_home = tempdir().expect("temp dir");
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("Test API Key"));
let provider = provider_for("http://example.test".to_string());
let mut manager = ModelsManager::with_provider_for_tests(
codex_home.path().to_path_buf(),
auth_manager,
provider,
);
manager.custom_models = HashMap::from([(
"gpt-5.4 1m".to_string(),
CustomModelConfig {
model: "gpt-5.4".to_string(),
model_context_window: Some(1_000_000),
model_auto_compact_token_limit: Some(800_000),
},
)]);
let available = manager.build_available_models(vec![remote_model(
"gpt-5.4", "GPT 5.4", /*priority*/ 0,
)]);
let alias = available
.iter()
.find(|preset| preset.model == "gpt-5.4 1m")
.expect("custom alias should be listed");
assert!(alias.show_in_picker);
assert_eq!(alias.display_name, "gpt-5.4 1m");
}
#[test]
fn build_available_models_lists_custom_aliases_before_remote_models() {
let codex_home = tempdir().expect("temp dir");
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("Test API Key"));
let provider = provider_for("http://example.test".to_string());
let mut manager = ModelsManager::with_provider_for_tests(
codex_home.path().to_path_buf(),
auth_manager,
provider,
);
manager.custom_models = HashMap::from([(
"gpt-5.4 1m".to_string(),
CustomModelConfig {
model: "gpt-5.4".to_string(),
model_context_window: Some(1_000_000),
model_auto_compact_token_limit: Some(800_000),
},
)]);
let available = manager.build_available_models(vec![
remote_model("gpt-5.4", "GPT 5.4", /*priority*/ 0),
remote_model("gpt-5.3", "GPT 5.3", /*priority*/ 1),
]);
assert_eq!(
available
.iter()
.map(|preset| preset.model.as_str())
.collect::<Vec<_>>(),
vec!["gpt-5.4 1m", "gpt-5.4", "gpt-5.3"]
);
assert_eq!(
available
.iter()
.find(|preset| preset.is_default)
.map(|preset| preset.model.as_str()),
Some("gpt-5.4")
);
}
#[test]
fn bundled_models_json_roundtrips() {
let file_contents = include_str!("../../models.json");
@@ -62,6 +62,7 @@ pub(crate) fn model_info_from_slug(slug: &str) -> ModelInfo {
warn!("Unknown model {slug} is used. This will use fallback model metadata.");
ModelInfo {
slug: slug.to_string(),
request_model: None,
display_name: slug.to_string(),
description: None,
default_reasoning_level: None,
+2
View File
@@ -9,9 +9,11 @@ pub use codex_rollout::append_thread_name;
pub use codex_rollout::find_archived_thread_path_by_id_str;
#[deprecated(note = "use find_thread_path_by_id_str")]
pub use codex_rollout::find_conversation_path_by_id_str;
pub use codex_rollout::find_or_unarchive_thread_path_by_id_str;
pub use codex_rollout::find_thread_name_by_id;
pub use codex_rollout::find_thread_path_by_id_str;
pub use codex_rollout::find_thread_path_by_name_str;
pub use codex_rollout::resolve_fork_reference_rollout_path;
pub use codex_rollout::rollout_date_parts;
impl codex_rollout::RolloutConfigView for Config {
+11
View File
@@ -428,6 +428,17 @@ pub(crate) fn last_assistant_message_from_item(
pub(crate) fn response_input_to_response_item(input: &ResponseInputItem) -> Option<ResponseItem> {
match input {
ResponseInputItem::FunctionCall {
name,
arguments,
call_id,
} => Some(ResponseItem::FunctionCall {
id: None,
name: name.clone(),
namespace: None,
arguments: arguments.clone(),
call_id: call_id.clone(),
}),
ResponseInputItem::FunctionCallOutput { call_id, output } => {
Some(ResponseItem::FunctionCallOutput {
call_id: call_id.clone(),
+5
View File
@@ -44,6 +44,11 @@ impl SessionTask for CompactTask {
);
crate::compact::run_compact_task(session.clone(), ctx, input).await
};
session
.services
.agent_control
.finish_watchdog_parent_compaction(session.conversation_id)
.await;
None
}
}
+1
View File
@@ -330,6 +330,7 @@ impl Session {
turn_context
.turn_metadata_state
.cancel_git_enrichment_task();
self.snapshot_agent_send_input_on_turn_complete();
let mut pending_input = Vec::<ResponseInputItem>::new();
let mut should_clear_active_turn = false;
+207 -13
View File
@@ -8,6 +8,7 @@ use crate::codex::CodexSpawnOk;
use crate::codex::INITIAL_SUBMIT_ID;
use crate::codex_thread::CodexThread;
use crate::config::Config;
use crate::config::CustomModelConfig;
use crate::error::CodexErr;
use crate::error::Result as CodexResult;
use crate::file_watcher::FileWatcher;
@@ -31,8 +32,10 @@ use codex_protocol::config_types::CollaborationModeMask;
#[cfg(test)]
use codex_protocol::models::ResponseItem;
use codex_protocol::openai_models::ModelPreset;
use codex_protocol::openai_models::ModelsResponse;
use codex_protocol::protocol::Event;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::ForkReferenceItem;
use codex_protocol::protocol::InitialHistory;
use codex_protocol::protocol::McpServerRefreshConfig;
use codex_protocol::protocol::Op;
@@ -45,6 +48,7 @@ use codex_protocol::protocol::W3cTraceContext;
use futures::StreamExt;
use futures::stream::FuturesUnordered;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
@@ -216,6 +220,8 @@ impl ThreadManager {
config: &Config,
auth_manager: Arc<AuthManager>,
session_source: SessionSource,
model_catalog: Option<ModelsResponse>,
custom_models: HashMap<String, CustomModelConfig>,
collaboration_modes_config: CollaborationModesConfig,
environment_manager: Arc<EnvironmentManager>,
) -> Self {
@@ -245,7 +251,8 @@ impl ThreadManager {
models_manager: Arc::new(ModelsManager::new_with_provider(
codex_home,
auth_manager.clone(),
config.model_catalog.clone(),
model_catalog,
custom_models,
collaboration_modes_config,
openai_models_provider,
)),
@@ -607,18 +614,22 @@ impl ThreadManager {
S: Into<ForkSnapshot>,
{
let snapshot = snapshot.into();
let history = RolloutRecorder::get_rollout_history(&path).await?;
// True forks must discard the source rollout's conversation id so the child gets a
// distinct thread id and preserves `forked_from_id` in its SessionMeta. Using the
// resume loader here silently turns a fork into an in-place resume.
let history = RolloutRecorder::get_fork_history(&path).await?;
let snapshot_state = snapshot_turn_state(&history);
let history = match snapshot {
let mut history = match snapshot {
ForkSnapshot::TruncateBeforeNthUserMessage(nth_user_message) => {
truncate_before_nth_user_message(history, nth_user_message, &snapshot_state)
truncate_before_nth_user_message(
config.codex_home.as_path(),
history,
i64::try_from(nth_user_message).unwrap_or(i64::MAX),
&snapshot_state,
)
.await
}
ForkSnapshot::Interrupted => {
let history = match history {
InitialHistory::New => InitialHistory::New,
InitialHistory::Forked(history) => InitialHistory::Forked(history),
InitialHistory::Resumed(resumed) => InitialHistory::Forked(resumed.history),
};
if snapshot_state.ends_mid_turn {
append_interrupted_boundary(history, snapshot_state.active_turn_id)
} else {
@@ -626,6 +637,33 @@ impl ThreadManager {
}
}
};
if let (
ForkSnapshot::TruncateBeforeNthUserMessage(nth_user_message),
InitialHistory::Forked(items),
) = (snapshot, &mut history)
{
let source_session_meta = items.iter().find_map(|item| match item {
RolloutItem::SessionMeta(meta_line) => Some(meta_line.clone()),
RolloutItem::ForkReference(_)
| RolloutItem::ResponseItem(_)
| RolloutItem::Compacted(_)
| RolloutItem::TurnContext(_)
| RolloutItem::EventMsg(_) => None,
});
// Keep the source SessionMeta in-memory so startup can derive `forked_from_id`
// for SessionConfigured while still persisting only the compact ForkReference
// suffix to the child rollout on disk.
*items = source_session_meta
.into_iter()
.map(RolloutItem::SessionMeta)
.chain(std::iter::once(RolloutItem::ForkReference(
ForkReferenceItem {
rollout_path: path.clone(),
nth_user_message: i64::try_from(nth_user_message).unwrap_or(i64::MAX),
},
)))
.collect();
}
Box::pin(self.state.spawn_thread(
config,
history,
@@ -918,14 +956,23 @@ impl ThreadManagerState {
/// when the source thread is currently mid-turn they fall back to cutting
/// before the active turn's opening boundary so the fork omits the unfinished
/// suffix entirely.
fn truncate_before_nth_user_message(
async fn truncate_before_nth_user_message(
codex_home: &Path,
history: InitialHistory,
n: usize,
n: i64,
snapshot_state: &SnapshotTurnState,
) -> InitialHistory {
let items: Vec<RolloutItem> = history.get_rollout_items();
let mut items: Vec<RolloutItem> = history.get_rollout_items();
if items
.iter()
.any(|item| matches!(item, RolloutItem::ForkReference(_)))
{
items = truncation::materialize_rollout_items_for_replay(codex_home, &items).await;
}
let user_positions = truncation::user_message_positions_in_rollout(&items);
let rolled = if snapshot_state.ends_mid_turn && n >= user_positions.len() {
let rolled = if snapshot_state.ends_mid_turn
&& usize::try_from(n).map_or(true, |n| n >= user_positions.len())
{
if let Some(cut_idx) = snapshot_state
.active_turn_start_index
.or_else(|| user_positions.last().copied())
@@ -1037,3 +1084,150 @@ fn append_interrupted_boundary(history: InitialHistory, turn_id: Option<String>)
#[cfg(test)]
#[path = "thread_manager_tests.rs"]
mod tests;
// Keep this inline fork-reference test module disabled on the refreshed main API;
// branch coverage now comes from the package/integration tests that match current types.
#[cfg(any())]
mod fork_reference_tests {
use super::*;
use crate::codex::make_session_and_context;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ReasoningItemReasoningSummary;
use codex_protocol::models::ResponseItem;
use pretty_assertions::assert_eq;
fn user_msg(text: &str) -> ResponseItem {
ResponseItem::Message {
id: None,
role: "user".to_string(),
content: vec![ContentItem::OutputText {
text: text.to_string(),
}],
end_turn: None,
phase: None,
}
}
fn assistant_msg(text: &str) -> ResponseItem {
ResponseItem::Message {
id: None,
role: "assistant".to_string(),
content: vec![ContentItem::OutputText {
text: text.to_string(),
}],
end_turn: None,
phase: None,
}
}
#[tokio::test]
async fn drops_from_last_user_only() {
let items = [
user_msg("u1"),
assistant_msg("a1"),
assistant_msg("a2"),
user_msg("u2"),
assistant_msg("a3"),
ResponseItem::Reasoning {
id: "r1".to_string(),
summary: vec![ReasoningItemReasoningSummary::SummaryText {
text: "s".to_string(),
}],
content: None,
encrypted_content: None,
},
ResponseItem::FunctionCall {
id: None,
call_id: "c1".to_string(),
name: "tool".to_string(),
namespace: None,
arguments: "{}".to_string(),
},
assistant_msg("a4"),
];
let initial: Vec<RolloutItem> = items
.iter()
.cloned()
.map(RolloutItem::ResponseItem)
.collect();
let truncated = truncate_before_nth_user_message(
Path::new("/tmp"),
InitialHistory::Forked(initial),
1,
&SnapshotTurnState {
ends_mid_turn: false,
active_turn_id: None,
active_turn_start_index: None,
},
)
.await;
let got_items = truncated.get_rollout_items();
let expected_items = vec![
RolloutItem::ResponseItem(items[0].clone()),
RolloutItem::ResponseItem(items[1].clone()),
RolloutItem::ResponseItem(items[2].clone()),
];
assert_eq!(
serde_json::to_value(&got_items).unwrap(),
serde_json::to_value(&expected_items).unwrap()
);
let initial2: Vec<RolloutItem> = items
.iter()
.cloned()
.map(RolloutItem::ResponseItem)
.collect();
let truncated2 = truncate_before_nth_user_message(
Path::new("/tmp"),
InitialHistory::Forked(initial2),
2,
&SnapshotTurnState {
ends_mid_turn: false,
active_turn_id: None,
active_turn_start_index: None,
},
)
.await;
assert!(matches!(truncated2, InitialHistory::New));
}
#[tokio::test]
async fn ignores_session_prefix_messages_when_truncating() {
let (session, turn_context) = make_session_and_context().await;
let mut items = session.build_initial_context(&turn_context).await;
items.push(user_msg("feature request"));
items.push(assistant_msg("ack"));
items.push(user_msg("second question"));
items.push(assistant_msg("answer"));
let rollout_items: Vec<RolloutItem> = items
.iter()
.cloned()
.map(RolloutItem::ResponseItem)
.collect();
let truncated = truncate_before_nth_user_message(
Path::new("/tmp"),
InitialHistory::Forked(rollout_items),
1,
&SnapshotTurnState {
ends_mid_turn: false,
active_turn_id: None,
active_turn_start_index: None,
},
)
.await;
let got_items = truncated.get_rollout_items();
let expected: Vec<RolloutItem> = vec![
RolloutItem::ResponseItem(items[0].clone()),
RolloutItem::ResponseItem(items[1].clone()),
RolloutItem::ResponseItem(items[2].clone()),
RolloutItem::ResponseItem(items[3].clone()),
];
assert_eq!(
serde_json::to_value(&got_items).unwrap(),
serde_json::to_value(&expected).unwrap()
);
}
}
+33 -14
View File
@@ -3,7 +3,6 @@ use crate::codex::make_session_and_context;
use crate::config::test_config;
use crate::models_manager::collaboration_mode_presets::CollaborationModesConfig;
use crate::models_manager::manager::RefreshStrategy;
use crate::rollout::RolloutRecorder;
use crate::tasks::interrupted_turn_history_marker;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ReasoningItemReasoningSummary;
@@ -15,6 +14,8 @@ use codex_protocol::protocol::UserMessageEvent;
use core_test_support::PathExt;
use core_test_support::responses::mount_models_once;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
use std::path::Path;
use std::time::Duration;
use tempfile::tempdir;
use wiremock::MockServer;
@@ -42,8 +43,8 @@ fn assistant_msg(text: &str) -> ResponseItem {
}
}
#[test]
fn truncates_before_requested_user_message() {
#[tokio::test]
async fn truncates_before_requested_user_message() {
let items = [
user_msg("u1"),
assistant_msg("a1"),
@@ -74,6 +75,7 @@ fn truncates_before_requested_user_message() {
.map(RolloutItem::ResponseItem)
.collect();
let truncated = truncate_before_nth_user_message(
Path::new("/tmp"),
InitialHistory::Forked(initial),
/*n*/ 1,
&SnapshotTurnState {
@@ -81,7 +83,8 @@ fn truncates_before_requested_user_message() {
active_turn_id: None,
active_turn_start_index: None,
},
);
)
.await;
let got_items = truncated.get_rollout_items();
let expected_items = vec![
RolloutItem::ResponseItem(items[0].clone()),
@@ -99,6 +102,7 @@ fn truncates_before_requested_user_message() {
.map(RolloutItem::ResponseItem)
.collect();
let truncated2 = truncate_before_nth_user_message(
Path::new("/tmp"),
InitialHistory::Forked(initial2.clone()),
/*n*/ 2,
&SnapshotTurnState {
@@ -106,15 +110,16 @@ fn truncates_before_requested_user_message() {
active_turn_id: None,
active_turn_start_index: None,
},
);
)
.await;
assert_eq!(
serde_json::to_value(truncated2.get_rollout_items()).unwrap(),
serde_json::to_value(initial2).unwrap()
);
}
#[test]
fn out_of_range_truncation_drops_only_unfinished_suffix_mid_turn() {
#[tokio::test]
async fn out_of_range_truncation_drops_only_unfinished_suffix_mid_turn() {
let items = vec![
RolloutItem::ResponseItem(user_msg("u1")),
RolloutItem::ResponseItem(assistant_msg("a1")),
@@ -123,14 +128,16 @@ fn out_of_range_truncation_drops_only_unfinished_suffix_mid_turn() {
];
let truncated = truncate_before_nth_user_message(
Path::new("/tmp"),
InitialHistory::Forked(items.clone()),
usize::MAX,
/*n*/ -1,
&SnapshotTurnState {
ends_mid_turn: true,
active_turn_id: None,
active_turn_start_index: None,
},
);
)
.await;
assert_eq!(
serde_json::to_value(truncated.get_rollout_items()).unwrap(),
@@ -157,8 +164,8 @@ fn fork_thread_accepts_legacy_usize_snapshot_argument() {
let _: fn(&ThreadManager, Config, std::path::PathBuf) = assert_legacy_snapshot_callsite;
}
#[test]
fn out_of_range_truncation_drops_pre_user_active_turn_prefix() {
#[tokio::test]
async fn out_of_range_truncation_drops_pre_user_active_turn_prefix() {
let items = vec![
RolloutItem::ResponseItem(user_msg("u1")),
RolloutItem::ResponseItem(assistant_msg("a1")),
@@ -182,10 +189,12 @@ fn out_of_range_truncation_drops_pre_user_active_turn_prefix() {
);
let truncated = truncate_before_nth_user_message(
Path::new("/tmp"),
InitialHistory::Forked(items.clone()),
usize::MAX,
/*n*/ -1,
&snapshot_state,
);
)
.await;
assert_eq!(
serde_json::to_value(truncated.get_rollout_items()).unwrap(),
@@ -209,6 +218,7 @@ async fn ignores_session_prefix_messages_when_truncating() {
.collect();
let truncated = truncate_before_nth_user_message(
Path::new("/tmp"),
InitialHistory::Forked(rollout_items),
/*n*/ 1,
&SnapshotTurnState {
@@ -216,7 +226,8 @@ async fn ignores_session_prefix_messages_when_truncating() {
active_turn_id: None,
active_turn_start_index: None,
},
);
)
.await;
let got_items = truncated.get_rollout_items();
let expected: Vec<RolloutItem> = vec![
@@ -294,6 +305,8 @@ async fn new_uses_configured_openai_provider_for_model_refresh() {
&config,
auth_manager,
SessionSource::Exec,
/*model_catalog*/ None,
HashMap::new(),
CollaborationModesConfig::default(),
Arc::new(codex_exec_server::EnvironmentManager::new(
/*exec_server_url*/ None,
@@ -424,6 +437,8 @@ async fn interrupted_fork_snapshot_does_not_synthesize_turn_id_for_legacy_histor
&config,
auth_manager.clone(),
SessionSource::Exec,
config.model_catalog.clone(),
config.custom_models.clone(),
CollaborationModesConfig::default(),
Arc::new(codex_exec_server::EnvironmentManager::new(
/*exec_server_url*/ None,
@@ -524,6 +539,8 @@ async fn interrupted_fork_snapshot_preserves_explicit_turn_id() {
&config,
auth_manager.clone(),
SessionSource::Exec,
config.model_catalog.clone(),
config.custom_models.clone(),
CollaborationModesConfig::default(),
Arc::new(codex_exec_server::EnvironmentManager::new(
/*exec_server_url*/ None,
@@ -613,6 +630,8 @@ async fn interrupted_fork_snapshot_uses_persisted_mid_turn_history_without_live_
&config,
auth_manager.clone(),
SessionSource::Exec,
config.model_catalog.clone(),
config.custom_models.clone(),
CollaborationModesConfig::default(),
Arc::new(codex_exec_server::EnvironmentManager::new(
/*exec_server_url*/ None,
+96 -4
View File
@@ -5,11 +5,17 @@
use crate::context_manager::is_user_turn_boundary;
use crate::event_mapping;
use crate::resolve_fork_reference_rollout_path;
use crate::rollout::RolloutRecorder;
use codex_protocol::items::TurnItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::InterAgentCommunication;
use codex_protocol::protocol::RolloutItem;
use std::path::Path;
use tracing::warn;
const MAX_FORK_REFERENCE_DEPTH: usize = 8;
/// Return the indices of user message boundaries in a rollout.
///
@@ -88,21 +94,30 @@ pub(crate) fn fork_turn_positions_in_rollout(items: &[RolloutItem]) -> Vec<usize
fork_turn_positions
}
/// Return the current fork boundary to persist in a `ForkReferenceItem`.
///
/// The boundary is the next user-message index in the current effective rollout. Persisting that
/// snapshot, instead of a "live tail" sentinel, prevents later parent turns from being pulled
/// into the child when the child rollout is replayed.
pub(crate) fn fork_reference_user_message_boundary(items: &[RolloutItem]) -> i64 {
i64::try_from(user_message_positions_in_rollout(items).len()).unwrap_or(i64::MAX)
}
/// Return a prefix of `items` obtained by cutting strictly before the nth user message.
///
/// The boundary index is 0-based from the start of `items` (so `n_from_start = 0` returns
/// a prefix that excludes the first user message and everything after it).
///
/// If `n_from_start` is `usize::MAX`, this returns the full rollout (no truncation).
/// If `n_from_start` is negative, this returns the full rollout (no truncation).
/// If fewer than or equal to `n_from_start` user messages exist, this returns the full
/// rollout unchanged.
pub(crate) fn truncate_rollout_before_nth_user_message_from_start(
items: &[RolloutItem],
n_from_start: usize,
n_from_start: i64,
) -> Vec<RolloutItem> {
if n_from_start == usize::MAX {
let Ok(n_from_start) = usize::try_from(n_from_start) else {
return items.to_vec();
}
};
let user_positions = user_message_positions_in_rollout(items);
@@ -153,6 +168,83 @@ fn is_trigger_turn_boundary(item: &ResponseItem) -> bool {
.is_some_and(|communication| communication.trigger_turn)
}
/// Expand `ForkReference` items into the referenced parent rollout slices they encode.
///
/// This preserves child rollout compactness on disk while letting replay callers rebuild the
/// effective inherited transcript before reconstructing conversation history or deriving thread
/// summaries.
pub async fn materialize_rollout_items_for_replay(
codex_home: &Path,
rollout_items: &[RolloutItem],
) -> Vec<RolloutItem> {
let mut materialized = Vec::new();
let mut stack: Vec<(Vec<RolloutItem>, usize, usize)> = vec![(rollout_items.to_vec(), 0, 0)];
while let Some((items, mut idx, depth)) = stack.pop() {
while idx < items.len() {
match &items[idx] {
RolloutItem::ForkReference(reference) => {
if depth >= MAX_FORK_REFERENCE_DEPTH {
warn!(
"skipping fork reference recursion at depth {} for {:?}",
depth, reference.rollout_path
);
materialized.push(RolloutItem::ForkReference(reference.clone()));
idx += 1;
continue;
}
let resolved_rollout_path = match resolve_fork_reference_rollout_path(
codex_home,
&reference.rollout_path,
)
.await
{
Ok(path) => path,
Err(err) => {
warn!(
"failed to resolve fork reference rollout {:?}: {err}",
reference.rollout_path
);
materialized.push(RolloutItem::ForkReference(reference.clone()));
idx += 1;
continue;
}
};
let parent_history = match RolloutRecorder::get_rollout_history(
&resolved_rollout_path,
)
.await
{
Ok(history) => history,
Err(err) => {
warn!(
"failed to load fork reference rollout {:?} (resolved from {:?}): {err}",
resolved_rollout_path, reference.rollout_path
);
materialized.push(RolloutItem::ForkReference(reference.clone()));
idx += 1;
continue;
}
};
let parent_items = truncate_rollout_before_nth_user_message_from_start(
&parent_history.get_rollout_items(),
reference.nth_user_message,
);
stack.push((items, idx + 1, depth));
stack.push((parent_items, 0, depth + 1));
break;
}
item => materialized.push(item.clone()),
}
idx += 1;
}
}
materialized
}
#[cfg(test)]
#[path = "thread_rollout_truncation_tests.rs"]
mod tests;
@@ -3,9 +3,11 @@ use crate::codex::make_session_and_context;
use codex_protocol::AgentPath;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ReasoningItemReasoningSummary;
use codex_protocol::protocol::ForkReferenceItem;
use codex_protocol::protocol::InterAgentCommunication;
use codex_protocol::protocol::ThreadRolledBackEvent;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
fn user_msg(text: &str) -> ResponseItem {
ResponseItem::Message {
@@ -102,7 +104,8 @@ fn truncation_max_keeps_full_rollout() {
RolloutItem::ResponseItem(user_msg("u2")),
];
let truncated = truncate_rollout_before_nth_user_message_from_start(&rollout, usize::MAX);
let truncated =
truncate_rollout_before_nth_user_message_from_start(&rollout, /*n_from_start*/ -1);
assert_eq!(
serde_json::to_value(&truncated).unwrap(),
@@ -316,3 +319,25 @@ fn truncates_rollout_to_last_n_fork_turns_keeps_full_rollout_when_n_is_large() {
serde_json::to_value(&rollout).unwrap()
);
}
#[tokio::test]
async fn materialize_rollout_items_for_replay_preserves_unresolved_fork_references() {
let codex_home = TempDir::new().unwrap();
let fork_reference = RolloutItem::ForkReference(ForkReferenceItem {
rollout_path: "missing-rollout.jsonl".into(),
nth_user_message: 1,
});
let rollout_items = vec![
RolloutItem::ResponseItem(user_msg("u1")),
fork_reference.clone(),
RolloutItem::ResponseItem(assistant_msg("a1")),
];
let materialized =
materialize_rollout_items_for_replay(codex_home.path(), &rollout_items).await;
assert_eq!(
serde_json::to_value(&materialized).unwrap(),
serde_json::to_value(&rollout_items).unwrap()
);
}
+10
View File
@@ -431,6 +431,16 @@ pub(crate) fn response_input_to_code_mode_result(response: ResponseInputItem) ->
raw_arguments: String::new(),
})
}
ResponseInputItem::FunctionCall {
name,
arguments,
call_id,
} => serde_json::json!({
"type": "function_call",
"name": name,
"arguments": arguments,
"call_id": call_id,
}),
}
}
@@ -24,7 +24,6 @@ use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::protocol::CollabAgentInteractionBeginEvent;
use codex_protocol::protocol::CollabAgentInteractionEndEvent;
use codex_protocol::protocol::CollabAgentRef;
use codex_protocol::protocol::CollabAgentSpawnBeginEvent;
use codex_protocol::protocol::CollabAgentSpawnEndEvent;
use codex_protocol::protocol::CollabCloseBeginEvent;
use codex_protocol::protocol::CollabCloseEndEvent;
@@ -43,32 +42,23 @@ pub(crate) fn parse_agent_id_target(target: &str) -> Result<ThreadId, FunctionCa
})
}
pub(crate) fn parse_agent_id_targets(
targets: Vec<String>,
) -> Result<Vec<ThreadId>, FunctionCallError> {
if targets.is_empty() {
return Err(FunctionCallError::RespondToModel(
"agent ids must be non-empty".to_string(),
));
}
targets
.into_iter()
.map(|target| parse_agent_id_target(&target))
.collect()
}
pub(crate) use close_agent::Handler as CloseAgentHandler;
pub(crate) use compact_parent_context::Handler as CompactParentContextHandler;
pub(crate) use list_agents::Handler as ListAgentsHandler;
pub(crate) use resume_agent::Handler as ResumeAgentHandler;
pub(crate) use send_input::Handler as SendInputHandler;
pub(crate) use spawn::Handler as SpawnAgentHandler;
pub(crate) use wait::Handler as WaitAgentHandler;
pub(crate) use watchdog_self_close::Handler as WatchdogSelfCloseHandler;
pub mod close_agent;
mod compact_parent_context;
mod list_agents;
mod resume_agent;
mod send_input;
mod spawn;
pub(crate) mod wait;
mod watchdog_self_close;
#[cfg(test)]
#[path = "multi_agents_tests.rs"]
@@ -0,0 +1,98 @@
use super::*;
use crate::agent::WatchdogParentCompactionResult;
pub(crate) struct Handler;
#[async_trait]
impl ToolHandler for Handler {
type Output = CompactParentContextResult;
fn kind(&self) -> ToolKind {
ToolKind::Function
}
fn matches_kind(&self, payload: &ToolPayload) -> bool {
matches!(payload, ToolPayload::Function { .. })
}
async fn handle(&self, invocation: ToolInvocation) -> Result<Self::Output, FunctionCallError> {
let ToolInvocation {
session, payload, ..
} = invocation;
let arguments = function_arguments(payload)?;
let _args: CompactParentContextArgs = parse_arguments(&arguments)?;
let helper_thread_id = session.conversation_id;
let result = session
.services
.agent_control
.compact_parent_for_watchdog_helper(helper_thread_id)
.await
.map_err(|err| {
FunctionCallError::RespondToModel(format!("compact_parent_context failed: {err}"))
})?;
Ok(CompactParentContextResult::from(result))
}
}
#[derive(Debug, Deserialize)]
struct CompactParentContextArgs {
#[serde(rename = "reason")]
_reason: Option<String>,
#[serde(rename = "evidence")]
_evidence: Option<String>,
}
#[derive(Debug, Serialize)]
pub(crate) struct CompactParentContextResult {
kind: &'static str,
parent_thread_id: Option<String>,
submission_id: Option<String>,
}
impl From<WatchdogParentCompactionResult> for CompactParentContextResult {
fn from(value: WatchdogParentCompactionResult) -> Self {
match value {
WatchdogParentCompactionResult::NotWatchdogHelper => Self {
kind: "not_watchdog_helper",
parent_thread_id: None,
submission_id: None,
},
WatchdogParentCompactionResult::ParentBusy { parent_thread_id } => Self {
kind: "parent_busy",
parent_thread_id: Some(parent_thread_id.to_string()),
submission_id: None,
},
WatchdogParentCompactionResult::AlreadyInProgress { parent_thread_id } => Self {
kind: "already_in_progress",
parent_thread_id: Some(parent_thread_id.to_string()),
submission_id: None,
},
WatchdogParentCompactionResult::Submitted {
parent_thread_id,
submission_id,
} => Self {
kind: "submitted",
parent_thread_id: Some(parent_thread_id.to_string()),
submission_id: Some(submission_id),
},
}
}
}
impl ToolOutput for CompactParentContextResult {
fn log_preview(&self) -> String {
tool_output_json_text(self, "compact_parent_context")
}
fn success_for_logging(&self) -> bool {
true
}
fn to_response_item(&self, call_id: &str, payload: &ToolPayload) -> ResponseInputItem {
tool_output_response_item(call_id, payload, self, Some(true), "compact_parent_context")
}
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
tool_output_code_mode_result(self, "compact_parent_context")
}
}
@@ -0,0 +1,109 @@
use super::*;
use crate::agent::AgentListing;
use crate::agent::agent_resolver::resolve_agent_target;
pub(crate) struct Handler;
#[async_trait]
impl ToolHandler for Handler {
type Output = ListAgentsResult;
fn kind(&self) -> ToolKind {
ToolKind::Function
}
fn matches_kind(&self, payload: &ToolPayload) -> bool {
matches!(payload, ToolPayload::Function { .. })
}
async fn handle(&self, invocation: ToolInvocation) -> Result<Self::Output, FunctionCallError> {
let ToolInvocation {
session,
turn,
payload,
..
} = invocation;
let arguments = function_arguments(payload)?;
let args: ListAgentsArgs = parse_arguments(&arguments)?;
let owner_thread_id = if args.all {
session.conversation_id
} else if let Some(target) = args
.id
.as_deref()
.map(str::trim)
.filter(|id| !id.is_empty())
{
resolve_agent_target(&session, &turn, target).await?
} else {
session.conversation_id
};
let agents = session
.services
.agent_control
.list_agents(owner_thread_id, args.recursive, args.all)
.await
.map_err(|err| {
FunctionCallError::RespondToModel(format!("list_agents failed: {err}"))
})?;
Ok(ListAgentsResult {
agents: agents.into_iter().map(ListedAgent::from_listing).collect(),
})
}
}
#[derive(Debug, Deserialize)]
struct ListAgentsArgs {
id: Option<String>,
#[serde(default = "default_recursive")]
recursive: bool,
#[serde(default)]
all: bool,
}
fn default_recursive() -> bool {
true
}
#[derive(Debug, Serialize)]
pub(crate) struct ListAgentsResult {
agents: Vec<ListedAgent>,
}
#[derive(Debug, Serialize)]
struct ListedAgent {
thread_id: String,
parent_thread_id: Option<String>,
status: AgentStatus,
depth: usize,
}
impl ListedAgent {
fn from_listing(value: AgentListing) -> Self {
Self {
thread_id: value.thread_id.to_string(),
parent_thread_id: value
.parent_thread_id
.map(|thread_id| thread_id.to_string()),
status: value.status,
depth: value.depth,
}
}
}
impl ToolOutput for ListAgentsResult {
fn log_preview(&self) -> String {
tool_output_json_text(self, "list_agents")
}
fn success_for_logging(&self) -> bool {
true
}
fn to_response_item(&self, call_id: &str, payload: &ToolPayload) -> ResponseInputItem {
tool_output_response_item(call_id, payload, self, Some(true), "list_agents")
}
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
tool_output_code_mode_result(self, "list_agents")
}
}
@@ -1,4 +1,5 @@
use super::*;
use crate::agent::agent_resolver::resolve_agent_target;
use crate::agent::control::render_input_preview;
pub(crate) struct Handler;
@@ -25,8 +26,8 @@ impl ToolHandler for Handler {
} = invocation;
let arguments = function_arguments(payload)?;
let args: SendInputArgs = parse_arguments(&arguments)?;
let receiver_thread_id = parse_agent_id_target(&args.target)?;
let input_items = parse_collab_input(args.message, args.items)?;
let receiver_thread_id = resolve_agent_target(&session, &turn, &args.target).await?;
let input_items = parse_collab_input(args.message.clone(), args.items.clone())?;
let prompt = render_input_preview(&input_items);
let receiver_agent = session
.services
@@ -53,9 +54,15 @@ impl ToolHandler for Handler {
.into(),
)
.await;
let agent_control = session.services.agent_control.clone();
let result = agent_control
.send_input(receiver_thread_id, input_items)
let result = session
.services
.agent_control
.send_agent_message_or_input(
receiver_thread_id,
session.conversation_id,
args.message,
args.items,
)
.await
.map_err(|err| collab_agent_error(receiver_thread_id, err));
let status = session
@@ -1,12 +1,20 @@
use super::*;
use crate::agent::RemovedWatchdog;
use crate::agent::WatchdogRegistration;
use crate::agent::control::SpawnAgentForkMode;
use crate::agent::control::SpawnAgentOptions;
use crate::agent::control::render_input_preview;
use crate::agent::role::DEFAULT_ROLE_NAME;
use crate::agent::role::apply_role_to_config;
use crate::agent::exceeds_thread_spawn_depth_limit;
use crate::agent::next_thread_spawn_depth;
use crate::agent::role::DEFAULT_ROLE_NAME;
use crate::agent::role::apply_role_to_config;
use crate::agent::role::default_fork_context_for_role;
use crate::agent::role::watchdog_interval_for_role;
use crate::config::Config;
use codex_features::Feature;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::SessionSource;
use std::collections::HashSet;
pub(crate) struct Handler;
@@ -42,68 +50,170 @@ impl ToolHandler for Handler {
let session_source = turn.session_source.clone();
let child_depth = next_thread_spawn_depth(&session_source);
let max_depth = turn.config.agent_max_depth;
let watchdog_interval_s = watchdog_interval_for_role(&turn.config, role_name);
let is_watchdog = watchdog_interval_s.is_some();
if is_watchdog && !turn.config.features.enabled(Feature::AgentWatchdog) {
return Err(FunctionCallError::RespondToModel(
"watchdogs are disabled".to_string(),
));
}
if is_watchdog && matches!(session_source, SessionSource::SubAgent(_)) {
return Err(FunctionCallError::RespondToModel(
"watchdogs can only be spawned by root agents".to_string(),
));
}
if exceeds_thread_spawn_depth_limit(child_depth, max_depth) {
return Err(FunctionCallError::RespondToModel(
"Agent depth limit reached. Solve the task yourself.".to_string(),
));
}
session
.send_event(
&turn,
CollabAgentSpawnBeginEvent {
call_id: call_id.clone(),
sender_thread_id: session.conversation_id,
prompt: prompt.clone(),
model: args.model.clone().unwrap_or_default(),
reasoning_effort: args.reasoning_effort.unwrap_or_default(),
}
.into(),
)
.await;
let mut config =
let fork_context = args
.fork_context
.unwrap_or_else(|| default_fork_context_for_role(&turn.config, role_name));
let config =
build_agent_spawn_config(&session.get_base_instructions().await, turn.as_ref())?;
apply_requested_spawn_agent_model_overrides(
&session,
turn.as_ref(),
&mut config,
let mut candidates_to_try = collect_spawn_agent_model_candidates(
args.model_fallback_list.as_ref(),
args.model.as_deref(),
args.reasoning_effort,
)
.await?;
apply_role_to_config(&mut config, role_name)
.await
.map_err(FunctionCallError::RespondToModel)?;
apply_spawn_agent_runtime_overrides(&mut config, turn.as_ref())?;
apply_spawn_agent_overrides(&mut config, child_depth);
);
if candidates_to_try.is_empty() {
candidates_to_try.push(SpawnAgentModelCandidate {
model: None,
reasoning_effort: None,
});
}
let result = session
.services
.agent_control
.spawn_agent_with_metadata(
config,
input_items,
Some(thread_spawn_source(
session.conversation_id,
&turn.session_source,
child_depth,
role_name,
/*task_name*/ None,
)?),
SpawnAgentOptions {
fork_parent_spawn_call_id: args.fork_context.then(|| call_id.clone()),
fork_mode: args.fork_context.then_some(SpawnAgentForkMode::FullHistory),
},
let mut spawn_result = None;
for (idx, candidate) in candidates_to_try.iter().enumerate() {
let attempt_call_id = spawn_attempt_event_call_id(&call_id, idx);
let candidate_model = candidate.model.clone().unwrap_or_default();
let candidate_reasoning_effort = candidate.reasoning_effort.unwrap_or_default();
send_collab_agent_spawn_begin_event(
&session,
&turn,
attempt_call_id.clone(),
prompt.clone(),
candidate_model.clone(),
candidate_reasoning_effort,
)
.await
.map_err(collab_spawn_error);
let (new_thread_id, new_agent_metadata, status) = match &result {
Ok(spawned_agent) => (
Some(spawned_agent.thread_id),
Some(spawned_agent.metadata.clone()),
spawned_agent.status.clone(),
),
Err(_) => (None, None, AgentStatus::NotFound),
.await;
let mut candidate_config = config.clone();
if !fork_context {
apply_requested_spawn_agent_model_overrides(
&session,
turn.as_ref(),
&mut candidate_config,
candidate.model.as_deref(),
candidate.reasoning_effort,
)
.await?;
}
apply_role_to_config(&mut candidate_config, role_name)
.await
.map_err(FunctionCallError::RespondToModel)?;
if fork_context {
restore_forked_spawn_agent_model_config(&mut candidate_config, turn.as_ref());
}
apply_spawn_agent_runtime_overrides(&mut candidate_config, turn.as_ref())?;
apply_spawn_agent_overrides(&mut candidate_config, child_depth);
let attempt_result = session
.services
.agent_control
.spawn_agent_with_metadata(
candidate_config,
input_items.clone(),
Some(thread_spawn_source(
session.conversation_id,
&turn.session_source,
child_depth,
role_name,
/*task_name*/ None,
)?),
SpawnAgentOptions {
fork_parent_spawn_call_id: if fork_context {
Some(call_id.clone())
} else {
None
},
fork_mode: if fork_context {
Some(SpawnAgentForkMode::FullHistory)
} else {
None
},
},
)
.await;
match attempt_result {
Ok(spawned_agent) => {
let status = if idx + 1 < candidates_to_try.len() {
match probe_spawn_attempt_for_async_quota_exhaustion(
spawned_agent.status.clone(),
spawned_agent.thread_id,
&session.services.agent_control,
)
.await
{
SpawnAttemptRetryDecision::Accept(status) => status,
SpawnAttemptRetryDecision::Retry(retry_status) => {
match close_quota_exhausted_spawn_attempt(
&session.services.agent_control,
spawned_agent.thread_id,
retry_status,
)
.await
{
SpawnAttemptRetryDecision::Accept(status) => status,
SpawnAttemptRetryDecision::Retry(status) => {
send_collab_agent_spawn_retry_preempted_event(
&session,
&turn,
attempt_call_id,
prompt.clone(),
candidate_model,
candidate_reasoning_effort,
status,
)
.await;
continue;
}
}
}
}
} else {
spawned_agent.status.clone()
};
spawn_result = Some((spawned_agent, status, attempt_call_id));
break;
}
Err(err) => {
send_collab_agent_spawn_error_event(
&session,
&turn,
attempt_call_id,
prompt.clone(),
candidate_model,
candidate_reasoning_effort,
&err,
)
.await;
if spawn_should_retry_on_quota_exhaustion(&err)
&& idx + 1 < candidates_to_try.len()
{
continue;
}
return Err(collab_spawn_error(err));
}
}
}
let Some((spawned_agent, status, spawn_event_call_id)) = spawn_result else {
return Err(FunctionCallError::RespondToModel(
"No spawn attempts were executed".to_string(),
));
};
let new_thread_id = Some(spawned_agent.thread_id);
let new_agent_metadata = Some(spawned_agent.metadata.clone());
let agent_snapshot = match new_thread_id {
Some(thread_id) => {
session
@@ -141,7 +251,7 @@ impl ToolHandler for Handler {
.send_event(
&turn,
CollabAgentSpawnEndEvent {
call_id,
call_id: spawn_event_call_id,
sender_thread_id: session.conversation_id,
new_thread_id,
new_agent_nickname,
@@ -154,7 +264,7 @@ impl ToolHandler for Handler {
.into(),
)
.await;
let new_thread_id = result?.thread_id;
let new_thread_id = spawned_agent.thread_id;
let role_tag = role_name.unwrap_or(DEFAULT_ROLE_NAME);
turn.session_telemetry.counter(
"codex.multi_agent.spawn",
@@ -163,7 +273,8 @@ impl ToolHandler for Handler {
);
Ok(SpawnAgentResult {
agent_id: new_thread_id.to_string(),
agent_id: Some(new_thread_id.to_string()),
task_name: None,
nickname,
})
}
@@ -173,16 +284,19 @@ impl ToolHandler for Handler {
struct SpawnAgentArgs {
message: Option<String>,
items: Option<Vec<UserInput>>,
#[serde(rename = "task_name")]
_task_name: Option<String>,
agent_type: Option<String>,
model: Option<String>,
model_fallback_list: Option<Vec<SpawnAgentModelFallbackCandidate>>,
reasoning_effort: Option<ReasoningEffort>,
#[serde(default)]
fork_context: bool,
fork_context: Option<bool>,
}
#[derive(Debug, Serialize)]
pub(crate) struct SpawnAgentResult {
agent_id: String,
agent_id: Option<String>,
task_name: Option<String>,
nickname: Option<String>,
}
@@ -203,3 +317,66 @@ impl ToolOutput for SpawnAgentResult {
tool_output_code_mode_result(self, "spawn_agent")
}
}
async fn spawn_watchdog(
agent_control: &crate::agent::AgentControl,
config: Config,
prompt: String,
owner_thread_id: ThreadId,
child_depth: i32,
interval_s: i64,
spawn_source: SessionSource,
) -> crate::error::Result<ThreadId> {
let target_thread_id = agent_control
.spawn_agent(
config.clone(),
Op::UserInput {
items: vec![codex_protocol::user_input::UserInput::Text {
text: prompt.clone(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
},
Some(spawn_source),
)
.await?;
let superseded_before_register = agent_control
.unregister_watchdogs_for_owner(owner_thread_id)
.await;
shutdown_removed_watchdogs(agent_control, superseded_before_register).await;
let registration = WatchdogRegistration {
owner_thread_id,
target_thread_id,
child_depth,
interval_s,
prompt: prompt.clone(),
config,
};
let superseded_after_register = match agent_control.register_watchdog(registration).await {
Ok(removed) => removed,
Err(err) => {
let _ = agent_control.close_agent(target_thread_id).await;
return Err(err);
}
};
shutdown_removed_watchdogs(agent_control, superseded_after_register).await;
Ok(target_thread_id)
}
async fn shutdown_removed_watchdogs(
agent_control: &crate::agent::AgentControl,
removed_watchdogs: Vec<RemovedWatchdog>,
) {
let mut thread_ids = HashSet::new();
for removed in removed_watchdogs {
thread_ids.insert(removed.target_thread_id);
if let Some(helper_id) = removed.active_helper_id {
thread_ids.insert(helper_id);
}
}
let mut thread_ids = thread_ids.into_iter().collect::<Vec<_>>();
thread_ids.sort_by_key(ToString::to_string);
for thread_id in thread_ids {
let _ = agent_control.close_agent(thread_id).await;
}
}
@@ -1,15 +1,16 @@
use super::*;
use crate::agent::agent_resolver::resolve_agent_targets;
use crate::agent::status::is_final;
use crate::error::CodexErr;
use futures::FutureExt;
use futures::StreamExt;
use futures::stream::FuturesUnordered;
use std::collections::HashMap;
use std::collections::HashSet;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::watch::Receiver;
use tokio::time::Instant;
use tokio::time::timeout_at;
pub(crate) struct Handler;
@@ -36,7 +37,19 @@ impl ToolHandler for Handler {
} = invocation;
let arguments = function_arguments(payload)?;
let args: WaitArgs = parse_arguments(&arguments)?;
let receiver_thread_ids = parse_agent_id_targets(args.targets)?;
if let Some(owner_thread_id) = session
.services
.agent_control
.watchdog_owner_for_active_helper(session.conversation_id)
.await
{
return Err(FunctionCallError::RespondToModel(format!(
"wait_agent is not available to watchdog check-in agents. This thread is a one-shot watchdog check-in for owner {owner_thread_id}. Send the result to the parent/root agent with `send_input`, or finish with a final assistant report that runtime can forward as fallback. If you exit without either one, runtime emits no root-visible fallback message and the next scheduled watchdog check-in will try again."
)));
}
let receiver_thread_ids = resolve_agent_targets(&session, &turn, args.targets).await?;
let mut receiver_agents = Vec::with_capacity(receiver_thread_ids.len());
let mut target_by_thread_id = HashMap::with_capacity(receiver_thread_ids.len());
for receiver_thread_id in &receiver_thread_ids {
@@ -60,6 +73,22 @@ impl ToolHandler for Handler {
});
}
let watchdog_target_ids = session
.services
.agent_control
.watchdog_targets(&receiver_thread_ids)
.await;
let mut waited_thread_ids = Vec::new();
let mut watchdog_statuses = Vec::new();
split_wait_ids(
&session,
receiver_thread_ids,
&watchdog_target_ids,
&mut waited_thread_ids,
&mut watchdog_statuses,
)
.await;
let timeout_ms = args.timeout_ms.unwrap_or(DEFAULT_WAIT_TIMEOUT_MS);
let timeout_ms = match timeout_ms {
ms if ms <= 0 => {
@@ -75,7 +104,7 @@ impl ToolHandler for Handler {
&turn,
CollabWaitingBeginEvent {
sender_thread_id: session.conversation_id,
receiver_thread_ids: receiver_thread_ids.clone(),
receiver_thread_ids: waited_thread_ids.clone(),
receiver_agents: receiver_agents.clone(),
call_id: call_id.clone(),
}
@@ -83,9 +112,31 @@ impl ToolHandler for Handler {
)
.await;
let mut status_rxs = Vec::with_capacity(receiver_thread_ids.len());
if waited_thread_ids.is_empty() {
let statuses_map = watchdog_statuses.iter().cloned().collect::<HashMap<_, _>>();
let content = serde_json::to_string(&statuses_map).map_err(|err| {
FunctionCallError::Fatal(format!("failed to serialize wait_agent status: {err}"))
})?;
session
.send_event(
&turn,
CollabWaitingEndEvent {
sender_thread_id: session.conversation_id,
call_id,
agent_statuses: Vec::new(),
statuses: statuses_map,
}
.into(),
)
.await;
return Err(FunctionCallError::RespondToModel(format!(
"wait_agent cannot be used to wait for watchdog check-ins. You passed only watchdog handle ids. Watchdog check-ins only happen after the current turn ends and the owner thread is idle for at least watchdog_interval_s. `wait_agent` on a watchdog handle is status-only and cannot confirm a new check-in. Do not poll with `wait_agent`, `list_agents`, or shell `sleep`: the owner thread is still active during this turn, so those calls cannot make the watchdog fire. Current watchdog handle statuses: {content}"
)));
}
let mut status_rxs = Vec::with_capacity(waited_thread_ids.len());
let mut initial_final_statuses = Vec::new();
for id in &receiver_thread_ids {
for id in &waited_thread_ids {
match session.services.agent_control.subscribe_status(*id).await {
Ok(rx) => {
let status = rx.borrow().clone();
@@ -98,8 +149,9 @@ impl ToolHandler for Handler {
initial_final_statuses.push((*id, AgentStatus::NotFound));
}
Err(err) => {
let mut statuses = HashMap::with_capacity(1);
let mut statuses = HashMap::with_capacity(1 + watchdog_statuses.len());
statuses.insert(*id, session.services.agent_control.get_status(*id).await);
statuses.extend(watchdog_statuses.iter().cloned());
session
.send_event(
&turn,
@@ -124,7 +176,7 @@ impl ToolHandler for Handler {
initial_final_statuses
} else {
let mut futures = FuturesUnordered::new();
for (id, rx) in status_rxs.into_iter() {
for (id, rx) in status_rxs {
let session = session.clone();
futures.push(wait_for_final_status(session, id, rx));
}
@@ -153,16 +205,17 @@ impl ToolHandler for Handler {
};
let timed_out = statuses.is_empty();
let statuses_by_id = statuses.clone().into_iter().collect::<HashMap<_, _>>();
let mut statuses_by_id = statuses.clone().into_iter().collect::<HashMap<_, _>>();
statuses_by_id.extend(watchdog_statuses);
let agent_statuses = build_wait_agent_statuses(&statuses_by_id, &receiver_agents);
let result = WaitAgentResult {
status: statuses
.into_iter()
status: statuses_by_id
.iter()
.filter_map(|(thread_id, status)| {
target_by_thread_id
.get(&thread_id)
.get(thread_id)
.cloned()
.map(|target| (target, status))
.map(|target| (target, status.clone()))
})
.collect(),
timed_out,
@@ -229,7 +282,10 @@ async fn wait_for_final_status(
loop {
if status_rx.changed().await.is_err() {
let latest = session.services.agent_control.get_status(thread_id).await;
return is_final(&latest).then_some((thread_id, latest));
if is_final(&latest) {
return Some((thread_id, latest));
}
return None;
}
status = status_rx.borrow().clone();
if is_final(&status) {
@@ -237,3 +293,20 @@ async fn wait_for_final_status(
}
}
}
async fn split_wait_ids(
session: &Arc<Session>,
requested_thread_ids: Vec<ThreadId>,
watchdog_target_ids: &HashSet<ThreadId>,
waited_thread_ids: &mut Vec<ThreadId>,
watchdog_statuses: &mut Vec<(ThreadId, AgentStatus)>,
) {
for thread_id in requested_thread_ids {
if watchdog_target_ids.contains(&thread_id) {
let status = session.services.agent_control.get_status(thread_id).await;
watchdog_statuses.push((thread_id, status));
} else {
waited_thread_ids.push(thread_id);
}
}
}
@@ -0,0 +1,149 @@
use super::*;
pub(crate) struct Handler;
#[async_trait]
impl ToolHandler for Handler {
type Output = WatchdogSelfCloseResult;
fn kind(&self) -> ToolKind {
ToolKind::Function
}
fn matches_kind(&self, payload: &ToolPayload) -> bool {
matches!(payload, ToolPayload::Function { .. })
}
async fn handle(&self, invocation: ToolInvocation) -> Result<Self::Output, FunctionCallError> {
let ToolInvocation {
session,
payload,
call_id,
turn,
..
} = invocation;
let arguments = function_arguments(payload)?;
let _args: WatchdogSelfCloseArgs = parse_arguments(&arguments)?;
let helper_thread_id = session.conversation_id;
if session
.services
.agent_control
.watchdog_owner_for_active_helper(helper_thread_id)
.await
.is_none()
{
return Err(FunctionCallError::RespondToModel(
"watchdog_self_close is only available in watchdog check-in threads.".to_string(),
));
};
let receiver_agent = session
.services
.agent_control
.get_agent_metadata(helper_thread_id)
.unwrap_or_default();
session
.send_event(
&turn,
CollabCloseBeginEvent {
call_id: call_id.clone(),
sender_thread_id: helper_thread_id,
receiver_thread_id: helper_thread_id,
}
.into(),
)
.await;
let status = match session
.services
.agent_control
.subscribe_status(helper_thread_id)
.await
{
Ok(mut status_rx) => status_rx.borrow_and_update().clone(),
Err(err) => {
let status = session
.services
.agent_control
.get_status(helper_thread_id)
.await;
session
.send_event(
&turn,
CollabCloseEndEvent {
call_id: call_id.clone(),
sender_thread_id: helper_thread_id,
receiver_thread_id: helper_thread_id,
receiver_agent_nickname: receiver_agent.agent_nickname.clone(),
receiver_agent_role: receiver_agent.agent_role.clone(),
status,
}
.into(),
)
.await;
return Err(collab_agent_error(helper_thread_id, err));
}
};
let result = session
.services
.agent_control
.close_agent(helper_thread_id)
.await
.map_err(|err| collab_agent_error(helper_thread_id, err))
.map(|_| ());
let receiver_agent = session
.services
.agent_control
.get_agent_metadata(helper_thread_id)
.unwrap_or_default();
session
.send_event(
&turn,
CollabCloseEndEvent {
call_id,
sender_thread_id: helper_thread_id,
receiver_thread_id: helper_thread_id,
receiver_agent_nickname: receiver_agent.agent_nickname,
receiver_agent_role: receiver_agent.agent_role,
status: status.clone(),
}
.into(),
)
.await;
result?;
Ok(WatchdogSelfCloseResult {
previous_status: status,
})
}
}
#[derive(Debug, Deserialize)]
struct WatchdogSelfCloseArgs {}
#[derive(Debug, Serialize)]
pub(crate) struct WatchdogSelfCloseResult {
previous_status: AgentStatus,
}
impl ToolOutput for WatchdogSelfCloseResult {
fn log_preview(&self) -> String {
tool_output_json_text(self, "watchdog_self_close")
}
fn success_for_logging(&self) -> bool {
true
}
fn to_response_item(&self, call_id: &str, payload: &ToolPayload) -> ResponseInputItem {
tool_output_response_item(call_id, payload, self, Some(true), "watchdog_self_close")
}
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
tool_output_code_mode_result(self, "watchdog_self_close")
}
}
@@ -16,19 +16,39 @@ use codex_protocol::models::ResponseInputItem;
use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::openai_models::ReasoningEffortPreset;
use codex_protocol::protocol::CollabAgentRef;
use codex_protocol::protocol::CollabAgentSpawnBeginEvent;
use codex_protocol::protocol::CollabAgentSpawnEndEvent;
use codex_protocol::protocol::CollabAgentStatusEntry;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
use codex_protocol::user_input::UserInput;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use tokio::time::Duration;
use tokio::time::Instant;
use tokio::time::timeout;
/// Minimum wait timeout to prevent tight polling loops from burning CPU.
pub(crate) const MIN_WAIT_TIMEOUT_MS: i64 = 10_000;
pub(crate) const DEFAULT_WAIT_TIMEOUT_MS: i64 = 30_000;
pub(crate) const MAX_WAIT_TIMEOUT_MS: i64 = 3600 * 1000;
const ASYNC_QUOTA_EXHAUSTION_STATUS_TIMEOUT: Duration = Duration::from_secs(2);
pub(crate) enum SpawnAttemptRetryDecision {
Accept(AgentStatus),
Retry(AgentStatus),
}
pub(crate) fn spawn_attempt_event_call_id(call_id: &str, attempt_index: usize) -> String {
if attempt_index == 0 {
call_id.to_string()
} else {
format!("{call_id}#{}", attempt_index + 1)
}
}
pub(crate) fn function_arguments(payload: ToolPayload) -> Result<String, FunctionCallError> {
match payload {
@@ -71,6 +91,177 @@ where
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SpawnAgentModelCandidate {
pub(crate) model: Option<String>,
pub(crate) reasoning_effort: Option<ReasoningEffort>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub(crate) struct SpawnAgentModelFallbackCandidate {
pub(crate) model: String,
#[serde(default)]
pub(crate) reasoning_effort: Option<ReasoningEffort>,
}
pub(crate) fn collect_spawn_agent_model_candidates(
model_fallback_list: Option<&Vec<SpawnAgentModelFallbackCandidate>>,
requested_model: Option<&str>,
requested_reasoning_effort: Option<ReasoningEffort>,
) -> Vec<SpawnAgentModelCandidate> {
if let Some(model_fallback_list) = model_fallback_list {
return model_fallback_list
.iter()
.map(|candidate| SpawnAgentModelCandidate {
model: Some(candidate.model.clone()),
reasoning_effort: candidate.reasoning_effort.or(requested_reasoning_effort),
})
.collect();
}
let mut candidates = Vec::new();
if requested_model.is_some() || requested_reasoning_effort.is_some() {
candidates.push(SpawnAgentModelCandidate {
model: requested_model.map(ToString::to_string),
reasoning_effort: requested_reasoning_effort,
});
}
candidates
}
pub(crate) async fn close_quota_exhausted_spawn_attempt(
agent_control: &crate::agent::control::AgentControl,
thread_id: ThreadId,
retry_status: AgentStatus,
) -> SpawnAttemptRetryDecision {
let retry_decision =
recheck_spawn_attempt_retry_decision(retry_status, thread_id, agent_control).await;
let SpawnAttemptRetryDecision::Retry(status) = retry_decision else {
return retry_decision;
};
// There is still a narrow TOCTOU window: a child can leave `PendingInit` after the final
// status read above and before `close_agent` runs. `AgentControl` does not currently expose
// a compare-and-close primitive, so this is the strongest local mitigation available.
if let Err(err) = agent_control.close_agent(thread_id).await
&& !matches!(
err,
CodexErr::ThreadNotFound(_) | CodexErr::InternalAgentDied
)
{
tracing::warn!("failed to close quota-exhausted spawn attempt {thread_id}: {err}");
}
SpawnAttemptRetryDecision::Retry(status)
}
pub(crate) fn spawn_should_retry_on_quota_exhaustion(error: &CodexErr) -> bool {
matches!(
error,
CodexErr::QuotaExceeded | CodexErr::UsageLimitReached(_)
)
}
pub(crate) async fn probe_spawn_attempt_for_async_quota_exhaustion(
thread_status: AgentStatus,
thread_id: ThreadId,
agent_control: &crate::agent::control::AgentControl,
) -> SpawnAttemptRetryDecision {
match thread_status {
AgentStatus::Completed(_)
| AgentStatus::Errored(_)
| AgentStatus::Shutdown
| AgentStatus::NotFound => {
return retry_decision_for_final_spawn_status(thread_status);
}
AgentStatus::PendingInit | AgentStatus::Running | AgentStatus::Interrupted => {}
}
let Ok(mut status_rx) = agent_control.subscribe_status(thread_id).await else {
return match thread_status {
AgentStatus::Running | AgentStatus::Interrupted => {
SpawnAttemptRetryDecision::Accept(thread_status)
}
_ => SpawnAttemptRetryDecision::Retry(AgentStatus::PendingInit),
};
};
let deadline = Instant::now() + ASYNC_QUOTA_EXHAUSTION_STATUS_TIMEOUT;
loop {
let status = status_rx.borrow_and_update().clone();
match status {
AgentStatus::Completed(_)
| AgentStatus::Errored(_)
| AgentStatus::Shutdown
| AgentStatus::NotFound => {
return retry_decision_for_final_spawn_status(status);
}
AgentStatus::PendingInit | AgentStatus::Running | AgentStatus::Interrupted => {}
}
let Some(remaining) = deadline.checked_duration_since(Instant::now()) else {
return match status {
AgentStatus::PendingInit => {
SpawnAttemptRetryDecision::Retry(AgentStatus::PendingInit)
}
AgentStatus::Running | AgentStatus::Interrupted => {
SpawnAttemptRetryDecision::Accept(status)
}
AgentStatus::Completed(_)
| AgentStatus::Errored(_)
| AgentStatus::Shutdown
| AgentStatus::NotFound => retry_decision_for_final_spawn_status(status),
};
};
match timeout(remaining, status_rx.changed()).await {
Ok(Ok(())) => {}
Ok(Err(_)) => return SpawnAttemptRetryDecision::Retry(AgentStatus::PendingInit),
Err(_) => return SpawnAttemptRetryDecision::Retry(AgentStatus::PendingInit),
}
}
}
pub(crate) async fn recheck_spawn_attempt_retry_decision(
status: AgentStatus,
thread_id: ThreadId,
agent_control: &crate::agent::control::AgentControl,
) -> SpawnAttemptRetryDecision {
if !matches!(status, AgentStatus::PendingInit) {
return SpawnAttemptRetryDecision::Retry(status);
}
let latest_status = agent_control.get_status(thread_id).await;
match latest_status {
AgentStatus::Running | AgentStatus::Interrupted => {
SpawnAttemptRetryDecision::Accept(latest_status)
}
AgentStatus::Completed(_)
| AgentStatus::Errored(_)
| AgentStatus::Shutdown
| AgentStatus::NotFound => retry_decision_for_final_spawn_status(latest_status),
AgentStatus::PendingInit => SpawnAttemptRetryDecision::Retry(AgentStatus::PendingInit),
}
}
fn retry_decision_for_final_spawn_status(status: AgentStatus) -> SpawnAttemptRetryDecision {
if spawn_should_retry_on_quota_exhaustion_status(&status) {
SpawnAttemptRetryDecision::Retry(status)
} else {
SpawnAttemptRetryDecision::Accept(status)
}
}
fn spawn_should_retry_on_quota_exhaustion_status(status: &AgentStatus) -> bool {
match status {
AgentStatus::Errored(message) => {
let message = message.to_lowercase();
message.contains("insufficient_quota")
|| message.contains("usage limit")
|| message.contains("quota")
}
AgentStatus::NotFound => false,
_ => false,
}
}
pub(crate) fn build_wait_agent_statuses(
statuses: &HashMap<ThreadId, AgentStatus>,
receiver_agents: &[CollabAgentRef],
@@ -118,6 +309,88 @@ pub(crate) fn collab_spawn_error(err: CodexErr) -> FunctionCallError {
}
}
pub(crate) async fn send_collab_agent_spawn_error_event(
session: &Session,
turn: &TurnContext,
call_id: String,
prompt: String,
model: String,
reasoning_effort: ReasoningEffort,
err: &CodexErr,
) {
session
.send_event(
turn,
CollabAgentSpawnEndEvent {
call_id,
sender_thread_id: session.conversation_id,
new_thread_id: None,
new_agent_nickname: None,
new_agent_role: None,
prompt,
model,
reasoning_effort,
status: match err {
CodexErr::ThreadNotFound(_) => AgentStatus::NotFound,
err => AgentStatus::Errored(err.to_string()),
},
}
.into(),
)
.await;
}
pub(crate) async fn send_collab_agent_spawn_begin_event(
session: &Session,
turn: &TurnContext,
call_id: String,
prompt: String,
model: String,
reasoning_effort: ReasoningEffort,
) {
session
.send_event(
turn,
CollabAgentSpawnBeginEvent {
call_id,
sender_thread_id: session.conversation_id,
prompt,
model,
reasoning_effort,
}
.into(),
)
.await;
}
pub(crate) async fn send_collab_agent_spawn_retry_preempted_event(
session: &Session,
turn: &TurnContext,
call_id: String,
prompt: String,
model: String,
reasoning_effort: ReasoningEffort,
status: AgentStatus,
) {
session
.send_event(
turn,
CollabAgentSpawnEndEvent {
call_id,
sender_thread_id: session.conversation_id,
new_thread_id: None,
new_agent_nickname: None,
new_agent_role: None,
prompt,
model,
reasoning_effort,
status,
}
.into(),
)
.await;
}
pub(crate) fn collab_agent_error(agent_id: ThreadId, err: CodexErr) -> FunctionCallError {
match err {
CodexErr::ThreadNotFound(id) => {
@@ -225,7 +498,11 @@ fn build_agent_shared_config(turn: &TurnContext) -> Result<Config, FunctionCallE
let mut config = (*base_config).clone();
config.model = Some(turn.model_info.slug.clone());
config.model_provider = turn.provider.clone();
config.model_reasoning_effort = turn.reasoning_effort;
// Forked children must preserve the spawning turn's effective model settings, including a
// model catalog default effort, so their config snapshot matches the actual request shape.
config.model_reasoning_effort = turn
.reasoning_effort
.or(turn.model_info.default_reasoning_level);
config.model_reasoning_summary = Some(turn.reasoning_summary);
config.developer_instructions = turn.developer_instructions.clone();
config.compact_prompt = turn.compact_prompt.clone();
@@ -234,6 +511,24 @@ fn build_agent_shared_config(turn: &TurnContext) -> Result<Config, FunctionCallE
Ok(config)
}
/// Restores parent-owned model selection after role application on forked spawns.
pub(crate) fn restore_forked_spawn_agent_model_config(config: &mut Config, turn: &TurnContext) {
config.model = Some(turn.model_info.slug.clone());
config.service_tier = turn.config.service_tier;
config.model_provider_id = turn.config.model_provider_id.clone();
config.model_provider = turn.provider.clone();
config.model_reasoning_effort = turn
.reasoning_effort
.or(turn.model_info.default_reasoning_level);
config.plan_mode_reasoning_effort = turn.config.plan_mode_reasoning_effort;
config.model_reasoning_summary = Some(turn.reasoning_summary);
config.model_verbosity = turn.config.model_verbosity;
config.model_context_window = turn.config.model_context_window;
config.model_auto_compact_token_limit = turn.config.model_auto_compact_token_limit;
config.model_supports_reasoning_summaries = turn.config.model_supports_reasoning_summaries;
config.active_profile = turn.config.active_profile.clone();
}
/// Copies runtime-only turn state onto a child config before it is handed to `AgentControl`.
///
/// These values are chosen by the live turn rather than persisted config, so leaving them stale
@@ -363,3 +658,111 @@ fn validate_spawn_agent_reasoning_effort(
"Reasoning effort `{requested_reasoning_effort}` is not supported for model `{model}`. Supported reasoning efforts: {supported}"
)))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::error::UsageLimitReachedError;
use crate::protocol::AgentStatus;
#[test]
fn collect_spawn_agent_model_candidates_prefers_fallback_list() {
let candidates = collect_spawn_agent_model_candidates(
Some(&vec![
SpawnAgentModelFallbackCandidate {
model: "fallback-a".to_string(),
reasoning_effort: Some(ReasoningEffort::High),
},
SpawnAgentModelFallbackCandidate {
model: "fallback-b".to_string(),
reasoning_effort: Some(ReasoningEffort::Minimal),
},
]),
Some("legacy-model"),
Some(ReasoningEffort::Low),
);
assert_eq!(
candidates,
vec![
SpawnAgentModelCandidate {
model: Some("fallback-a".to_string()),
reasoning_effort: Some(ReasoningEffort::High),
},
SpawnAgentModelCandidate {
model: Some("fallback-b".to_string()),
reasoning_effort: Some(ReasoningEffort::Minimal),
},
]
);
}
#[test]
fn collect_spawn_agent_model_candidates_falls_back_to_legacy_args() {
let candidates = collect_spawn_agent_model_candidates(
/*model_fallback_list*/ None,
Some("legacy-model"),
Some(ReasoningEffort::Minimal),
);
assert_eq!(
candidates,
vec![SpawnAgentModelCandidate {
model: Some("legacy-model".to_string()),
reasoning_effort: Some(ReasoningEffort::Minimal),
}]
);
}
#[test]
fn collect_spawn_agent_model_candidates_empty_when_no_model_is_set() {
let candidates = collect_spawn_agent_model_candidates(
/*model_fallback_list*/ None, /*requested_model*/ None,
/*requested_reasoning_effort*/ None,
);
assert_eq!(candidates, Vec::new());
}
#[test]
fn spawn_should_retry_on_quota_exhaustion_checks_expected_error_variants() {
assert!(spawn_should_retry_on_quota_exhaustion(
&CodexErr::QuotaExceeded
));
assert!(spawn_should_retry_on_quota_exhaustion(
&CodexErr::UsageLimitReached(UsageLimitReachedError {
plan_type: None,
resets_at: None,
rate_limits: None,
promo_message: None,
})
));
assert!(!spawn_should_retry_on_quota_exhaustion(
&CodexErr::UnsupportedOperation("thread manager dropped".to_string())
));
}
#[test]
fn collab_spawn_error_handles_thread_manager_drop() {
assert_eq!(
collab_spawn_error(CodexErr::UnsupportedOperation(
"thread manager dropped".to_string()
)),
FunctionCallError::RespondToModel("collab manager unavailable".to_string())
);
}
#[test]
fn build_wait_agent_statuses_includes_extras_in_sorted_order() {
let receiver_agents = vec![];
let mut statuses = HashMap::new();
let thread_a = ThreadId::new();
let thread_b = ThreadId::new();
statuses.insert(thread_b, AgentStatus::Completed(Some("done".to_string())));
statuses.insert(thread_a, AgentStatus::Completed(Some("done".to_string())));
let entries = build_wait_agent_statuses(&statuses, &receiver_agents);
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].thread_id, thread_a);
assert_eq!(entries[1].thread_id, thread_b);
}
}
@@ -1,7 +1,10 @@
use super::*;
use crate::ThreadManager;
use crate::agent::WatchdogRegistration;
use crate::built_in_model_providers;
use crate::codex::make_session_and_context;
use crate::codex::make_session_and_context_with_rx;
use crate::config::AgentRoleConfig;
use crate::config::DEFAULT_AGENT_MAX_DEPTH;
use crate::function_tool::FunctionCallError;
use crate::session_prefix::format_subagent_notification_message;
@@ -15,6 +18,7 @@ use crate::tools::handlers::multi_agents_v2::ListAgentsHandler as ListAgentsHand
use crate::tools::handlers::multi_agents_v2::SendMessageHandler as SendMessageHandlerV2;
use crate::tools::handlers::multi_agents_v2::SpawnAgentHandler as SpawnAgentHandlerV2;
use crate::tools::handlers::multi_agents_v2::WaitAgentHandler as WaitAgentHandlerV2;
use crate::tools::handlers::multi_agents_v2::WatchdogSelfCloseHandlerV2;
use crate::turn_diff_tracker::TurnDiffTracker;
use codex_config::types::ShellEnvironmentPolicy;
use codex_features::Feature;
@@ -22,13 +26,18 @@ use codex_login::AuthManager;
use codex_login::CodexAuth;
use codex_protocol::AgentPath;
use codex_protocol::ThreadId;
use codex_protocol::config_types::ServiceTier;
use codex_protocol::config_types::Verbosity;
use codex_protocol::models::BaseInstructions;
use codex_protocol::models::ContentItem;
use codex_protocol::models::FunctionCallOutputBody;
use codex_protocol::models::ResponseInputItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::protocol::AgentStatus;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::CollabAgentSpawnEndEvent;
use codex_protocol::protocol::Event;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::FileSystemSandboxPolicy;
use codex_protocol::protocol::InitialHistory;
@@ -54,6 +63,7 @@ use std::time::Duration;
use tokio::sync::Mutex;
use tokio::time::timeout;
use tokio_util::sync::CancellationToken;
use tracing_test::traced_test;
fn invocation(
session: Arc<crate::codex::Session>,
@@ -89,6 +99,93 @@ fn thread_manager() -> ThreadManager {
)
}
async fn attach_watchdog_helper_for_tests(
manager: &ThreadManager,
agent_control: &crate::agent::AgentControl,
config: &crate::config::Config,
) -> ThreadId {
let owner = manager
.start_thread(config.clone())
.await
.expect("owner thread should start");
let target = agent_control
.spawn_agent_handle(config.clone(), /*session_source*/ None)
.await
.expect("watchdog target thread should start");
let helper = manager
.start_thread(config.clone())
.await
.expect("helper thread should start");
agent_control
.register_watchdog(WatchdogRegistration {
owner_thread_id: owner.thread_id,
target_thread_id: target,
child_depth: 1,
interval_s: 30,
prompt: "check in".to_string(),
config: config.clone(),
})
.await
.expect("watchdog registration should succeed");
agent_control
.set_watchdog_active_helper_for_tests(target, helper.thread_id)
.await;
assert_eq!(
agent_control
.watchdog_owner_for_active_helper(helper.thread_id)
.await,
Some(owner.thread_id),
"watchdog helper should be registered for owner"
);
helper.thread_id
}
async fn install_role_with_model_provider_and_profile_override(turn: &mut TurnContext) -> String {
let role_name = "fork-context-role".to_string();
tokio::fs::create_dir_all(&turn.config.codex_home)
.await
.expect("codex home should be created");
let role_config_path = turn.config.codex_home.join("fork-context-role.toml");
tokio::fs::write(
&role_config_path,
r#"developer_instructions = "Forked children should keep the parent model config."
model_provider = "openai"
model_context_window = 12345
model_auto_compact_token_limit = 1234
model_verbosity = "low"
plan_mode_reasoning_effort = "minimal"
profile = "role-profile"
service_tier = "fast"
[profiles.role-profile]
model_provider = "openai"
"#,
)
.await
.expect("role config should be written");
let mut config = (*turn.config).clone();
config.service_tier = Some(ServiceTier::Flex);
config.plan_mode_reasoning_effort = Some(ReasoningEffort::High);
config.model_verbosity = Some(Verbosity::High);
config.model_context_window = Some(200_000);
config.model_auto_compact_token_limit = Some(180_000);
config.agent_roles.insert(
role_name.clone(),
AgentRoleConfig {
description: Some("Role with model-provider and profile overrides".to_string()),
model: None,
config_file: Some(role_config_path),
watchdog_interval_s: None,
nickname_candidates: None,
fork_context: None,
},
);
turn.config = Arc::new(config);
role_name
}
fn history_contains_inter_agent_communication(
history_items: &[ResponseItem],
expected: &InterAgentCommunication,
@@ -163,6 +260,20 @@ where
}
}
async fn wait_for_collab_spawn_end_event(
rx: &async_channel::Receiver<Event>,
) -> CollabAgentSpawnEndEvent {
loop {
let event = timeout(Duration::from_secs(1), rx.recv())
.await
.expect("collab spawn-end event timed out")
.expect("collab spawn-end event missing");
if let EventMsg::CollabAgentSpawnEnd(event) = event.msg {
return event;
}
}
}
#[derive(Debug, Deserialize)]
struct ListAgentsResult {
agents: Vec<ListedAgentResult>,
@@ -175,6 +286,11 @@ struct ListedAgentResult {
last_task_message: Option<String>,
}
#[derive(Debug, Deserialize, PartialEq)]
struct WatchdogSelfCloseResult {
previous_status: AgentStatus,
}
#[tokio::test]
async fn handler_rejects_non_function_payloads() {
let (session, turn) = make_session_and_context().await;
@@ -248,7 +364,12 @@ async fn spawn_agent_uses_explorer_role_and_preserves_approval_policy() {
let (mut session, mut turn) = make_session_and_context().await;
let manager = thread_manager();
let root = manager
.start_thread((*turn.config).clone())
.await
.expect("root thread should start");
session.services.agent_control = manager.agent_control();
session.conversation_id = root.thread_id;
let mut config = (*turn.config).clone();
let provider =
built_in_model_providers(/* openai_base_url */ /*openai_base_url*/ None)["ollama"].clone();
@@ -271,7 +392,8 @@ async fn spawn_agent_uses_explorer_role_and_preserves_approval_policy() {
"spawn_agent",
function_payload(json!({
"message": "inspect this repo",
"agent_type": "explorer"
"agent_type": "explorer",
"fork_context": false
})),
);
let output = SpawnAgentHandler
@@ -299,10 +421,26 @@ async fn spawn_agent_uses_explorer_role_and_preserves_approval_policy() {
}
#[tokio::test]
async fn spawn_agent_returns_agent_id_without_task_name() {
let (mut session, turn) = make_session_and_context().await;
#[traced_test]
async fn spawn_agent_fork_context_ignores_child_model_overrides() {
let (mut session, mut turn) = make_session_and_context().await;
let role_name = install_role_with_model_provider_and_profile_override(&mut turn).await;
let manager = thread_manager();
let root = manager
.start_thread((*turn.config).clone())
.await
.expect("root thread should start");
session.services.agent_control = manager.agent_control();
session.conversation_id = root.thread_id;
let expected_model = turn.model_info.slug.clone();
let expected_model_provider_id = turn.config.model_provider_id.clone();
let expected_active_profile = turn.config.active_profile.clone();
let expected_reasoning_effort = turn.reasoning_effort;
let expected_service_tier = turn.config.service_tier;
let expected_plan_mode_reasoning_effort = turn.config.plan_mode_reasoning_effort;
let expected_model_verbosity = turn.config.model_verbosity;
let expected_model_context_window = turn.config.model_context_window;
let expected_model_auto_compact_token_limit = turn.config.model_auto_compact_token_limit;
let output = SpawnAgentHandler
.handle(invocation(
@@ -310,7 +448,186 @@ async fn spawn_agent_returns_agent_id_without_task_name() {
Arc::new(turn),
"spawn_agent",
function_payload(json!({
"message": "inspect this repo"
"message": "inspect this repo",
"agent_type": role_name,
"model": "not-a-real-model",
"reasoning_effort": "low",
"fork_context": true
})),
))
.await
.expect("spawn_agent should succeed");
let (content, _) = expect_text_output(output);
let result: serde_json::Value =
serde_json::from_str(&content).expect("spawn_agent result should be json");
let agent_id = parse_agent_id(
result["agent_id"]
.as_str()
.expect("spawn_agent result should include agent_id"),
);
let snapshot = manager
.get_thread(agent_id)
.await
.expect("spawned agent thread should exist")
.config_snapshot()
.await;
assert_eq!(snapshot.model, expected_model);
assert_eq!(snapshot.model_provider_id, expected_model_provider_id);
assert_eq!(snapshot.active_profile, expected_active_profile);
assert_eq!(snapshot.reasoning_effort, expected_reasoning_effort);
assert_eq!(snapshot.service_tier, expected_service_tier);
assert_eq!(
snapshot.plan_mode_reasoning_effort,
expected_plan_mode_reasoning_effort
);
assert_eq!(snapshot.model_verbosity, expected_model_verbosity);
assert_eq!(snapshot.model_context_window, expected_model_context_window);
assert_eq!(
snapshot.model_auto_compact_token_limit,
expected_model_auto_compact_token_limit
);
}
#[tokio::test]
async fn multi_agent_v2_spawn_fork_turns_ignores_child_model_overrides() {
let (mut session, mut turn) = make_session_and_context().await;
let role_name = install_role_with_model_provider_and_profile_override(&mut turn).await;
let manager = thread_manager();
let root = manager
.start_thread((*turn.config).clone())
.await
.expect("root thread should start");
session.services.agent_control = manager.agent_control();
session.conversation_id = root.thread_id;
let mut config = (*turn.config).clone();
config
.features
.enable(Feature::MultiAgentV2)
.expect("test config should allow feature update");
let turn = TurnContext {
config: Arc::new(config),
..turn
};
let expected_model = turn.model_info.slug.clone();
let expected_model_provider_id = turn.config.model_provider_id.clone();
let expected_active_profile = turn.config.active_profile.clone();
let expected_reasoning_effort = turn.reasoning_effort;
let expected_service_tier = turn.config.service_tier;
let expected_plan_mode_reasoning_effort = turn.config.plan_mode_reasoning_effort;
let expected_model_verbosity = turn.config.model_verbosity;
let expected_model_context_window = turn.config.model_context_window;
let expected_model_auto_compact_token_limit = turn.config.model_auto_compact_token_limit;
let output = SpawnAgentHandlerV2
.handle(invocation(
Arc::new(session),
Arc::new(turn),
"spawn_agent",
function_payload(json!({
"message": "inspect this repo",
"agent_type": role_name,
"model": "not-a-real-model",
"reasoning_effort": "low",
"fork_turns": "all",
"task_name": "fork_context_v2"
})),
))
.await
.expect("spawn_agent should succeed");
let (content, _) = expect_text_output(output);
let result: serde_json::Value =
serde_json::from_str(&content).expect("spawn_agent result should be json");
assert_eq!(result["task_name"], "/root/fork_context_v2");
let agent_id = manager
.captured_ops()
.into_iter()
.map(|(thread_id, _)| thread_id)
.find(|thread_id| *thread_id != root.thread_id)
.expect("spawned agent should receive an op");
let snapshot = manager
.get_thread(agent_id)
.await
.expect("spawned agent thread should exist")
.config_snapshot()
.await;
assert_eq!(snapshot.model, expected_model);
assert_eq!(snapshot.model_provider_id, expected_model_provider_id);
assert_eq!(snapshot.active_profile, expected_active_profile);
assert_eq!(snapshot.reasoning_effort, expected_reasoning_effort);
assert_eq!(snapshot.service_tier, expected_service_tier);
assert_eq!(
snapshot.plan_mode_reasoning_effort,
expected_plan_mode_reasoning_effort
);
assert_eq!(snapshot.model_verbosity, expected_model_verbosity);
assert_eq!(snapshot.model_context_window, expected_model_context_window);
assert_eq!(
snapshot.model_auto_compact_token_limit,
expected_model_auto_compact_token_limit
);
}
#[tokio::test]
async fn spawn_agent_watchdog_role_returns_handle_with_role_defaults() {
let (mut session, mut turn) = make_session_and_context().await;
let manager = thread_manager();
session.services.agent_control = manager.agent_control();
let mut config = (*turn.config).clone();
config
.features
.enable(Feature::AgentWatchdog)
.expect("test config should allow feature update");
turn.config = Arc::new(config);
let output = SpawnAgentHandler
.handle(invocation(
Arc::new(session),
Arc::new(turn),
"spawn_agent",
function_payload(json!({
"message": "check in periodically",
"agent_type": "watchdog"
})),
))
.await
.expect("spawn_agent should succeed");
let (content, success) = expect_text_output(output);
let result: serde_json::Value =
serde_json::from_str(&content).expect("spawn_agent result should be json");
let agent_id = parse_agent_id(
result["agent_id"]
.as_str()
.expect("spawn_agent result should include agent_id"),
);
assert_eq!(success, Some(true));
assert_eq!(
manager.agent_control().get_status(agent_id).await,
AgentStatus::PendingInit
);
}
#[tokio::test]
async fn spawn_agent_returns_agent_id_without_task_name() {
let (mut session, turn) = make_session_and_context().await;
let manager = thread_manager();
let root = manager
.start_thread((*turn.config).clone())
.await
.expect("root thread should start");
session.services.agent_control = manager.agent_control();
session.conversation_id = root.thread_id;
let output = SpawnAgentHandler
.handle(invocation(
Arc::new(session),
Arc::new(turn),
"spawn_agent",
function_payload(json!({
"message": "inspect this repo",
"fork_context": false
})),
))
.await
@@ -320,7 +637,7 @@ async fn spawn_agent_returns_agent_id_without_task_name() {
serde_json::from_str(&content).expect("spawn_agent result should be json");
assert!(result["agent_id"].is_string());
assert!(result.get("task_name").is_none());
assert_eq!(result["task_name"], serde_json::Value::Null);
assert!(result.get("nickname").is_some());
assert_eq!(success, Some(true));
}
@@ -397,22 +714,175 @@ async fn multi_agent_v2_spawn_rejects_legacy_items_field() {
#[tokio::test]
async fn spawn_agent_errors_when_manager_dropped() {
let (session, turn) = make_session_and_context().await;
let (session, turn, rx) = make_session_and_context_with_rx().await;
let invocation = invocation(
Arc::new(session),
Arc::new(turn),
session.clone(),
turn.clone(),
"spawn_agent",
function_payload(json!({"message": "hello"})),
function_payload(json!({"message": "hello", "fork_context": false})),
);
let Err(err) = SpawnAgentHandler.handle(invocation).await else {
panic!("spawn should fail without a manager");
};
let spawn_end_event = wait_for_collab_spawn_end_event(&rx).await;
assert_eq!(spawn_end_event.call_id, "call-1");
assert_eq!(spawn_end_event.sender_thread_id, session.conversation_id);
assert_eq!(spawn_end_event.new_thread_id, None);
assert_eq!(spawn_end_event.new_agent_nickname, None);
assert_eq!(spawn_end_event.new_agent_role, None);
assert_eq!(spawn_end_event.prompt, "hello");
assert_eq!(spawn_end_event.model, "");
assert_eq!(spawn_end_event.reasoning_effort, ReasoningEffort::default());
assert!(matches!(
spawn_end_event.status,
AgentStatus::Errored(ref message) if message.contains("thread manager dropped")
));
assert_eq!(
err,
FunctionCallError::RespondToModel("collab manager unavailable".to_string())
);
}
#[tokio::test]
async fn multi_agent_v2_spawn_agent_errors_when_manager_dropped() {
let (session, mut turn, rx) = make_session_and_context_with_rx().await;
let turn_context = Arc::get_mut(&mut turn).expect("single turn context ref");
let mut config = (*turn_context.config).clone();
config
.features
.enable(Feature::MultiAgentV2)
.expect("test config should allow feature update");
turn_context.config = Arc::new(config);
let invocation = invocation(
session.clone(),
turn.clone(),
"spawn_agent",
function_payload(json!({
"message": "inspect this repo",
"task_name": "worker"
})),
);
let Err(err) = SpawnAgentHandlerV2.handle(invocation).await else {
panic!("spawn should fail without a manager");
};
let spawn_end_event = wait_for_collab_spawn_end_event(&rx).await;
assert_eq!(spawn_end_event.call_id, "call-1");
assert_eq!(spawn_end_event.sender_thread_id, session.conversation_id);
assert_eq!(spawn_end_event.new_thread_id, None);
assert_eq!(spawn_end_event.new_agent_nickname, None);
assert_eq!(spawn_end_event.new_agent_role, None);
assert_eq!(spawn_end_event.prompt, "inspect this repo");
assert_eq!(spawn_end_event.model, "");
assert_eq!(spawn_end_event.reasoning_effort, ReasoningEffort::default());
assert!(matches!(
spawn_end_event.status,
AgentStatus::Errored(ref message) if message.contains("thread manager dropped")
));
assert_eq!(
err,
FunctionCallError::RespondToModel("collab manager unavailable".to_string())
);
}
#[tokio::test]
async fn spawn_retry_preempted_event_omits_thread_identity() {
let (session, turn, rx) = make_session_and_context_with_rx().await;
send_collab_agent_spawn_retry_preempted_event(
session.as_ref(),
turn.as_ref(),
"call-1".to_string(),
"inspect this repo".to_string(),
"gpt-5.4-mini".to_string(),
ReasoningEffort::Medium,
AgentStatus::PendingInit,
)
.await;
let spawn_end_event = wait_for_collab_spawn_end_event(&rx).await;
assert_eq!(spawn_end_event.call_id, "call-1");
assert_eq!(spawn_end_event.sender_thread_id, session.conversation_id);
assert_eq!(spawn_end_event.new_thread_id, None);
assert_eq!(spawn_end_event.new_agent_nickname, None);
assert_eq!(spawn_end_event.new_agent_role, None);
assert_eq!(spawn_end_event.prompt, "inspect this repo");
assert_eq!(spawn_end_event.model, "gpt-5.4-mini");
assert_eq!(spawn_end_event.reasoning_effort, ReasoningEffort::Medium);
assert_eq!(spawn_end_event.status, AgentStatus::PendingInit);
}
#[tokio::test]
async fn spawn_async_quota_probe_accepts_running_child() {
let decision = probe_spawn_attempt_for_async_quota_exhaustion(
AgentStatus::Running,
ThreadId::default(),
&crate::agent::control::AgentControl::default(),
)
.await;
assert!(matches!(
decision,
SpawnAttemptRetryDecision::Accept(AgentStatus::Running)
));
}
#[tokio::test]
async fn close_quota_exhausted_spawn_attempt_accepts_child_that_started_running() {
let (_session, turn) = make_session_and_context().await;
let manager = thread_manager();
let thread = manager
.start_thread((*turn.config).clone())
.await
.expect("child thread should start");
let active_turn = thread.thread.codex.session.new_default_turn().await;
thread
.thread
.codex
.session
.spawn_task(
Arc::clone(&active_turn),
vec![UserInput::Text {
text: "working".to_string(),
text_elements: Vec::new(),
}],
NeverEndingTask,
)
.await;
timeout(Duration::from_secs(1), async {
loop {
if manager.agent_control().get_status(thread.thread_id).await == AgentStatus::Running {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("child should reach running");
let decision = close_quota_exhausted_spawn_attempt(
&manager.agent_control(),
thread.thread_id,
AgentStatus::PendingInit,
)
.await;
assert!(matches!(
decision,
SpawnAttemptRetryDecision::Accept(AgentStatus::Running)
));
assert_eq!(
manager.agent_control().get_status(thread.thread_id).await,
AgentStatus::Running
);
let _ = thread
.thread
.submit(Op::Shutdown {})
.await
.expect("shutdown should submit");
}
#[tokio::test]
async fn multi_agent_v2_spawn_returns_path_and_send_message_accepts_relative_path() {
#[derive(Debug, Deserialize)]
@@ -1647,7 +2117,12 @@ async fn spawn_agent_reapplies_runtime_sandbox_after_role_config() {
let (mut session, mut turn) = make_session_and_context().await;
let manager = thread_manager();
let root = manager
.start_thread((*turn.config).clone())
.await
.expect("root thread should start");
session.services.agent_control = manager.agent_control();
session.conversation_id = root.thread_id;
let expected_sandbox = pick_allowed_sandbox_policy(
&turn.config.permissions.sandbox_policy,
turn.config.permissions.sandbox_policy.get().clone(),
@@ -1675,7 +2150,8 @@ async fn spawn_agent_reapplies_runtime_sandbox_after_role_config() {
"spawn_agent",
function_payload(json!({
"message": "await this command",
"agent_type": "explorer"
"agent_type": "explorer",
"fork_context": false
})),
);
let output = SpawnAgentHandler
@@ -1735,7 +2211,7 @@ async fn spawn_agent_rejects_when_depth_limit_exceeded() {
Arc::new(session),
Arc::new(turn),
"spawn_agent",
function_payload(json!({"message": "hello"})),
function_payload(json!({"message": "hello", "fork_context": false})),
);
let Err(err) = SpawnAgentHandler.handle(invocation).await else {
panic!("spawn should fail when depth limit exceeded");
@@ -1758,13 +2234,18 @@ async fn spawn_agent_allows_depth_up_to_configured_max_depth() {
let (mut session, mut turn) = make_session_and_context().await;
let manager = thread_manager();
let root = manager
.start_thread((*turn.config).clone())
.await
.expect("root thread should start");
session.services.agent_control = manager.agent_control();
session.conversation_id = root.thread_id;
let mut config = (*turn.config).clone();
config.agent_max_depth = DEFAULT_AGENT_MAX_DEPTH + 1;
turn.config = Arc::new(config);
turn.session_source = SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
parent_thread_id: session.conversation_id,
parent_thread_id: root.thread_id,
depth: DEFAULT_AGENT_MAX_DEPTH,
agent_path: None,
agent_nickname: None,
@@ -1775,7 +2256,7 @@ async fn spawn_agent_allows_depth_up_to_configured_max_depth() {
Arc::new(session),
Arc::new(turn),
"spawn_agent",
function_payload(json!({"message": "hello"})),
function_payload(json!({"message": "hello", "fork_context": false})),
);
let output = SpawnAgentHandler
.handle(invocation)
@@ -1851,7 +2332,10 @@ async fn send_input_rejects_invalid_id() {
let FunctionCallError::RespondToModel(msg) = err else {
panic!("expected respond-to-model error");
};
assert!(msg.starts_with("invalid agent id not-a-uuid:"));
assert_eq!(
msg,
"agent_name must use only lowercase letters, digits, and underscores"
);
}
#[tokio::test]
@@ -2188,7 +2672,7 @@ async fn wait_agent_rejects_invalid_target() {
let FunctionCallError::RespondToModel(msg) = err else {
panic!("expected respond-to-model error");
};
assert!(msg.starts_with("invalid agent id invalid:"));
assert!(msg.contains("invalid"));
}
#[tokio::test]
@@ -2205,7 +2689,7 @@ async fn wait_agent_rejects_empty_targets() {
};
assert_eq!(
err,
FunctionCallError::RespondToModel("agent ids must be non-empty".to_string())
FunctionCallError::RespondToModel("agent targets must be non-empty".to_string())
);
}
@@ -2962,6 +3446,116 @@ async fn close_agent_submits_shutdown_and_returns_previous_status() {
assert_eq!(status_after, AgentStatus::NotFound);
}
#[tokio::test]
async fn watchdog_self_close_rejects_non_watchdog_thread() {
let (mut session, turn) = make_session_and_context().await;
let manager = thread_manager();
let agent_control = manager.agent_control();
let thread = manager
.start_thread(turn.config.as_ref().clone())
.await
.expect("thread should start");
session.services.agent_control = agent_control.clone();
session.conversation_id = thread.thread_id;
let err = WatchdogSelfCloseHandler
.handle(invocation(
Arc::new(session),
Arc::new(turn),
"watchdog_self_close",
function_payload(json!({})),
))
.await
.expect_err("non-watchdog threads should be rejected");
assert_eq!(
err,
FunctionCallError::RespondToModel(
"watchdog_self_close is only available in watchdog check-in threads.".to_string(),
)
);
}
#[tokio::test]
async fn watchdog_self_close_closes_watchdog_helper_and_returns_previous_status() {
let (mut session, turn) = make_session_and_context().await;
let manager = thread_manager();
let agent_control = manager.agent_control();
session.services.agent_control = agent_control.clone();
let helper_thread_id =
attach_watchdog_helper_for_tests(&manager, &agent_control, turn.config.as_ref()).await;
session.conversation_id = helper_thread_id;
let status_before = agent_control.get_status(helper_thread_id).await;
let output = WatchdogSelfCloseHandler
.handle(invocation(
Arc::new(session),
Arc::new(turn),
"watchdog_self_close",
function_payload(json!({})),
))
.await
.expect("watchdog helper should be allowed to self-close");
let (content, success) = expect_text_output(output);
let result: WatchdogSelfCloseResult =
serde_json::from_str(&content).expect("watchdog self-close result should be json");
assert_eq!(
result,
WatchdogSelfCloseResult {
previous_status: status_before,
}
);
assert_eq!(success, Some(true));
assert_eq!(
agent_control.get_status(helper_thread_id).await,
AgentStatus::NotFound
);
}
#[tokio::test]
async fn multi_agent_v2_watchdog_self_close_closes_watchdog_helper_and_returns_previous_status() {
let (mut session, mut turn) = make_session_and_context().await;
let manager = thread_manager();
let agent_control = manager.agent_control();
session.services.agent_control = agent_control.clone();
let mut config = turn.config.as_ref().clone();
config
.features
.enable(Feature::MultiAgentV2)
.expect("test config should allow feature update");
let helper_thread_id =
attach_watchdog_helper_for_tests(&manager, &agent_control, &config).await;
session.conversation_id = helper_thread_id;
turn.config = Arc::new(config);
let status_before = agent_control.get_status(helper_thread_id).await;
let output = WatchdogSelfCloseHandlerV2
.handle(invocation(
Arc::new(session),
Arc::new(turn),
"watchdog_self_close",
function_payload(json!({})),
))
.await
.expect("watchdog helper should be allowed to self-close");
let (content, success) = expect_text_output(output);
let result: WatchdogSelfCloseResult =
serde_json::from_str(&content).expect("watchdog self-close result should be json");
assert_eq!(
result,
WatchdogSelfCloseResult {
previous_status: status_before,
}
);
assert_eq!(success, Some(true));
assert_eq!(
agent_control.get_status(helper_thread_id).await,
AgentStatus::NotFound
);
}
#[tokio::test]
async fn tool_handlers_cascade_close_and_resume_and_keep_explicitly_closed_subtrees_closed() {
let (_session, turn) = make_session_and_context().await;
@@ -3204,6 +3798,7 @@ async fn build_agent_spawn_config_uses_turn_context_values() {
let config = build_agent_spawn_config(&base_instructions, &turn).expect("spawn config");
let mut expected = (*turn.config).clone();
expected.features = config.features.clone();
expected.base_instructions = Some(base_instructions.text);
expected.model = Some(turn.model_info.slug.clone());
expected.model_provider = turn.provider.clone();
@@ -17,7 +17,6 @@ use codex_protocol::models::ResponseInputItem;
use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::protocol::CollabAgentInteractionBeginEvent;
use codex_protocol::protocol::CollabAgentInteractionEndEvent;
use codex_protocol::protocol::CollabAgentSpawnBeginEvent;
use codex_protocol::protocol::CollabAgentSpawnEndEvent;
use codex_protocol::protocol::CollabCloseBeginEvent;
use codex_protocol::protocol::CollabCloseEndEvent;
@@ -34,6 +33,7 @@ pub(crate) use list_agents::Handler as ListAgentsHandler;
pub(crate) use send_message::Handler as SendMessageHandler;
pub(crate) use spawn::Handler as SpawnAgentHandler;
pub(crate) use wait::Handler as WaitAgentHandler;
pub(crate) use watchdog_self_close::Handler as WatchdogSelfCloseHandlerV2;
mod assign_task;
mod close_agent;
@@ -42,3 +42,4 @@ mod message_tool;
mod send_message;
mod spawn;
pub(crate) mod wait;
mod watchdog_self_close;
@@ -31,7 +31,7 @@ impl ToolHandler for Handler {
let agents = session
.services
.agent_control
.list_agents(&turn.session_source, args.path_prefix.as_deref())
.list_agents_by_path(&turn.session_source, args.path_prefix.as_deref())
.await
.map_err(collab_spawn_error)?;
@@ -5,6 +5,7 @@ use crate::agent::control::render_input_preview;
use crate::agent::next_thread_spawn_depth;
use crate::agent::role::DEFAULT_ROLE_NAME;
use crate::agent::role::apply_role_to_config;
use crate::agent::role::default_fork_context_for_role;
use codex_protocol::AgentPath;
use codex_protocol::protocol::InterAgentCommunication;
use codex_protocol::protocol::Op;
@@ -33,12 +34,13 @@ impl ToolHandler for Handler {
} = invocation;
let arguments = function_arguments(payload)?;
let args: SpawnAgentArgs = parse_arguments(&arguments)?;
let fork_mode = args.fork_mode()?;
let role_name = args
.agent_type
.as_deref()
.map(str::trim)
.filter(|role| !role.is_empty());
let fork_context = default_fork_context_for_role(&turn.config, role_name);
let fork_mode = args.fork_mode(fork_context)?;
let initial_operation = parse_collab_input(Some(args.message), /*items*/ None)?;
let prompt = render_input_preview(&initial_operation);
@@ -51,34 +53,8 @@ impl ToolHandler for Handler {
"Agent depth limit reached. Solve the task yourself.".to_string(),
));
}
session
.send_event(
&turn,
CollabAgentSpawnBeginEvent {
call_id: call_id.clone(),
sender_thread_id: session.conversation_id,
prompt: prompt.clone(),
model: args.model.clone().unwrap_or_default(),
reasoning_effort: args.reasoning_effort.unwrap_or_default(),
}
.into(),
)
.await;
let mut config =
let config =
build_agent_spawn_config(&session.get_base_instructions().await, turn.as_ref())?;
apply_requested_spawn_agent_model_overrides(
&session,
turn.as_ref(),
&mut config,
args.model.as_deref(),
args.reasoning_effort,
)
.await?;
apply_role_to_config(&mut config, role_name)
.await
.map_err(FunctionCallError::RespondToModel)?;
apply_spawn_agent_runtime_overrides(&mut config, turn.as_ref())?;
apply_spawn_agent_overrides(&mut config, child_depth);
let spawn_source = thread_spawn_source(
session.conversation_id,
@@ -87,47 +63,153 @@ impl ToolHandler for Handler {
role_name,
Some(args.task_name.clone()),
)?;
let result = session
.services
.agent_control
.spawn_agent_with_metadata(
config,
match (spawn_source.get_agent_path(), initial_operation) {
(Some(recipient), Op::UserInput { items, .. })
if items
.iter()
.all(|item| matches!(item, UserInput::Text { .. })) =>
{
Op::InterAgentCommunication {
communication: InterAgentCommunication::new(
turn.session_source
.get_agent_path()
.unwrap_or_else(AgentPath::root),
recipient,
Vec::new(),
prompt.clone(),
/*trigger_turn*/ true,
),
}
}
(_, initial_operation) => initial_operation,
},
Some(spawn_source),
SpawnAgentOptions {
fork_parent_spawn_call_id: fork_mode.as_ref().map(|_| call_id.clone()),
fork_mode,
},
)
.await
.map_err(collab_spawn_error);
let (new_thread_id, new_agent_metadata, status) = match &result {
Ok(spawned_agent) => (
Some(spawned_agent.thread_id),
Some(spawned_agent.metadata.clone()),
spawned_agent.status.clone(),
),
Err(_) => (None, None, AgentStatus::NotFound),
let initial_agent_op = match (spawn_source.get_agent_path(), initial_operation) {
(Some(recipient), Op::UserInput { items, .. })
if items
.iter()
.all(|item| matches!(item, UserInput::Text { .. })) =>
{
Op::InterAgentCommunication {
communication: InterAgentCommunication::new(
turn.session_source
.get_agent_path()
.unwrap_or_else(AgentPath::root),
recipient,
Vec::new(),
prompt.clone(),
/*trigger_turn*/ true,
),
}
}
(_, initial_operation) => initial_operation,
};
let mut candidates_to_try = collect_spawn_agent_model_candidates(
args.model_fallback_list.as_ref(),
args.model.as_deref(),
args.reasoning_effort,
);
if candidates_to_try.is_empty() {
candidates_to_try.push(SpawnAgentModelCandidate {
model: None,
reasoning_effort: None,
});
}
let mut spawn_result = None;
for (idx, candidate) in candidates_to_try.iter().enumerate() {
let attempt_call_id = spawn_attempt_event_call_id(&call_id, idx);
let candidate_model = candidate.model.clone().unwrap_or_default();
let candidate_reasoning_effort = candidate.reasoning_effort.unwrap_or_default();
send_collab_agent_spawn_begin_event(
&session,
&turn,
attempt_call_id.clone(),
prompt.clone(),
candidate_model.clone(),
candidate_reasoning_effort,
)
.await;
let mut candidate_config = config.clone();
if fork_mode.is_none() {
apply_requested_spawn_agent_model_overrides(
&session,
turn.as_ref(),
&mut candidate_config,
candidate.model.as_deref(),
candidate.reasoning_effort,
)
.await?;
}
apply_role_to_config(&mut candidate_config, role_name)
.await
.map_err(FunctionCallError::RespondToModel)?;
if fork_mode.is_some() {
restore_forked_spawn_agent_model_config(&mut candidate_config, turn.as_ref());
}
apply_spawn_agent_runtime_overrides(&mut candidate_config, turn.as_ref())?;
apply_spawn_agent_overrides(&mut candidate_config, child_depth);
let attempt_result = session
.services
.agent_control
.spawn_agent_with_metadata(
candidate_config,
initial_agent_op.clone(),
Some(spawn_source.clone()),
SpawnAgentOptions {
fork_parent_spawn_call_id: fork_mode.as_ref().map(|_| call_id.clone()),
fork_mode: fork_mode.clone(),
},
)
.await;
match attempt_result {
Ok(spawned_agent) => {
let status = if idx + 1 < candidates_to_try.len() {
match probe_spawn_attempt_for_async_quota_exhaustion(
spawned_agent.status.clone(),
spawned_agent.thread_id,
&session.services.agent_control,
)
.await
{
SpawnAttemptRetryDecision::Accept(status) => status,
SpawnAttemptRetryDecision::Retry(retry_status) => {
match close_quota_exhausted_spawn_attempt(
&session.services.agent_control,
spawned_agent.thread_id,
retry_status,
)
.await
{
SpawnAttemptRetryDecision::Accept(status) => status,
SpawnAttemptRetryDecision::Retry(status) => {
send_collab_agent_spawn_retry_preempted_event(
&session,
&turn,
attempt_call_id,
prompt.clone(),
candidate_model,
candidate_reasoning_effort,
status,
)
.await;
continue;
}
}
}
}
} else {
spawned_agent.status.clone()
};
spawn_result = Some((spawned_agent, status, attempt_call_id));
break;
}
Err(err) => {
send_collab_agent_spawn_error_event(
&session,
&turn,
attempt_call_id,
prompt.clone(),
candidate_model,
candidate_reasoning_effort,
&err,
)
.await;
if spawn_should_retry_on_quota_exhaustion(&err)
&& idx + 1 < candidates_to_try.len()
{
continue;
}
return Err(collab_spawn_error(err));
}
}
}
let Some((spawned_agent, status, spawn_event_call_id)) = spawn_result else {
return Err(FunctionCallError::RespondToModel(
"No spawn attempts were executed".to_string(),
));
};
let new_thread_id = Some(spawned_agent.thread_id);
let new_agent_metadata = Some(spawned_agent.metadata.clone());
let agent_snapshot = match new_thread_id {
Some(thread_id) => {
session
@@ -165,7 +247,7 @@ impl ToolHandler for Handler {
.send_event(
&turn,
CollabAgentSpawnEndEvent {
call_id,
call_id: spawn_event_call_id,
sender_thread_id: session.conversation_id,
new_thread_id,
new_agent_nickname,
@@ -178,7 +260,6 @@ impl ToolHandler for Handler {
.into(),
)
.await;
let _ = result?;
let role_tag = role_name.unwrap_or(DEFAULT_ROLE_NAME);
turn.session_telemetry.counter(
"codex.multi_agent.spawn",
@@ -206,13 +287,17 @@ struct SpawnAgentArgs {
task_name: String,
agent_type: Option<String>,
model: Option<String>,
model_fallback_list: Option<Vec<SpawnAgentModelFallbackCandidate>>,
reasoning_effort: Option<ReasoningEffort>,
fork_turns: Option<String>,
fork_context: Option<bool>,
}
impl SpawnAgentArgs {
fn fork_mode(&self) -> Result<Option<SpawnAgentForkMode>, FunctionCallError> {
fn fork_mode(
&self,
default_fork_context: bool,
) -> Result<Option<SpawnAgentForkMode>, FunctionCallError> {
if self.fork_context.is_some() {
return Err(FunctionCallError::RespondToModel(
"fork_context is not supported in MultiAgentV2; use fork_turns instead".to_string(),
@@ -225,7 +310,7 @@ impl SpawnAgentArgs {
.map(str::trim)
.filter(|fork_turns| !fork_turns.is_empty())
else {
return Ok(None);
return Ok(default_fork_context.then_some(SpawnAgentForkMode::FullHistory));
};
if fork_turns.eq_ignore_ascii_case("none") {
@@ -0,0 +1,150 @@
use super::*;
pub(crate) struct Handler;
#[async_trait]
impl ToolHandler for Handler {
type Output = WatchdogSelfCloseResult;
fn kind(&self) -> ToolKind {
ToolKind::Function
}
fn matches_kind(&self, payload: &ToolPayload) -> bool {
matches!(payload, ToolPayload::Function { .. })
}
async fn handle(&self, invocation: ToolInvocation) -> Result<Self::Output, FunctionCallError> {
let ToolInvocation {
session,
turn,
payload,
call_id,
..
} = invocation;
let arguments = function_arguments(payload)?;
let _args: WatchdogSelfCloseArgs = parse_arguments(&arguments)?;
let helper_thread_id = session.conversation_id;
if session
.services
.agent_control
.watchdog_owner_for_active_helper(helper_thread_id)
.await
.is_none()
{
return Err(FunctionCallError::RespondToModel(
"watchdog_self_close is only available in watchdog check-in threads.".to_string(),
));
};
let receiver_agent = session
.services
.agent_control
.get_agent_metadata(helper_thread_id)
.unwrap_or_default();
session
.send_event(
&turn,
CollabCloseBeginEvent {
call_id: call_id.clone(),
sender_thread_id: helper_thread_id,
receiver_thread_id: helper_thread_id,
}
.into(),
)
.await;
let status = match session
.services
.agent_control
.subscribe_status(helper_thread_id)
.await
{
Ok(mut status_rx) => status_rx.borrow_and_update().clone(),
Err(err) => {
let status = session
.services
.agent_control
.get_status(helper_thread_id)
.await;
session
.send_event(
&turn,
CollabCloseEndEvent {
call_id: call_id.clone(),
sender_thread_id: helper_thread_id,
receiver_thread_id: helper_thread_id,
receiver_agent_nickname: receiver_agent.agent_nickname.clone(),
receiver_agent_role: receiver_agent.agent_role.clone(),
status,
}
.into(),
)
.await;
return Err(collab_agent_error(helper_thread_id, err));
}
};
let result = session
.services
.agent_control
.close_agent(helper_thread_id)
.await
.map_err(|err| collab_agent_error(helper_thread_id, err))
.map(|_| ());
let receiver_agent = session
.services
.agent_control
.get_agent_metadata(helper_thread_id)
.unwrap_or_default();
session
.send_event(
&turn,
CollabCloseEndEvent {
call_id,
sender_thread_id: helper_thread_id,
receiver_thread_id: helper_thread_id,
receiver_agent_nickname: receiver_agent.agent_nickname,
receiver_agent_role: receiver_agent.agent_role,
status: status.clone(),
}
.into(),
)
.await;
result?;
Ok(WatchdogSelfCloseResult {
previous_status: status,
})
}
}
#[derive(Debug, Deserialize)]
struct WatchdogSelfCloseArgs {}
#[derive(Debug, Serialize)]
pub(crate) struct WatchdogSelfCloseResult {
previous_status: AgentStatus,
}
impl ToolOutput for WatchdogSelfCloseResult {
fn log_preview(&self) -> String {
tool_output_json_text(self, "watchdog_self_close")
}
fn success_for_logging(&self) -> bool {
true
}
fn to_response_item(&self, call_id: &str, payload: &ToolPayload) -> ResponseInputItem {
tool_output_response_item(call_id, payload, self, Some(true), "watchdog_self_close")
}
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
tool_output_code_mode_result(self, "watchdog_self_close")
}
}
+5
View File
@@ -739,6 +739,11 @@ impl JsReplManager {
fn summarize_tool_call_response(response: &ResponseInputItem) -> JsReplToolCallResponseSummary {
match response {
ResponseInputItem::Message { content, .. } => Self::summarize_message_payload(content),
ResponseInputItem::FunctionCall { arguments, .. } => Self::summarize_text_payload(
Some("function_call"),
JsReplToolCallPayloadKind::FunctionText,
arguments,
),
ResponseInputItem::FunctionCallOutput { output, .. } => {
let payload_kind = if output.content_items().is_some() {
JsReplToolCallPayloadKind::FunctionContentItems
+3 -1
View File
@@ -18,7 +18,6 @@ use codex_tools::WaitAgentTimeoutOptions;
use codex_tools::build_tool_registry_plan;
use std::collections::HashMap;
use std::sync::Arc;
pub(crate) fn tool_user_shell_type(user_shell: &Shell) -> ToolUserShellType {
match user_shell.shell_type {
ShellType::Zsh => ToolUserShellType::Zsh,
@@ -56,10 +55,13 @@ pub(crate) fn build_specs_with_discoverable_tools(
use crate::tools::handlers::UnifiedExecHandler;
use crate::tools::handlers::ViewImageHandler;
use crate::tools::handlers::multi_agents::CloseAgentHandler;
use crate::tools::handlers::multi_agents::CompactParentContextHandler;
use crate::tools::handlers::multi_agents::ListAgentsHandler;
use crate::tools::handlers::multi_agents::ResumeAgentHandler;
use crate::tools::handlers::multi_agents::SendInputHandler;
use crate::tools::handlers::multi_agents::SpawnAgentHandler;
use crate::tools::handlers::multi_agents::WaitAgentHandler;
use crate::tools::handlers::multi_agents::WatchdogSelfCloseHandler;
use crate::tools::handlers::multi_agents_v2::AssignTaskHandler as AssignTaskHandlerV2;
use crate::tools::handlers::multi_agents_v2::CloseAgentHandler as CloseAgentHandlerV2;
use crate::tools::handlers::multi_agents_v2::ListAgentsHandler as ListAgentsHandlerV2;
+718 -5
View File
@@ -20,6 +20,7 @@ use codex_protocol::protocol::SessionSource;
use codex_tools::ConfiguredToolSpec;
use codex_tools::DiscoverableTool;
use codex_tools::JsonSchema;
use codex_tools::ResponsesApiNamespaceTool;
use codex_tools::ResponsesApiTool;
use codex_tools::ShellCommandBackendConfig;
use codex_tools::TOOL_SEARCH_TOOL_NAME;
@@ -153,10 +154,56 @@ fn shell_tool_name(config: &ToolsConfig) -> Option<&'static str> {
}
fn find_tool<'a>(tools: &'a [ConfiguredToolSpec], expected_name: &str) -> &'a ConfiguredToolSpec {
tools
if let Some(tool) = tools.iter().find(|tool| tool.name() == expected_name) {
return tool;
}
for tool in tools {
let ToolSpec::Namespace(namespace) = &tool.spec else {
continue;
};
if let Some(tool) = namespace.tools.iter().find_map(|tool| match tool {
ResponsesApiNamespaceTool::Function(tool) if tool.name == expected_name => {
Some(tool.clone())
}
_ => None,
}) {
return Box::leak(Box::new(ConfiguredToolSpec::new(
ToolSpec::Function(tool),
/*supports_parallel_tool_calls*/ false,
)));
}
}
panic!("expected tool {expected_name}")
}
fn find_namespaced_tool(
tools: &[ConfiguredToolSpec],
namespace_name: &str,
expected_name: &str,
) -> ConfiguredToolSpec {
let namespace = tools
.iter()
.find(|tool| tool.name() == expected_name)
.unwrap_or_else(|| panic!("expected tool {expected_name}"))
.find_map(|tool| match &tool.spec {
ToolSpec::Namespace(namespace) if namespace.name == namespace_name => Some(namespace),
_ => None,
})
.unwrap_or_else(|| panic!("expected namespace {namespace_name}"));
let tool = namespace
.tools
.iter()
.find_map(|tool| match tool {
ResponsesApiNamespaceTool::Function(tool) if tool.name == expected_name => {
Some(tool.clone())
}
_ => None,
})
.unwrap_or_else(|| panic!("expected tool {expected_name} in {namespace_name}"));
ConfiguredToolSpec::new(
ToolSpec::Function(tool),
/*supports_parallel_tool_calls*/ false,
)
}
fn model_info_from_models_json(slug: &str) -> ModelInfo {
@@ -211,6 +258,654 @@ fn model_provided_unified_exec_is_blocked_for_windows_sandboxed_policies() {
assert_eq!(config.shell_type, expected_shell_type);
}
#[test]
fn test_full_toolset_specs_for_gpt5_codex_unified_exec_web_search() {
let model_info = model_info_from_models_json("gpt-5-codex");
let mut features = Features::with_defaults();
features.enable(Feature::UnifiedExec);
let available_models = Vec::new();
let config = ToolsConfig::new(&ToolsConfigParams {
model_info: &model_info,
available_models: &available_models,
features: &features,
web_search_mode: Some(WebSearchMode::Live),
session_source: SessionSource::Cli,
sandbox_policy: &SandboxPolicy::DangerFullAccess,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
});
let (tools, _) = build_specs(
&config,
/*mcp_tools*/ None,
/*app_tools*/ None,
&[],
)
.build();
// Build actual map name -> spec
use std::collections::BTreeMap;
use std::collections::HashSet;
let mut actual: BTreeMap<String, ToolSpec> = BTreeMap::from([]);
let mut duplicate_names = Vec::new();
for t in &tools {
let name = t.name().to_string();
if actual.insert(name.clone(), t.spec.clone()).is_some() {
duplicate_names.push(name);
}
}
assert!(
duplicate_names.is_empty(),
"duplicate tool entries detected: {duplicate_names:?}"
);
// Build expected from the same helpers used by the builder.
let mut expected: BTreeMap<String, ToolSpec> = BTreeMap::from([]);
for spec in [
create_exec_command_tool(CommandToolOptions {
allow_login_shell: true,
exec_permission_approvals_enabled: false,
}),
create_write_stdin_tool(),
PLAN_TOOL.clone(),
request_user_input_tool_spec(/*default_mode_request_user_input*/ false),
create_apply_patch_freeform_tool(),
ToolSpec::WebSearch {
external_web_access: Some(true),
filters: None,
user_location: None,
search_context_size: None,
search_content_types: None,
},
create_view_image_tool(ViewImageToolOptions {
can_request_original_image_detail: config.can_request_original_image_detail,
}),
] {
expected.insert(spec.name().to_string(), spec);
}
let mut collab_specs = if config.multi_agent_v2 {
vec![
create_spawn_agent_tool_v2(spawn_agent_tool_options(&config)),
create_send_message_tool(),
create_wait_agent_tool_v2(wait_agent_timeout_options()),
create_close_agent_tool_v2(),
create_list_agents_tool_v2(),
]
} else {
let mut collab_specs = vec![
create_spawn_agent_tool_v1(spawn_agent_tool_options(&config)),
create_send_input_tool_v1(),
create_resume_agent_tool(),
create_wait_agent_tool_v1(wait_agent_timeout_options()),
create_close_agent_tool_v1(),
];
if config.agent_watchdog {
collab_specs.push(create_list_agents_tool(config.agent_watchdog));
}
collab_specs
};
for spec in collab_specs.split_off(0) {
expected.insert(spec.name().to_string(), spec);
}
if config.agent_watchdog {
let spec = create_watchdog_tools_namespace(vec![
create_compact_parent_context_tool(),
create_watchdog_self_close_tool(),
]);
expected.insert(spec.name().to_string(), spec);
}
if config.exec_permission_approvals_enabled {
let spec = create_request_permissions_tool(request_permissions_tool_description());
expected.insert(spec.name().to_string(), spec);
}
// Exact name set match — this is the only test allowed to fail when tools change.
let actual_names: HashSet<_> = actual.keys().cloned().collect();
let expected_names: HashSet<_> = expected.keys().cloned().collect();
assert_eq!(actual_names, expected_names, "tool name set mismatch");
// Compare specs ignoring human-readable descriptions.
for name in expected.keys() {
let mut a = actual.get(name).expect("present").clone();
let mut e = expected.get(name).expect("present").clone();
strip_descriptions_tool(&mut a);
strip_descriptions_tool(&mut e);
assert_eq!(a, e, "spec mismatch for {name}");
}
}
#[test]
fn test_build_specs_collab_tools_enabled() {
let config = test_config();
let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config);
let mut features = Features::with_defaults();
features.enable(Feature::Collab);
let available_models = Vec::new();
let tools_config = ToolsConfig::new(&ToolsConfigParams {
model_info: &model_info,
available_models: &available_models,
features: &features,
web_search_mode: Some(WebSearchMode::Cached),
session_source: SessionSource::Cli,
sandbox_policy: &SandboxPolicy::DangerFullAccess,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
});
let (tools, _) = build_specs(
&tools_config,
/*mcp_tools*/ None,
/*app_tools*/ None,
&[],
)
.build();
assert_contains_tool_names(&tools, &["tool_search"]);
assert_contains_tool_names(
&tools,
&["spawn_agent", "send_input", "wait_agent", "close_agent"],
);
assert_lacks_tool_name(&tools, "spawn_agents_on_csv");
assert_lacks_tool_name(&tools, "list_agents");
assert_lacks_tool_name(&tools, "watchdog");
}
#[test]
fn test_build_specs_watchdog_collab_tools_include_self_close_tool() {
let config = test_config();
let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config);
let mut features = Features::with_defaults();
features.enable(Feature::Collab);
features.enable(Feature::AgentWatchdog);
features.normalize_dependencies();
let available_models = Vec::new();
let tools_config = ToolsConfig::new(&ToolsConfigParams {
model_info: &model_info,
available_models: &available_models,
features: &features,
web_search_mode: Some(WebSearchMode::Cached),
session_source: SessionSource::Cli,
sandbox_policy: &SandboxPolicy::DangerFullAccess,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
});
let (tools, _) = build_specs(
&tools_config,
/*mcp_tools*/ None,
/*app_tools*/ None,
&[],
)
.build();
assert_contains_top_level_tool_name(&tools, "watchdog");
assert_contains_top_level_tool_name(&tools, "spawn_agent");
assert_contains_top_level_tool_name(&tools, "send_input");
assert_contains_top_level_tool_name(&tools, "wait_agent");
assert_contains_top_level_tool_name(&tools, "close_agent");
assert_contains_top_level_tool_name(&tools, "list_agents");
assert_contains_tool_names(&tools, &["tool_search", "list_agents", "close_agent"]);
assert_lacks_top_level_tool_name(&tools, "watchdog_self_close");
assert_lacks_top_level_tool_name(&tools, "compact_parent_context");
let watchdog_self_close = find_namespaced_tool(&tools, "watchdog", "watchdog_self_close");
let ToolSpec::Function(ResponsesApiTool {
defer_loading: Some(deferred),
..
}) = &watchdog_self_close.spec
else {
panic!("watchdog_self_close should be a function tool");
};
assert!(*deferred);
let compact_parent_context = find_namespaced_tool(&tools, "watchdog", "compact_parent_context");
let ToolSpec::Function(ResponsesApiTool {
defer_loading: Some(deferred),
..
}) = &compact_parent_context.spec
else {
panic!("compact_parent_context should be a function tool");
};
assert!(*deferred);
}
#[test]
fn test_build_specs_multi_agent_v2_uses_task_names_and_hides_resume() {
let config = test_config();
let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config);
let mut features = Features::with_defaults();
features.enable(Feature::Collab);
features.enable(Feature::MultiAgentV2);
let available_models = Vec::new();
let tools_config = ToolsConfig::new(&ToolsConfigParams {
model_info: &model_info,
available_models: &available_models,
features: &features,
web_search_mode: Some(WebSearchMode::Cached),
session_source: SessionSource::Cli,
sandbox_policy: &SandboxPolicy::DangerFullAccess,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
});
let (tools, _) = build_specs(
&tools_config,
/*mcp_tools*/ None,
/*app_tools*/ None,
&[],
)
.build();
assert_contains_tool_names(
&tools,
&[
"spawn_agent",
"send_message",
"assign_task",
"wait_agent",
"close_agent",
"list_agents",
],
);
let spawn_agent = find_tool(&tools, "spawn_agent");
let ToolSpec::Function(ResponsesApiTool {
parameters,
output_schema,
..
}) = &spawn_agent.spec
else {
panic!("spawn_agent should be a function tool");
};
let JsonSchema::Object {
properties,
required,
..
} = parameters
else {
panic!("spawn_agent should use object params");
};
assert!(properties.contains_key("task_name"));
assert_eq!(required.as_ref(), Some(&vec!["task_name".to_string()]));
let output_schema = output_schema
.as_ref()
.expect("spawn_agent should define output schema");
assert_eq!(
output_schema["required"],
json!(["agent_id", "task_name", "nickname"])
);
let send_message = find_tool(&tools, "send_message");
let ToolSpec::Function(ResponsesApiTool { parameters, .. }) = &send_message.spec else {
panic!("send_message should be a function tool");
};
let JsonSchema::Object {
properties,
required,
..
} = parameters
else {
panic!("send_message should use object params");
};
assert!(properties.contains_key("target"));
assert!(!properties.contains_key("message"));
assert_eq!(
required.as_ref(),
Some(&vec!["target".to_string(), "items".to_string()])
);
let assign_task = find_tool(&tools, "assign_task");
let ToolSpec::Function(ResponsesApiTool { parameters, .. }) = &assign_task.spec else {
panic!("assign_task should be a function tool");
};
let JsonSchema::Object {
properties,
required,
..
} = parameters
else {
panic!("assign_task should use object params");
};
assert!(properties.contains_key("target"));
assert!(!properties.contains_key("message"));
assert_eq!(
required.as_ref(),
Some(&vec!["target".to_string(), "items".to_string()])
);
let wait_agent = find_tool(&tools, "wait_agent");
let ToolSpec::Function(ResponsesApiTool {
parameters,
output_schema,
..
}) = &wait_agent.spec
else {
panic!("wait_agent should be a function tool");
};
let JsonSchema::Object {
properties,
required,
..
} = parameters
else {
panic!("wait_agent should use object params");
};
assert!(properties.contains_key("targets"));
assert_eq!(required.as_ref(), Some(&vec!["targets".to_string()]));
let output_schema = output_schema
.as_ref()
.expect("wait_agent should define output schema");
assert_eq!(
output_schema["properties"]["message"]["description"],
json!("Brief wait summary without the agent's final content.")
);
let list_agents = find_tool(&tools, "list_agents");
let ToolSpec::Function(ResponsesApiTool {
parameters,
output_schema,
..
}) = &list_agents.spec
else {
panic!("list_agents should be a function tool");
};
let JsonSchema::Object {
properties,
required,
..
} = parameters
else {
panic!("list_agents should use object params");
};
assert!(properties.contains_key("path_prefix"));
assert_eq!(required.as_ref(), None);
let output_schema = output_schema
.as_ref()
.expect("list_agents should define output schema");
assert_eq!(
output_schema["properties"]["agents"]["items"]["required"],
json!(["agent_name", "agent_status", "last_task_message"])
);
assert_lacks_tool_name(&tools, "send_input");
assert_lacks_tool_name(&tools, "resume_agent");
}
#[test]
fn test_build_specs_enable_fanout_enables_agent_jobs_and_collab_tools() {
let config = test_config();
let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config);
let mut features = Features::with_defaults();
features.enable(Feature::SpawnCsv);
features.normalize_dependencies();
let available_models = Vec::new();
let tools_config = ToolsConfig::new(&ToolsConfigParams {
model_info: &model_info,
available_models: &available_models,
features: &features,
web_search_mode: Some(WebSearchMode::Cached),
session_source: SessionSource::Cli,
sandbox_policy: &SandboxPolicy::DangerFullAccess,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
});
let (tools, _) = build_specs(
&tools_config,
/*mcp_tools*/ None,
/*app_tools*/ None,
&[],
)
.build();
assert_contains_tool_names(
&tools,
&[
"spawn_agent",
"send_input",
"wait_agent",
"close_agent",
"spawn_agents_on_csv",
],
);
}
#[test]
fn view_image_tool_omits_detail_without_original_detail_feature() {
let config = test_config();
let mut model_info =
ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config);
model_info.supports_image_detail_original = true;
let features = Features::with_defaults();
let available_models = Vec::new();
let tools_config = ToolsConfig::new(&ToolsConfigParams {
model_info: &model_info,
available_models: &available_models,
features: &features,
web_search_mode: Some(WebSearchMode::Cached),
session_source: SessionSource::Cli,
sandbox_policy: &SandboxPolicy::DangerFullAccess,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
});
let (tools, _) = build_specs(
&tools_config,
/*mcp_tools*/ None,
/*app_tools*/ None,
&[],
)
.build();
let view_image = find_tool(&tools, VIEW_IMAGE_TOOL_NAME);
let ToolSpec::Function(ResponsesApiTool { parameters, .. }) = &view_image.spec else {
panic!("view_image should be a function tool");
};
let JsonSchema::Object { properties, .. } = parameters else {
panic!("view_image should use an object schema");
};
assert!(!properties.contains_key("detail"));
}
#[test]
fn view_image_tool_includes_detail_with_original_detail_feature() {
let config = test_config();
let mut model_info =
ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config);
model_info.supports_image_detail_original = true;
let mut features = Features::with_defaults();
features.enable(Feature::ImageDetailOriginal);
let available_models = Vec::new();
let tools_config = ToolsConfig::new(&ToolsConfigParams {
model_info: &model_info,
available_models: &available_models,
features: &features,
web_search_mode: Some(WebSearchMode::Cached),
session_source: SessionSource::Cli,
sandbox_policy: &SandboxPolicy::DangerFullAccess,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
});
let (tools, _) = build_specs(
&tools_config,
/*mcp_tools*/ None,
/*app_tools*/ None,
&[],
)
.build();
let view_image = find_tool(&tools, VIEW_IMAGE_TOOL_NAME);
let ToolSpec::Function(ResponsesApiTool { parameters, .. }) = &view_image.spec else {
panic!("view_image should be a function tool");
};
let JsonSchema::Object { properties, .. } = parameters else {
panic!("view_image should use an object schema");
};
assert!(properties.contains_key("detail"));
let Some(JsonSchema::String {
description: Some(description),
}) = properties.get("detail")
else {
panic!("view_image detail should include a description");
};
assert!(description.contains("only supported value is `original`"));
assert!(description.contains("omit this field for default resized behavior"));
}
#[test]
fn test_build_specs_agent_job_worker_tools_enabled() {
let config = test_config();
let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config);
let mut features = Features::with_defaults();
features.enable(Feature::SpawnCsv);
features.normalize_dependencies();
features.enable(Feature::Sqlite);
let available_models = Vec::new();
let tools_config = ToolsConfig::new(&ToolsConfigParams {
model_info: &model_info,
available_models: &available_models,
features: &features,
web_search_mode: Some(WebSearchMode::Cached),
session_source: SessionSource::SubAgent(SubAgentSource::Other(
"agent_job:test".to_string(),
)),
sandbox_policy: &SandboxPolicy::DangerFullAccess,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
});
let (tools, _) = build_specs(
&tools_config,
/*mcp_tools*/ None,
/*app_tools*/ None,
&[],
)
.build();
assert_contains_tool_names(
&tools,
&[
"spawn_agent",
"send_input",
"resume_agent",
"wait_agent",
"close_agent",
"spawn_agents_on_csv",
"report_agent_job_result",
],
);
assert_lacks_tool_name(&tools, "request_user_input");
}
#[test]
fn request_user_input_description_reflects_default_mode_feature_flag() {
let config = test_config();
let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config);
let mut features = Features::with_defaults();
let available_models = Vec::new();
let tools_config = ToolsConfig::new(&ToolsConfigParams {
model_info: &model_info,
available_models: &available_models,
features: &features,
web_search_mode: Some(WebSearchMode::Cached),
session_source: SessionSource::Cli,
sandbox_policy: &SandboxPolicy::DangerFullAccess,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
});
let (tools, _) = build_specs(
&tools_config,
/*mcp_tools*/ None,
/*app_tools*/ None,
&[],
)
.build();
let request_user_input_tool = find_tool(&tools, "request_user_input");
assert_eq!(
request_user_input_tool.spec,
request_user_input_tool_spec(/*default_mode_request_user_input*/ false)
);
features.enable(Feature::DefaultModeRequestUserInput);
let available_models = Vec::new();
let tools_config = ToolsConfig::new(&ToolsConfigParams {
model_info: &model_info,
available_models: &available_models,
features: &features,
web_search_mode: Some(WebSearchMode::Cached),
session_source: SessionSource::Cli,
sandbox_policy: &SandboxPolicy::DangerFullAccess,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
});
let (tools, _) = build_specs(
&tools_config,
/*mcp_tools*/ None,
/*app_tools*/ None,
&[],
)
.build();
let request_user_input_tool = find_tool(&tools, "request_user_input");
assert_eq!(
request_user_input_tool.spec,
request_user_input_tool_spec(/*default_mode_request_user_input*/ true)
);
}
#[test]
fn request_permissions_requires_feature_flag() {
let config = test_config();
let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config);
let features = Features::with_defaults();
let available_models = Vec::new();
let tools_config = ToolsConfig::new(&ToolsConfigParams {
model_info: &model_info,
available_models: &available_models,
features: &features,
web_search_mode: Some(WebSearchMode::Cached),
session_source: SessionSource::Cli,
sandbox_policy: &SandboxPolicy::DangerFullAccess,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
});
let (tools, _) = build_specs(
&tools_config,
/*mcp_tools*/ None,
/*app_tools*/ None,
&[],
)
.build();
assert_lacks_tool_name(&tools, "request_permissions");
let mut features = Features::with_defaults();
features.enable(Feature::RequestPermissionsTool);
let available_models = Vec::new();
let tools_config = ToolsConfig::new(&ToolsConfigParams {
model_info: &model_info,
available_models: &available_models,
features: &features,
web_search_mode: Some(WebSearchMode::Cached),
session_source: SessionSource::Cli,
sandbox_policy: &SandboxPolicy::DangerFullAccess,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
});
let (tools, _) = build_specs(
&tools_config,
/*mcp_tools*/ None,
/*app_tools*/ None,
&[],
)
.build();
let request_permissions_tool = find_tool(&tools, "request_permissions");
assert_eq!(
request_permissions_tool.spec,
create_request_permissions_tool(request_permissions_tool_description())
);
}
#[test]
fn request_permissions_tool_is_independent_from_additional_permissions() {
let config = test_config();
let model_info = ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config);
let mut features = Features::with_defaults();
features.enable(Feature::ExecPermissionApprovals);
let available_models = Vec::new();
let tools_config = ToolsConfig::new(&ToolsConfigParams {
model_info: &model_info,
available_models: &available_models,
features: &features,
web_search_mode: Some(WebSearchMode::Cached),
session_source: SessionSource::Cli,
sandbox_policy: &SandboxPolicy::DangerFullAccess,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
});
let (tools, _) = build_specs(
&tools_config,
/*mcp_tools*/ None,
/*app_tools*/ None,
&[],
)
.build();
assert_lacks_tool_name(&tools, "request_permissions");
}
#[test]
fn get_memory_requires_feature_flag() {
let config = test_config();
@@ -270,7 +965,16 @@ fn assert_model_tools(
let model_visible_specs = router.model_visible_specs();
let tool_names = model_visible_specs
.iter()
.map(ToolSpec::name)
.flat_map(|tool| match tool {
ToolSpec::Namespace(namespace) => namespace
.tools
.iter()
.map(|tool| match tool {
codex_tools::ResponsesApiNamespaceTool::Function(tool) => tool.name.as_str(),
})
.collect::<Vec<_>>(),
_ => vec![tool.name()],
})
.collect::<Vec<_>>();
assert_eq!(&tool_names, &expected_tools,);
}
@@ -302,6 +1006,7 @@ fn test_build_specs_gpt5_codex_default() {
&[
"update_plan",
"request_user_input",
"tool_search",
"apply_patch",
"web_search",
"view_image",
@@ -325,6 +1030,7 @@ fn test_build_specs_gpt51_codex_default() {
&[
"update_plan",
"request_user_input",
"tool_search",
"apply_patch",
"web_search",
"view_image",
@@ -350,6 +1056,7 @@ fn test_build_specs_gpt5_codex_unified_exec_web_search() {
"write_stdin",
"update_plan",
"request_user_input",
"tool_search",
"apply_patch",
"web_search",
"view_image",
@@ -375,6 +1082,7 @@ fn test_build_specs_gpt51_codex_unified_exec_web_search() {
"write_stdin",
"update_plan",
"request_user_input",
"tool_search",
"apply_patch",
"web_search",
"view_image",
@@ -398,6 +1106,7 @@ fn test_gpt_5_1_codex_max_defaults() {
&[
"update_plan",
"request_user_input",
"tool_search",
"apply_patch",
"web_search",
"view_image",
@@ -421,6 +1130,7 @@ fn test_codex_5_1_mini_defaults() {
&[
"update_plan",
"request_user_input",
"tool_search",
"apply_patch",
"web_search",
"view_image",
@@ -444,6 +1154,7 @@ fn test_gpt_5_defaults() {
&[
"update_plan",
"request_user_input",
"tool_search",
"web_search",
"view_image",
"spawn_agent",
@@ -466,6 +1177,7 @@ fn test_gpt_5_1_defaults() {
&[
"update_plan",
"request_user_input",
"tool_search",
"apply_patch",
"web_search",
"view_image",
@@ -672,7 +1384,8 @@ fn search_tool_description_handles_no_enabled_apps() {
panic!("expected tool_search tool");
};
assert!(description.contains("None currently enabled."));
assert!(description.contains("agents"));
assert!(description.contains("Agent collaboration tools for spawning, messaging, waiting on, listing, and closing subagents."));
assert!(!description.contains("{{app_descriptions}}"));
}
+39
View File
@@ -0,0 +1,39 @@
# You are a Subagent
You are a **subagent** in a multi-agent Codex session. Your role is no longer root. Your goal is the task given by the parent/root agent.
Term definitions in this file:
- **parent thread**: the thread that spawned this subagent.
- **root thread**: the top-level user-facing thread.
- **`send_input`**: send a message to an existing agent thread; it does not spawn agents. Delivery is asynchronous.
- **durable state**: thread-level task state needed across later turns/check-ins (not disk/database persistence).
- In this runtime, when a subagent calls `send_input`, `id = "parent"` and `id = "root"` both route to the immediate parent thread.
## Subagent Responsibilities
- Stay within parent/root scope (listed files/questions/constraints). Use additional files/tools only when needed to complete or verify the task.
- Blocking question = one clarification to parent via `send_input`. Ask only if missing information would change user-visible output, tool/action choice (multi-agent tool, target thread, or ask-vs-continue), file edits, control flow, or durable-state decisions; otherwise state one assumption and continue.
- Prefer concrete progress: edit files, run commands, and validate outcomes.
- Your responses go to the root/parent agent, not the end user.
## Multi-Agent Guidance (Upstream Surface)
The only multi-agent tools available in this environment are `spawn_agent`, `send_input`, `wait`, `close_agent`, and `list_agents`.
Important: to coordinate with parent/root, use `send_input`. A plain assistant message in your own thread does not reliably notify the parent.
You can call `send_input` without an `id` (or with `id = "parent"` / `id = "root"`); these forms target the immediate parent thread in this runtime.
## Reporting Expectations
When you make meaningful progress or complete a task, report back with:
- The key outcome.
- Files changed (with paths).
- Commands run.
- Validation performed (tests, checks, or observed outputs).
- Risks, follow-ups, or open questions.
Be specific enough that the root agent can integrate your work safely.
Do not reference multi-agent tools that do not exist in the upstream surface.
+10
View File
@@ -0,0 +1,10 @@
## Watchdog-only Guidance
If you are acting as a watchdog check-in agent, the deferred `watchdog` namespace may be available
through `tool_search`.
- Use `watchdog.compact_parent_context` only when the parent thread is idle and appears stuck.
- `watchdog.compact_parent_context` is not part of the general subagent tool surface; do not
mention or rely on it unless you are explicitly operating as a watchdog check-in agent.
- `watchdog.watchdog_self_close` is also available to this watchdog thread and can be used to end
the check-in when work is complete.
+2
View File
@@ -486,6 +486,8 @@ impl TestCodexBuilder {
&config,
codex_core::test_support::auth_manager_from_auth(auth.clone()),
SessionSource::Exec,
config.model_catalog.clone(),
config.custom_models.clone(),
CollaborationModesConfig::default(),
Arc::clone(&environment_manager),
)
+49 -15
View File
@@ -205,11 +205,16 @@ fn message_input_texts(body: &Value) -> Vec<String> {
};
items
.iter()
.filter(|item| item.get("type").and_then(Value::as_str) == Some("message"))
.filter(|item| {
item.get("role").and_then(Value::as_str).is_some()
|| item.get("type").and_then(Value::as_str) == Some("message")
})
.filter_map(|item| item.get("content").and_then(Value::as_array))
.flatten()
.filter(|span| span.get("type").and_then(Value::as_str) == Some("input_text"))
.filter_map(|span| span.get("text").and_then(Value::as_str))
.filter_map(|span| match span.get("type").and_then(Value::as_str) {
Some("input_text") | None => span.get("text").and_then(Value::as_str),
_ => None,
})
.map(str::to_string)
.collect()
}
@@ -320,9 +325,31 @@ async fn spawn_agents_on_csv_runs_and_exports() -> Result<()> {
test.submit_turn("run batch job").await?;
let output = fs::read_to_string(&output_path)?;
assert!(output.contains("result_json"));
assert!(output.contains("item_id"));
assert!(output.contains("\"item_id\""));
let mut lines = output.lines();
let headers = lines.next().expect("csv headers");
let header_cols = parse_simple_csv_line(headers);
let status_index = header_cols
.iter()
.position(|header| header == "status")
.expect("status column");
let result_json_index = header_cols
.iter()
.position(|header| header == "result_json")
.expect("result_json column");
assert!(header_cols.iter().any(|header| header == "result_json"));
assert!(header_cols.iter().any(|header| header == "item_id"));
let rows: Vec<Vec<String>> = lines.map(parse_simple_csv_line).collect();
assert_eq!(rows.len(), 2);
assert_eq!(
rows.iter()
.map(|cols| cols[status_index].as_str())
.collect::<Vec<_>>(),
vec!["completed", "completed"]
);
assert!(
rows.iter()
.all(|cols| !cols[result_json_index].trim().is_empty())
);
Ok(())
}
@@ -423,21 +450,28 @@ async fn spawn_agents_on_csv_stop_halts_future_items() -> Result<()> {
test.submit_turn("run job").await?;
let output = fs::read_to_string(&output_path)?;
let rows: Vec<&str> = output.lines().skip(1).collect();
let mut lines = output.lines();
let headers = lines.next().expect("csv headers");
let header_cols = parse_simple_csv_line(headers);
let job_id_index = header_cols
.iter()
.position(|header| header == "job_id")
.expect("job_id column");
let rows: Vec<&str> = lines.collect();
assert_eq!(rows.len(), 3);
let job_id = rows
let job_id: String = rows
.first()
.and_then(|line| {
parse_simple_csv_line(line)
.iter()
.find(|value| value.len() == 36)
.cloned()
})
.map(|line| parse_simple_csv_line(line))
.and_then(|cols| cols.get(job_id_index).cloned())
.expect("job_id from csv");
let db = test.codex.state_db().expect("state db");
let job = db.get_agent_job(job_id.as_str()).await?.expect("job");
assert_eq!(job.status, codex_state::AgentJobStatus::Cancelled);
let progress = db.get_agent_job_progress(job_id.as_str()).await?;
assert_eq!(
job.status,
codex_state::AgentJobStatus::Cancelled,
"unexpected final job state: job={job:?} progress={progress:?} output={output}"
);
assert_eq!(progress.total_items, 3);
assert_eq!(progress.completed_items, 1);
assert_eq!(progress.failed_items, 0);
+12 -4
View File
@@ -1059,6 +1059,8 @@ async fn prefers_apikey_when_config_prefers_apikey_even_with_chatgpt_tokens() {
&config,
auth_manager,
SessionSource::Exec,
config.model_catalog.clone(),
config.custom_models.clone(),
CollaborationModesConfig {
default_mode_request_user_input: config
.features
@@ -1980,12 +1982,18 @@ async fn includes_developer_instructions_message_in_request() {
.iter()
.filter(|item| item.get("role").and_then(|role| role.as_str()) == Some("developer"))
.collect();
let developer_contents: Vec<&str> = developer_messages
.iter()
.filter_map(|item| item.get("content").and_then(serde_json::Value::as_array))
.flat_map(|content| content.iter())
.filter(|span| span.get("type").and_then(serde_json::Value::as_str) == Some("input_text"))
.filter_map(|span| span.get("text").and_then(serde_json::Value::as_str))
.collect();
assert!(
developer_messages
developer_contents
.iter()
.any(|item| message_input_texts(item).contains(&"be useful")),
"expected developer instructions in a developer message, got {:?}",
request_body["input"]
.any(|content| content.contains("be useful")),
"expected developer instructions in a developer message, got {developer_contents:?}",
);
assert_message_role(&request_body["input"][1], "user");
Loaded 100 of 180 files, more files were not shown because too many files have changed in this diff. Show more