yolop 0.4.0

Yolop — a terminal coding agent built on everruns-runtime
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
// The `hooks` capability — authoring and inspecting Yolop hook config.
//
// The hook engine itself is upstream `user_hooks`; this capability is only the
// natural-language-safe write surface for Yolop's global/workspace `hooks.json`
// files.

use crate::capabilities::narration::stable_labeled;
use crate::hooks_config::{HookScope, HooksStore};
use async_trait::async_trait;
use everruns_core::capabilities::{Capability, CapabilityStatus, SystemPromptContext};
use everruns_core::tool_narration::{ToolNarrationPhase, arg_str, truncate};
use everruns_core::tool_types::ToolCall;
use everruns_core::tools::{Tool, ToolExecutionResult};
use serde_json::{Value, json};
use std::sync::Arc;

pub(crate) const HOOKS_CAPABILITY_ID: &str = "hooks";

pub(crate) struct HooksCapability {
    pub(crate) hooks: Arc<HooksStore>,
}

#[async_trait]
impl Capability for HooksCapability {
    fn id(&self) -> &str {
        HOOKS_CAPABILITY_ID
    }

    fn name(&self) -> &str {
        "Hooks"
    }

    fn description(&self) -> &str {
        "Authoring and inspection tools for global and workspace hook configuration."
    }

    fn status(&self) -> CapabilityStatus {
        CapabilityStatus::Available
    }

    fn category(&self) -> Option<&str> {
        Some("Extensibility")
    }

    async fn system_prompt_contribution(&self, _ctx: &SystemPromptContext) -> Option<String> {
        Some(
            "<capability id=\"hooks\">\n\
             Configure hook requests such as \"setup a hook to prevent calls to git\" with \
             `validate_hook` and `upsert_hook`. Use `list_hooks` before changing existing hooks \
             and `remove_hook` when removing or disabling one. Do not store hook requests as \
             memory notes; hooks are real global/workspace configuration.\n\
             </capability>"
                .to_string(),
        )
    }

    fn system_prompt_preview(&self) -> Option<String> {
        Some(
            "<capability id=\"hooks\">\n\
             Configure global/workspace hooks with `list_hooks`, `validate_hook`, `upsert_hook`, \
             and `remove_hook`.\n\
             </capability>"
                .to_string(),
        )
    }

    fn tools(&self) -> Vec<Box<dyn Tool>> {
        vec![
            Box::new(ListHooksTool {
                hooks: self.hooks.clone(),
            }),
            Box::new(ValidateHookTool {
                hooks: self.hooks.clone(),
            }),
            Box::new(UpsertHookTool {
                hooks: self.hooks.clone(),
            }),
            Box::new(RemoveHookTool {
                hooks: self.hooks.clone(),
            }),
        ]
    }
}

struct ListHooksTool {
    hooks: Arc<HooksStore>,
}

#[async_trait]
impl Tool for ListHooksTool {
    fn narrate(
        &self,
        _tool_call: &ToolCall,
        phase: ToolNarrationPhase,
        locale: Option<&str>,
    ) -> Option<String> {
        let _ = locale;
        Some(stable_labeled("List hooks", None, phase))
    }

    fn name(&self) -> &str {
        "list_hooks"
    }

    fn display_name(&self) -> Option<&str> {
        Some("List hooks")
    }

    fn description(&self) -> &str {
        "List Yolop hooks from global and workspace hook config. Use for \
         \"what hooks are configured?\" or before changing an existing hook."
    }

    fn parameters_schema(&self) -> Value {
        json!({ "type": "object", "properties": {}, "additionalProperties": false })
    }

    async fn execute(&self, _arguments: Value) -> ToolExecutionResult {
        let effective = self.hooks.effective();
        ToolExecutionResult::success(json!({
            "ok": true,
            "global_path": effective.global_path.display().to_string(),
            "workspace_path": effective.workspace_path.display().to_string(),
            "count": effective.hooks.len(),
            "scope_counts": effective.scope_counts(),
            "hooks": effective.summaries(),
        }))
    }
}

struct ValidateHookTool {
    hooks: Arc<HooksStore>,
}

