Repository navigation
Expand file tree
/
Copy pathopenai_models.rs
More file actions
2016 lines (1875 loc) · 75.4 KB
/
Copy pathopenai_models.rs
File metadata and controls
2016 lines (1875 loc) · 75.4 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
//! Shared model metadata types exchanged between Codex services and clients.
//!
//! These types are serialized across core, TUI, app-server, and SDK boundaries, so field defaults
//! are used to preserve compatibility when older payloads omit newly introduced attributes.
use std::fmt;
use std::str::FromStr;
use chrono::DateTime;
use chrono::Utc;
use schemars::JsonSchema;
use schemars::r#gen::SchemaGenerator;
use schemars::schema::InstanceType;
use schemars::schema::Metadata;
use schemars::schema::Schema;
use schemars::schema::SchemaObject;
use schemars::schema::StringValidation;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use serde::Serializer;
use serde::de::DeserializeOwned;
use serde::de::Error;
use strum_macros::Display;
use strum_macros::EnumIter;
use tracing::warn;
use ts_rs::TS;
use crate::config_types::ReasoningSummary;
use crate::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE;
use crate::config_types::ServiceTier;
use crate::config_types::Verbosity;
use crate::protocol::MultiAgentVersion;
mod access_programs;
#[path = "openai_models/guardian.rs"]
mod guardian;
pub use guardian::GuardianModelPolicy;
pub use guardian::GuardianReviewMode;
pub use guardian::GuardianScope;
pub use guardian::GuardianUnscoredAction;
#[path = "openai_models/guardian_v2.rs"]
mod guardian_v2;
#[path = "openai_models/reasoning_effort.rs"]
mod reasoning_effort;
pub use access_programs::ModelAccessPrograms;
pub use guardian_v2::GuardianV2ModelConfig;
pub use guardian_v2::GuardianV2TranscriptModelConfig;
/// Backend model-catalog specialty identifying cybersecurity-focused models.
pub const MODEL_SPECIALTY_CYBER: &str = "cyber";
pub const SPEED_TIER_FAST: &str = "fast";
/// See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning
#[derive(Debug, Default, Clone, PartialEq, Eq, TS, Hash)]
#[ts(type = "string")]
pub enum ReasoningEffort {
None,
Minimal,
Low,
#[default]
Medium,
High,
XHigh,
Max,
Ultra,
Persistent,
/// A model-defined effort value that this client does not know yet.
Custom(String),
}
impl ReasoningEffort {
/// Returns the exact value used on the wire.
pub fn as_str(&self) -> &str {
match self {
Self::None => "none",
Self::Minimal => "minimal",
Self::Low => "low",
Self::Medium => "medium",
Self::High => "high",
Self::XHigh => "xhigh",
Self::Max => "max",
Self::Ultra => "ultra",
Self::Persistent => "persistent",
Self::Custom(effort) => effort,
}
}
}
impl fmt::Display for ReasoningEffort {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl JsonSchema for ReasoningEffort {
fn schema_name() -> String {
"ReasoningEffort".to_string()
}
fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
Schema::Object(SchemaObject {
instance_type: Some(InstanceType::String.into()),
metadata: Some(Box::new(Metadata {
description: Some(
"A non-empty reasoning effort value advertised by the model.".to_string(),
),
..Default::default()
})),
string: Some(Box::new(StringValidation {
min_length: Some(1),
..Default::default()
})),
..Default::default()
})
}
}
impl Serialize for ReasoningEffort {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for ReasoningEffort {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let effort = String::deserialize(deserializer)?;
effort.parse().map_err(D::Error::custom)
}
}
impl FromStr for ReasoningEffort {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"none" => Ok(Self::None),
"minimal" => Ok(Self::Minimal),
"low" => Ok(Self::Low),
"medium" => Ok(Self::Medium),
"high" => Ok(Self::High),
"xhigh" => Ok(Self::XHigh),
"max" => Ok(Self::Max),
"ultra" => Ok(Self::Ultra),
"persistent" => Ok(Self::Persistent),
"" => Err("reasoning_effort must not be empty".to_string()),
effort => Ok(Self::Custom(effort.to_string())),
}
}
}
/// Canonical user-input modality tags advertised by a model.
#[derive(
Debug,
Serialize,
Deserialize,
Clone,
Copy,
PartialEq,
Eq,
Display,
JsonSchema,
TS,
EnumIter,
Hash,
)]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum InputModality {
/// Plain text turns and tool payloads.
Text,
/// Image attachments included in user turns.
Image,
/// Audio attachments included in user turns.
Audio,
}
/// Backward-compatible default when `input_modalities` is omitted on the wire.
///
/// Legacy payloads predate modality metadata, so we conservatively assume both text and images are
/// accepted unless a preset explicitly narrows support.
pub fn default_input_modalities() -> Vec<InputModality> {
vec![InputModality::Text, InputModality::Image]
}
/// A reasoning effort option that can be surfaced for a model.
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq, Eq)]
pub struct ReasoningEffortPreset {
/// Effort level that the model supports.
pub effort: ReasoningEffort,
/// Short human description shown next to the effort in UIs.
pub description: String,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq)]
pub struct ModelUpgrade {
pub id: String,
pub migration_config_key: String,
pub model_link: Option<String>,
pub upgrade_copy: Option<String>,
pub migration_markdown: Option<String>,
/// Informational time when the model associated with this upgrade is scheduled to retire.
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "deserialize_optional_rfc3339_timestamp"
)]
#[schemars(with = "Option<String>")]
#[ts(type = "string", optional)]
pub retirement_at: Option<DateTime<Utc>>,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq, Eq)]
pub struct ModelAvailabilityNux {
pub message: String,
}
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq, Eq)]
pub struct ModelServiceTier {
pub id: String,
pub name: String,
pub description: String,
}
/// Metadata describing a Codex-supported model.
#[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema, PartialEq)]
pub struct ModelPreset {
/// Stable identifier for the preset.
pub id: String,
/// Model slug (e.g., "gpt-5").
pub model: String,
/// Display name shown in UIs.
pub display_name: String,
/// Short human description shown in UIs.
pub description: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub model_specialty: Option<String>,
/// Reasoning effort applied when none is explicitly chosen.
pub default_reasoning_effort: ReasoningEffort,
/// Supported reasoning effort options.
pub supported_reasoning_efforts: Vec<ReasoningEffortPreset>,
/// Deprecated catalog field, always false for new model presets.
#[serde(default)]
pub supports_personality: bool,
/// Deprecated: use `service_tiers` instead.
#[serde(default)]
pub additional_speed_tiers: Vec<String>,
/// Service tiers this model can run with.
#[serde(default)]
pub service_tiers: Vec<ModelServiceTier>,
/// Catalog default service tier id for this model.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_service_tier: Option<String>,
/// Caller-specific explicit access programs, when discovery resolved them.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub available_access_programs: Option<ModelAccessPrograms>,
/// Whether this is the default model for new users.
pub is_default: bool,
/// recommended upgrade model
pub upgrade: Option<ModelUpgrade>,
/// Whether this preset should appear in the picker UI.
pub show_in_picker: bool,
/// Multi-agent backend selected when this model starts a new thread.
#[serde(default, skip_serializing, skip_deserializing)]
#[schemars(skip)]
#[ts(skip)]
pub multi_agent_version: Option<MultiAgentVersion>,
/// Availability NUX shown when this preset becomes accessible to the user.
pub availability_nux: Option<ModelAvailabilityNux>,
/// whether this model is supported in the api
pub supported_in_api: bool,
/// Input modalities accepted when composing user turns for this preset.
#[serde(default = "default_input_modalities")]
pub input_modalities: Vec<InputModality>,
}
/// Visibility of a model in the picker or APIs.
#[derive(
Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, TS, JsonSchema, EnumIter, Display,
)]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum ModelVisibility {
List,
Hide,
None,
}
/// Shell execution capability for a model.
#[derive(
Debug,
Serialize,
Deserialize,
Clone,
Copy,
PartialEq,
Eq,
TS,
JsonSchema,
EnumIter,
Display,
Hash,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum ConfigShellToolType {
#[serde(alias = "default", alias = "local", alias = "shell_command")]
UnifiedExec,
Disabled,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, TS, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ApplyPatchToolType {
Freeform,
}
#[derive(
Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash, TS, JsonSchema, Default,
)]
#[serde(rename_all = "snake_case")]
pub enum WebSearchToolType {
#[default]
Text,
TextAndImage,
}
/// Server-provided truncation policy metadata for a model.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, TS, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum TruncationMode {
Bytes,
Tokens,
}
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, TS, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ToolMode {
Direct,
CodeMode,
CodeModeOnly,
}
fn deserialize_optional_model_selector<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
D: Deserializer<'de>,
T: DeserializeOwned,
{
let Some(value) = Option::<String>::deserialize(deserializer)? else {
return Ok(None);
};
Ok(serde_json::from_value(serde_json::Value::String(value)).ok())
}
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, TS, JsonSchema)]
pub struct TruncationPolicyConfig {
pub mode: TruncationMode,
pub limit: i64,
}
impl TruncationPolicyConfig {
pub const fn bytes(limit: i64) -> Self {
Self {
mode: TruncationMode::Bytes,
limit,
}
}
pub const fn tokens(limit: i64) -> Self {
Self {
mode: TruncationMode::Tokens,
limit,
}
}
}
/// Semantic version triple encoded as an array in JSON (e.g. [0, 62, 0]).
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, TS, JsonSchema)]
pub struct ClientVersion(pub i32, pub i32, pub i32);
const fn default_effective_context_window_percent() -> i64 {
95
}
const fn default_true() -> bool {
true
}
#[allow(clippy::trivially_copy_pass_by_ref)]
const fn is_true(value: &bool) -> bool {
*value
}
/// Model metadata returned by the Codex backend `/models` endpoint.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct ModelInfo {
/// Model-owned approval coverage. Absent preserves legacy settings; an empty map disables
/// ordinary Guardian review. Keys are computer_use, shell, file_changes, mcp, network,
/// and permissions. This does not override mandatory safety or administrator requirements.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub guardian: Option<GuardianModelPolicy>,
pub slug: String,
pub display_name: String,
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_reasoning_level: Option<ReasoningEffort>,
pub supported_reasoning_levels: Vec<ReasoningEffortPreset>,
pub shell_type: ConfigShellToolType,
pub visibility: ModelVisibility,
pub supported_in_api: bool,
pub priority: i32,
#[serde(default)]
pub additional_speed_tiers: Vec<String>,
#[serde(default)]
pub service_tiers: Vec<ModelServiceTier>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_service_tier: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub available_access_programs: Option<ModelAccessPrograms>,
pub availability_nux: Option<ModelAvailabilityNux>,
pub upgrade: Option<ModelInfoUpgrade>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub model_messages: Option<ModelMessages>,
#[serde(default)]
pub include_skills_usage_instructions: bool,
#[serde(default)]
pub include_plugin_usage_instructions: bool,
#[serde(default = "default_true")]
pub include_apps_usage_instructions: bool,
/// Whether the model accepts the Responses API `reasoning.summary` parameter.
#[serde(default = "default_true", skip_serializing_if = "is_true")]
pub supports_reasoning_summary_parameter: bool,
#[serde(default)]
pub default_reasoning_summary: ReasoningSummary,
pub support_verbosity: bool,
pub default_verbosity: Option<Verbosity>,
pub apply_patch_tool_type: Option<ApplyPatchToolType>,
#[serde(default)]
pub web_search_tool_type: WebSearchToolType,
pub truncation_policy: TruncationPolicyConfig,
#[serde(default)]
pub supports_image_detail_original: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub context_window: Option<i64>,
/// Maximum context window allowed for config overrides.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_context_window: Option<i64>,
/// Token threshold for automatic compaction. When omitted, core derives it
/// from `context_window` (90%). When provided, core clamps it to 90% of the
/// context window when available.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auto_compact_token_limit: Option<i64>,
/// Opaque identifier for compaction-compatible model configurations.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub comp_hash: Option<String>,
/// Percentage of the context window considered usable for inputs, after
/// reserving headroom for system prompts, tool overhead, and model output.
#[serde(default = "default_effective_context_window_percent")]
pub effective_context_window_percent: i64,
pub experimental_supported_tools: Vec<String>,
/// Input modalities accepted by the backend for this model.
#[serde(default = "default_input_modalities")]
pub input_modalities: Vec<InputModality>,
/// Internal-only marker set by core when a model slug resolved to fallback metadata.
#[serde(default, skip_serializing, skip_deserializing)]
#[schemars(skip)]
#[ts(skip)]
pub used_fallback_model_metadata: bool,
#[serde(default)]
pub supports_search_tool: bool,
/// Whether experimental context management may be activated at session startup.
#[serde(default)]
pub supports_experimental_context: bool,
#[serde(default)]
pub use_responses_lite: bool,
/// Whether the model accepts reasoning-effort `configuration_update` items.
/// Missing metadata keeps effort changes on the ordinary request parameter.
#[serde(default)]
pub supports_reasoning_effort_updates: bool,
#[serde(default)]
pub node_repl_auto_review_required: bool,
#[serde(default)]
pub node_repl_disabled: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auto_review_model_override: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub model_specialty: Option<String>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "deserialize_optional_model_selector"
)]
pub tool_mode: Option<ToolMode>,
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "deserialize_optional_model_selector"
)]
pub multi_agent_version: Option<MultiAgentVersion>,
/// Reasoning effort used for multi-agent work when the user selects Ultra.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub multi_agent_reasoning_effort: Option<ReasoningEffort>,
}
impl ModelInfo {
pub fn resolved_context_window(&self) -> Option<i64> {
self.context_window.or(self.max_context_window)
}
/// Context available to inference after reserving this model's configured headroom.
pub fn usable_context_window(&self) -> Option<i64> {
self.resolved_context_window().map(|context_window| {
context_window.saturating_mul(self.effective_context_window_percent) / 100
})
}
pub fn auto_compact_token_limit(&self) -> Option<i64> {
let context_limit = self
.resolved_context_window()
.map(|context_window| (context_window * 9) / 10);
let config_limit = self.auto_compact_token_limit;
if let Some(context_limit) = context_limit {
return Some(
config_limit.map_or(context_limit, |limit| std::cmp::min(limit, context_limit)),
);
}
config_limit
}
}
/// A strongly-typed template for assembling model instructions and developer messages.
///
/// `instructions_template` is literal text. The deprecated `instructions_variables` field is
/// retained to decode catalogs produced before personality selection was removed.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct ModelMessages {
/// Developer guidance after a content-filter block. Missing, null, blank, or values over
/// 512 UTF-8 bytes use the bundled guidance.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content_filter_guidance: Option<String>,
/// Additional developer instructions for persistent mode. Missing or null uses the built-in
/// instructions; an empty string disables them.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub persistent_instructions: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tools: Option<ToolMessages>,
pub instructions_template: Option<String>,
pub instructions_variables: Option<ModelInstructionsVariables>,
pub approvals: Option<ApprovalMessages>,
pub collaboration_modes: Option<CollaborationModeMessages>,
pub auto_review: Option<AutoReviewMessages>,
pub permissions: Option<PermissionMessages>,
pub multi_agent: Option<MultiAgentMessages>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub token_budget: Option<ModelTokenBudgetConfig>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub guardian_v2: Option<GuardianV2ModelConfig>,
/// Replacement confirmation-policy documents forwarded in actor MCP request metadata.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub confirmation_policies: Option<ConfirmationPolicies>,
}
/// Model-owned confirmation-policy Markdown, forwarded unchanged to actor tools.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct ConfirmationPolicies {
/// Replacement Markdown for the Browser Use confirmation-policy document.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub browser_use: Option<String>,
/// Replacement Markdown for the native Computer Use confirmation policy.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub computer_use: Option<String>,
}
/// Model-owned tool messages and indirect namespace guidance.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct ToolMessages {
/// Optional guidance for indirectly presented tools; missing or empty adds no prefix.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub indirect_description_prefixes: Option<IndirectDescriptionPrefixes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub send_user_message_async: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub multi_agent: Option<MultiAgentToolMessages>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code_mode: Option<CodeModeToolMessages>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mcp_resources: Option<McpResourceToolMessages>,
}
/// Plain-text prefixes for Code Mode documentation, ALL_TOOLS, and loaded tool-search namespaces.
/// Values are trimmed, and selectors for the same final namespace must agree, including empty values.
/// Empty values add no prefix; unregistered targets are ignored.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct IndirectDescriptionPrefixes {
/// Exact rendered namespaces, including `functions` for plain tools.
/// Overlap with an MCP server prefix is allowed only when the trimmed values match.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub namespaces: Option<std::collections::BTreeMap<String, String>>,
/// Configured MCP server names, before callable namespace normalization.
/// Each prefix applies to all namespaces exposed by that server.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mcp_servers: Option<std::collections::BTreeMap<String, String>>,
}
/// Model-owned messages for a built-in tool.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct ToolMessage {
/// Missing or null uses the built-in description; an empty string suppresses its static
/// text without disabling the tool. Tool-owned runtime guidance is retained.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// Complete JSON Schema encoded as a string. Consumed by Multi-Agent V2 tools, Code Mode wait,
/// request_user_input_async (the send_user_message_async catalog key), and MCP resource helpers.
/// Uses the harness's supported schema subset; unrecognized keywords are ignored.
/// Missing, null, invalid or unsupported structures, or a root without `type: "object"`
/// retains the harness parameters. Schema semantics must remain API-compatible.
/// Overrides must declare harness-encrypted properties so their annotations can be retained.
/// Argument handling is unchanged.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parameters: Option<String>,
}
/// Model-owned descriptions and parameters for Multi-Agent V2 tools, independent of their namespace.
/// Channel tools consume only the description; their parameter schemas are fixed.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct MultiAgentToolMessages {
/// Replaces the static description. Missing or null uses the bundled text; an empty string
/// suppresses it. Generated model information and local usage hints are retained.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub spawn_agent: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub send_message: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub followup_task: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub wait_agent: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub interrupt_agent: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub list_agents: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub create_channel: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub get_channels: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub list_threads: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub search_posts: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub read_thread: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub read_post: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub subscribe: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unsubscribe: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub post: Option<ToolMessage>,
}
impl MultiAgentToolMessages {
/// Returns the catalog entry for a tool, independently of its runtime namespace.
pub fn by_name(&self, name: &str) -> Option<&ToolMessage> {
match name {
"spawn_agent" => &self.spawn_agent,
"send_message" => &self.send_message,
"followup_task" => &self.followup_task,
"wait_agent" => &self.wait_agent,
"interrupt_agent" => &self.interrupt_agent,
"list_agents" => &self.list_agents,
"create_channel" => &self.create_channel,
"get_channels" => &self.get_channels,
"list_threads" => &self.list_threads,
"search_posts" => &self.search_posts,
"read_thread" => &self.read_thread,
"read_post" => &self.read_post,
"subscribe" => &self.subscribe,
"unsubscribe" => &self.unsubscribe,
"post" => &self.post,
_ => return None,
}
.as_ref()
}
}
/// Model-owned descriptions and parameters for the built-in MCP resource helpers.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct McpResourceToolMessages {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub list_mcp_resources: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub list_mcp_resource_templates: Option<ToolMessage>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub read_mcp_resource: Option<ToolMessage>,
}
/// Model-owned instructions for Code Mode's exec and wait tools.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct CodeModeToolMessages {
/// Instructional template supporting `{{ default_exec_yield_time_ms }}` and `{{ image_helper }}`.
/// Runtime tool declarations are appended. Unknown placeholders remain literal.
/// Exec accepts raw JavaScript; `parameters` is not consumed and its grammar is unchanged.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub exec: Option<ToolMessage>,
/// Complete description and JSON parameter schema, selected independently.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub wait: Option<ToolMessage>,
/// Literal guidance appended when deferred nested tools exist.
/// Missing or null uses bundled text; an empty string omits the section.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub deferred_nested_tools_guidance: Option<String>,
/// Literal shared TypeScript definitions, emitted when Code Mode Only exposes MCP results.
/// Missing or null uses bundled definitions; an empty string omits the section.
/// Custom definitions must remain compatible with the generated tool declarations.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mcp_typescript_preamble: Option<String>,
}
/// Model-owned defaults for the context-window token-budget feature.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct ModelTokenBudgetConfig {
#[serde(default)]
pub enabled: bool,
#[serde(default)]
pub use_history_notes_extension: bool,
pub reminder_threshold_tokens: i64,
pub reminder_message_template: String,
pub guidance_message: String,
pub auto_compact_fallback_prompt: String,
pub auto_compact_fallback_buffer_tokens: i64,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct ApprovalMessages {
pub on_request: Option<String>,
pub on_request_auto_review: Option<String>,
pub never: Option<String>,
pub unless_trusted: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct CollaborationModeMessages {
pub default: Option<String>,
pub plan: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct AutoReviewMessages {
pub policy: Option<String>,
pub policy_template: Option<String>,
/// Extra developer policy for `node_repl` and `cua_repl` reviews.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub node_repl_policy: Option<String>,
pub rejection_instructions: Option<String>,
pub timeout_instructions: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct PermissionMessages {
pub danger_full_access: Option<String>,
pub workspace_write: Option<String>,
pub read_only: Option<String>,
}
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct MultiAgentMessages {
pub role: Option<MultiAgentRoleMessages>,
pub mode: Option<MultiAgentModeMessages>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct MultiAgentRoleMessages {
pub root: Option<String>,
pub subagent: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct MultiAgentModeMessages {
pub explicit: Option<String>,
/// Ultra-only mode instructions. Missing or null uses the built-in proactive hint;
/// an empty string suppresses the mode message. `hint_text` takes precedence.
pub proactive: Option<String>,
pub hint_text: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct ModelInstructionsVariables {
pub personality_default: Option<String>,
pub personality_friendly: Option<String>,
pub personality_pragmatic: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct ModelInfoUpgrade {
pub model: String,
pub migration_markdown: String,
/// Informational time when the model associated with this upgrade is scheduled to retire.
#[serde(
default,
skip_serializing_if = "Option::is_none",
deserialize_with = "deserialize_optional_rfc3339_timestamp"
)]
#[schemars(with = "Option<String>")]
#[ts(type = "string", optional)]
pub retirement_at: Option<DateTime<Utc>>,
}
fn deserialize_optional_rfc3339_timestamp<'de, D>(
deserializer: D,
) -> Result<Option<DateTime<Utc>>, D::Error>
where
D: Deserializer<'de>,
{
let value = Option::<serde_json::Value>::deserialize(deserializer)?;
Ok(value
.as_ref()
.and_then(serde_json::Value::as_str)
.and_then(|value| DateTime::parse_from_rfc3339(value).ok())
.map(|value| value.with_timezone(&Utc)))
}
impl From<&ModelUpgrade> for ModelInfoUpgrade {
fn from(upgrade: &ModelUpgrade) -> Self {
ModelInfoUpgrade {
model: upgrade.id.clone(),
migration_markdown: upgrade.migration_markdown.clone().unwrap_or_default(),
retirement_at: upgrade.retirement_at,
}
}
}
/// Response wrapper for `/models`.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema, Default)]
pub struct ModelsResponse {
#[serde(
serialize_with = "serialize_model_infos_with_legacy_base",
deserialize_with = "deserialize_model_infos_with_legacy_base"
)]
pub models: Vec<ModelInfo>,
}
#[derive(Serialize)]
struct ModelInfoWithLegacyBaseInstructionsRef<'a> {
#[serde(flatten)]
model: &'a ModelInfo,
base_instructions: String,
}
#[derive(Deserialize)]
struct ModelInfoWithLegacyBaseInstructions {
#[serde(default)]
base_instructions: Option<String>,
#[serde(flatten)]
model: ModelInfo,
}
/// Serializes catalog models with the deprecated top-level instruction field required by older
/// clients.
#[doc(hidden)]
pub fn serialize_model_infos_with_legacy_base<S>(
models: &[ModelInfo],
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
models
.iter()
.map(|model| {
// Mirror the literal instruction template for clients using the deprecated wire field.
let base_instructions = if let Some(template) = model
.model_messages
.as_ref()
.and_then(|messages| messages.instructions_template.as_deref())
{
template.to_owned()
} else {
warn!(
model = %model.slug,
"Model has no instruction template; returning empty instructions."
);
String::new()
};
ModelInfoWithLegacyBaseInstructionsRef {
model,
base_instructions,
}
})
.collect::<Vec<_>>()
.serialize(serializer)
}
/// Deserializes catalog models while promoting the legacy top-level instruction field into Model
/// Messages V2 when no canonical instruction template is present.
#[doc(hidden)]
pub fn deserialize_model_infos_with_legacy_base<'de, D>(
deserializer: D,
) -> Result<Vec<ModelInfo>, D::Error>
where
D: Deserializer<'de>,
{
let models = Vec::<ModelInfoWithLegacyBaseInstructions>::deserialize(deserializer)?;
models
.into_iter()
.map(|legacy_model| {
let ModelInfoWithLegacyBaseInstructions {
base_instructions,
mut model,
} = legacy_model;
if let Some(base_instructions) = base_instructions
&& model
.model_messages
.as_ref()
.and_then(|messages| messages.instructions_template.as_ref())
.is_none()
{
let messages = model.model_messages.get_or_insert_default();
messages.instructions_template = Some(base_instructions);
}
if model
.model_messages
.as_ref()
.and_then(|messages| messages.instructions_template.as_ref())
.is_none()
{
let model_slug = &model.slug;
return Err(D::Error::custom(format!(
"model `{model_slug}` is missing both `base_instructions` and \
`model_messages.instructions_template`"
)));
}
Ok(model)
})
.collect()
}
// convert ModelInfo to ModelPreset
impl From<ModelInfo> for ModelPreset {
fn from(info: ModelInfo) -> Self {
ModelPreset {
id: info.slug.clone(),
model: info.slug.clone(),
display_name: info.display_name,
description: info.description.unwrap_or_default(),
model_specialty: info.model_specialty,
default_reasoning_effort: info
.default_reasoning_level
.unwrap_or(ReasoningEffort::None),
supported_reasoning_efforts: info.supported_reasoning_levels.clone(),
supports_personality: false,
additional_speed_tiers: info.additional_speed_tiers,
service_tiers: info.service_tiers,
default_service_tier: info.default_service_tier,
available_access_programs: info.available_access_programs,
is_default: false, // default is the highest priority available model
upgrade: info.upgrade.as_ref().map(|upgrade| ModelUpgrade {
id: upgrade.model.clone(),
migration_config_key: info.slug.clone(),
// todo(aibrahim): add the model link here.
model_link: None,
upgrade_copy: None,
migration_markdown: Some(upgrade.migration_markdown.clone()),
retirement_at: upgrade.retirement_at,
}),
show_in_picker: info.visibility == ModelVisibility::List,
multi_agent_version: info.multi_agent_version,
availability_nux: info.availability_nux,
supported_in_api: info.supported_in_api,
input_modalities: info.input_modalities,
}
}
}
impl ModelPreset {
pub fn supports_fast_mode(&self) -> bool {
self.service_tiers
.iter()
.any(|tier| tier.id == ServiceTier::Fast.request_value())
|| self
.additional_speed_tiers
.iter()
.any(|tier| tier == SPEED_TIER_FAST)
}
}
impl ModelInfo {
pub fn supports_service_tier(&self, service_tier: &str) -> bool {
// Flex is an API request option, even when the Codex catalog does not advertise it.
service_tier == ServiceTier::Flex.request_value()
|| self
.service_tiers
.iter()