Repository navigation
Expand file tree
/
Copy pathspec_plan.rs
More file actions
1479 lines (1383 loc) · 56.1 KB
/
Copy pathspec_plan.rs
File metadata and controls
1479 lines (1383 loc) · 56.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::agent::exceeds_thread_spawn_depth_limit;
use crate::agent::next_thread_spawn_depth;
use crate::environment_selection::TurnEnvironmentSnapshot;
use crate::image_preparation::unified_image_budget_enabled;
use crate::session::session::Session;
use crate::session::turn_context::TurnContext;
use crate::tools::code_mode::execute_spec::create_code_mode_tool;
use crate::tools::effective_tool_mode;
use crate::tools::handlers::ApplyPatchHandler;
use crate::tools::handlers::CodeModeExecuteHandler;
use crate::tools::handlers::CodeModeWaitHandler;
use crate::tools::handlers::CurrentTimeHandler;
use crate::tools::handlers::DynamicToolHandler;
use crate::tools::handlers::ExecCommandHandler;
use crate::tools::handlers::ExecCommandHandlerOptions;
use crate::tools::handlers::GetContextRemainingHandler;
use crate::tools::handlers::ListAvailablePluginsToInstallHandler;
use crate::tools::handlers::ListMcpResourceTemplatesHandler;
use crate::tools::handlers::ListMcpResourcesHandler;
use crate::tools::handlers::NewContextWindowHandler;
use crate::tools::handlers::PlanHandler;
use crate::tools::handlers::ReadMcpResourceHandler;
use crate::tools::handlers::RequestPermissionsHandler;
use crate::tools::handlers::RequestPluginInstallHandler;
use crate::tools::handlers::RequestUserInputAsyncHandler;
use crate::tools::handlers::RequestUserInputHandler;
use crate::tools::handlers::SendMessageToUserAsyncHandler;
use crate::tools::handlers::SleepHandler;
use crate::tools::handlers::TestSyncHandler;
use crate::tools::handlers::ToolSearchHandlerCache;
use crate::tools::handlers::ViewImageHandler;
use crate::tools::handlers::WaitForEnvironmentHandler;
use crate::tools::handlers::WriteStdinHandler;
use crate::tools::handlers::extension_tools::ExtensionToolAdapter;
use crate::tools::handlers::multi_agents::CloseAgentHandler;
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_common::DEFAULT_WAIT_TIMEOUT_MS;
use crate::tools::handlers::multi_agents_common::MAX_WAIT_TIMEOUT_MS;
use crate::tools::handlers::multi_agents_common::MIN_WAIT_TIMEOUT_MS;
use crate::tools::handlers::multi_agents_spec::MULTI_AGENT_V1_NAMESPACE;
use crate::tools::handlers::multi_agents_spec::SpawnAgentToolOptions;
use crate::tools::handlers::multi_agents_spec::WaitAgentTimeoutOptions;
use crate::tools::handlers::multi_agents_v2::FollowupTaskHandler as FollowupTaskHandlerV2;
use crate::tools::handlers::multi_agents_v2::InterruptAgentHandler;
use crate::tools::handlers::multi_agents_v2::ListAgentsHandler as ListAgentsHandlerV2;
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::tool_search_spec::ToolSearchSourceListing;
use crate::tools::handlers::view_image_spec::ViewImageToolOptions;
use crate::tools::hosted_spec::WebSearchToolOptions;
use crate::tools::hosted_spec::create_web_search_tool;
use crate::tools::multi_agent_tool::multi_agent_v2_handler;
#[cfg(test)]
use crate::tools::registry::RegisteredTool;
use crate::tools::registry::ToolExposure;
use crate::tools::registry::ToolRegistry;
use crate::tools::router::ToolRouter;
use crate::tools::tool_namespaces_info::collect_tool_namespaces_info;
use codex_connectors::apps_config_from_layer_stack;
use codex_extension_api::ExtensionData;
use codex_features::Feature;
use codex_features::SleepToolMode;
use codex_login::AuthManager;
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
use codex_prompts::ResolvedModelMessages;
use codex_protocol::DEFAULT_FUNCTION_NAMESPACE;
use codex_protocol::account::PlanType;
use codex_protocol::config_types::WebSearchMode;
use codex_protocol::dynamic_tools::DynamicToolNamespaceTool;
use codex_protocol::dynamic_tools::DynamicToolSpec;
use codex_protocol::error::CodexErrorDetails;
use codex_protocol::error::Result as CodexResult;
use codex_protocol::models::PermissionProfile;
use codex_protocol::openai_models::ConfigShellToolType;
use codex_protocol::openai_models::InputModality;
use codex_protocol::openai_models::ModelInfo;
use codex_protocol::openai_models::ToolMode;
use codex_protocol::protocol::MultiAgentVersion;
use codex_tools::ResponsesApiNamespaceTool;
use codex_tools::TOOL_SEARCH_TOOL_NAME;
use codex_tools::ToolCall as ExtensionToolCall;
use codex_tools::ToolEnvironmentMode;
use codex_tools::ToolExecutor;
use codex_tools::ToolExposures;
use codex_tools::ToolName;
use codex_tools::ToolSpec;
use codex_tools::UnifiedExecShellMode;
use codex_tools::can_request_original_image_detail;
use codex_tools::collect_code_mode_exec_prompt_tool_definitions;
use codex_tools::collect_request_plugin_install_entries;
use codex_tools::default_namespace_description;
use codex_tools::request_user_input_available_modes;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::btree_map::Entry;
use std::sync::Arc;
use tracing::instrument;
const IMAGE_GEN_NAMESPACE: &str = "image_gen";
const IMAGEGEN_TOOL_NAME: &str = "imagegen";
#[derive(Clone, Copy)]
struct CoreToolPlanContext<'a> {
tool_policy: &'a codex_extension_api::ToolPolicy,
turn_context: &'a TurnContext,
model_info: &'a ModelInfo,
environments: &'a TurnEnvironmentSnapshot,
mcp: &'a codex_mcp::McpBinding,
tool_suggest_candidates: Option<&'a crate::tools::router::ToolSuggestCandidates>,
wait_for_environment_tool_config: Option<&'a Arc<crate::WaitForEnvironmentToolConfig>>,
default_agent_type_description: &'a str,
wait_agent_timeouts: WaitAgentTimeoutOptions,
}
#[instrument(level = "trace", skip_all)]
#[allow(clippy::too_many_arguments)]
pub(crate) fn build_tool_router(
session: &Session,
turn_context: &TurnContext,
model_info: &ModelInfo,
environments: &TurnEnvironmentSnapshot,
mcp: &Arc<codex_mcp::McpBinding>,
apps_enabled: bool,
step_store: &ExtensionData,
tool_suggest_candidates: Option<&crate::tools::router::ToolSuggestCandidates>,
) -> CodexResult<ToolRouter> {
let default_agent_type_description =
crate::agent::role::spawn_tool_spec::build(&std::collections::BTreeMap::new());
let wait_for_environment_tool_config = session
.services
.thread_extension_data
.get::<crate::WaitForEnvironmentToolConfig>();
let context = CoreToolPlanContext {
tool_policy: &session.tool_policy,
turn_context,
model_info,
environments,
mcp,
tool_suggest_candidates,
wait_for_environment_tool_config: wait_for_environment_tool_config.as_ref(),
default_agent_type_description: &default_agent_type_description,
wait_agent_timeouts: wait_agent_timeout_options(turn_context),
};
let mut registry = ToolRegistry::with_tool_policy(Arc::clone(&session.tool_policy));
add_core_tool_sources(&context, &mut registry);
let registered_mcp_tools = session.services.mcp_handler_cache.append_mcp_tools(
mcp,
&turn_context.config,
apps_enabled,
&mcp.config().mcp_server_catalog,
search_tool_enabled(turn_context, model_info),
&mut registry,
);
apply_mcp_tool_exposure_policy(
turn_context,
model_info,
mcp,
®istered_mcp_tools,
&mut registry,
);
let standalone_web_search_tool = append_extension_tool_executors(
turn_context,
model_info,
extension_tool_executors(session, step_store),
&mut registry,
);
append_dynamic_tool_runtimes(&turn_context.dynamic_tools, &mut registry);
let hosted_specs = hosted_model_tool_specs(
turn_context,
model_info,
standalone_web_search_tool.as_slice(),
);
finalize_tool_router(
turn_context,
model_info,
registry,
hosted_specs,
&session.services.tool_search_handler_cache,
)
}
fn apply_mcp_tool_exposure_policy(
turn_context: &TurnContext,
model_info: &ModelInfo,
mcp: &codex_mcp::McpBinding,
registered_mcp_tools: &HashSet<ToolName>,
registry: &mut ToolRegistry,
) {
let mut omitted_exposures_by_tool = HashMap::new();
let apps_config = apps_config_from_layer_stack(&turn_context.config.config_layer_stack);
for tool in mcp.tools() {
let tool_name = tool.canonical_tool_name();
if !registered_mcp_tools.contains(&tool_name) {
continue;
}
let Some(server) = mcp.config().mcp_server_catalog.server(&tool.server_name) else {
continue;
};
omitted_exposures_by_tool
.entry(tool_name)
.or_insert_with(|| {
let connector_omissions = (tool.server_name == CODEX_APPS_MCP_SERVER_NAME)
.then_some(tool.connector_id.as_deref())
.flatten()
.and_then(|id| apps_config.as_ref()?.apps.get(id))
.and_then(|app| app.omit_tools_from.as_deref())
.unwrap_or_default();
server
.config()
.omit_tools_from
.as_deref()
.unwrap_or_default()
.iter()
.chain(connector_omissions)
.copied()
.collect::<ToolExposures>()
});
}
for tool in registry.entries_mut() {
let tool_name = tool.runtime.tool_name();
let Some(omitted_exposures) = omitted_exposures_by_tool.get(&tool_name) else {
continue;
};
let tool_name = tool_name.with_default_namespace();
let mut exposures = ToolExposures::ALL.difference(*omitted_exposures);
if tool_name.namespace.as_ref().is_some_and(|namespace| {
turn_context
.config
.code_mode
.direct_only_tool_namespaces
.contains(namespace)
}) {
exposures = exposures.difference(ToolExposures::DEFERRED | ToolExposures::CODE_MODE);
}
exposures = if search_tool_enabled(turn_context, model_info)
&& exposures.contains(ToolExposures::DEFERRED)
&& (effective_tool_mode(turn_context, model_info) != ToolMode::CodeModeOnly
|| exposures.contains(ToolExposures::CODE_MODE))
{
exposures.difference(ToolExposures::DIRECT)
} else {
exposures.difference(ToolExposures::DEFERRED)
};
tool.exposure = match (
exposures.contains(ToolExposures::DIRECT),
exposures.contains(ToolExposures::DEFERRED),
exposures.contains(ToolExposures::CODE_MODE),
) {
(false, false, false) => ToolExposure::Hidden,
(false, false, true) => ToolExposure::CodeModeOnly,
(true, false, false) => ToolExposure::DirectModelOnly,
(true, false, true) => ToolExposure::Direct,
(false, true, false) => ToolExposure::DeferredModelOnly,
(false, true, true) => ToolExposure::Deferred,
(true, true, _) => unreachable!("direct and deferred exposure are mutually exclusive"),
};
}
}
#[cfg(test)]
#[instrument(level = "trace", skip_all)]
pub(crate) fn build_core_tool_registry(
turn_context: &TurnContext,
model_info: &ModelInfo,
environments: &TurnEnvironmentSnapshot,
mcp: &codex_mcp::McpBinding,
tool_suggest_candidates: Option<&crate::tools::router::ToolSuggestCandidates>,
wait_for_environment_tool_config: Option<&Arc<crate::WaitForEnvironmentToolConfig>>,
) -> ToolRegistry {
let default_agent_type_description =
crate::agent::role::spawn_tool_spec::build(&std::collections::BTreeMap::new());
let context = CoreToolPlanContext {
tool_policy: &Default::default(),
turn_context,
model_info,
environments,
mcp,
tool_suggest_candidates,
wait_for_environment_tool_config,
default_agent_type_description: &default_agent_type_description,
wait_agent_timeouts: wait_agent_timeout_options(turn_context),
};
let mut registry = ToolRegistry::default();
add_core_tool_sources(&context, &mut registry);
registry
}
#[cfg(test)]
#[instrument(level = "trace", skip_all)]
pub(crate) fn append_source_tools(
turn_context: &TurnContext,
model_info: &ModelInfo,
registry: &mut ToolRegistry,
mcp_tools: Vec<RegisteredTool>,
extension_tool_executors: impl IntoIterator<
Item = Arc<dyn for<'call> ToolExecutor<ExtensionToolCall<'call>>>,
>,
dynamic_tools: &[DynamicToolSpec],
) -> Vec<ToolSpec> {
for tool in mcp_tools {
registry.register_external_with_exposure(tool.runtime, tool.exposure);
}
let standalone_web_search_tool = append_extension_tool_executors(
turn_context,
model_info,
extension_tool_executors,
registry,
);
append_dynamic_tool_runtimes(dynamic_tools, registry);
hosted_model_tool_specs(
turn_context,
model_info,
standalone_web_search_tool.as_slice(),
)
}
#[instrument(level = "trace", skip_all)]
pub(crate) fn extension_tool_executors<'a>(
session: &'a Session,
step_store: &'a ExtensionData,
) -> impl Iterator<Item = Arc<dyn for<'call> ToolExecutor<ExtensionToolCall<'call>>>> + 'a {
session
.services
.extensions
.tool_contributors()
.iter()
.flat_map(move |contributor| {
contributor.tools_for_step(
&session.services.session_extension_data,
&session.services.thread_extension_data,
step_store,
)
})
}
#[instrument(level = "trace", skip_all)]
pub(crate) fn finalize_tool_router(
turn_context: &TurnContext,
model_info: &ModelInfo,
mut registry: ToolRegistry,
mut hosted_specs: Vec<ToolSpec>,
tool_search_handler_cache: &ToolSearchHandlerCache,
) -> CodexResult<ToolRouter> {
hosted_specs.retain(|spec| registry.tool_policy.allows(&ToolName::plain(spec.name())));
apply_direct_model_only_namespace_overrides(turn_context, &mut registry);
let tool_mode = effective_tool_mode(turn_context, model_info);
let code_mode_enabled = matches!(tool_mode, ToolMode::CodeMode | ToolMode::CodeModeOnly);
if code_mode_enabled {
for tool_name in [
ToolName::plain(codex_code_mode::PUBLIC_TOOL_NAME),
ToolName::plain(codex_code_mode::WAIT_TOOL_NAME),
] {
if registry.remove(&tool_name).is_some() {
registry.record_collision(tool_name);
}
}
}
let tool_search_name = ToolName::plain(TOOL_SEARCH_TOOL_NAME);
if search_tool_enabled(turn_context, model_info)
&& registry.entries().any(|tool| {
tool.runtime.tool_name() != tool_search_name
&& tool.exposure.is_deferred()
&& tool.runtime.search_info().is_some()
})
{
if registry.remove(&tool_search_name).is_some() {
registry.record_collision(tool_search_name.clone());
}
// Special model tools own the namespace matching their wire identity, so
// regular namespace tools cannot advertise that same model-visible surface.
let conflicting_tool_names = registry
.entries()
.filter_map(|tool| {
let owned_spec;
let spec = if let Some(spec) = tool.runtime.immutable_spec() {
spec.as_ref()
} else {
owned_spec = tool.runtime.spec();
&owned_spec
};
let ToolSpec::Namespace(namespace) = spec else {
return None;
};
(namespace.name == tool_search_name.name).then(|| tool.runtime.tool_name())
})
.collect::<Vec<_>>();
for tool_name in conflicting_tool_names {
if registry.remove(&tool_name).is_some() {
registry.record_collision(tool_name);
}
}
append_tool_search_executor(turn_context, &mut registry, tool_search_handler_cache);
}
let code_mode_tool_names =
register_code_mode_executors(turn_context, model_info, &mut registry);
let include_tool_namespaces_info = turn_context
.config
.tool_registry
.turn_metadata_includes_tool_info
&& model_info.use_responses_lite;
if turn_context.config.tool_registry.error_on_tool_collisions {
if let Some(tool_name) = registry.first_collision() {
let namespace = tool_name.namespace.as_deref().unwrap_or("functions");
let name = format!("{namespace}.{}", tool_name.name);
return Err(CodexErrorDetails::ToolCollision(name).into());
}
let mut namespace_descriptions = BTreeMap::new();
let mut namespace_owners = BTreeMap::new();
for tool in registry.entries() {
let owned_spec;
let spec = if let Some(spec) = tool.runtime.immutable_spec() {
spec.as_ref()
} else {
owned_spec = tool.runtime.spec();
&owned_spec
};
if include_tool_namespaces_info && tool.exposure != ToolExposure::Hidden {
let namespace_name = match spec {
ToolSpec::Namespace(namespace) => namespace.name.as_str(),
ToolSpec::Function(_) | ToolSpec::Freeform(_) => DEFAULT_FUNCTION_NAMESPACE,
ToolSpec::ToolSearch { .. } => TOOL_SEARCH_TOOL_NAME,
ToolSpec::WebSearch { .. } => continue,
};
let owner = tool.runtime.mcp_server_name();
match namespace_owners.get(namespace_name) {
Some(existing_owner) if existing_owner != &owner => {
return Err(
CodexErrorDetails::ToolCollision(namespace_name.to_string()).into()
);
}
Some(_) => {}
None => {
namespace_owners.insert(namespace_name.to_string(), owner);
}
}
}
let ToolSpec::Namespace(namespace) = spec else {
continue;
};
if namespace.description.trim().is_empty() {
continue;
}
match namespace_descriptions.entry(namespace.name.clone()) {
Entry::Vacant(entry) => {
entry.insert(namespace.description.clone());
}
Entry::Occupied(entry) if entry.get() != &namespace.description => {
return Err(CodexErrorDetails::ToolCollision(entry.key().clone()).into());
}
Entry::Occupied(_) => {}
}
}
}
let model_visible_specs = build_model_visible_specs(
turn_context,
model_info,
®istry,
&code_mode_tool_names,
hosted_specs,
);
let tool_namespaces_info = include_tool_namespaces_info
.then(|| {
collect_tool_namespaces_info(®istry, &code_mode_tool_names, &model_visible_specs)
})
.filter(|info| !info.is_empty());
let child_management_tools = required_child_management_tool_names(turn_context, model_info);
Ok(ToolRouter::from_parts(
registry,
model_visible_specs,
tool_mode,
code_mode_tool_names,
tool_namespaces_info,
&child_management_tools,
))
}
fn apply_direct_model_only_namespace_overrides(
turn_context: &TurnContext,
registry: &mut ToolRegistry,
) {
if turn_context
.config
.code_mode
.direct_only_tool_namespaces
.is_empty()
{
return;
}
for tool in registry.entries_mut() {
let configured = tool
.runtime
.tool_name()
.with_default_namespace()
.namespace
.as_ref()
.is_some_and(|namespace| {
turn_context
.config
.code_mode
.direct_only_tool_namespaces
.contains(namespace)
});
if configured && tool.exposure.is_available_in_code_mode() {
tool.exposure = ToolExposure::DirectModelOnly;
}
}
}
#[instrument(level = "trace", skip_all)]
fn build_model_visible_specs(
turn_context: &TurnContext,
model_info: &ModelInfo,
registry: &ToolRegistry,
code_mode_tool_names: &BTreeMap<String, ToolName>,
hosted_specs: Vec<ToolSpec>,
) -> Vec<ToolSpec> {
let mut specs = Vec::new();
for tool in registry.entries() {
let exposure = tool.exposure;
if !exposure.is_direct() {
continue;
}
let tool_name = tool.runtime.tool_name();
if is_hidden_by_code_mode_only(turn_context, model_info, &tool_name, exposure) {
continue;
}
let spec = tool.runtime.spec();
specs.push(spec_for_model_request(
turn_context,
model_info,
exposure,
&tool_name,
code_mode_tool_names,
spec,
));
}
specs.extend(hosted_specs);
merge_into_namespaces(specs)
.into_iter()
.filter(|spec| {
namespace_tools_enabled(turn_context) || !matches!(spec, ToolSpec::Namespace(_))
})
.collect()
}
fn spec_for_model_request(
turn_context: &TurnContext,
model_info: &ModelInfo,
exposure: ToolExposure,
tool_name: &ToolName,
code_mode_tool_names: &BTreeMap<String, ToolName>,
spec: ToolSpec,
) -> ToolSpec {
let tool_mode = effective_tool_mode(turn_context, model_info);
if matches!(tool_mode, ToolMode::CodeMode | ToolMode::CodeModeOnly)
&& exposure.is_available_in_code_mode()
&& !is_excluded_from_code_mode(turn_context, tool_name)
&& codex_code_mode::is_code_mode_nested_tool(spec.name())
&& code_mode_tool_names
.get(&codex_code_mode::normalize_code_mode_identifier(
&codex_tools::code_mode_name_for_tool_name(tool_name),
))
.is_some_and(|winner| winner == tool_name)
{
codex_tools::augment_tool_spec_for_code_mode(spec)
} else {
spec
}
}
#[instrument(level = "trace", skip_all)]
fn hosted_model_tool_specs(
turn_context: &TurnContext,
model_info: &ModelInfo,
registered_extension_tool_names: &[ToolName],
) -> Vec<ToolSpec> {
// Responses Lite accepts schemas for client-executed tools, not hosted Responses tools.
if model_info.use_responses_lite {
return Vec::new();
}
let mut specs = Vec::new();
let standalone_web_search_available = standalone_web_search_enabled(turn_context, model_info)
&& registered_extension_tool_names.contains(&ToolName::namespaced("web", "run"));
// `Some(Cached/Live/Disabled)` are the options for mode when standalone search is unavailable
// and the provider supports hosted search. `None` prevents emitting a hosted search tool.
let web_search_mode = (!standalone_web_search_available
&& turn_context.provider.capabilities().web_search)
.then_some(turn_context.config.web_search_mode.value());
let web_search_config = web_search_mode
.as_ref()
.and(turn_context.config.web_search_config.as_ref());
if let Some(hosted_web_search_tool) = create_web_search_tool(WebSearchToolOptions {
web_search_mode,
web_search_config,
web_search_tool_type: model_info.web_search_tool_type,
}) {
specs.push(hosted_web_search_tool);
}
specs
}
pub(crate) fn search_tool_enabled(turn_context: &TurnContext, model_info: &ModelInfo) -> bool {
model_info.supports_search_tool && namespace_tools_enabled(turn_context)
}
pub(crate) fn tool_suggest_enabled(turn_context: &TurnContext) -> bool {
let features = turn_context.config.features.get();
features.enabled(Feature::ToolSuggest)
&& features.enabled(Feature::Apps)
&& features.enabled(Feature::Plugins)
}
fn namespace_tools_enabled(turn_context: &TurnContext) -> bool {
turn_context.provider.capabilities().namespace_tools
}
fn multi_agent_v2_enabled(turn_context: &TurnContext) -> bool {
turn_context.multi_agent_version == MultiAgentVersion::V2
}
fn collab_tools_enabled(turn_context: &TurnContext, model_info: &ModelInfo) -> bool {
match turn_context.multi_agent_version {
MultiAgentVersion::Disabled => false,
MultiAgentVersion::V1 => !exceeds_thread_spawn_depth_limit(
next_thread_spawn_depth(&turn_context.session_source),
turn_context.config.agent_max_depth,
),
MultiAgentVersion::V2 => {
turn_context.session_source.get_agent_path().is_none()
|| model_info.multi_agent_version == Some(MultiAgentVersion::V2)
}
}
}
fn required_child_management_tool_names(
turn_context: &TurnContext,
model_info: &ModelInfo,
) -> Vec<ToolName> {
if !collab_tools_enabled(turn_context, model_info) {
return Vec::new();
}
let (namespace, names): (_, &[&str]) = match turn_context.multi_agent_version {
MultiAgentVersion::Disabled => return Vec::new(),
MultiAgentVersion::V1 => (
Some(MULTI_AGENT_V1_NAMESPACE),
&["send_input", "wait_agent", "resume_agent", "close_agent"],
),
MultiAgentVersion::V2 => (
namespace_tools_enabled(turn_context)
.then_some(turn_context.config.multi_agent_v2.tool_namespace.as_deref())
.flatten(),
&[
"send_message",
"followup_task",
"interrupt_agent",
"list_agents",
],
),
};
let mut tools = names
.iter()
.map(|name| ToolName::new(namespace.map(str::to_owned), (*name).to_owned()))
.collect::<Vec<_>>();
if multi_agent_v2_enabled(turn_context) && turn_context.config.multi_agent_v2.wait_agent_enabled
{
tools.push(ToolName::new(namespace.map(str::to_owned), "wait_agent"));
}
tools
}
fn image_generation_available(turn_context: &TurnContext, model_info: &ModelInfo) -> bool {
if !turn_context
.config
.features
.get()
.enabled(Feature::ImageGeneration)
{
return false;
}
if turn_context
.auth_manager
.as_deref()
.and_then(AuthManager::auth_cached)
.and_then(|auth| auth.account_plan_type())
== Some(PlanType::Free)
{
return false;
}
let capabilities = turn_context.provider.capabilities();
if !capabilities.image_generation || !capabilities.namespace_tools {
return false;
}
if !model_info.input_modalities.contains(&InputModality::Image) {
return false;
}
let provider = turn_context.provider.info();
provider.uses_openai_actor_authorization()
|| (provider.requires_openai_auth
&& turn_context
.auth_manager
.as_deref()
.is_some_and(AuthManager::current_auth_uses_codex_backend))
}
fn wait_agent_timeout_options(turn_context: &TurnContext) -> WaitAgentTimeoutOptions {
if multi_agent_v2_enabled(turn_context) {
return WaitAgentTimeoutOptions {
default_timeout_ms: turn_context.config.multi_agent_v2.default_wait_timeout_ms,
min_timeout_ms: turn_context.config.multi_agent_v2.min_wait_timeout_ms,
max_timeout_ms: turn_context.config.multi_agent_v2.max_wait_timeout_ms,
};
}
WaitAgentTimeoutOptions {
default_timeout_ms: DEFAULT_WAIT_TIMEOUT_MS,
min_timeout_ms: MIN_WAIT_TIMEOUT_MS,
max_timeout_ms: MAX_WAIT_TIMEOUT_MS,
}
}
fn agent_type_description(
turn_context: &TurnContext,
default_agent_type_description: &str,
) -> String {
let agent_type_description =
crate::agent::role::spawn_tool_spec::build(&turn_context.config.agent_roles);
if agent_type_description.is_empty() {
default_agent_type_description.to_string()
} else {
agent_type_description
}
}
fn is_hidden_by_code_mode_only(
turn_context: &TurnContext,
model_info: &ModelInfo,
tool_name: &ToolName,
exposure: ToolExposure,
) -> bool {
let tool_mode = effective_tool_mode(turn_context, model_info);
tool_mode == ToolMode::CodeModeOnly
&& exposure.is_available_in_code_mode()
&& codex_code_mode::is_code_mode_nested_tool(&codex_tools::code_mode_name_for_tool_name(
tool_name,
))
}
fn is_excluded_from_code_mode(turn_context: &TurnContext, tool_name: &ToolName) -> bool {
let tool_name = tool_name.clone().with_default_namespace();
tool_name.namespace.as_ref().is_some_and(|namespace| {
turn_context
.config
.code_mode
.excluded_tool_namespaces
.contains(namespace)
})
}
fn register_code_mode_executors(
turn_context: &TurnContext,
model_info: &ModelInfo,
registry: &mut ToolRegistry,
) -> BTreeMap<String, ToolName> {
let tool_mode = effective_tool_mode(turn_context, model_info);
if !matches!(tool_mode, ToolMode::CodeMode | ToolMode::CodeModeOnly) {
return BTreeMap::new();
}
let mut code_mode_tool_names = BTreeMap::new();
let mut code_mode_nested_tool_specs = Vec::new();
let mut exec_prompt_tool_specs = Vec::new();
let mut deferred_exec_prompt_tool_specs = Vec::new();
let mut included_deferred_mcp_output_schema = false;
let deferred_tools_guidance_enabled = search_tool_enabled(turn_context, model_info);
for tool in registry.entries() {
let exposure = tool.exposure;
if !exposure.is_available_in_code_mode() {
continue;
}
let tool_name = tool.runtime.tool_name();
if is_excluded_from_code_mode(turn_context, &tool_name) {
continue;
}
let immutable_spec = tool.runtime.immutable_spec();
let cached_runtime = immutable_spec.map(|_| Arc::clone(&tool.runtime));
let spec = immutable_spec
.map(Arc::clone)
.unwrap_or_else(|| Arc::new(tool.runtime.spec()));
// Derive the name without serializing and augmenting every tool schema.
let code_mode_name = match spec.as_ref() {
ToolSpec::Function(_) | ToolSpec::Freeform(_) => {
codex_tools::code_mode_name_for_tool_name(&tool_name)
}
ToolSpec::Namespace(namespace) if !namespace.tools.is_empty() => {
codex_tools::code_mode_name_for_tool_name(&tool_name)
}
ToolSpec::Namespace(_) | ToolSpec::ToolSearch { .. } | ToolSpec::WebSearch { .. } => {
continue;
}
};
if !codex_code_mode::is_code_mode_nested_tool(&code_mode_name) {
continue;
}
match code_mode_tool_names.entry(codex_code_mode::normalize_code_mode_identifier(
&code_mode_name,
)) {
Entry::Vacant(entry) => {
entry.insert(tool_name);
}
Entry::Occupied(_) => {
tracing::warn!(
tool_name = %tool_name,
code_mode_name = %code_mode_name,
"skipping tool with a duplicate normalized code-mode name"
);
continue;
}
}
if exposure == ToolExposure::Deferred {
if deferred_tools_guidance_enabled
&& (cached_runtime.is_none() || !included_deferred_mcp_output_schema)
{
if cached_runtime.is_some() {
included_deferred_mcp_output_schema = true;
}
deferred_exec_prompt_tool_specs.push(Arc::clone(&spec));
}
} else {
exec_prompt_tool_specs.push(spec.as_ref().clone());
}
code_mode_nested_tool_specs.push((spec, cached_runtime));
}
let namespace_descriptions = code_mode_namespace_descriptions(&exec_prompt_tool_specs);
let mut enabled_tools =
collect_code_mode_exec_prompt_tool_definitions(exec_prompt_tool_specs.iter());
let deferred_tools = collect_code_mode_exec_prompt_tool_definitions(
deferred_exec_prompt_tool_specs.iter().map(Arc::as_ref),
);
enabled_tools
.sort_by(|left, right| compare_code_mode_tools(left, right, &namespace_descriptions));
let model_messages = ResolvedModelMessages::from_model(model_info);
let execute_handler = CodeModeExecuteHandler::new(
create_code_mode_tool(
&enabled_tools,
&deferred_tools,
&namespace_descriptions,
turn_context.config.code_mode.default_exec_yield_time_ms,
tool_mode == ToolMode::CodeModeOnly,
if unified_image_budget_enabled(&turn_context.config.features, model_info) {
codex_code_mode::ImageDetailVisibility::Hidden
} else {
codex_code_mode::ImageDetailVisibility::Visible
},
model_messages.code_mode(),
),
code_mode_nested_tool_specs,
);
registry.prepend_trusted(Arc::new(CodeModeWaitHandler::new(
model_messages.code_mode_wait_description_override(),
model_messages.code_mode_wait_parameters_override(),
)));
registry.prepend_trusted(Arc::new(execute_handler));
code_mode_tool_names
}
#[instrument(level = "trace", skip_all, fields(tool_spec_count = specs.len()))]
fn merge_into_namespaces(specs: Vec<ToolSpec>) -> Vec<ToolSpec> {
let mut merged_specs = Vec::with_capacity(specs.len());
let mut namespace_indices = BTreeMap::<String, usize>::new();
for spec in specs {
match spec {
ToolSpec::Namespace(mut namespace) => {
if let Some(index) = namespace_indices.get(&namespace.name).copied() {
let ToolSpec::Namespace(existing_namespace) = &mut merged_specs[index] else {
unreachable!("namespace index must point to a namespace spec");
};
if existing_namespace.description.trim().is_empty()
&& !namespace.description.trim().is_empty()
{
existing_namespace.description = namespace.description;
}
existing_namespace.tools.append(&mut namespace.tools);
continue;
}
namespace_indices.insert(namespace.name.clone(), merged_specs.len());
merged_specs.push(ToolSpec::Namespace(namespace));
}
spec => merged_specs.push(spec),
}
}
for spec in &mut merged_specs {
let ToolSpec::Namespace(namespace) = spec else {
continue;
};
namespace.tools.sort_by(|left, right| {
let left_name = match left {
ResponsesApiNamespaceTool::Function(tool) => &tool.name,
ResponsesApiNamespaceTool::Custom(tool) => &tool.name,
};
let right_name = match right {
ResponsesApiNamespaceTool::Function(tool) => &tool.name,
ResponsesApiNamespaceTool::Custom(tool) => &tool.name,
};
left_name.cmp(right_name)
});
if namespace.description.trim().is_empty() {
namespace.description = default_namespace_description(&namespace.name);
}
}
merged_specs
}
fn code_mode_namespace_descriptions(
specs: &[ToolSpec],
) -> BTreeMap<String, codex_code_mode::ToolNamespaceDescription> {
let mut namespace_descriptions = BTreeMap::new();
for spec in specs {
let ToolSpec::Namespace(namespace) = spec else {
continue;
};
let entry = namespace_descriptions
.entry(namespace.name.clone())
.or_insert_with(|| codex_code_mode::ToolNamespaceDescription {
name: namespace.name.clone(),
description: namespace.description.clone(),
});
if entry.description.trim().is_empty() && !namespace.description.trim().is_empty() {
entry.description = namespace.description.clone();
}
}
namespace_descriptions
}
#[instrument(level = "trace", skip_all)]
fn add_core_tool_sources(context: &CoreToolPlanContext<'_>, registry: &mut ToolRegistry) {
// The startup ceiling applies to the thread and every selected environment.
if context.tool_policy.require_managed_sandbox
&& (!matches!(
context.turn_context.permission_profile(),
PermissionProfile::Managed { .. }
) || context.environments.turn_environments().any(|environment| {
!matches!(
environment.permission_profile(),
PermissionProfile::Managed { .. }
)
}))
{
return;
}
add_shell_tools(context, registry);
add_mcp_resource_tools(context, registry);
add_core_utility_tools(context, registry);
add_collaboration_tools(context, registry);
}
fn standalone_web_search_enabled(turn_context: &TurnContext, model_info: &ModelInfo) -> bool {
namespace_tools_enabled(turn_context)
&& turn_context.provider.capabilities().web_search
&& (model_info.use_responses_lite
|| turn_context