rho-coding-agent 1.6.0

A lightweight agent harness inspired by Pi
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
468
469
470
//! Compatibility adapter that exposes application coding tools through the
//! public [`rho_sdk::tool::Tool`] contract.
//!
//! Shared filesystem implementations live with the application tools. This
//! module only supplies SDK-facing wrappers that require an explicit workspace
//! and authorize every read or write through
//! [`WorkspacePolicy`](rho_sdk::WorkspacePolicy) and
//! [`ApprovalHandler`](rho_sdk::ApprovalHandler). Default SDK construction still
//! grants no capabilities.
//!
//! The interactive and automation runtimes register these adapters on the public
//! SDK runtime. They do not participate in tool presentation, which is derived
//! from SDK events and metadata by the application presenter.

use std::{path::PathBuf, sync::Arc};

use serde::Deserialize;
use serde_json::Value;

use rho_sdk::{
    tool::{
        OperationKind, Tool, ToolContext, ToolError, ToolErrorKind, ToolFuture, ToolInvocation,
        ToolMetadata, ToolOutput, ToolProgress, ToolSecurity,
    },
    CapabilityKind, CapabilityRequest, CapabilitySource, WorkspacePathError, WorkspacePathState,
};

#[cfg(test)]
use rho_sdk::tool::{DuplicateToolName, ToolRegistry};

use crate::{
    config::DEFAULT_MAX_OUTPUT_BYTES,
    tool::{compact_display_path, truncate, Tool as AppTool, ToolError as AppToolError},
};

use super::{
    edit_file::{apply_edits, EditFile},
    edit_file_args::Args as EditArgs,
    list_dir::{list_directory, ListDir},
    read_file::{read_file_content, read_file_display_content, ReadFile},
    sdk_support::{check_cancelled, workspace, workspace_root},
    write_file::{write_file_content, WriteFile},
};

/// Options for coding tools registered on an SDK runtime.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CodingToolOptions {
    max_output_bytes: usize,
}

impl Default for CodingToolOptions {
    fn default() -> Self {
        Self {
            max_output_bytes: DEFAULT_MAX_OUTPUT_BYTES,
        }
    }
}

impl CodingToolOptions {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn max_output_bytes(mut self, max_output_bytes: usize) -> Self {
        self.max_output_bytes = max_output_bytes.max(1);
        self
    }

    #[cfg(test)]
    pub fn output_budget(&self) -> usize {
        self.max_output_bytes
    }
}

/// Registers the four workspace coding tools on an SDK registry.
///
/// The tools do not grant capabilities by themselves. Hosts must attach a
/// workspace and a non-default policy on the runtime before reads or writes
/// succeed.
#[cfg(test)]
pub fn register_coding_tools(
    registry: &mut ToolRegistry,
    options: CodingToolOptions,
) -> Result<(), DuplicateToolName> {
    for tool in coding_tools(options) {
        registry.register_shared(tool)?;
    }
    Ok(())
}

/// Returns the SDK coding tools as shared trait objects.
pub fn coding_tools(options: CodingToolOptions) -> Vec<Arc<dyn Tool>> {
    vec![
        Arc::new(ListDirTool {
            max_output_bytes: options.max_output_bytes,
        }),
        Arc::new(ReadFileTool {
            max_output_bytes: options.max_output_bytes,
        }),
        Arc::new(WriteFileTool {
            max_output_bytes: options.max_output_bytes,
        }),
        Arc::new(EditFileTool {
            max_output_bytes: options.max_output_bytes,
        }),
    ]
}

struct ListDirTool {
    max_output_bytes: usize,
}

struct ReadFileTool {
    max_output_bytes: usize,
}

struct WriteFileTool {
    max_output_bytes: usize,
}

struct EditFileTool {
    max_output_bytes: usize,
}

#[derive(Deserialize)]
struct PathArgs {
    path: String,
}

