yolop 0.9.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
437
438
439
440
441
442
443
//! `doctor` — a conformance probe for an extension's capability server.
//!
//! Spawns the server, runs the YEP `initialize` handshake, and checks the
//! result against the package manifest and the protocol: version
//! compatibility, that the server only *narrows* the manifest's tool/prompt
//! grant (the D4 clamp), and that its declared facets line up. It is a
//! diagnostic — a one-shot spawn that shuts the server down again — so
//! authors can validate a server before shipping it (`/extensions doctor`),
//! and the runtime dual of the CI schema/drift guards.

use super::client::YepConnection;
use super::package::ExtensionManifest;
use super::protocol::{InitializeParams, InitializeResult, PROTOCOL_VERSION, version_compatible};
use serde::Serialize;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::Duration;
use tokio::process::Command;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Status {
    Pass,
    Warn,
    Fail,
}

#[derive(Debug, Clone, Serialize)]
pub struct Check {
    pub name: &'static str,
    pub status: Status,
    pub detail: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct Report {
    /// `true` when no check failed (warnings are allowed).
    pub ok: bool,
    pub checks: Vec<Check>,
}

impl Report {
    fn from(checks: Vec<Check>) -> Self {
        let ok = !checks.iter().any(|c| c.status == Status::Fail);
        Self { ok, checks }
    }

    /// A report where spawning/handshake failed outright — a single failed
    /// check, since nothing else could run.
    fn fatal(name: &'static str, detail: impl Into<String>) -> Self {
        Self::from(vec![Check {
            name,
            status: Status::Fail,
            detail: detail.into(),
        }])
    }
}

fn pass(name: &'static str, detail: impl Into<String>) -> Check {
    Check {
        name,
        status: Status::Pass,
        detail: detail.into(),
    }
}
fn warn(name: &'static str, detail: impl Into<String>) -> Check {
    Check {
        name,
        status: Status::Warn,
        detail: detail.into(),
    }
}

/// Probe one extension server described by `manifest`, spawning its command
/// with `package_dir`'s `bin/` on `PATH` (as the runtime does). Never panics;
/// a spawn/handshake failure becomes a `Fail` check rather than an error.
pub async fn doctor(
    manifest: &ExtensionManifest,
    package_dir: &Path,
    workspace_root: &Path,
    timeout: Duration,
) -> Report {
    let server = &manifest.capability_server;
    let mut command = Command::new(&server.command);
    command
        .args(&server.args)
        .current_dir(workspace_root)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::inherit())
        .kill_on_drop(true);
    let bin_dir = package_dir.join("bin");
    if bin_dir.is_dir()
        && let Some(path) = std::env::var_os("PATH")
    {
        let mut paths: Vec<PathBuf> = vec![bin_dir];
        paths.extend(std::env::split_paths(&path));
        if let Ok(joined) = std::env::join_paths(paths) {
            command.env("PATH", joined);
        }
    }

    let mut child = match command.spawn() {
        Ok(child) => child,
        Err(err) => {
            return Report::fatal(
                "spawn",
                format!(
                    "cannot spawn `{}`: {err} (is it installed / on PATH?)",
                    server.command
                ),
            );
        }
    };
    let (Some(stdout), Some(stdin)) = (child.stdout.take(), child.stdin.take()) else {
        return Report::fatal("spawn", "server has no stdio pipes");
    };

    let init = InitializeParams {
        protocol_version: PROTOCOL_VERSION.to_string(),
        session_id: "doctor".into(),
        workspace_root: workspace_root.display().to_string(),
        config: serde_json::Value::Null,
        capabilities: vec!["cancel".into(), "streaming".into()],
    };
    let handshake = match YepConnection::connect(
        stdout,
        stdin,
        &manifest.name,
        init,
        timeout,
        None,
        None,
    )
    .await
    {
        Ok((connection, handshake)) => {
            connection.notify("shutdown", serde_json::Value::Null);
            handshake
        }
        Err(err) => {
            return Report::fatal("handshake", format!("initialize failed: {err}"));
        }
    };

    Report::from(evaluate(manifest, &handshake))
}

