@howaboua/pi-codex-web-run 0.0.6 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,318 +0,0 @@
1
- use crate::auth::SharedAuthProvider;
2
- use crate::endpoint::session::EndpointSession;
3
- use crate::error::ApiError;
4
- use crate::provider::Provider;
5
- use crate::search::SearchRequest;
6
- use crate::search::SearchResponse;
7
- use codex_client::HttpTransport;
8
- use codex_client::RequestTelemetry;
9
- use http::HeaderMap;
10
- use http::Method;
11
- use serde_json::to_value;
12
- use std::sync::Arc;
13
-
14
- pub struct SearchClient<T: HttpTransport> {
15
- session: EndpointSession<T>,
16
- }
17
-
18
- impl<T: HttpTransport> SearchClient<T> {
19
- pub fn new(transport: T, provider: Provider, auth: SharedAuthProvider) -> Self {
20
- Self {
21
- session: EndpointSession::new(transport, provider, auth),
22
- }
23
- }
24
-
25
- pub fn with_telemetry(self, request: Option<Arc<dyn RequestTelemetry>>) -> Self {
26
- Self {
27
- session: self.session.with_request_telemetry(request),
28
- }
29
- }
30
-
31
- fn path() -> &'static str {
32
- "alpha/search"
33
- }
34
-
35
- pub async fn search(
36
- &self,
37
- request: &SearchRequest,
38
- extra_headers: HeaderMap,
39
- ) -> Result<SearchResponse, ApiError> {
40
- let body = to_value(request)
41
- .map_err(|e| ApiError::Stream(format!("failed to encode search request: {e}")))?;
42
- let resp = self
43
- .session
44
- .execute(Method::POST, Self::path(), extra_headers, Some(body))
45
- .await?;
46
- serde_json::from_slice(&resp.body)
47
- .map_err(|e| ApiError::Stream(format!("failed to decode search response: {e}")))
48
- }
49
- }
50
-
51
- #[cfg(test)]
52
- mod tests {
53
- use super::*;
54
- use crate::auth::AuthProvider;
55
- use crate::provider::RetryConfig;
56
- use crate::search::AllowedCaller;
57
- use crate::search::ApproximateLocation;
58
- use crate::search::ExternalWebAccess;
59
- use crate::search::LocationType;
60
- use crate::search::OpenOperation;
61
- use crate::search::SearchCommands;
62
- use crate::search::SearchContextSize;
63
- use crate::search::SearchFilters;
64
- use crate::search::SearchImageSettings;
65
- use crate::search::SearchInput;
66
- use crate::search::SearchQuery;
67
- use crate::search::SearchSettings;
68
- use codex_client::Request;
69
- use codex_client::RequestBody;
70
- use codex_client::Response;
71
- use codex_client::StreamResponse;
72
- use codex_client::TransportError;
73
- use codex_protocol::ResponseItemId;
74
- use codex_protocol::models::ContentItem;
75
- use codex_protocol::models::ResponseItem;
76
- use http::StatusCode;
77
- use pretty_assertions::assert_eq;
78
- use serde_json::json;
79
- use std::sync::Mutex;
80
- use std::time::Duration;
81
-
82
- #[derive(Clone, Default)]
83
- struct DummyAuth;
84
-
85
- impl AuthProvider for DummyAuth {
86
- fn add_auth_headers(&self, _headers: &mut HeaderMap) {}
87
- }
88
-
89
- #[derive(Clone)]
90
- struct CapturingTransport {
91
- last_request: Arc<Mutex<Option<Request>>>,
92
- response_body: Arc<Vec<u8>>,
93
- }
94
-
95
- impl CapturingTransport {
96
- fn new(response_body: Vec<u8>) -> Self {
97
- Self {
98
- last_request: Arc::new(Mutex::new(None)),
99
- response_body: Arc::new(response_body),
100
- }
101
- }
102
- }
103
-
104
- impl HttpTransport for CapturingTransport {
105
- async fn execute(&self, req: Request) -> Result<Response, TransportError> {
106
- *self.last_request.lock().expect("lock request store") = Some(req);
107
- Ok(Response {
108
- status: StatusCode::OK,
109
- headers: HeaderMap::new(),
110
- body: self.response_body.as_ref().clone().into(),
111
- })
112
- }
113
-
114
- async fn stream(&self, _req: Request) -> Result<StreamResponse, TransportError> {
115
- Err(TransportError::Build("stream should not run".to_string()))
116
- }
117
- }
118
-
119
- fn provider() -> Provider {
120
- Provider {
121
- name: "test".to_string(),
122
- base_url: "https://example.com/v1".to_string(),
123
- query_params: None,
124
- headers: HeaderMap::new(),
125
- retry: RetryConfig {
126
- max_attempts: 1,
127
- base_delay: Duration::from_millis(1),
128
- retry_429: false,
129
- retry_5xx: true,
130
- retry_transport: true,
131
- },
132
- stream_idle_timeout: Duration::from_secs(1),
133
- }
134
- }
135
-
136
- #[tokio::test]
137
- async fn search_posts_typed_request_and_parses_output() {
138
- let transport = CapturingTransport::new(
139
- serde_json::to_vec(&json!({
140
- "encrypted_output": "ciphertext",
141
- "output": "search result",
142
- "results": [{
143
- "type": "text_result",
144
- "ref_id": "turn0search0",
145
- "url": "https://example.com/result",
146
- "future_field": {"preserved": true},
147
- }],
148
- }))
149
- .expect("serialize response"),
150
- );
151
- let client = SearchClient::new(transport.clone(), provider(), Arc::new(DummyAuth));
152
-
153
- let response = client
154
- .search(
155
- &SearchRequest {
156
- id: "search-session".to_string(),
157
- model: "gpt-test".to_string(),
158
- reasoning: None,
159
- input: Some(SearchInput::Items(vec![ResponseItem::Message {
160
- id: Some(ResponseItemId::with_suffix("msg", "search")),
161
- role: "user".to_string(),
162
- content: vec![
163
- ContentItem::InputText {
164
- text: "find this".to_string(),
165
- },
166
- ContentItem::InputImage {
167
- image_url: "https://example.com/image.png".to_string(),
168
- detail: None,
169
- },
170
- ],
171
- phase: None,
172
- internal_chat_message_metadata_passthrough: None,
173
- }])),
174
- commands: Some(SearchCommands {
175
- search_query: Some(vec![SearchQuery {
176
- q: "OpenAI news".to_string(),
177
- recency: Some(7),
178
- domains: Some(vec!["openai.com".to_string()]),
179
- }]),
180
- open: Some(vec![OpenOperation {
181
- ref_id: "https://openai.com".to_string(),
182
- lineno: Some(12),
183
- }]),
184
- ..Default::default()
185
- }),
186
- settings: Some(SearchSettings {
187
- user_location: Some(ApproximateLocation {
188
- r#type: LocationType::Approximate,
189
- country: Some("US".to_string()),
190
- region: None,
191
- city: Some("San Francisco".to_string()),
192
- timezone: None,
193
- }),
194
- search_context_size: Some(SearchContextSize::Low),
195
- filters: Some(SearchFilters {
196
- allowed_domains: Some(vec!["openai.com".to_string()]),
197
- blocked_domains: Some(vec!["example.com".to_string()]),
198
- }),
199
- image_settings: Some(SearchImageSettings {
200
- max_results: Some(4),
201
- caption: Some(true),
202
- }),
203
- allowed_callers: Some(vec![AllowedCaller::Direct]),
204
- external_web_access: Some(ExternalWebAccess::Boolean(true)),
205
- }),
206
- max_output_tokens: Some(2500),
207
- },
208
- HeaderMap::new(),
209
- )
210
- .await
211
- .expect("search request should succeed");
212
-
213
- assert_eq!(
214
- response,
215
- SearchResponse {
216
- encrypted_output: Some("ciphertext".to_string()),
217
- output: "search result".to_string(),
218
- results: Some(vec![json!({
219
- "type": "text_result",
220
- "ref_id": "turn0search0",
221
- "url": "https://example.com/result",
222
- "future_field": {"preserved": true},
223
- })]),
224
- }
225
- );
226
-
227
- let request = transport
228
- .last_request
229
- .lock()
230
- .expect("lock request store")
231
- .clone()
232
- .expect("request should be captured");
233
- let body = request
234
- .body
235
- .as_ref()
236
- .and_then(RequestBody::json)
237
- .expect("request body should be JSON");
238
- assert_eq!(
239
- body,
240
- &json!({
241
- "id": "search-session",
242
- "model": "gpt-test",
243
- "input": [{
244
- "type": "message",
245
- "id": "msg_search",
246
- "role": "user",
247
- "content": [
248
- {"type": "input_text", "text": "find this"},
249
- {
250
- "type": "input_image",
251
- "image_url": "https://example.com/image.png"
252
- }
253
- ]
254
- }],
255
- "commands": {
256
- "search_query": [{
257
- "q": "OpenAI news",
258
- "recency": 7,
259
- "domains": ["openai.com"]
260
- }],
261
- "open": [{"ref_id": "https://openai.com", "lineno": 12}]
262
- },
263
- "settings": {
264
- "user_location": {
265
- "type": "approximate",
266
- "country": "US",
267
- "city": "San Francisco"
268
- },
269
- "search_context_size": "low",
270
- "filters": {
271
- "allowed_domains": ["openai.com"],
272
- "blocked_domains": ["example.com"]
273
- },
274
- "image_settings": {"max_results": 4, "caption": true},
275
- "allowed_callers": ["direct"],
276
- "external_web_access": true
277
- },
278
- "max_output_tokens": 2500
279
- })
280
- );
281
- }
282
- #[test]
283
- fn search_response_defaults_missing_results_for_older_endpoints() {
284
- let response: SearchResponse = serde_json::from_value(json!({
285
- "encrypted_output": null,
286
- "output": "search result",
287
- }))
288
- .expect("response without results should deserialize");
289
-
290
- assert_eq!(
291
- response,
292
- SearchResponse {
293
- encrypted_output: None,
294
- output: "search result".to_string(),
295
- results: None,
296
- }
297
- );
298
- }
299
-
300
- #[test]
301
- fn search_response_preserves_supported_empty_results() {
302
- let response: SearchResponse = serde_json::from_value(json!({
303
- "encrypted_output": null,
304
- "output": "search result",
305
- "results": [],
306
- }))
307
- .expect("response with empty results should deserialize");
308
-
309
- assert_eq!(
310
- response,
311
- SearchResponse {
312
- encrypted_output: None,
313
- output: "search result".to_string(),
314
- results: Some(Vec::new()),
315
- }
316
- );
317
- }
318
- }
@@ -1,305 +0,0 @@
1
- use crate::common::Reasoning;
2
- use codex_protocol::models::ResponseItem;
3
- use schemars::JsonSchema;
4
- use serde::Deserialize;
5
- use serde::Serialize;
6
- use serde_json::Value as JsonValue;
7
-
8
- #[derive(Debug, Clone, Serialize, PartialEq)]
9
- pub struct SearchRequest {
10
- pub id: String,
11
- pub model: String,
12
- #[serde(skip_serializing_if = "Option::is_none")]
13
- pub reasoning: Option<Reasoning>,
14
- #[serde(skip_serializing_if = "Option::is_none")]
15
- pub input: Option<SearchInput>,
16
- #[serde(skip_serializing_if = "Option::is_none")]
17
- pub commands: Option<SearchCommands>,
18
- #[serde(skip_serializing_if = "Option::is_none")]
19
- pub settings: Option<SearchSettings>,
20
- #[serde(skip_serializing_if = "Option::is_none")]
21
- pub max_output_tokens: Option<u64>,
22
- }
23
-
24
- #[derive(Debug, Clone, Serialize, PartialEq)]
25
- #[serde(untagged)]
26
- pub enum SearchInput {
27
- Text(String),
28
- Items(Vec<ResponseItem>),
29
- }
30
-
31
- #[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, JsonSchema)]
32
- pub struct SearchCommands {
33
- /// Query the internet search engine for a given list of queries.
34
- #[serde(skip_serializing_if = "Option::is_none")]
35
- pub search_query: Option<Vec<SearchQuery>>,
36
- /// Query the image search engine for a given list of queries.
37
- #[serde(skip_serializing_if = "Option::is_none")]
38
- pub image_query: Option<Vec<SearchQuery>>,
39
- /// Open pages by reference id or URL.
40
- #[serde(skip_serializing_if = "Option::is_none")]
41
- pub open: Option<Vec<OpenOperation>>,
42
- /// Open links from previously opened pages.
43
- #[serde(skip_serializing_if = "Option::is_none")]
44
- pub click: Option<Vec<ClickOperation>>,
45
- /// Find text patterns in pages.
46
- #[serde(skip_serializing_if = "Option::is_none")]
47
- pub find: Option<Vec<FindOperation>>,
48
- /// Take screenshots of PDF pages.
49
- #[serde(skip_serializing_if = "Option::is_none")]
50
- pub screenshot: Option<Vec<ScreenshotOperation>>,
51
- /// Look up prices for the given stock symbols.
52
- #[serde(skip_serializing_if = "Option::is_none")]
53
- pub finance: Option<Vec<FinanceOperation>>,
54
- /// Look up weather forecasts.
55
- #[serde(skip_serializing_if = "Option::is_none")]
56
- pub weather: Option<Vec<WeatherOperation>>,
57
- /// Look up sports schedules and standings.
58
- #[serde(skip_serializing_if = "Option::is_none")]
59
- pub sports: Option<Vec<SportsOperation>>,
60
- /// Get time for the given UTC offsets.
61
- #[serde(skip_serializing_if = "Option::is_none")]
62
- pub time: Option<Vec<TimeOperation>>,
63
- /// Set the length of the response to be returned.
64
- #[serde(skip_serializing_if = "Option::is_none")]
65
- pub response_length: Option<SearchResponseLength>,
66
- }
67
-
68
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
69
- pub struct SearchQuery {
70
- /// Search query.
71
- pub q: String,
72
- /// Whether to filter by recency, as a number of recent days.
73
- #[serde(skip_serializing_if = "Option::is_none")]
74
- pub recency: Option<u64>,
75
- /// Whether to filter by a specific list of domains.
76
- #[serde(skip_serializing_if = "Option::is_none")]
77
- pub domains: Option<Vec<String>>,
78
- }
79
-
80
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
81
- pub struct OpenOperation {
82
- /// Reference id or URL to open.
83
- pub ref_id: String,
84
- /// Line number to position the page at.
85
- #[serde(skip_serializing_if = "Option::is_none")]
86
- pub lineno: Option<u64>,
87
- }
88
-
89
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
90
- pub struct ClickOperation {
91
- /// Reference id containing the numbered link.
92
- pub ref_id: String,
93
- /// Numbered link id to open.
94
- pub id: u64,
95
- }
96
-
97
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
98
- pub struct FindOperation {
99
- /// Reference id or URL to search within.
100
- pub ref_id: String,
101
- /// Text pattern to find.
102
- pub pattern: String,
103
- }
104
-
105
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
106
- pub struct ScreenshotOperation {
107
- /// Reference id or URL to screenshot.
108
- pub ref_id: String,
109
- /// Zero-indexed PDF page number.
110
- pub pageno: u64,
111
- }
112
-
113
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
114
- pub struct FinanceOperation {
115
- /// Ticker symbol to look up.
116
- pub ticker: String,
117
- /// Asset type to look up.
118
- pub r#type: FinanceAssetType,
119
- /// ISO 3166-1 alpha-3 country code, "OTC", or "" for cryptocurrency.
120
- #[serde(skip_serializing_if = "Option::is_none")]
121
- pub market: Option<String>,
122
- }
123
-
124
- #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
125
- #[serde(rename_all = "lowercase")]
126
- pub enum FinanceAssetType {
127
- Equity,
128
- Fund,
129
- Crypto,
130
- Index,
131
- }
132
-
133
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
134
- pub struct WeatherOperation {
135
- /// Location in "Country, Area, City" format.
136
- pub location: String,
137
- /// Start date in YYYY-MM-DD format. Defaults to today.
138
- #[serde(skip_serializing_if = "Option::is_none")]
139
- pub start: Option<String>,
140
- /// Number of days to return. Defaults to 7.
141
- #[serde(skip_serializing_if = "Option::is_none")]
142
- pub duration: Option<u64>,
143
- }
144
-
145
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
146
- pub struct SportsOperation {
147
- /// Tool name for sports requests.
148
- #[serde(skip_serializing_if = "Option::is_none")]
149
- pub tool: Option<SportsToolName>,
150
- /// Sports function to call.
151
- pub r#fn: SportsFunction,
152
- /// League to look up.
153
- pub league: SportsLeague,
154
- /// Team to look up, using the common 3 or 4 letter alias used in broadcasts.
155
- #[serde(skip_serializing_if = "Option::is_none")]
156
- pub team: Option<String>,
157
- /// Opponent to use with `team` when narrowing the lookup.
158
- #[serde(skip_serializing_if = "Option::is_none")]
159
- pub opponent: Option<String>,
160
- /// Start date in YYYY-MM-DD format.
161
- #[serde(skip_serializing_if = "Option::is_none")]
162
- pub date_from: Option<String>,
163
- /// End date in YYYY-MM-DD format.
164
- #[serde(skip_serializing_if = "Option::is_none")]
165
- pub date_to: Option<String>,
166
- /// Number of games to return.
167
- #[serde(skip_serializing_if = "Option::is_none")]
168
- pub num_games: Option<u64>,
169
- /// Locale for the lookup.
170
- #[serde(skip_serializing_if = "Option::is_none")]
171
- pub locale: Option<String>,
172
- }
173
-
174
- #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
175
- #[serde(rename_all = "lowercase")]
176
- pub enum SportsToolName {
177
- Sports,
178
- }
179
-
180
- #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
181
- #[serde(rename_all = "lowercase")]
182
- pub enum SportsFunction {
183
- Schedule,
184
- Standings,
185
- }
186
-
187
- #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
188
- #[serde(rename_all = "lowercase")]
189
- pub enum SportsLeague {
190
- Nba,
191
- Wnba,
192
- Nfl,
193
- Nhl,
194
- Mlb,
195
- Epl,
196
- Ncaamb,
197
- Ncaawb,
198
- Ipl,
199
- }
200
-
201
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
202
- pub struct TimeOperation {
203
- /// UTC offset formatted like "+03:00".
204
- pub utc_offset: String,
205
- }
206
-
207
- #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
208
- #[serde(rename_all = "lowercase")]
209
- pub enum SearchResponseLength {
210
- Short,
211
- Medium,
212
- Long,
213
- }
214
-
215
- #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
216
- #[serde(rename_all = "snake_case")]
217
- pub enum ExternalWebAccessMode {
218
- Cached,
219
- Indexed,
220
- Live,
221
- }
222
-
223
- #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
224
- #[serde(untagged)]
225
- pub enum ExternalWebAccess {
226
- Boolean(bool),
227
- Mode(ExternalWebAccessMode),
228
- }
229
-
230
- #[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
231
- pub struct SearchSettings {
232
- #[serde(skip_serializing_if = "Option::is_none")]
233
- pub user_location: Option<ApproximateLocation>,
234
- #[serde(skip_serializing_if = "Option::is_none")]
235
- pub search_context_size: Option<SearchContextSize>,
236
- #[serde(skip_serializing_if = "Option::is_none")]
237
- pub filters: Option<SearchFilters>,
238
- #[serde(skip_serializing_if = "Option::is_none")]
239
- pub image_settings: Option<SearchImageSettings>,
240
- #[serde(skip_serializing_if = "Option::is_none")]
241
- pub allowed_callers: Option<Vec<AllowedCaller>>,
242
- #[serde(skip_serializing_if = "Option::is_none")]
243
- pub external_web_access: Option<ExternalWebAccess>,
244
- }
245
-
246
- #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
247
- pub struct ApproximateLocation {
248
- pub r#type: LocationType,
249
- #[serde(skip_serializing_if = "Option::is_none")]
250
- pub country: Option<String>,
251
- #[serde(skip_serializing_if = "Option::is_none")]
252
- pub region: Option<String>,
253
- #[serde(skip_serializing_if = "Option::is_none")]
254
- pub city: Option<String>,
255
- #[serde(skip_serializing_if = "Option::is_none")]
256
- pub timezone: Option<String>,
257
- }
258
-
259
- #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
260
- #[serde(rename_all = "lowercase")]
261
- pub enum LocationType {
262
- Approximate,
263
- }
264
-
265
- #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
266
- #[serde(rename_all = "lowercase")]
267
- pub enum SearchContextSize {
268
- Low,
269
- Medium,
270
- High,
271
- }
272
-
273
- #[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
274
- pub struct SearchFilters {
275
- #[serde(skip_serializing_if = "Option::is_none")]
276
- pub allowed_domains: Option<Vec<String>>,
277
- #[serde(skip_serializing_if = "Option::is_none")]
278
- pub blocked_domains: Option<Vec<String>>,
279
- }
280
-
281
- #[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
282
- pub struct SearchImageSettings {
283
- #[serde(skip_serializing_if = "Option::is_none")]
284
- pub max_results: Option<u64>,
285
- #[serde(skip_serializing_if = "Option::is_none")]
286
- pub caption: Option<bool>,
287
- }
288
-
289
- #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
290
- #[serde(rename_all = "snake_case")]
291
- pub enum AllowedCaller {
292
- Direct,
293
- Shell,
294
- CodeInterpreter,
295
- }
296
-
297
- #[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
298
- pub struct SearchResponse {
299
- pub encrypted_output: Option<String>,
300
- pub output: String,
301
- /// Structured result DTOs are passed to clients out-of-band from `output`.
302
- /// Keep them opaque here so newer result variants remain forward-compatible.
303
- #[serde(default)]
304
- pub results: Option<Vec<JsonValue>>,
305
- }