objectiveai-api 2.0.5

ObjectiveAI API Server
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
//! Translates the upstream's [`Message`] / [`ContinuationItem`] inputs
//! into the JSON shape the Python runner accepts on `--input`, plus
//! materializes any image attachments into the per-request CWD tempdir
//! owned by the client.
//!
//! The runner expects a single user-message JSON object on `--input`:
//!
//! ```text
//! {
//!   "content": "string" | [
//!     {"type": "text",        "text": "..."},
//!     {"type": "local_image", "path": "..."}
//!   ],
//!   "name": "optional-author-name"
//! }
//! ```
//!
//! Codex has no native system role; system / developer messages are
//! concatenated into the leading text part of `content`. Continuation
//! `UserMessage` items are appended as additional content parts after
//! the original user message.

use std::path::Path;

use serde::{Deserialize, Serialize};

use objectiveai_sdk::agent::completions::message::{
    Message, RichContent, RichContentPart, SimpleContent, SimpleContentPart,
};

use super::super::ContinuationItem;

/// The `--input` JSON payload — a single user message.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RunnerUserMessage {
    pub content: Vec<RunnerContentPart>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

/// One element of [`RunnerUserMessage::content`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum RunnerContentPart {
    Text { text: String },
    LocalImage { path: String },
}

/// Output of [`Prompt::new`] — what `super::Client::create` hands to the
/// runner.
#[derive(Debug, Clone, PartialEq)]
pub struct Prompt {
    /// The `--input` JSON value (a single user message).
    pub input: RunnerUserMessage,
    /// `--resume` value: latest `thread_id` seen in continuation, or
    /// from `request_continuation`. Empty string means "fresh thread".
    pub thread_id: String,
}

fn simple_content_to_text(content: &SimpleContent) -> String {
    match content {
        SimpleContent::Text(s) => s.clone(),
        SimpleContent::Parts(parts) => parts
            .iter()
            .map(|p| match p {
                SimpleContentPart::Text { text } => text.as_str(),
            })
            .collect::<Vec<_>>()
            .join("\n\n"),
    }
}

fn mime_to_ext(mime: &str) -> &'static str {
    match mime {
        "image/png" => "png",
        "image/jpeg" | "image/jpg" => "jpg",
        "image/gif" => "gif",
        "image/webp" => "webp",
        "image/bmp" => "bmp",
        "image/tiff" => "tiff",
        "image/svg+xml" => "svg",
        _ => "bin",
    }
}

/// Decode a `data:` URL into raw bytes plus a probable file extension.
/// Only base64-encoded data URLs are supported (the common case for
/// embedded images); raw percent-encoded payloads are rejected.
fn decode_data_url(url: &str) -> Result<(Vec<u8>, &'static str), super::Error> {
    let rest = url.strip_prefix("data:").ok_or_else(|| {
        super::Error::InvalidMessages("data URL must start with `data:`".into())
    })?;
    let (meta, payload) = rest.split_once(',').ok_or_else(|| {
        super::Error::InvalidMessages("data URL is missing `,` separator".into())
    })?;

    let mut mime = "application/octet-stream";
    let mut is_base64 = false;
    for part in meta.split(';') {
        if part == "base64" {
            is_base64 = true;
        } else if part.contains('/') {
            mime = part;
        }
    }

    if !is_base64 {
        return Err(super::Error::InvalidMessages(
            "only base64-encoded data URLs are supported".into(),
        ));
    }

    use base64::Engine as _;
    let bytes = base64::engine::general_purpose::STANDARD
        .decode(payload.trim())
        .or_else(|_| {
            base64::engine::general_purpose::STANDARD_NO_PAD.decode(payload.trim())
        })
        .or_else(|_| {
            base64::engine::general_purpose::URL_SAFE.decode(payload.trim())
        })
        .or_else(|_| {
            base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(payload.trim())
        })
        .map_err(|e| {
            super::Error::InvalidMessages(format!(
                "data URL base64 decode failed: {e}"
            ))
        })?;

    Ok((bytes, mime_to_ext(mime)))
}

