nanocodex-oai-api 0.3.0

Tower-native OpenAI Responses API and managed context for Nanocodex
Documentation
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
#![doc = include_str!("../README.md")]
#![deny(missing_docs, rustdoc::broken_intra_doc_links)]
#![cfg_attr(docsrs, feature(doc_cfg))]

#[cfg(all(target_family = "wasm", not(target_os = "unknown")))]
compile_error!(
    "nanocodex-oai-api supports native targets and hosted wasm*-unknown-unknown targets; WASI is not yet supported"
);

/// Authentication sources and managed credential snapshots.
pub mod auth;
/// Complete typed lifecycle events emitted around Responses operations.
pub mod events;
mod openai;
/// Automatic `gpt-5.6-sol` USD estimates from provider token usage.
pub mod pricing;
/// Complete typed request, event, and item model for the Responses protocol.
pub mod responses;
/// Managed session identities, inputs, and compaction results.
pub mod session;
/// Tool contracts shared by agent loops and concrete tool runtimes.
pub mod tools;
/// Generic Tower attempt, service, retry, and streamed-output contracts.
pub mod tower;
/// Responses transport policy, errors, and connection statistics.
pub mod transport;

use std::{fmt, path::PathBuf, str::FromStr};

use serde::{Deserialize, Serialize};

pub(crate) use auth::{OpenAiAuth, OpenAiAuthError, OpenAiAuthMode, OpenAiAuthSnapshot};
pub(crate) use events::stream::EventSink;
pub(crate) use events::{
    AgentEventData, AgentEventKind, AssistantEvent, ContextEvent, EventError, ModelEvent,
    ReasoningEvent, RunEvent, ToolEvent, TransportEvent, monotonic_now_ns,
};
pub(crate) use openai::ModelConfig;
pub use openai::{OpenAi, OpenAiBuilder, OpenAiError};
pub(crate) use pricing::{CostStatus, EstimatedUsdCost};
pub use responses::ResponseEvent;
pub(crate) use responses::{
    ContentItem, FunctionOutputBody, FunctionOutputContent, MessagePhase, MessageRole,
    ResponseItem, ResponseItemId, ToolDefinition, Usage,
};
pub use session::{
    CompletedResponse, Response, ResponseError, ResponseErrorKind, ResponseTurn, Session,
    SessionBuildError, SessionBuilder,
};
pub(crate) use tools::ToolOutputBody;
pub(crate) use tower::attempt::{
    ResponsesAttempt, ResponsesAttemptFactory, ResponsesOutput, ResponsesServiceResponse,
    TransportStats,
};
pub(crate) use tower::service::ResponsesService;
pub(crate) use tower::{
    DefaultResponsesService, ResponsesClient, ResponsesRetryPolicy, ResponsesServiceError,
};
pub(crate) use transport::EncodedRequest;
pub(crate) use transport::{ResponsesError, ResponsesHistory, ResponsesTransport, RetryAdvice};

pub(crate) use tower::{attempt, middleware, service, service_error, stream};
#[cfg(not(target_family = "wasm"))]
pub(crate) use transport::{connector, http};
pub(crate) use transport::{socket, telemetry};

/// Internal bridge for the higher-level `nanocodex-agent` crate.
///
/// This namespace is not a supported caller API. It keeps mutable model
/// configuration, event emission authority, and attempt construction out of
/// the normal rustdoc surface while allowing the separately versioned agent
/// crate to compose this crate without duplicating those mechanics.
#[doc(hidden)]
pub mod __private {
    pub use crate::{
        events::stream::EventSink,
        openai::{
            CallerServiceFactory, LayeredServiceFactory, ModelConfig, ResponsesServiceFactory,
        },
        session::{
            context::{ContextManager, assign_missing_response_item_id},
            state::{ManagedSessionState, ManagedSessionStateError},
        },
        tower::attempt::ResponsesAttemptFactory,
    };

    /// Agent-owned context accounting and compaction policy primitives.
    pub mod compaction {
        pub use crate::session::compaction::{
            auto_compact_token_limit, install_history, trigger,
            trim_tool_outputs_to_fit_context_window,
        };
    }

    /// Decomposes a validated client recipe for the higher-level agent driver.
    pub fn into_openai_parts<F>(openai: crate::OpenAi<F>) -> (ModelConfig, F)
    where
        F: ResponsesServiceFactory,
    {
        openai.into_parts()
    }

