1use super::{
8 binding_resources::NativeHookCallbacks,
9 ordinary::{BackendError, BackendResult, OrdinaryBinding},
10 AgentMode, AgentSpec, ExecutionMode,
11};
12use rpi_harness::types::{AgentHarnessOptions, AgentHarnessStreamOptions, HarnessTool, ToolReplay};
13use rpi_runtime::{ModelRequest, ProviderRegistry, RuntimeConfig};
14use rpi_tools::{tools::*, OsExecutionEnv};
15use std::{
16 collections::{BTreeMap, BTreeSet},
17 path::PathBuf,
18 sync::Arc,
19};
20
21#[derive(Default)]
25pub enum NativeToolPolicy {
26 #[default]
27 DenyAll,
28 Preapproved(BTreeSet<String>),
29}
30impl NativeToolPolicy {
31 fn allows(&self, name: &str) -> bool {
32 matches!(self, Self::Preapproved(names) if names.contains(name))
33 }
34}
35
36pub struct NativeBindingProfile {
40 pub runtime: RuntimeConfig,
41 pub provider_values: BTreeMap<String, String>,
44 pub tool_environment: BTreeMap<String, String>,
47 pub shell_path: PathBuf,
48 pub tools: NativeToolPolicy,
49 pub thinking: rpi_ai::ThinkingLevel,
50 pub stream_options: AgentHarnessStreamOptions,
51 pub instruction_resources: Option<Arc<super::NativeBindingResources>>,
54}
55impl NativeBindingProfile {
56 pub async fn bind(&self, expected: AgentSpec) -> BackendResult<OrdinaryBinding> {
62 let (resolved, env) = self
63 .resolve_binding(&expected, AgentMode::Persistent)
64 .await?;
65 let stream_options = self.stream_options.clone();
66 let resources = self.instruction_resources.clone();
67 let configured_resources = resources.clone();
68 let binder: super::ordinary::OrdinaryBinder = Box::new(move |spec, env, facts| {
69 if spec != &expected {
70 return Err(BackendError::Binding(
71 "prepared Agent identity or launch changed",
72 ));
73 }
74 if configured_resources.is_none() {
78 crate::resource_selection::validate_session_binding(&facts.values, None).map_err(
79 |_| {
80 BackendError::Binding("saved resources require their exact resource binder")
81 },
82 )?;
83 }
84 if facts.values.iter().any(|(key, _)| {
85 key.starts_with("rpi.resource-inventory.")
86 || (key.starts_with("rpi.resource-selection.")
87 && key != "rpi.resource-selection.v1")
88 }) {
89 return Err(BackendError::Binding(
90 "saved resource inventory or version is unsupported by native binding",
91 ));
92 }
93 let tools = native_tools(spec, &env)?;
94 let granted: BTreeSet<_> = spec.launch.tools.iter().cloned().collect();
95 let before_tool_call: rpi_agent::BeforeToolCall = Arc::new(move |context, signal| {
96 let allowed = granted.contains(&context.tool_call.name) && !signal.is_cancelled();
97 Box::pin(async move {
98 (!allowed).then(|| rpi_agent::BeforeToolCallResult {
99 block: true,
100 reason: Some("tool not granted by Host profile".into()),
101 ..Default::default()
102 })
103 })
104 });
105 let mut options = AgentHarnessOptions {
106 system_prompt: Some(crate::session::default_system_prompt_with_tools(
107 &spec.launch.cwd.to_string_lossy(),
108 rpi_ai::model::prior_reasoning_is_replayed(&resolved.model),
109 &spec.launch.tools,
110 )),
111 model: resolved.model,
112 thinking_level: resolved.thinking_level,
113 models: vec![resolved.provider],
114 tools,
115 active_tool_names: spec.launch.tools.clone(),
116 stream_options,
117 before_tool_call: Some(before_tool_call),
118 ..Default::default()
119 };
120 if let Some(resources) = &configured_resources {
121 resources.configure_parts(&mut options.system_prompt, &mut options.resources);
122 }
123 Ok(options)
124 });
125 let mut binding =
126 if let Some(resources) = resources.as_ref().filter(|resources| resources.has_hooks()) {
127 let frozen = resources.clone();
128 let owner = super::NativeExtensionCustody::new();
129 let assembly_owner = owner.clone();
130 OrdinaryBinding::new_deferred(
131 env,
132 Box::new(move |spec, env, facts| {
133 let options = binder(spec, env, facts)?;
134 frozen.validate(&facts.values, &options.tools)?;
136 let spec = spec.clone();
137 Ok(Box::pin(async move {
138 frozen.assemble(&spec, assembly_owner, options).await
139 }))
140 }),
141 )?
142 .with_extensions(owner)
143 } else {
144 OrdinaryBinding::new(env, binder)?
145 };
146 binding.instruction_resources = resources;
147 Ok(binding)
148 }
149
150 #[cfg(unix)]
153 pub(super) async fn preflight_mini(&self, expected: &AgentSpec) -> BackendResult<()> {
154 drop(self.resolve_binding(expected, AgentMode::Mini).await?);
155 Ok(())
156 }
157
158 pub async fn bind_mini_agent(
162 &self,
163 expected: AgentSpec,
164 catalog: super::HostCatalog,
165 custody: Arc<super::NativeExtensionCustody>,
166 ) -> BackendResult<NativeMiniAgent> {
167 let (resolved, env) = self.resolve_binding(&expected, AgentMode::Mini).await?;
168 let tools = native_tools(&expected, &env)?;
169 let granted: BTreeSet<_> = expected.launch.tools.iter().cloned().collect();
170 let before_tool_call: rpi_agent::BeforeToolCall = Arc::new(move |context, signal| {
171 let allowed = granted.contains(&context.tool_call.name) && !signal.is_cancelled();
172 Box::pin(async move {
173 (!allowed).then(|| rpi_agent::BeforeToolCallResult {
174 block: true,
175 reason: Some("tool not granted by Host profile".into()),
176 ..Default::default()
177 })
178 })
179 });
180 let mut prompt = Some(crate::session::default_system_prompt_with_tools(
181 &expected.launch.cwd.to_string_lossy(),
182 rpi_ai::model::prior_reasoning_is_replayed(&resolved.model),
183 &expected.launch.tools,
184 ));
185 let mut provenance = rpi_harness::types::AgentHarnessResources::empty();
186 if let Some(resources) = &self.instruction_resources {
187 resources.configure_parts(&mut prompt, &mut provenance);
188 }
189 let callbacks = match self.instruction_resources.as_ref() {
190 Some(resources) if resources.has_hooks() => {
191 custody.claim(catalog)?;
192 resources
193 .assemble_callbacks(&expected, custody.clone())
194 .await?
195 }
196 _ => NativeHookCallbacks::default(),
197 };
198 let provider = resolved.provider;
199 let provider_hooks = callbacks.provider_hooks.clone();
200 let stream_options = self.stream_options.clone();
201 let stream = rpi_agent::async_stream_fn(move |model, context, options| {
202 let provider = provider.clone();
203 let hooks = provider_hooks.clone();
204 let pinned = stream_options.clone();
205 Box::pin(async move {
206 let mut context = std::borrow::Cow::Borrowed(context);
207 let mut options = pinned.merge_into(options.clone());
208 if let Some(hooks) = &hooks {
209 if let Some(patch) = hooks.transform_context(model, &context) {
210 if patch != rpi_ai::ContextPatch::default() {
211 patch.apply(context.to_mut());
212 }
213 }
214 if let Some(patch) = hooks.before_request_async(model, &context, &options).await
215 {
216 patch.apply(&mut options);
217 }
218 }
219 provider.stream_simple(model, &context, &options).await
220 })
221 });
222 let mut builder = rpi_agent::AgentBuilder::new()
223 .model(resolved.model)
224 .thinking_level(resolved.thinking_level)
225 .system_prompt(prompt.unwrap_or_default())
226 .tools(tools.into_iter().map(|tool| tool.tool).collect())
227 .async_stream_fn(stream)
228 .before_tool_call(before_tool_call);
229 if let Some(after_tool_call) = callbacks.after_tool_call {
230 builder = builder.after_tool_call(after_tool_call);
231 }
232 if let Some(provider_hooks) = callbacks.provider_hooks {
233 builder = builder.provider_hooks(provider_hooks);
234 }
235 let agent = builder
236 .build()
237 .map_err(|_| BackendError::Binding("native mini Agent construction failed"))?;
238 Ok(NativeMiniAgent {
239 agent,
240 custody: self
241 .instruction_resources
242 .as_ref()
243 .is_some_and(|resources| resources.has_hooks())
244 .then_some(custody),
245 })
246 }
247
248 async fn resolve_binding(
249 &self,
250 expected: &AgentSpec,
251 mode: AgentMode,
252 ) -> BackendResult<(rpi_runtime::ResolvedModel, Arc<OsExecutionEnv>)> {
253 expected
254 .validate()
255 .map_err(|_| BackendError::Binding("invalid Agent metadata"))?;
256 if expected.mode != mode || expected.execution != ExecutionMode::InProcess {
257 return Err(BackendError::Binding("native binding mode is unsupported"));
258 }
259 if expected.launch.resource_profile.as_deref()
260 != self
261 .instruction_resources
262 .as_ref()
263 .map(|resources| resources.identity())
264 {
265 return Err(BackendError::Binding(
266 "resource profile requires its exact frozen instruction binding",
267 ));
268 }
269 if let Some(resources) = &self.instruction_resources {
270 resources.validate_tools(&expected.launch.tools)?;
271 }
272 if expected
273 .launch
274 .tools
275 .iter()
276 .any(|name| !self.tools.allows(name))
277 {
278 return Err(BackendError::Binding(
279 "requested tool is not preapproved by Host policy",
280 ));
281 }
282 if expected
283 .launch
284 .tools
285 .iter()
286 .any(|name| !crate::session::BUILTIN_TOOL_NAMES.contains(&name.as_str()))
287 {
288 return Err(BackendError::Binding(
289 "native binding does not implement requested tool",
290 ));
291 }
292 let home_key = if cfg!(windows) { "USERPROFILE" } else { "HOME" };
293 if !self.shell_path.is_absolute()
294 || self
295 .tool_environment
296 .get(home_key)
297 .is_none_or(|home| !std::path::Path::new(home).is_absolute())
298 || self.tool_environment.iter().any(|(name, value)| {
299 name.is_empty()
300 || name.contains(['=', '\0'])
301 || value.contains('\0')
302 || rpi_tools::is_host_private_env(name)
303 })
304 {
305 return Err(BackendError::Binding(
306 "invalid explicit tool environment or shell path",
307 ));
308 }
309 let unresolved_header = self.runtime.models.providers.values().any(|provider| {
310 provider
311 .headers
312 .iter()
313 .chain(
314 provider
315 .models
316 .iter()
317 .filter_map(|model| model.headers.as_ref()),
318 )
319 .flat_map(|headers| headers.values())
320 .any(|raw| {
321 rpi_runtime::values::resolve_config_value(
322 raw,
323 None,
324 &self.provider_values,
325 false,
326 )
327 .is_none()
328 })
329 });
330 let command_key = self
331 .runtime
332 .models
333 .providers
334 .values()
335 .filter_map(|provider| provider.api_key.as_deref())
336 .any(|key| key.starts_with('!'))
337 || self.runtime.credentials.values().any(|credential| {
338 matches!(credential,
339 rpi_runtime::config::Credential::ApiKey { key: Some(key), .. } if key.starts_with('!'))
340 });
341 if unresolved_header || command_key {
342 return Err(BackendError::Binding(
343 "native binding requires fully resolved headers and non-command credentials",
344 ));
345 }
346 let model = expected
347 .launch
348 .model
349 .as_ref()
350 .ok_or(BackendError::Binding("model reference required"))?;
351 let resolved = self
352 .runtime
353 .resolve(
354 &ModelRequest {
355 provider: Some(&model.provider),
356 model: Some(&model.model),
357 thinking: Some(self.thinking),
358 ..Default::default()
359 },
360 &ProviderRegistry::default(),
361 &self.provider_values,
362 )
363 .map_err(|_| {
364 BackendError::Binding("explicit Provider configuration could not be resolved")
365 })?;
366 if resolved.model.provider != model.provider || resolved.model.id != model.model {
367 return Err(BackendError::Binding(
368 "Provider resolution must match the exact model reference",
369 ));
370 }
371 let cwd = tokio::fs::canonicalize(&expected.launch.cwd).await?;
372 let shell = tokio::fs::canonicalize(&self.shell_path).await?;
373 if !tokio::fs::metadata(&shell).await?.is_file() {
374 return Err(BackendError::Binding("explicit shell must be a file"));
375 }
376 let env = Arc::new(
377 OsExecutionEnv::with_cwd(cwd)
378 .with_environment(self.tool_environment.clone().into_iter().collect())
379 .with_shell_path(shell),
380 );
381 Ok((resolved, env))
382 }
383}
384
385pub struct NativeMiniAgent {
388 agent: rpi_agent::Agent,
389 custody: Option<Arc<super::NativeExtensionCustody>>,
390}
391impl NativeMiniAgent {
392 pub fn agent(&self) -> &rpi_agent::Agent {
393 &self.agent
394 }
395 pub fn cancel(&self) {
396 self.agent.abort();
397 }
398 pub async fn close(&self) -> BackendResult<()> {
401 self.agent.abort();
402 self.agent.wait_for_idle().await;
403 if let Some(custody) = &self.custody {
404 custody.close().await?;
405 }
406 Ok(())
407 }
408}
409
410fn native_tools(spec: &AgentSpec, env: &Arc<OsExecutionEnv>) -> BackendResult<Vec<HarnessTool>> {
411 let ctx = ExecutionToolContext::new(env.clone(), Some(env.clone()));
412 spec.launch
413 .tools
414 .iter()
415 .map(|name| {
416 Ok(match name.as_str() {
417 "read" => HarnessTool::new(create_read_tool(
418 &ctx,
419 Some(ReadToolOptions {
420 image_processor: Some(Arc::new(
421 rpi_tools::image_processing::InlineImageProcessor,
422 )),
423 ..Default::default()
424 }),
425 ))
426 .with_replay(ToolReplay::Safe),
427 "bash" => HarnessTool::new(create_bash_tool(
428 &ctx,
429 Some(BashToolOptions {
430 default_timeout: Some(rpi_tools::tools::bash::DEFAULT_BASH_TIMEOUT_SECONDS),
431 ..Default::default()
432 }),
433 )),
434 "edit" => HarnessTool::new(create_edit_tool(&ctx)),
435 "write" => HarnessTool::new(create_write_tool(&ctx)),
436 "docs" => HarnessTool::new(crate::docs_tool::create_docs_tool())
437 .with_replay(ToolReplay::Safe),
438 _ => return Err(BackendError::Binding("unsupported native tool")),
439 })
440 })
441 .collect()
442}
443
444#[cfg(all(test, unix))]
445#[path = "bindings_tests.rs"]
446mod tests;