/// Materialize one image (data: or http(s):) into `<cwd>/img-<idx>.<ext>`.
async fn materialize_image(
    cwd: &Path,
    http_client: &reqwest::Client,
    url: &str,
    idx: usize,
) -> Result<String, super::Error> {
    const MAX_BYTES: u64 = 20 * 1024 * 1024; // 20 MiB

    let (bytes, ext) = if url.starts_with("data:") {
        decode_data_url(url)?
    } else if url.starts_with("http://") || url.starts_with("https://") {
        let resp = http_client
            .get(url)
            .send()
            .await
            .map_err(|e| super::Error::ImageFetch(e.to_string()))?
            .error_for_status()
            .map_err(|e| super::Error::ImageFetch(e.to_string()))?;

        if let Some(len) = resp.content_length() {
            if len > MAX_BYTES {
                return Err(super::Error::ImageFetch(format!(
                    "image too large: {len} bytes (max {MAX_BYTES})"
                )));
            }
        }

        let ext = resp
            .headers()
            .get(reqwest::header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .map(|ct| mime_to_ext(ct.split(';').next().unwrap_or("").trim()))
            .unwrap_or("bin");

        let bytes = resp
            .bytes()
            .await
            .map_err(|e| super::Error::ImageFetch(e.to_string()))?;
        if bytes.len() as u64 > MAX_BYTES {
            return Err(super::Error::ImageFetch(format!(
                "image too large: {} bytes (max {MAX_BYTES})",
                bytes.len()
            )));
        }
        (bytes.to_vec(), ext)
    } else {
        return Err(super::Error::InvalidMessages(format!(
            "unsupported image URL scheme: {url}"
        )));
    };

    let path = cwd.join(format!("img-{idx}.{ext}"));
    tokio::fs::write(&path, &bytes)
        .await
        .map_err(|e| super::Error::Io(e.to_string()))?;
    Ok(path.to_string_lossy().into_owned())
}

async fn push_rich_content(
    cwd: &Path,
    http_client: &reqwest::Client,
    out: &mut Vec<RunnerContentPart>,
    image_idx: &mut usize,
    content: &RichContent,
) -> Result<(), super::Error> {
    match content {
        RichContent::Text(text) => {
            out.push(RunnerContentPart::Text { text: text.clone() });
        }
        RichContent::Parts(parts) => {
            for part in parts {
                match part {
                    RichContentPart::Text { text } => {
                        out.push(RunnerContentPart::Text {
                            text: text.clone(),
                        });
                    }
                    RichContentPart::ImageUrl { image_url } => {
                        let path = materialize_image(
                            cwd,
                            http_client,
                            &image_url.url,
                            *image_idx,
                        )
                        .await?;
                        *image_idx += 1;
                        out.push(RunnerContentPart::LocalImage { path });
                    }
                    RichContentPart::InputAudio { .. } => {
                        return Err(super::Error::InvalidMessages(
                            "audio input is not supported by Codex SDK".into(),
                        ));
                    }
                    RichContentPart::InputVideo { .. }
                    | RichContentPart::VideoUrl { .. } => {
                        return Err(super::Error::InvalidMessages(
                            "video input is not supported by Codex SDK".into(),
                        ));
                    }
                    RichContentPart::File { .. } => {
                        return Err(super::Error::InvalidMessages(
                            "file input is not supported by Codex SDK".into(),
                        ));
                    }
                }
            }
        }
    }
    Ok(())
}

impl Prompt {
    /// Build the runner input from the agent-completions inputs.
    ///
    /// `cwd` is the per-request tempdir owned by the client; image
    /// attachments are written into it and referenced by absolute path.
    /// `http_client` is used to fetch any `http(s):` image URLs.
    pub async fn new(
        cwd: &Path,
        http_client: &reqwest::Client,
        messages: &[Message],
        continuation: Option<&[ContinuationItem<super::State>]>,
        request_continuation: Option<&objectiveai_sdk::agent::codex_sdk::Continuation>,
    ) -> Result<Self, super::Error> {
        let mut system_parts: Vec<String> = Vec::new();
        let mut user_msg: Option<&objectiveai_sdk::agent::completions::message::UserMessage> =
            None;
        let mut saw_user = false;

        for msg in messages {
            match msg {
                Message::System(sys) if !saw_user => {
                    let text = simple_content_to_text(&sys.content);
                    if !text.is_empty() {
                        system_parts.push(text);
                    }
                }
                Message::Developer(dev) if !saw_user => {
                    let text = simple_content_to_text(&dev.content);
                    if !text.is_empty() {
                        system_parts.push(text);
                    }
                }
                Message::User(u) if !saw_user => {
                    saw_user = true;
                    user_msg = Some(u);
                }
                Message::System(_) | Message::Developer(_) => {
                    return Err(super::Error::InvalidMessages(
                        "system/developer messages must precede the user message"
                            .to_string(),
                    ));
                }
                Message::User(_) => {
                    return Err(super::Error::InvalidMessages(
                        "only one user message is allowed".to_string(),
                    ));
                }
                Message::Assistant(_) => {
                    return Err(super::Error::InvalidMessages(
                        "assistant messages are not allowed".to_string(),
                    ));
                }
                Message::Tool(_) => {
                    return Err(super::Error::InvalidMessages(
                        "tool messages are not allowed".to_string(),
                    ));
                }
            }
        }

        let mut content: Vec<RunnerContentPart> = Vec::new();
        let mut image_idx: usize = 0;

        // Codex has no system role — fold system/developer text into a
        // leading text part.
        if !system_parts.is_empty() {
            content.push(RunnerContentPart::Text {
                text: system_parts.join("\n\n"),
            });
        }

        // The user message's `name` field becomes the runner-message
        // top-level `name`, and is also validated against any
        // continuation user-message name (as claude does).
        let mut author_name: Option<String> = None;
        if let Some(u) = user_msg {
            author_name = u
                .name
                .as_deref()
                .filter(|n| !n.is_empty())
                .map(str::to_owned);
            push_rich_content(
                cwd,
                http_client,
                &mut content,
                &mut image_idx,
                &u.content,
            )
            .await?;
        }

        let session_id = if let Some(items) = continuation {
            let last_state_pos = items
                .iter()
                .rposition(|item| matches!(item, ContinuationItem::State(_)));

            let start = last_state_pos.unwrap_or(0);
            let mut session_id = String::new();

            for (i, item) in items.iter().enumerate() {
                if i < start {
                    continue;
                }
                match item {
                    ContinuationItem::State(state) => {
                        session_id = state.thread_id.clone();
                    }
                    ContinuationItem::ToolMessage(_)
                        if i > start || last_state_pos.is_none() =>
                    {
                        return Err(super::Error::InvalidContinuation(
                            "tool messages must precede a state item".to_string(),
                        ));
                    }
                    ContinuationItem::ToolMessage(_) => {
                        // Tool message at-or-before the most recent state
                        // — handled by an earlier turn.
                    }
                    ContinuationItem::UserMessage(u) => {
                        let cont_name =
                            u.name.as_deref().filter(|n| !n.is_empty());
                        if let Some(name) = cont_name {
                            match &author_name {
                                Some(expected) if expected != name => {
                                    return Err(super::Error::InvalidMessages(
                                        format!(
                                            "continuation user message name '{name}' does not match expected '{expected}'"
                                        ),
                                    ));
                                }
                                None => author_name = Some(name.to_string()),
                                _ => {}
                            }
                        }
                        push_rich_content(
                            cwd,
                            http_client,
                            &mut content,
                            &mut image_idx,
                            &u.content,
                        )
                        .await?;
                    }
                }
            }

            session_id
        } else {
            String::new()
        };

        let thread_id = if session_id.is_empty() {
            request_continuation
                .map(|rc| rc.thread_id.clone())
                .unwrap_or_default()
        } else {
            session_id
        };

        // Empty content is invalid — codex won't accept an empty input.
        if content.is_empty() {
            return Err(super::Error::InvalidMessages(
                "user message has no content".to_string(),
            ));
        }

        Ok(Prompt {
            input: RunnerUserMessage {
                content,
                name: author_name,
            },
            thread_id,
        })
    }
}