rho-coding-agent 3.7.0

A fast Rust agent harness with a small footprint and opinionated defaults
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
//! Serializable views of the hook configuration and recent hook activity:
//! [`HookReport`] for diagnostics and the `/hooks` overlay, and the typed
//! report a daemon session answers, both read from one [`HookSnapshot`].
//!
//! A daemon session's report reads its hooks files again and checks them
//! against the hooks the session runs ([`HookSnapshot::checked`]); it never
//! installs what it read. The `rho` tool's report is the running hooks alone.
//!
//! Kept next to the hook types rather than in the diagnostics module so the
//! hook contract stays explicit. Diagnostics and the `/hooks` overlay consume
//! that data; they do not decide which programs run.

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

use rho_protocol::{
    HookActivityRecord, HookContract, HookStatus, HookTools, HookWarning, InvalidHooksFile,
    SessionHooksReport, SkippedHooksFile,
};
use rho_sdk::hooks::HookEventKind;
use serde::{Deserialize, Serialize};

use super::{
    activity::{HookActivity, HookOutcome},
    catalog::{HookCatalog, HookSpawnContract},
    config::{ConfiguredHookEvent, HookConfigError, WorkflowHookEventKind},
    dispatch::HookEngine,
    HookPipeline, HookPorts,
};

/// What a hook will execute, ready to show before trust is granted.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct HookContractView {
    /// Whether the session runs it now: false for a pending hook, true for
    /// a stale one.
    pub active: bool,
    /// How it differs from what the session runs, when its file changed
    /// since the session loaded its hooks.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub drift: Option<HookDrift>,
    pub id: String,
    pub event: String,
    pub tools: String,
    pub command: Vec<String>,
    pub working_directory: String,
    pub timeout: String,
    pub environment: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub warning: Option<String>,
}

/// How a listed hook differs from what its session runs.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HookDrift {
    /// Its file defines it, but the session does not run it yet.
    Pending,
    /// Its file defines it, but the session started without a hook of its
    /// kind, so it runs only once the session is opened again.
    NeedsReopen,
    /// The session still runs it, but its file no longer defines it so.
    Stale,
}

/// One recorded hook invocation.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct HookActivityView {
    pub hook: String,
    pub event: String,
    pub outcome: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub duration_ms: Option<u64>,
    pub truncated: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
}

impl From<&HookActivity> for HookActivityView {
    fn from(activity: &HookActivity) -> Self {
        Self {
            hook: activity.hook_label().to_owned(),
            event: activity.event.wire_name().to_owned(),
            outcome: activity.outcome.label().to_owned(),
            duration_ms: activity
                .duration
                .map(|duration| duration.as_millis() as u64),
            truncated: activity.truncated,
            detail: activity.outcome.detail().map(str::to_owned),
        }
    }
}

/// Everything `rho(action="hooks")` reports.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct HookReport {
    pub enabled: bool,
    pub files: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub skipped_untrusted: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub skipped_untrusted_error: Option<String>,
    /// A hooks file that loads but could not be read or validated; the
    /// session keeps the hooks listed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub invalid: Option<InvalidHooksFileView>,
    pub hooks: Vec<HookContractView>,
    pub recent_activity: Vec<HookActivityView>,
}

/// A hooks file that does not load, as [`HookReport`] shows it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct InvalidHooksFileView {
    pub path: String,
    /// What is wrong, without the path.
    pub error: String,
}

/// What a session's hooks are and did, read at one moment: the source of
/// both [`HookReport`] and the typed report a daemon session answers
/// (`SessionReport::Hooks`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HookSnapshot {
    enabled: bool,
    files: Vec<PathBuf>,
    skipped_untrusted: Option<SkippedHooksFile>,
    invalid: Option<InvalidHooksFile>,
    hooks: Vec<ListedHook>,
    activity: Vec<HookActivity>,
}

/// One hook a report lists, and whether its session runs it.
#[derive(Clone, Debug, PartialEq, Eq)]
struct ListedHook {
    contract: HookSpawnContract,
    status: ListedStatus,
}

/// Whether a session runs a listed hook, as [`HookStatus`] tells it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ListedStatus {
    Active,
    Untrusted,
    Pending,
    NeedsReopen,
    Stale,
}

impl HookSnapshot {
    /// A session with no hook runtime.
    pub fn disabled() -> Self {
        Self {
            enabled: false,
            files: Vec::new(),
            skipped_untrusted: None,
            invalid: None,
            hooks: Vec::new(),
            activity: Vec::new(),
        }
    }