    /// Installs the server-visible mapping for tools nested under Code Mode.
    pub fn with_code_mode_tool_names(
        profile: crate::responses::RequestProfile,
        names: Vec<(String, String)>,
    ) -> crate::responses::RequestProfile {
        profile.with_code_mode_tool_names(names)
    }
}

/// The single Responses model contract supported by this SDK.
pub const MODEL: &str = "gpt-5.6-sol";

/// Context-window size of the supported Responses model contract.
pub const CONTEXT_WINDOW_TOKENS: u64 = 272_000;

/// User input for one agent turn.
///
/// Session policy such as the filesystem workspace belongs to the agent
/// builder rather than an individual prompt.
///
/// # Examples
///
/// ```
/// use nanocodex_oai_api::{ImageDetail, Prompt, UserInput};
///
/// let prompt = Prompt::content([
///     UserInput::Text {
///         text: "Describe the deployment diagram.".to_owned(),
///     },
///     UserInput::Image {
///         image_url: "https://example.com/deployment.png".to_owned(),
///         detail: Some(ImageDetail::High),
///     },
/// ]);
///
/// assert!(!prompt.instruction.is_empty());
/// ```
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Prompt {
    /// Ordered text and multimodal content for this turn.
    pub instruction: PromptInput,
}

impl Prompt {
    /// Creates a text-only prompt.
    #[must_use]
    pub fn new(instruction: impl Into<String>) -> Self {
        Self {
            instruction: PromptInput::Text(instruction.into()),
        }
    }

    /// Creates a prompt from ordered content items.
    #[must_use]
    pub fn content(input: impl IntoIterator<Item = UserInput>) -> Self {
        Self {
            instruction: PromptInput::Content(input.into_iter().collect()),
        }
    }
}

impl From<String> for Prompt {
    fn from(instruction: String) -> Self {
        Self::new(instruction)
    }
}

impl From<&str> for Prompt {
    fn from(instruction: &str) -> Self {
        Self::new(instruction)
    }
}

/// Ordered input for one agent turn.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum PromptInput {
    /// A text-only instruction.
    Text(String),
    /// Ordered text and multimodal input items.
    Content(Vec<UserInput>),
}

impl PromptInput {
    /// Returns the total UTF-8 byte length of text items.
    #[must_use]
    pub fn text_bytes(&self) -> usize {
        match self {
            Self::Text(text) => text.len(),
            Self::Content(items) => items.iter().map(UserInput::text_bytes).sum(),
        }
    }

    /// Returns the total Unicode scalar-value count of text items.
    #[must_use]
    pub fn text_chars(&self) -> usize {
        match self {
            Self::Text(text) => text.chars().count(),
            Self::Content(items) => items.iter().map(UserInput::text_chars).sum(),
        }
    }

    /// Returns whether this input contains no non-whitespace text or media.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        match self {
            Self::Text(text) => text.trim().is_empty(),
            Self::Content(items) => items.is_empty() || items.iter().all(UserInput::is_empty),
        }
    }
}

impl From<String> for PromptInput {
    fn from(value: String) -> Self {
        Self::Text(value)
    }
}

impl From<&str> for PromptInput {
    fn from(value: &str) -> Self {
        Self::Text(value.to_owned())
    }
}

/// One ordered user-supplied prompt item.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum UserInput {
    /// Model-visible text.
    Text {
        /// Text supplied by the user.
        text: String,
    },
    /// An image supplied as a URL or data URL.
    Image {
        /// Image URL visible to the model.
        image_url: String,
        /// Optional image-detail policy.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        detail: Option<ImageDetail>,
    },
    /// An image loaded from the local filesystem by a native runtime.
    LocalImage {
        /// Path to the local image.
        path: PathBuf,
        /// Optional image-detail policy.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        detail: Option<ImageDetail>,
    },
    /// A reserved remote audio input.
    Audio {
        /// Audio URL retained by the input contract.
        audio_url: String,
    },
    /// A reserved local audio input.
    LocalAudio {
        /// Path retained by the input contract.
        path: PathBuf,
    },
}

/// Image fidelity requested from the model.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ImageDetail {
    /// Lets the provider select the detail level.
    Auto,
    /// Requests lower-resolution image processing.
    Low,
    /// Requests high-resolution image processing.
    High,
    /// Requests original-resolution image processing.
    Original,
}