#[async_trait]
impl Tool for ValidateHookTool {
    fn narrate(
        &self,
        tool_call: &ToolCall,
        phase: ToolNarrationPhase,
        locale: Option<&str>,
    ) -> Option<String> {
        let _ = locale;
        let id = tool_call
            .arguments
            .get("hook")
            .and_then(|hook| hook.get("id"))
            .and_then(Value::as_str)
            .map(|value| truncate(value, 48));
        Some(stable_labeled("Validate hook", id, phase))
    }

    fn name(&self) -> &str {
        "validate_hook"
    }

    fn display_name(&self) -> Option<&str> {
        Some("Validate hook")
    }

    fn description(&self) -> &str {
        "Validate a candidate Yolop hook spec without writing it. Use before `upsert_hook`, \
         especially when translating a natural-language request into hook JSON."
    }

    fn parameters_schema(&self) -> Value {
        hook_value_schema()
    }

    async fn execute(&self, arguments: Value) -> ToolExecutionResult {
        let hook = match arguments.get("hook") {
            Some(hook) => hook.clone(),
            None => return ToolExecutionResult::tool_error("'hook' is required"),
        };
        match self.hooks.validate_hook(&hook) {
            Ok(entry) => ToolExecutionResult::success(json!({
                "ok": true,
                "hook": entry.to_validation_json(),
            })),
            Err(error) => ToolExecutionResult::tool_error(format!("invalid hook: {error}")),
        }
    }
}

struct UpsertHookTool {
    hooks: Arc<HooksStore>,
}

#[async_trait]
impl Tool for UpsertHookTool {
    fn narrate(
        &self,
        tool_call: &ToolCall,
        phase: ToolNarrationPhase,
        locale: Option<&str>,
    ) -> Option<String> {
        let _ = locale;
        let id = tool_call
            .arguments
            .get("hook")
            .and_then(|hook| hook.get("id"))
            .and_then(Value::as_str)
            .map(|value| truncate(value, 48));
        Some(stable_labeled("Save hook", id, phase))
    }

    fn name(&self) -> &str {
        "upsert_hook"
    }

    fn display_name(&self) -> Option<&str> {
        Some("Save hook")
    }

    fn description(&self) -> &str {
        "Create or replace one Yolop hook by id. Use global scope for personal Yolop behavior \
         and workspace scope for project-owned hook config. Validates before writing."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "scope": {
                    "type": "string",
                    "enum": ["global", "workspace"],
                    "description": "Where to write the hook. Use global for personal Yolop configuration; workspace for this repo."
                },
                "hook": {
                    "type": "object",
                    "description": "A UserHookSpec object with a stable id."
                }
            },
            "required": ["scope", "hook"],
            "additionalProperties": false
        })
    }

    async fn execute(&self, arguments: Value) -> ToolExecutionResult {
        let scope = match parse_scope_arg(&arguments) {
            Ok(scope) => scope,
            Err(error) => return ToolExecutionResult::tool_error(error),
        };
        let hook = match arguments.get("hook") {
            Some(hook) => hook.clone(),
            None => return ToolExecutionResult::tool_error("'hook' is required"),
        };
        match self.hooks.upsert_hook(scope, hook) {
            Ok(entry) => ToolExecutionResult::success(json!({
                "ok": true,
                "message": format!("saved {} hook", scope.as_str()),
                "hook": entry.to_summary_json(),
                "path": self.hooks.path_for(scope).display().to_string(),
            })),
            Err(error) => ToolExecutionResult::tool_error(format!("could not save hook: {error}")),
        }
    }
}

struct RemoveHookTool {
    hooks: Arc<HooksStore>,
}

#[async_trait]
impl Tool for RemoveHookTool {
    fn narrate(
        &self,
        tool_call: &ToolCall,
        phase: ToolNarrationPhase,
        locale: Option<&str>,
    ) -> Option<String> {
        let _ = locale;
        let id = arg_str(&tool_call.arguments, &["id"]).map(|value| truncate(value, 48));
        Some(stable_labeled("Remove hook", id, phase))
    }

    fn name(&self) -> &str {
        "remove_hook"
    }

    fn display_name(&self) -> Option<&str> {
        Some("Remove hook")
    }