    /// The hooks files as read now (`files`), checked against the hooks a
    /// session running `running` runs; `None` for a session without a hook
    /// runtime.
    ///
    /// A hook the files define is active when the session runs it exactly
    /// so; otherwise it is pending when a reload would load it, and needs a
    /// reopen when the files define a kind of hook the session started
    /// without (see [`HookPorts`]), which refuses the whole reload. One the
    /// session runs that the files no longer define is stale. Files that do
    /// not load are reported as `invalid` with the hooks the session runs.
    pub(super) fn checked(
        running: Option<&HookPipeline>,
        files: Result<HookCatalog, HookConfigError>,
    ) -> Self {
        let ports = HookPorts::of(running);
        let current = running.map(|hooks| hooks.engine().catalog());
        let activity = running.map_or_else(Vec::new, |hooks| hooks.engine().activity());
        let files = match files {
            Ok(files) => files,
            Err(error) => {
                return Self {
                    enabled: running.is_some(),
                    invalid: Some(InvalidHooksFile {
                        path: error.path.clone(),
                        error: error.detail(),
                    }),
                    activity,
                    ..current
                        .as_deref()
                        .map_or_else(Self::disabled, Self::running)
                };
            }
        };
        let runs: Vec<HookSpawnContract> = current
            .map(|catalog| {
                catalog
                    .spawn_contract()
                    .into_iter()
                    .filter(|contract| contract.active)
                    .collect()
            })
            .unwrap_or_default();
        let reloadable = ports.missing(&files).is_none();
        let defined = files.spawn_contract();
        let stale: Vec<ListedHook> = runs
            .iter()
            .filter(|contract| !defined.contains(contract))
            .map(|contract| ListedHook {
                contract: contract.clone(),
                status: ListedStatus::Stale,
            })
            .collect();
        let hooks = defined
            .into_iter()
            .map(|contract| {
                let status = if !contract.active {
                    ListedStatus::Untrusted
                } else if runs.contains(&contract) {
                    ListedStatus::Active
                } else if reloadable {
                    ListedStatus::Pending
                } else {
                    ListedStatus::NeedsReopen
                };
                ListedHook { contract, status }
            })
            .chain(stale)
            .collect();
        Self {
            enabled: running.is_some(),
            files: files.files().to_vec(),
            skipped_untrusted: skipped_untrusted(&files),
            invalid: None,
            hooks,
            activity,
        }
    }

    /// The hooks `catalog` runs, with no activity.
    fn running(catalog: &HookCatalog) -> Self {
        Self {
            enabled: true,
            files: catalog.files().to_vec(),
            skipped_untrusted: skipped_untrusted(catalog),
            invalid: None,
            hooks: catalog
                .spawn_contract()
                .into_iter()
                .map(|contract| ListedHook {
                    status: if contract.active {
                        ListedStatus::Active
                    } else {
                        ListedStatus::Untrusted
                    },
                    contract,
                })
                .collect(),
            activity: Vec::new(),
        }
    }

    /// The serializable view `rho(action="hooks")` and the `/hooks` overlay
    /// show.
    pub fn report(&self) -> HookReport {
        HookReport {
            enabled: self.enabled,
            files: self
                .files
                .iter()
                .map(|path| crate::paths::display(path))
                .collect(),
            skipped_untrusted: self
                .skipped_untrusted
                .as_ref()
                .map(|skipped| crate::paths::display(&skipped.path)),
            skipped_untrusted_error: self
                .skipped_untrusted
                .as_ref()
                .and_then(|skipped| skipped.error.clone()),
            invalid: self.invalid.as_ref().map(|invalid| InvalidHooksFileView {
                path: crate::paths::display(&invalid.path),
                error: invalid.error.clone(),
            }),
            hooks: self.hooks.iter().map(contract_view).collect(),
            recent_activity: self.activity.iter().map(HookActivityView::from).collect(),
        }
    }

    /// The typed report a daemon session answers.
    pub fn session_report(&self) -> SessionHooksReport {
        SessionHooksReport {
            enabled: self.enabled,
            files: self.files.clone(),
            skipped_untrusted: self.skipped_untrusted.clone(),
            invalid: self.invalid.clone(),
            hooks: self.hooks.iter().map(listed_contract).collect(),
            recent_activity: self.activity.iter().map(activity_record).collect(),
        }
    }
}

fn skipped_untrusted(catalog: &HookCatalog) -> Option<SkippedHooksFile> {
    catalog.skipped_untrusted().map(|skipped| SkippedHooksFile {
        path: skipped.path.clone(),
        error: skipped.error().map(HookConfigError::detail),
    })
}

/// Live hook state a diagnostics surface can read at any time.
#[derive(Clone)]
pub struct HookInspector {
    engine: Arc<HookEngine>,
}

impl HookInspector {
    pub fn new(runtime: &HookPipeline) -> Self {
        Self {
            engine: Arc::clone(runtime.engine()),
        }
    }

    /// The hooks the session runs and what they did.
    pub fn snapshot(&self) -> HookSnapshot {
        HookSnapshot {
            activity: self.engine.activity(),
            ..HookSnapshot::running(&self.engine.catalog())
        }
    }

    pub fn report(&self) -> HookReport {
        self.snapshot().report()
    }
}