#[derive(Deserialize)]
struct ReadArgs {
    path: String,
    offset: Option<usize>,
    limit: Option<usize>,
}

#[derive(Deserialize)]
struct WriteArgs {
    path: String,
    content: String,
}

impl Tool for ListDirTool {
    fn spec(&self) -> rho_sdk::model::ToolSpec {
        ListDir.spec()
    }

    fn security(&self) -> ToolSecurity {
        ToolSecurity::built_in([CapabilityKind::Read])
    }

    fn start_metadata(&self, arguments: &Value) -> ToolMetadata {
        path_start_metadata(arguments, OperationKind::Read)
    }

    fn call<'a>(&'a self, invocation: ToolInvocation, context: ToolContext) -> ToolFuture<'a> {
        Box::pin(async move {
            check_cancelled(&context)?;
            let args: PathArgs = parse_args(invocation.into_arguments())?;
            let path =
                authorize_existing_path(&context, &args.path, PathCapability::Read, "list_dir")
                    .await?;
            let content = list_directory(&path).await.map_err(map_app_error)?;
            let display = display_path(&context, &args.path);
            Ok(
                ToolOutput::text(truncate(content, self.max_output_bytes)).metadata(
                    ToolMetadata::new()
                        .operation(OperationKind::Read)
                        .affected_path(display),
                ),
            )
        })
    }
}

impl Tool for ReadFileTool {
    fn spec(&self) -> rho_sdk::model::ToolSpec {
        ReadFile.spec()
    }

    fn security(&self) -> ToolSecurity {
        ToolSecurity::built_in([CapabilityKind::Read])
    }

    fn start_metadata(&self, arguments: &Value) -> ToolMetadata {
        path_start_metadata(arguments, OperationKind::Read)
    }

    fn call<'a>(&'a self, invocation: ToolInvocation, context: ToolContext) -> ToolFuture<'a> {
        Box::pin(async move {
            check_cancelled(&context)?;
            let args: ReadArgs = parse_args(invocation.into_arguments())?;
            let path =
                authorize_existing_path(&context, &args.path, PathCapability::Read, "read_file")
                    .await?;
            let content = read_file_content(&path, args.offset, args.limit)
                .await
                .map_err(map_app_error)?;
            let display = read_file_display_content(
                workspace_root(&context)?,
                &args.path,
                &serde_json::json!({
                    "offset": args.offset,
                    "limit": args.limit,
                }),
            );
            Ok(
                ToolOutput::text(truncate(content, self.max_output_bytes)).metadata(
                    ToolMetadata::new()
                        .operation(OperationKind::Read)
                        .affected_path(display),
                ),
            )
        })
    }
}

impl Tool for WriteFileTool {
    fn spec(&self) -> rho_sdk::model::ToolSpec {
        WriteFile.spec()
    }

    fn security(&self) -> ToolSecurity {
        // Diff-producing writes read existing content, so both capabilities are
        // independently required and independently authorized.
        ToolSecurity::built_in([CapabilityKind::Write, CapabilityKind::Read])
    }

    fn start_metadata(&self, arguments: &Value) -> ToolMetadata {
        path_start_metadata(arguments, OperationKind::Write)
    }

    fn call<'a>(&'a self, invocation: ToolInvocation, context: ToolContext) -> ToolFuture<'a> {
        Box::pin(async move {
            check_cancelled(&context)?;
            let args: WriteArgs = parse_args(invocation.into_arguments())?;
            let path = authorize_write_path(&context, &args.path, "write_file").await?;
            let display = display_path(&context, &args.path);
            let _ = context
                .progress()
                .send(
                    ToolProgress::message(format!("writing {display}"))
                        .metadata(ToolMetadata::new().operation(OperationKind::Write)),
                )
                .await;
            let outcome = write_file_content(&path, &display, &args.content, self.max_output_bytes)
                .await
                .map_err(map_app_error)?;
            Ok(ToolOutput::text(outcome.content).metadata(
                ToolMetadata::new()
                    .operation(OperationKind::Write)
                    .affected_path(outcome.display_path)
                    .diff(outcome.diff),
            ))
        })
    }
}

