roder-api 0.2.5

Agentic software development tools and SDKs for Roder.
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
use std::collections::BTreeMap;
use std::fmt;
use std::path::PathBuf;
use std::sync::Arc;

use serde::{Deserialize, Serialize};

use crate::artifacts::ContextArtifactAccess;
use crate::discovery::{
    DiscoveryAuthState, DiscoveryCacheStatus, DiscoveryCatalogItem, DiscoveryCatalogSource,
    DiscoveryItemStatus, DiscoveryLifecycleState, DiscoveryPromotionState, DiscoveryRedaction,
    DiscoverySchemaFormat, DiscoverySchemaReference, DiscoverySourceKind,
};
use crate::events::{ThreadId, TurnId};
use crate::extension::ToolProviderId;
use crate::goals::ThreadGoalController;
use crate::inference::ModelSchemaPolicy;
use crate::policy_mode::PolicyMode;
use crate::remote_runner::RemoteWorkspace;
use crate::trace::SubagentTraceSink;
use crate::{ToolSchemaPolicy, normalize_tool_schema};

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ToolSpec {
    pub name: String,
    pub description: String,
    pub parameters: serde_json::Value,
}

impl ToolSpec {
    /// The argument field a raw freeform-channel body maps to, for tools that
    /// are best emitted on a provider's freeform/custom tool channel instead of
    /// as a JSON-schema function.
    ///
    /// `apply_patch` emits grammar-constrained patches on the supported
    /// OpenAI Responses custom-tool channel (`type:"custom"`),
    /// where the call carries the raw patch text as a string `input` rather than
    /// JSON arguments. Ordinary function tools return `None`.
    /// Providers without a freeform channel ignore
    /// it and always serialize `type:"function"`.
    pub fn freeform_input_field(&self) -> Option<&'static str> {
        Self::freeform_field_for_name(&self.name)
    }

    pub fn freeform_field_for_name(name: &str) -> Option<&'static str> {
        match name {
            "apply_patch" => Some("patch"),
            _ => None,
        }
    }

    pub fn normalized_for_model(&self, policy: ToolSchemaPolicy) -> Self {
        let mut spec = self.clone();
        spec.parameters = normalize_tool_schema(&spec.name, &spec.parameters, policy).schema;
        spec
    }

    pub fn normalized_for_model_profile(&self, policy: ModelSchemaPolicy) -> Self {
        match policy {
            ModelSchemaPolicy::StandardRequiredFirst => {
                self.normalized_for_model(ToolSchemaPolicy::warning())
            }
            ModelSchemaPolicy::RequiredFirstFlat => {
                self.normalized_for_model(ToolSchemaPolicy::strict())
            }
        }
    }

    pub fn discovery_item(
        &self,
        provider_id: impl Into<String>,
        schema_uri: impl Into<String>,
    ) -> DiscoveryCatalogItem {
        let provider_id = provider_id.into();
        DiscoveryCatalogItem {
            id: format!("tool:{provider_id}/{}", self.name),
            group_id: format!("tools:{provider_id}"),
            source: DiscoveryCatalogSource {
                kind: DiscoverySourceKind::InternalTools,
                id: provider_id.clone(),
                display_name: provider_id,
                origin: None,
                auth_state: DiscoveryAuthState::NotRequired,
                redaction: DiscoveryRedaction::none(),
            },
            name: self.name.clone(),
            title: self.name.clone(),
            description: Some(self.description.clone()),
            status: DiscoveryItemStatus::Available,
            lifecycle: DiscoveryLifecycleState::Discovered,
            promotion: DiscoveryPromotionState::NotPromoted,
            cache_status: DiscoveryCacheStatus::Cold,
            schema: Some(DiscoverySchemaReference {
                format: DiscoverySchemaFormat::JsonSchema,
                uri: schema_uri.into(),
                content_hash: None,
                byte_count: None,
                redaction: DiscoveryRedaction::none(),
            }),
            tags: vec!["tool".to_string()],
            hints: Vec::new(),
            redaction: DiscoveryRedaction::none(),
            last_refreshed_at: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum ToolChoice {
    Auto,
    Any,
    None,
    Specific(String),
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ToolCall {
    pub id: String,
    pub name: String,
    pub arguments: serde_json::Value,
    pub raw_arguments: String,
    pub thread_id: ThreadId,
    pub turn_id: TurnId,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ToolResult {
    pub id: String,
    pub name: String,
    pub text: String,
    pub data: serde_json::Value,
    pub is_error: bool,
}

#[derive(Clone, Default)]
pub struct ToolExecutionHandles {
    pub workspace: Option<Arc<dyn ScopedWorkspaceHandle>>,
    /**
     * Remote-runner workspace for the thread. When present it takes
     * precedence over `workspace`: coding tools must route file and shell
     * operations through the runner session instead of the local filesystem.
     */
    pub remote_workspace: Option<Arc<RemoteWorkspace>>,
    pub process_runner: Option<Arc<dyn ScopedProcessRunner>>,
    pub subagent_trace_sink: Option<Arc<dyn SubagentTraceSink>>,
    pub context_artifacts: Option<Arc<dyn ContextArtifactAccess>>,
    pub goal_controller: Option<Arc<dyn ThreadGoalController>>,
    /// Live swarm-progress publisher for the `agent_swarm` tool.
    pub swarm_progress_sink: Option<Arc<dyn crate::subagents::AgentSwarmProgressSink>>,
    /// Parent turn's concrete model selection so `task` / `agent_swarm`
    /// children inherit the live provider+model instead of process startup
    /// defaults (for example SuperGrok/grok-4.5 rather than gpt-5.5).
    pub parent_model_selection: Option<crate::inference::ModelSelection>,
}

impl fmt::Debug for ToolExecutionHandles {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ToolExecutionHandles")
            .field("workspace", &self.workspace.is_some())
            .field("remote_workspace", &self.remote_workspace.is_some())
            .field("process_runner", &self.process_runner.is_some())
            .field("subagent_trace_sink", &self.subagent_trace_sink.is_some())
            .field("context_artifacts", &self.context_artifacts.is_some())
            .field("goal_controller", &self.goal_controller.is_some())
            .field("swarm_progress_sink", &self.swarm_progress_sink.is_some())
            .field("parent_model_selection", &self.parent_model_selection)
            .finish()
    }
}

pub trait ScopedWorkspaceHandle: Send + Sync + 'static {
    fn workspace_root(&self) -> Option<PathBuf>;
}

pub trait ScopedProcessRunner: Send + Sync + 'static {
    fn runner_name(&self) -> &str;
}

#[derive(Debug, Clone)]
pub struct LocalWorkspaceHandle {
    root: PathBuf,
}

impl LocalWorkspaceHandle {
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self { root: root.into() }
    }
}

