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
use super::*;
#[cfg(not(target_family = "wasm"))]
use crate::rollout::RolloutConfig;
/// Builder for one owned agent lifecycle.
#[derive(Clone)]
pub struct NanocodexBuilder<F = StandardServiceFactory> {
pub(super) config: ModelConfig,
pub(super) tools: ToolsConfiguration,
pub(super) workspace: Option<PathBuf>,
pub(super) session_id: Option<SessionId>,
pub(super) prompt_cache: PromptCacheConfig,
pub(super) codex: CodexCompatibility,
pub(super) resume: Option<SessionSnapshot>,
pub(super) factory: F,
}
#[derive(Clone, Default)]
pub(super) struct PromptCacheConfig {
pub(super) key: Option<String>,
pub(super) shared: Option<SharedPromptCache>,
}
#[derive(Clone, Default)]
pub(super) struct CodexCompatibility {
pub(super) context: ContextSourceConfig,
pub(super) durability: DurabilityConfig,
}
impl<F> NanocodexBuilder<F> {
/// Replaces the stable system/developer instructions.
#[must_use]
pub fn instructions(mut self, instructions: impl Into<Arc<str>>) -> Self {
self.config.system_prompt = instructions.into();
self
}
/// Overrides the `OpenAi` recipe's model thinking level for this agent.
///
/// Without this call the agent inherits the client default. A later
/// [`Nanocodex::set_thinking`] call affects subsequently accepted turns.
#[must_use]
pub const fn thinking(mut self, thinking: Thinking) -> Self {
self.config.thinking = thinking;
self
}
/// Overrides the `OpenAi` recipe's priority-processing policy for this
/// agent.
///
/// Without this call the agent inherits the client default. A later
/// [`Nanocodex::set_fast_mode`] call affects subsequently accepted turns.
#[must_use]
pub const fn fast_mode(mut self, enabled: bool) -> Self {
self.config.fast_mode = enabled;
self
}
/// Overrides the `OpenAi` recipe's Responses reasoning execution mode for
/// this agent.
///
/// Without this call the agent inherits the client default.
#[must_use]
pub const fn reasoning_mode(mut self, reasoning_mode: ReasoningMode) -> Self {
self.config.reasoning_mode = reasoning_mode;
self
}
/// Replaces the standard built-in tool selection.
#[must_use]
pub fn tools(mut self, tools: Tools) -> Self {
self.tools = ToolsConfiguration::Shared(tools);
self
}
/// Builds a fresh tool collection for every agent driver.
///
/// The factory receives a weak capability targeting the driver whose tool
/// runtime is being built. Use this for agent-relative tools such as Code
/// Mode child-agent tools; stateless tools may continue using
/// [`Self::tools`].
#[cfg(not(target_family = "wasm"))]
#[cfg_attr(docsrs, doc(cfg(not(target_family = "wasm"))))]
#[must_use]
pub fn tools_factory<T>(mut self, factory: T) -> Self
where
T: Fn(AgentHandle) -> std::result::Result<Tools, ToolsBuildError> + Send + Sync + 'static,
{
self.tools = ToolsConfiguration::PerAgent(Arc::new(factory));
self
}
/// Fixes the workspace used by every prompt in this agent session.
#[must_use]
pub fn workspace(mut self, workspace: impl Into<PathBuf>) -> Self {
self.workspace = Some(workspace.into());
self
}
/// Sets the root agent's `UUIDv7` session identity.
///
/// The root identity also seeds its checkpoint lineage. Spawned siblings
/// and forks receive fresh session IDs; forks retain the root's opaque
/// lineage so [`Nanocodex::fork_from`] can reject unrelated results.
#[must_use]
pub const fn session_id(mut self, session_id: SessionId) -> Self {
self.session_id = Some(session_id);
self
}
/// Sets a stable cache identity for the immutable request prefix.
///
/// Independent root agents may share this key without sharing their
/// session, conversation, response chain, tools, or workspace. When
/// omitted, each independently built root uses its own session lineage.
/// Clean children and forks inherit their root's cache identity.
#[must_use]
pub fn prompt_cache_key(mut self, prompt_cache_key: impl Into<String>) -> Self {
self.prompt_cache.key = Some(prompt_cache_key.into());
self
}
/// Shares completed immutable-prefix warmups among builders cloned from
/// this recipe.
///
/// The first agent primes the provider cache. Other agents skip the
/// redundant warmup and send their first complete generation with the same
/// prefix cache key. Every clean agent still owns an independent session,
/// conversation, response chain, service stack, tool runtime, event stream,
/// and workspace. Entries are fingerprinted from the exact prefix and key.
#[must_use]
pub fn shared_prompt_cache(mut self) -> Self {
self.prompt_cache.shared = Some(SharedPromptCache::default());
self
}
/// Loads global user instructions from `AGENTS.override.md` or `AGENTS.md`
/// in the supplied Codex state directory.
#[cfg(not(target_family = "wasm"))]
#[cfg_attr(docsrs, doc(cfg(not(target_family = "wasm"))))]
#[must_use]
pub fn codex_home(mut self, codex_home: impl Into<PathBuf>) -> Self {
self.codex.context.set_codex_home(codex_home.into());
self
}
/// Records committed history in Codex's resumable JSONL rollout layout.
#[cfg(not(target_family = "wasm"))]
#[cfg_attr(docsrs, doc(cfg(not(target_family = "wasm"))))]
#[must_use]
pub fn rollout(mut self, rollout: RolloutConfig) -> Self {
if self.codex.context.codex_home().is_none() {
self.codex
.context
.set_codex_home(rollout.codex_home().to_path_buf());
}
self.codex.durability.set_rollout(rollout);
self
}
/// Restores a completed session boundary into a fresh driver, WebSocket,
/// and tool runtime while retaining its typed history and cache lineage.
///
/// An explicitly configured session ID names the new runtime/event stream;
/// it does not replace the snapshot's prompt-cache lineage. Configure the
/// same instructions, tool definitions, and custom handlers used by the
/// original session; incompatible policy is rejected during [`Self::build`].
#[must_use]
pub fn resume(mut self, snapshot: SessionSnapshot) -> Self {
self.resume = Some(snapshot);
self
}
}
#[cfg(not(target_family = "wasm"))]
impl<F> NanocodexBuilder<F>
where
F: ResponsesServiceFactory + Send + Sync + 'static,
F::Service: Service<ResponsesAttempt, Response = ResponsesServiceResponse> + Send + 'static,
<F::Service as Service<ResponsesAttempt>>::Error: Into<ResponseError> + Send + 'static,
<F::Service as Service<ResponsesAttempt>>::Future: Send,
{
/// Builds an agent from the configured [`OpenAi`] client recipe.
///
/// Each root, spawned sibling, and fork receives a fresh concrete Tower
/// service, tool runtime, event stream, and mutable conversation state.
///
/// # Errors
///
/// Returns an error for invalid agent policy or, on native targets, when
/// no Tokio runtime is active.
pub fn build(self) -> Result<(Nanocodex, AgentEvents)> {
build(self)
}
}
#[cfg(all(target_family = "wasm", target_os = "unknown"))]
impl<F> NanocodexBuilder<F>
where
F: ResponsesServiceFactory + 'static,
F::Service: Service<ResponsesAttempt, Response = ResponsesServiceResponse> + 'static,
<F::Service as Service<ResponsesAttempt>>::Error: Into<ResponseError> + 'static,
{
/// Builds an agent from the configured [`OpenAi`] client recipe.
///
/// Each root, spawned sibling, and fork receives a fresh concrete Tower
/// service, tool runtime, event stream, and mutable conversation state.
///
/// # Errors
///
/// Returns an error for invalid agent policy.
pub fn build(self) -> Result<(Nanocodex, AgentEvents)> {
build(self)
}
}
fn build<F>(builder: NanocodexBuilder<F>) -> Result<(Nanocodex, AgentEvents)>
where
F: ResponsesServiceFactory + AgentFactory + 'static,
F::Service:
Service<ResponsesAttempt, Response = ResponsesServiceResponse> + AgentSend + 'static,
<F::Service as Service<ResponsesAttempt>>::Error: Into<ResponseError> + AgentSend + 'static,
<F::Service as Service<ResponsesAttempt>>::Future: AgentSend,
{
validate(&builder.config, builder.prompt_cache.key.as_deref())?;
let config = Arc::new(builder.config);
let factory = builder.factory;
let service_factory: ServiceFactory<F::Service> = Arc::new({
let service_config = Arc::clone(&config);
move || factory.make(Arc::clone(&service_config))
});
build_agent(
config,
builder.tools,
builder.workspace,
builder.session_id,
builder.prompt_cache,
builder.codex,
builder.resume,
service_factory,
)
}