impl Tool for EditFileTool {
    fn spec(&self) -> rho_sdk::model::ToolSpec {
        EditFile.spec()
    }

    fn security(&self) -> ToolSecurity {
        // Edits always read current file contents before applying replacements.
        ToolSecurity::built_in([CapabilityKind::Write, CapabilityKind::Read])
    }

    fn start_metadata(&self, arguments: &Value) -> ToolMetadata {
        path_start_metadata(arguments, OperationKind::Write)
    }

    fn call<'a>(&'a self, invocation: ToolInvocation, context: ToolContext) -> ToolFuture<'a> {
        Box::pin(async move {
            check_cancelled(&context)?;
            let args: EditArgs = parse_args(invocation.into_arguments())?;
            let edits = args.into_edits().map_err(map_app_error)?;
            let root = workspace_root(&context)?.to_path_buf();
            let mut authorized_paths = std::collections::HashMap::new();
            for edit in &edits {
                let workspace = workspace(&context)?;
                let resolved = workspace
                    .resolve_for_read(&edit.path)
                    .map_err(map_path_error)?;
                authorize_path(&context, &resolved, PathCapability::Write, "edit_file").await?;
                authorize_path(&context, &resolved, PathCapability::Read, "edit_file").await?;
                workspace.revalidate(&resolved).map_err(map_path_error)?;
                authorized_paths.insert(edit.path.clone(), resolved.path().to_path_buf());
            }
            let total = edits.len() as u64;
            let _ = context
                .progress()
                .send(
                    ToolProgress::message(format!("editing {total} change(s)"))
                        .units(0, total.max(1))
                        .metadata(ToolMetadata::new().operation(OperationKind::Write)),
                )
                .await;

            let outcome = apply_edits(
                edits,
                |path| {
                    authorized_paths.get(path).cloned().ok_or_else(|| {
                        AppToolError::Message(format!(
                            "edit path '{path}' was not authorized for this invocation"
                        ))
                    })
                },
                |path| compact_display_path(&root, path),
                self.max_output_bytes,
            )
            .await
            .map_err(map_app_error)?;

            let _ = context
                .progress()
                .send(
                    ToolProgress::message(format!("edited {} file(s)", outcome.file_count))
                        .units(total.max(1), total.max(1))
                        .metadata(ToolMetadata::new().operation(OperationKind::Write)),
                )
                .await;

            let mut metadata = ToolMetadata::new().operation(OperationKind::Write);
            for path in &outcome.display_paths {
                metadata = metadata.affected_path(path);
            }
            metadata = metadata.diff(outcome.diffs);
            Ok(ToolOutput::text(outcome.content).metadata(metadata))
        })
    }
}

fn path_start_metadata(arguments: &Value, operation: OperationKind) -> ToolMetadata {
    let mut metadata = ToolMetadata::new().operation(operation);
    if let Some(path) = arguments.get("path").and_then(Value::as_str) {
        metadata = metadata.affected_path(path);
    }
    for path in arguments
        .get("edits")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter_map(|edit| edit.get("path").and_then(Value::as_str))
    {
        metadata = metadata.affected_path(path);
    }
    metadata
}

#[derive(Clone, Copy)]
enum PathCapability {
    Read,
    Write,
}

fn parse_args<T: for<'de> Deserialize<'de>>(args: Value) -> Result<T, ToolError> {
    serde_json::from_value(args).map_err(|error| {
        ToolError::new(
            ToolErrorKind::InvalidArguments,
            format!("invalid arguments: {error}"),
        )
    })
}

fn display_path(context: &ToolContext, path: &str) -> String {
    match context.workspace_root() {
        Some(root) => compact_display_path(root, path),
        None => path.to_string(),
    }
}