impl std::fmt::Debug for HookInspector {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("HookInspector")
            .field("hooks", &self.engine.catalog().len())
            .finish()
    }
}

/// Renders one listed hook's resolved spawn contract.
fn contract_view(hook: &ListedHook) -> HookContractView {
    let contract = &hook.contract;
    let (active, drift) = match hook.status {
        ListedStatus::Active => (true, None),
        ListedStatus::Untrusted => (false, None),
        ListedStatus::Pending => (false, Some(HookDrift::Pending)),
        ListedStatus::NeedsReopen => (false, Some(HookDrift::NeedsReopen)),
        ListedStatus::Stale => (true, Some(HookDrift::Stale)),
    };
    HookContractView {
        active,
        drift,
        id: contract.id.clone(),
        event: contract.event.wire_name().to_owned(),
        tools: contract.tools.describe(),
        command: contract.command.clone(),
        working_directory: crate::paths::display(&contract.working_directory),
        timeout: humantime::format_duration(contract.timeout).to_string(),
        environment: contract.environment.clone(),
        warning: (!contract.missing_edit_tools.is_empty()).then(|| {
            format!(
                "skips some edit tools; add {} so this hook runs for every edit format",
                contract.missing_edit_tools.join(", ")
            )
        }),
    }
}

/// A listed hook as the typed report carries it.
fn listed_contract(hook: &ListedHook) -> HookContract {
    let status = match hook.status {
        ListedStatus::Active => HookStatus::Active,
        ListedStatus::Untrusted => HookStatus::Untrusted,
        ListedStatus::Pending => HookStatus::Pending,
        ListedStatus::NeedsReopen => HookStatus::NeedsReopen,
        ListedStatus::Stale => HookStatus::Stale,
    };
    contract(&hook.contract, status)
}

/// `contract` as the typed reports carry it, with `status`.
pub(super) fn contract(contract: &HookSpawnContract, status: HookStatus) -> HookContract {
    HookContract {
        id: contract.id.clone(),
        status,
        event: wire_event(contract.event),
        tools: contract
            .tools
            .patterns()
            .map_or(HookTools::All, |patterns| HookTools::Matching { patterns }),
        command: contract.command.clone(),
        working_directory: contract.working_directory.clone(),
        timeout_ms: u64::try_from(contract.timeout.as_millis()).unwrap_or(u64::MAX),
        environment: contract.environment.clone(),
        warnings: (!contract.missing_edit_tools.is_empty())
            .then(|| HookWarning::MissingEditTools {
                tools: contract
                    .missing_edit_tools
                    .iter()
                    .map(|tool| (*tool).to_owned())
                    .collect(),
            })
            .into_iter()
            .collect(),
    }
}

fn activity_record(activity: &HookActivity) -> HookActivityRecord {
    HookActivityRecord {
        hook: activity.hook_id.clone(),
        event: wire_event(activity.event),
        outcome: match &activity.outcome {
            HookOutcome::Continued => rho_protocol::HookOutcome::Continued,
            HookOutcome::Denied { reason } => rho_protocol::HookOutcome::Denied {
                reason: reason.clone(),
            },
            HookOutcome::Observed => rho_protocol::HookOutcome::Observed,
            HookOutcome::Failed { reason } => rho_protocol::HookOutcome::Failed {
                reason: reason.clone(),
            },
            HookOutcome::Dropped => rho_protocol::HookOutcome::Dropped,
        },
        duration_ms: activity
            .duration
            .map(|duration| u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)),
        output_truncated: activity.truncated,
    }
}

fn wire_event(event: ConfiguredHookEvent) -> rho_protocol::HookEvent {
    use rho_protocol::HookEvent as Wire;
    match event {
        ConfiguredHookEvent::Sdk(event) => match event {
            HookEventKind::SessionStarted => Wire::SessionStarted,
            HookEventKind::BeforeToolUse => Wire::BeforeToolUse,
            HookEventKind::AfterToolUse => Wire::AfterToolUse,
            HookEventKind::RunCompleted => Wire::RunCompleted,
            HookEventKind::RunFailed => Wire::RunFailed,
            HookEventKind::InputRequested => Wire::InputRequested,
            HookEventKind::SessionCompleted => Wire::SessionCompleted,
            HookEventKind::SessionFailed => Wire::SessionFailed,
            // An SDK event this rho does not name yet.
            _ => Wire::Unknown,
        },
        ConfiguredHookEvent::Workflow(event) => match event {
            WorkflowHookEventKind::Started => Wire::WorkflowStarted,
            WorkflowHookEventKind::NodeStarted => Wire::WorkflowNodeStarted,
            WorkflowHookEventKind::NodeFinished => Wire::WorkflowNodeFinished,
            WorkflowHookEventKind::Completed => Wire::WorkflowCompleted,
            WorkflowHookEventKind::Failed => Wire::WorkflowFailed,
            WorkflowHookEventKind::Cancelled => Wire::WorkflowCancelled,
        },
    }
}

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