    fn description(&self) -> &str {
        "Remove one Yolop hook by id from the selected scope. Workspace removal also writes a \
         disabled marker so a lower-precedence global hook with the same id stays disabled."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "scope": {
                    "type": "string",
                    "enum": ["global", "workspace"]
                },
                "id": {
                    "type": "string",
                    "description": "Stable hook id to remove or disable."
                }
            },
            "required": ["scope", "id"],
            "additionalProperties": false
        })
    }

    async fn execute(&self, arguments: Value) -> ToolExecutionResult {
        let scope = match parse_scope_arg(&arguments) {
            Ok(scope) => scope,
            Err(error) => return ToolExecutionResult::tool_error(error),
        };
        let id = match arguments.get("id").and_then(Value::as_str) {
            Some(id) if !id.trim().is_empty() => id,
            _ => return ToolExecutionResult::tool_error("'id' is required"),
        };
        match self.hooks.remove_hook(scope, id) {
            Ok(removed) => ToolExecutionResult::success(json!({
                "ok": true,
                "removed": removed,
                "id": id,
                "scope": scope.as_str(),
                "path": self.hooks.path_for(scope).display().to_string(),
            })),
            Err(error) => {
                ToolExecutionResult::tool_error(format!("could not remove hook: {error}"))
            }
        }
    }
}

fn parse_scope_arg(arguments: &Value) -> std::result::Result<HookScope, String> {
    let scope = arguments
        .get("scope")
        .and_then(Value::as_str)
        .ok_or_else(|| "'scope' is required".to_string())?;
    HookScope::parse(scope).map_err(|error| error.to_string())
}

fn hook_value_schema() -> Value {
    json!({
        "type": "object",
        "properties": {
            "hook": {
                "type": "object",
                "description": "A UserHookSpec object."
            }
        },
        "required": ["hook"],
        "additionalProperties": false
    })
}

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

    fn hooks_in_tmp() -> (tempfile::TempDir, HooksStore) {
        let tmp = tempfile::tempdir().expect("hooks tmp");
        let store = HooksStore::new(tmp.path().join("hooks.json"), tmp.path().join("workspace"));
        (tmp, store)
    }

    #[test]
    fn capability_exposes_unprefixed_hook_tools_without_slash_command() {
        let (_hooks_tmp, hooks) = hooks_in_tmp();
        let capability = HooksCapability {
            hooks: Arc::new(hooks),
        };

        let names = capability
            .tools()
            .iter()
            .map(|tool| tool.name().to_string())
            .collect::<Vec<_>>();

        assert_eq!(
            names,
            vec!["list_hooks", "validate_hook", "upsert_hook", "remove_hook"]
        );
        assert!(capability.commands().is_empty());
    }

    fn block_git_hook() -> Value {
        json!({
            "id": "block-git",
            "event": "pre_tool_use",
            "matcher": {
                "tool_name": "bash",
                "args_jsonpath": "$.command",
                "match_regex": "(^|[;&|()[:space:]])git([[:space:]]|$)"
            },
            "executor": {
                "type": "bash",
                "command": "printf '%s\\n' '{\"decision\":\"block\",\"reason\":\"blocked\"}'"
            },
            "timeout_ms": 1000,
            "on_error": "block",
            "description": "Block git"
        })
    }

    #[tokio::test]
    async fn hook_tools_validate_save_list_and_remove() {
        let (_tmp, hooks) = hooks_in_tmp();
        let hooks = Arc::new(hooks);
        let validate = ValidateHookTool {
            hooks: hooks.clone(),
        };
        let validated = validate.execute(json!({ "hook": block_git_hook() })).await;
        assert!(validated.is_success());

        let upsert = UpsertHookTool {
            hooks: hooks.clone(),
        };
        let saved = upsert
            .execute(json!({ "scope": "global", "hook": block_git_hook() }))
            .await;
        assert!(saved.is_success());

        let list = ListHooksTool {
            hooks: hooks.clone(),
        };
        let listed = list.execute(json!({})).await;
        assert!(listed.is_success());

        let remove = RemoveHookTool {
            hooks: hooks.clone(),
        };
        let removed = remove
            .execute(json!({ "scope": "global", "id": "block-git" }))
            .await;
        assert!(removed.is_success());
        assert!(hooks.effective().hooks.is_empty());
    }
}