async fn authorize_existing_path(
    context: &ToolContext,
    path: &str,
    capability: PathCapability,
    tool_name: &str,
) -> Result<PathBuf, ToolError> {
    let workspace = workspace(context)?;
    let resolved = workspace.resolve_for_read(path).map_err(map_path_error)?;
    authorize_path(context, &resolved, capability, tool_name).await?;
    workspace.revalidate(&resolved).map_err(map_path_error)?;
    Ok(resolved.path().to_path_buf())
}

async fn authorize_write_path(
    context: &ToolContext,
    path: &str,
    tool_name: &str,
) -> Result<PathBuf, ToolError> {
    let workspace = workspace(context)?;
    let resolved = workspace.resolve_for_write(path).map_err(map_path_error)?;
    authorize_path(context, &resolved, PathCapability::Write, tool_name).await?;
    // Existing targets are read to build unified diffs, so write-only policies
    // must not observe old content through tool output.
    if resolved.state() == WorkspacePathState::Existing {
        authorize_path(context, &resolved, PathCapability::Read, tool_name).await?;
    }
    workspace.revalidate(&resolved).map_err(map_path_error)?;
    Ok(resolved.path().to_path_buf())
}

async fn authorize_path(
    context: &ToolContext,
    path: &rho_sdk::ResolvedWorkspacePath,
    capability: PathCapability,
    tool_name: &str,
) -> Result<(), ToolError> {
    let source = CapabilitySource::built_in_tool(tool_name);
    let request = match capability {
        PathCapability::Read => {
            CapabilityRequest::read_path(path.path(), path.scope().clone(), source)
        }
        PathCapability::Write => {
            CapabilityRequest::write_path(path.path(), path.scope().clone(), source)
        }
    };
    context
        .authorize(request)
        .await
        .map(|_| ())
        .map_err(|error| {
            if error.kind() == rho_sdk::AuthorizationDenialKind::Cancelled {
                ToolError::cancelled()
            } else {
                ToolError::policy_denied(&error)
            }
        })
}

fn map_path_error(error: WorkspacePathError) -> ToolError {
    let kind = match error.kind() {
        rho_sdk::WorkspacePathErrorKind::ParentTraversal
        | rho_sdk::WorkspacePathErrorKind::OutsideGrantedRoots
        | rho_sdk::WorkspacePathErrorKind::InvalidPlatformPath
        | rho_sdk::WorkspacePathErrorKind::ChangedAfterAuthorization => ToolErrorKind::PolicyDenied,
        _ => ToolErrorKind::Execution,
    };
    ToolError::new(kind, error.to_string())
}

fn map_app_error(error: AppToolError) -> ToolError {
    match error {
        AppToolError::InvalidArguments(error) => ToolError::new(
            ToolErrorKind::InvalidArguments,
            format!("invalid arguments: {error}"),
        ),
        AppToolError::Io(error) => ToolError::new(ToolErrorKind::Execution, error.to_string()),
        AppToolError::Utf8(error) => ToolError::new(ToolErrorKind::Execution, error.to_string()),
        AppToolError::Message(message) if message == "tool interrupted" => ToolError::cancelled(),
        AppToolError::Message(message) => ToolError::new(ToolErrorKind::Execution, message),
    }
}

/// Test helper: build a deny-by-default tool context rooted at `workspace`.
#[cfg(test)]
pub(super) fn deny_context(
    workspace: Option<rho_sdk::Workspace>,
) -> (ToolContext, rho_sdk::tool::ToolProgressReceiver) {
    let (progress, receiver) =
        rho_sdk::tool::tool_progress_channel(std::num::NonZeroUsize::new(4).unwrap());
    (
        ToolContext::new(workspace, rho_sdk::CancellationToken::new(), progress),
        receiver,
    )
}

#[cfg(test)]
#[path = "sdk_adapter_tests.rs"]
mod tests;