impl ScopedWorkspaceHandle for LocalWorkspaceHandle {
    fn workspace_root(&self) -> Option<PathBuf> {
        Some(self.root.clone())
    }
}

#[derive(Debug, Clone, Default)]
pub struct LocalProcessRunnerHandle;

impl ScopedProcessRunner for LocalProcessRunnerHandle {
    fn runner_name(&self) -> &str {
        "local-process"
    }
}

#[derive(Debug, Clone)]
pub struct ToolExecutionContext {
    pub thread_id: ThreadId,
    pub turn_id: TurnId,
    pub effective_mode: PolicyMode,
    pub command_shell: Option<String>,
    pub deadline_remaining_seconds: Option<u64>,
    pub handles: ToolExecutionHandles,
}

impl ToolExecutionContext {
    pub fn new(
        thread_id: impl Into<ThreadId>,
        turn_id: impl Into<TurnId>,
        effective_mode: PolicyMode,
    ) -> Self {
        Self {
            thread_id: thread_id.into(),
            turn_id: turn_id.into(),
            effective_mode,
            command_shell: None,
            deadline_remaining_seconds: None,
            handles: ToolExecutionHandles::default(),
        }
    }

    pub fn with_command_shell(mut self, shell: impl Into<String>) -> Self {
        let shell = shell.into();
        if !shell.trim().is_empty() {
            self.command_shell = Some(shell);
        }
        self
    }