/// The manifest-vs-handshake checks (pure; unit-tested without a process).
pub fn evaluate(manifest: &ExtensionManifest, handshake: &InitializeResult) -> Vec<Check> {
    let mut checks = vec![
        pass("spawn", "server started"),
        pass("handshake", "initialize ok"),
    ];

    // Protocol version.
    checks.push(if handshake.protocol_version.is_empty() {
        warn(
            "protocol_version",
            "server did not report a protocol_version",
        )
    } else if version_compatible(&handshake.protocol_version) {
        pass(
            "protocol_version",
            format!("{} (compatible)", handshake.protocol_version),
        )
    } else {
        Check {
            name: "protocol_version",
            status: Status::Fail,
            detail: format!(
                "server speaks YEP {} — incompatible with {PROTOCOL_VERSION}",
                handshake.protocol_version
            ),
        }
    });

    // Identity.
    if !handshake.name.is_empty() && handshake.name != manifest.name {
        checks.push(warn(
            "name",
            format!(
                "server introduced itself as `{}`; manifest name `{}` wins",
                handshake.name, manifest.name
            ),
        ));
    }

    // Tool clamp (D4): the handshake may only narrow the manifest's tools.
    let approved: HashSet<&str> = manifest.tools.iter().map(|t| t.name.as_str()).collect();
    let served: HashSet<&str> = handshake
        .capability_params
        .tools
        .iter()
        .map(|t| t.name.as_str())
        .collect();
    let widened: Vec<&str> = served.difference(&approved).copied().collect();
    let unserved: Vec<&str> = approved.difference(&served).copied().collect();
    checks.push(if !widened.is_empty() {
        Check {
            name: "tools",
            status: Status::Fail,
            detail: format!(
                "server advertises tool(s) not in the manifest: {} — this would be refused at runtime",
                widened.join(", ")
            ),
        }
    } else if !unserved.is_empty() {
        warn(
            "tools",
            format!(
                "manifest declares {} tool(s) the server did not serve: {}",
                unserved.len(),
                unserved.join(", ")
            ),
        )
    } else if approved.is_empty() {
        pass("tools", "no tools declared")
    } else {
        pass("tools", format!("{} tool(s), all served", approved.len()))
    });

    // Prompt facet consistency.
    let server_prompt = handshake.capability_params.prompt.is_some()
        || handshake.capabilities.iter().any(|c| c == "dynamic_prompt");
    let manifest_prompt = manifest.prompt || manifest.dynamic_prompt;
    if server_prompt && !manifest_prompt {
        checks.push(warn(
            "prompt",
            "server offers a prompt contribution but the manifest declares neither `prompt` nor `dynamic_prompt` — it will be ignored",
        ));
    } else if manifest.prompt
        && handshake.capability_params.prompt.is_none()
        && !manifest.dynamic_prompt
    {
        checks.push(warn(
            "prompt",
            "manifest declares `prompt: true` but the server sent no static prompt",
        ));
    } else if manifest_prompt {
        checks.push(pass("prompt", "prompt facet present"));
    }

    checks
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::extensions::package::parse_manifest;
    use serde_json::json;

    fn manifest(tools: &[&str], prompt: bool) -> ExtensionManifest {
        parse_manifest(
            &json!({
                "name": "echo", "description": "t",
                "yolop": {
                    "protocol_version": "1.0",
                    "capabilityServer": { "command": "x" },
                    "tools": tools.iter().map(|n| json!({"name": n})).collect::<Vec<_>>(),
                    "prompt": prompt,
                }
            })
            .to_string(),
        )
        .unwrap()
    }

    fn handshake(version: &str, tools: &[&str], prompt: bool) -> InitializeResult {
        serde_json::from_value(json!({
            "protocol_version": version,
            "name": "echo",
            "capabilities": if prompt { vec!["tools","prompt"] } else { vec!["tools"] },
            "capability_params": {
                "tools": tools.iter().map(|n| json!({"name": n})).collect::<Vec<_>>(),
                "prompt": if prompt { json!({"static": "hi"}) } else { json!(null) },
            }
        }))
        .unwrap()
    }

    #[test]
    fn clean_server_passes() {
        let checks = evaluate(
            &manifest(&["echo"], true),
            &handshake("1.0", &["echo"], true),
        );
        assert!(Report::from(checks.clone()).ok, "{checks:?}");
        assert!(checks.iter().all(|c| c.status == Status::Pass));
    }

    #[test]
    fn widened_tools_fail() {
        // Server advertises a tool not in the manifest → hard fail (would be refused).
        let checks = evaluate(
            &manifest(&["echo"], false),
            &handshake("1.0", &["echo", "sneaky"], false),
        );
        let report = Report::from(checks);
        assert!(!report.ok);
        assert!(
            report
                .checks
                .iter()
                .any(|c| c.name == "tools" && c.status == Status::Fail)
        );
    }

    #[test]
    fn incompatible_version_fails() {
        let report = Report::from(evaluate(
            &manifest(&["echo"], false),
            &handshake("2.0", &["echo"], false),
        ));
        assert!(!report.ok);
        assert!(
            report
                .checks
                .iter()
                .any(|c| c.name == "protocol_version" && c.status == Status::Fail)
        );
    }

    #[test]
    fn unserved_manifest_tool_warns_but_passes() {
        let report = Report::from(evaluate(
            &manifest(&["echo", "extra"], false),
            &handshake("1.0", &["echo"], false),
        ));
        assert!(report.ok); // warnings don't fail
        assert!(
            report
                .checks
                .iter()
                .any(|c| c.name == "tools" && c.status == Status::Warn)
        );
    }

    fn python3() -> Option<String> {
        for candidate in ["python3", "python"] {
            if std::process::Command::new(candidate)
                .arg("--version")
                .output()
                .is_ok_and(|out| out.status.success())
            {
                return Some(candidate.to_string());
            }
        }
        None
    }

    /// End-to-end: spawn the real Python fixture server, handshake, and grade
    /// it. The fixture serves `echo` but not the manifest-approved `unserved`,
    /// so a clean run reports `ok` with a warn on the unserved tool — the same
    /// shape `/extensions doctor` surfaces to an author.
    #[tokio::test]
    async fn doctor_probes_the_real_fixture_server() {
        let Some(python) = python3() else {
            eprintln!("skipping: python3 not available");
            return;
        };
        let server = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/yep_echo_server.py");
        let manifest = parse_manifest(
            &json!({
                "name": "echo", "description": "Echo fixture.",
                "yolop": {
                    "protocol_version": "1.0",
                    "capabilityServer": { "command": python,
                        "args": [server.display().to_string()] },
                    "tools": [
                        { "name": "echo", "description": "Echo text." },
                        { "name": "unserved", "description": "Never served." }
                    ],
                    "prompt": true
                }
            })
            .to_string(),
        )
        .unwrap();

        let report = super::doctor(
            &manifest,
            &std::env::temp_dir(),
            &std::env::temp_dir(),
            Duration::from_secs(20),
        )
        .await;

        assert!(report.ok, "clean fixture should pass: {:?}", report.checks);
        assert!(
            report
                .checks
                .iter()
                .any(|c| c.name == "spawn" && c.status == Status::Pass)
        );
        assert!(
            report
                .checks
                .iter()
                .any(|c| c.name == "handshake" && c.status == Status::Pass)
        );
        assert!(
            report
                .checks
                .iter()
                .any(|c| c.name == "tools" && c.status == Status::Warn),
            "unserved manifest tool should warn: {:?}",
            report.checks
        );
    }

    #[tokio::test]
    async fn doctor_reports_spawn_failure_without_panicking() {
        let manifest = parse_manifest(
            &json!({
                "name": "nope", "description": "missing binary",
                "yolop": {
                    "protocol_version": "1.0",
                    "capabilityServer": { "command": "yolop-definitely-not-a-real-binary-xyz" },
                    "tools": [{ "name": "noop", "description": "n" }]
                }
            })
            .to_string(),
        )
        .unwrap();
        let report = super::doctor(
            &manifest,
            &std::env::temp_dir(),
            &std::env::temp_dir(),
            Duration::from_secs(5),
        )
        .await;
        assert!(!report.ok);
        assert!(
            report
                .checks
                .iter()
                .any(|c| c.name == "spawn" && c.status == Status::Fail)
        );
    }
}