impl UserInput {
    /// Returns the UTF-8 byte length when this is text, or zero for media.
    #[must_use]
    pub const fn text_bytes(&self) -> usize {
        match self {
            Self::Text { text } => text.len(),
            Self::Image { .. }
            | Self::LocalImage { .. }
            | Self::Audio { .. }
            | Self::LocalAudio { .. } => 0,
        }
    }

    /// Returns the Unicode scalar-value count when this is text, or zero for media.
    #[must_use]
    pub fn text_chars(&self) -> usize {
        match self {
            Self::Text { text } => text.chars().count(),
            Self::Image { .. }
            | Self::LocalImage { .. }
            | Self::Audio { .. }
            | Self::LocalAudio { .. } => 0,
        }
    }

    /// Returns whether this item contains neither non-whitespace text nor media.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        match self {
            Self::Text { text } => text.trim().is_empty(),
            Self::Image { .. }
            | Self::LocalImage { .. }
            | Self::Audio { .. }
            | Self::LocalAudio { .. } => false,
        }
    }
}

/// Responses reasoning execution mode for the supported GPT-5.6 model family.
///
/// Standard mode preserves the default request behavior. Pro mode performs
/// additional model work before returning one final answer and can increase
/// latency and token usage independently of [`Thinking`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ReasoningMode {
    /// Standard reasoning behavior.
    #[default]
    Standard,
    /// Pro reasoning behavior.
    Pro,
}

impl ReasoningMode {
    /// Returns the request value used by the Responses API.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Standard => "standard",
            Self::Pro => "pro",
        }
    }

    pub(crate) const fn request_value(self) -> Option<&'static str> {
        match self {
            Self::Standard => None,
            Self::Pro => Some("pro"),
        }
    }
}

impl fmt::Display for ReasoningMode {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for ReasoningMode {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "standard" => Ok(Self::Standard),
            "pro" => Ok(Self::Pro),
            _ => Err(format!(
                "invalid reasoning mode {value:?}; expected standard or pro"
            )),
        }
    }
}

/// Requested model reasoning effort.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum Thinking {
    /// Disable reasoning when supported.
    None,
    /// Low reasoning effort.
    Low,
    /// Medium reasoning effort.
    Medium,
    /// High reasoning effort.
    #[default]
    High,
    /// Extra-high reasoning effort.
    Xhigh,
    /// Maximum reasoning effort.
    Max,
}

impl Thinking {
    /// Returns the request value used by the Responses API.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Low => "low",
            Self::Medium => "medium",
            Self::High => "high",
            Self::Xhigh => "xhigh",
            Self::Max => "max",
        }
    }
}

impl fmt::Display for Thinking {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for Thinking {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "none" => Ok(Self::None),
            "low" => Ok(Self::Low),
            "medium" => Ok(Self::Medium),
            "high" => Ok(Self::High),
            "xhigh" => Ok(Self::Xhigh),
            "max" => Ok(Self::Max),
            _ => Err(format!(
                "invalid reasoning effort {value:?}; expected none, low, medium, high, xhigh, or max"
            )),
        }
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::{Prompt, ReasoningMode, Thinking};

    #[test]
    fn reasoning_configuration_parses_every_public_value() {
        assert_eq!("standard".parse(), Ok(ReasoningMode::Standard));
        assert_eq!("pro".parse(), Ok(ReasoningMode::Pro));

        for (value, expected) in [
            ("none", Thinking::None),
            ("low", Thinking::Low),
            ("medium", Thinking::Medium),
            ("high", Thinking::High),
            ("xhigh", Thinking::Xhigh),
            ("max", Thinking::Max),
        ] {
            assert_eq!(value.parse(), Ok(expected));
        }
    }

    #[test]
    fn prompt_serialization_contains_only_user_input() {
        let prompt = Prompt::new("inspect the repository");
        assert_eq!(
            serde_json::to_value(prompt).unwrap(),
            json!({ "instruction": "inspect the repository" })
        );
    }

    #[test]
    fn prompt_deserialization_rejects_session_policy() {
        let error = serde_json::from_value::<Prompt>(json!({
            "instruction": "inspect the repository",
            "workspace": "/work/project"
        }))
        .unwrap_err();
        assert!(error.to_string().contains("unknown field `workspace`"));
    }
}