    pub fn with_deadline_remaining_seconds(mut self, seconds: u64) -> Self {
        self.deadline_remaining_seconds = Some(seconds);
        self
    }

    pub fn with_workspace_handle(mut self, handle: Arc<dyn ScopedWorkspaceHandle>) -> Self {
        self.handles.workspace = Some(handle);
        self
    }

    pub fn with_remote_workspace(mut self, remote: Arc<RemoteWorkspace>) -> Self {
        self.handles.remote_workspace = Some(remote);
        self
    }

    pub fn with_process_runner(mut self, runner: Arc<dyn ScopedProcessRunner>) -> Self {
        self.handles.process_runner = Some(runner);
        self
    }

    pub fn with_subagent_trace_sink(mut self, sink: Arc<dyn SubagentTraceSink>) -> Self {
        self.handles.subagent_trace_sink = Some(sink);
        self
    }

    pub fn with_context_artifacts(mut self, store: Arc<dyn ContextArtifactAccess>) -> Self {
        self.handles.context_artifacts = Some(store);
        self
    }

    pub fn with_goal_controller(mut self, controller: Arc<dyn ThreadGoalController>) -> Self {
        self.handles.goal_controller = Some(controller);
        self
    }

    pub fn with_parent_model_selection(
        mut self,
        selection: crate::inference::ModelSelection,
    ) -> Self {
        self.handles.parent_model_selection = Some(selection);
        self
    }

    pub fn with_swarm_progress_sink(
        mut self,
        sink: Arc<dyn crate::subagents::AgentSwarmProgressSink>,
    ) -> Self {
        self.handles.swarm_progress_sink = Some(sink);
        self
    }

    pub fn require_workspace(&self) -> anyhow::Result<Arc<dyn ScopedWorkspaceHandle>> {
        self.handles
            .workspace
            .clone()
            .ok_or_else(|| anyhow::anyhow!("workspace handle is not available"))
    }

    pub fn require_process_runner(&self) -> anyhow::Result<Arc<dyn ScopedProcessRunner>> {
        self.handles
            .process_runner
            .clone()
            .ok_or_else(|| anyhow::anyhow!("process runner is not available"))
    }

    pub fn require_context_artifacts(&self) -> anyhow::Result<Arc<dyn ContextArtifactAccess>> {
        self.handles
            .context_artifacts
            .clone()
            .ok_or_else(|| anyhow::anyhow!("context artifact store is not available"))
    }

    pub fn require_goal_controller(&self) -> anyhow::Result<Arc<dyn ThreadGoalController>> {
        self.handles
            .goal_controller
            .clone()
            .ok_or_else(|| anyhow::anyhow!("goal controller is not available"))
    }
}

#[async_trait::async_trait]
pub trait ToolExecutor: Send + Sync + 'static {
    fn spec(&self) -> ToolSpec;

    /// Whether this executor is safe to start while the model is still
    /// sampling other output items. Only independent, read-only tools opt in.
    /// Approval, validation and workspace authorization still run normally.
    fn supports_eager_execution(&self) -> bool {
        false
    }

    async fn execute(
        &self,
        ctx: ToolExecutionContext,
        call: ToolCall,
    ) -> anyhow::Result<ToolResult>;
}

#[derive(Default, Clone)]
pub struct ToolRegistry {
    tools: BTreeMap<String, Arc<dyn ToolExecutor>>,
}

impl ToolRegistry {
    pub fn register(&mut self, tool: Arc<dyn ToolExecutor>) -> anyhow::Result<()> {
        let name = tool.spec().name;
        if self.tools.contains_key(&name) {
            anyhow::bail!("tool {name:?} is already registered");
        }
        self.tools.insert(name, tool);
        Ok(())
    }

    /// Registers `tool`, replacing any executor already registered under the
    /// same name. Used by the runtime to swap fake reference tools for fully
    /// wired implementations.
    pub fn replace(&mut self, tool: Arc<dyn ToolExecutor>) {
        self.tools.insert(tool.spec().name, tool);
    }

    pub fn specs(&self) -> Vec<ToolSpec> {
        self.tools
            .values()
            .map(|tool| {
                tool.spec()
                    .normalized_for_model(ToolSchemaPolicy::warning())
            })
            .collect()
    }

    pub fn specs_for_edit_tool(&self, edit_tool: Option<&str>) -> Vec<ToolSpec> {
        self.specs_for_edit_tool_with_schema_policy(edit_tool, ModelSchemaPolicy::RequiredFirstFlat)
    }

    pub fn specs_for_edit_tool_with_schema_policy(
        &self,
        edit_tool: Option<&str>,
        schema_policy: ModelSchemaPolicy,
    ) -> Vec<ToolSpec> {
        self.tools
            .values()
            .map(|tool| tool.spec())
            .filter(|spec| keep_tool_for_edit_tool(&spec.name, edit_tool))
            .map(|spec| spec.normalized_for_model_profile(schema_policy))
            .collect()
    }

    pub fn get(&self, name: &str) -> Option<Arc<dyn ToolExecutor>> {
        self.tools.get(name).cloned()
    }

    pub fn is_empty(&self) -> bool {
        self.tools.is_empty()
    }
}

fn keep_tool_for_edit_tool(name: &str, edit_tool: Option<&str>) -> bool {
    match name {
        "apply_patch" => true,
        "write_file" | "edit" | "multi_edit" => !matches!(edit_tool, Some("patch")),
        _ => true,
    }
}

pub trait ToolContributor: Send + Sync + 'static {
    fn id(&self) -> ToolProviderId;
    fn contribute(&self, registry: &mut ToolRegistry) -> anyhow::Result<()>;
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn tool_spec_can_be_represented_as_discovery_item() {
        let spec = ToolSpec {
            name: "grep".to_string(),
            description: "Search files".to_string(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "query": { "type": "string" }
                },
                "required": ["query"]
            }),
        };

        let item = spec.discovery_item(
            "builtin-coding-tools",
            "discovery/tools/builtin-coding-tools/grep.schema.json",
        );
        assert_eq!(item.id, "tool:builtin-coding-tools/grep");
        assert_eq!(item.group_id, "tools:builtin-coding-tools");
        assert_eq!(item.source.kind, DiscoverySourceKind::InternalTools);
        assert_eq!(item.source.auth_state, DiscoveryAuthState::NotRequired);
        assert_eq!(item.status, DiscoveryItemStatus::Available);
        assert_eq!(item.lifecycle, DiscoveryLifecycleState::Discovered);
        assert_eq!(
            item.schema.as_ref().map(|schema| schema.format.clone()),
            Some(DiscoverySchemaFormat::JsonSchema)
        );
    }

    #[test]
    fn apply_patch_is_kept_for_all_edit_tool_profiles() {
        assert!(keep_tool_for_edit_tool("apply_patch", None));
        assert!(keep_tool_for_edit_tool("apply_patch", Some("edit")));
        assert!(keep_tool_for_edit_tool("apply_patch", Some("patch")));

        assert!(keep_tool_for_edit_tool("edit", None));
        assert!(keep_tool_for_edit_tool("edit", Some("edit")));
        assert!(!keep_tool_for_edit_tool("edit", Some("patch")));
        assert!(!keep_tool_for_edit_tool("multi_edit", Some("patch")));
        assert!(!keep_tool_for_edit_tool("write_file", Some("patch")));
    }
}