scv-tools 0.3.0

Workspace-scoped filesystem, process, skill, and agent tools for SCV
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
//! Unit tests for `src/delegate/scv.rs`.

use std::{os::unix::fs::PermissionsExt as _, sync::Mutex as StdMutex, time::Duration};

use async_trait::async_trait;
use scv_core::{AgentError, ApprovalGate, ApprovalRequest, ToolApprovals};

use super::*;
use crate::delegate::{
    conversation::ConversationLimits,
    records::{DelegationRegistry, ProcessIdentity},
};

/// A bash stand-in for `scv server --stdio`, in `tests/fake_scv.sh`. It
/// writes its PID to `<mode>.pid`, answers the handshake, logs each turn it
/// starts to `<mode>.turns`, and handles turns according to `mode`.
fn fake_scv(dir: &Path, mode: &str) -> PathBuf {
    let path = dir.join(format!("fake-scv-{mode}"));
    let script = include_str!("tests/fake_scv.sh")
        .replace(
            "@PID@",
            &dir.join(format!("{mode}.pid")).display().to_string(),
        )
        .replace(
            "@DEPTH@",
            &dir.join(format!("{mode}.depth")).display().to_string(),
        )
        .replace(
            "@CANCELS@",
            &dir.join(format!("{mode}.cancels")).display().to_string(),
        )
        .replace(
            "@TURNS@",
            &dir.join(format!("{mode}.turns")).display().to_string(),
        )
        .replace("@VERSION@", &PROTOCOL_VERSION.to_string())
        .replace("@MODE@", mode);
    std::fs::write(&path, script).unwrap();
    std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
    path
}

/// Open conversation `scv-1` with a turn that finishes at once, under the
/// default timeout.
async fn warm_up(tool: &ScvAgentTool, dir: &Path) {
    let output = tool
        .execute(json!({"prompt":"warm up"}), context(dir, None))
        .await
        .unwrap();
    assert_eq!(json(&output)["session"], "scv-1", "{}", output.content);
}

fn tool(
    script: &Path,
    conversations: Arc<ConversationStore>,
    delegation: Option<DelegationContext>,
) -> ScvAgentTool {
    ScvAgentTool {
        name: "agent_scv".into(),
        command: script.display().to_string(),
        resolved: Some(script.to_owned()),
        args: Vec::new(),
        environment: Vec::new(),
        timeouts: Timeouts {
            default: Duration::from_secs(20),
            max: Duration::from_secs(30),
        },
        output_limit: 64 * 1024,
        delegation,
        conversations,
    }
}

fn store(idle: Duration) -> Arc<ConversationStore> {
    Arc::new(ConversationStore::new(
        ConversationLimits { max: 8, idle },
        None,
    ))
}

/// Records relayed requests and answers them with `answer`.
struct Gate {
    answer: bool,
    requests: StdMutex<Vec<ApprovalRequest>>,
}

#[async_trait]
impl ApprovalGate for Gate {
    async fn approve(
        &self,
        request: ApprovalRequest,
        _cancellation: CancellationToken,
    ) -> Result<bool, AgentError> {
        self.requests.lock().unwrap().push(request);
        Ok(self.answer)
    }
}

fn context(workspace: &Path, gate: Option<Arc<Gate>>) -> ToolContext {
    let mut context = ToolContext::new(workspace.canonicalize().unwrap(), CancellationToken::new());
    if let Some(gate) = gate {
        context.approvals = ToolApprovals::new(gate, "call-1");
    }
    context.progress = scv_core::ProgressSink::buffered();
    context
}

fn pid(dir: &Path, mode: &str) -> u32 {
    std::fs::read_to_string(dir.join(format!("{mode}.pid")))
        .unwrap()
        .trim()
        .parse()
        .unwrap()
}

fn alive(pid: u32) -> bool {
    ProcessIdentity::of(pid).is_some_and(|identity| identity.is_alive())
}

async fn wait_gone(pid: u32) {
    for _ in 0..100 {
        if !alive(pid) {
            return;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    panic!("nested SCV {pid} is still running");
}

fn json(output: &ToolOutput) -> Value {
    serde_json::from_str(&output.content).unwrap()
}

#[tokio::test]
async fn conversations_continue_on_one_child_with_progress_and_records() {
    let dir = tempfile::tempdir().unwrap();
    let home = tempfile::tempdir().unwrap();
    let script = fake_scv(dir.path(), "echo");
    let registry = Arc::new(DelegationRegistry::new(&scv_client::Layout::new(
        home.path(),
    )));
    let delegation = DelegationContext {
        registry: Arc::clone(&registry),
        session: "parent-session".into(),
        depth: 0,
    };
    let conversations = store(Duration::from_secs(3600));
    let tool = tool(&script, Arc::clone(&conversations), Some(delegation));
    let context = context(dir.path(), None);

    let first = tool
        .execute(json!({"prompt":"one"}), context.clone())
        .await
        .unwrap();
    let first = json(&first);
    assert_eq!(first["agent"], "scv");
    assert_eq!(first["status"], "completed");
    assert_eq!(first["reply"], "reply 1");
    assert_eq!(first["session"], "scv-1");
    assert_eq!(first["turn"], 1);
    assert_eq!(first["usage"]["output_tokens"], 4);
    let child = pid(dir.path(), "echo");
    assert!(alive(child), "the nested SCV stays up between turns");
    // The child runs one level deeper and is recorded as a delegation.
    assert_eq!(
        std::fs::read_to_string(dir.path().join("echo.depth"))
            .unwrap()
            .trim(),
        "1"
    );
    let entries = registry.list(false);
    assert_eq!(entries.len(), 1);
    assert_eq!(entries[0].record.agent, "scv");
    assert_eq!(entries[0].record.conversation.as_deref(), Some("scv-1"));
    let progress = context.progress.take().unwrap_or_default();
    assert!(progress.contains("thinking"), "{progress}");
    assert!(progress.contains("bash done"), "{progress}");
    assert!(!progress.contains("stale event"), "{progress}");
    assert!(!progress.contains("PRIVATE"), "{progress}");

    let second = tool
        .execute(json!({"prompt":"two","session":"scv-1"}), context.clone())
        .await
        .unwrap();
    let second = json(&second);
    assert_eq!(second["reply"], "reply 2", "the same child served turn two");
    assert_eq!(second["turn"], 2);
    assert_eq!(pid(dir.path(), "echo"), child);
    assert_eq!(registry.list(false)[0].record.turn, Some(2));

    // Ending the session's conversations shuts the child down.
    drop(tool);
    drop(conversations);
    wait_gone(child).await;
    for _ in 0..100 {
        if registry.list(true).is_empty() {
            break;
        }
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    assert!(
        registry.list(true).is_empty(),
        "the record outlived the child"
    );
}

#[tokio::test]
async fn nested_approvals_are_relayed_to_the_session_gate() {
    for answer in [true, false] {
        let dir = tempfile::tempdir().unwrap();
        let script = fake_scv(dir.path(), "approve");
        let gate = Arc::new(Gate {
            answer,
            requests: StdMutex::new(Vec::new()),
        });
        let tool = tool(&script, store(Duration::from_secs(3600)), None);
        let output = tool
            .execute(
                json!({"prompt":"clean up"}),
                context(dir.path(), Some(Arc::clone(&gate))),
            )
            .await
            .unwrap();
        let requests = gate.requests.lock().unwrap();
        assert_eq!(requests.len(), 1);
        assert_eq!(requests[0].call_id, "call-1");
        assert_eq!(requests[0].name, "bash");
        assert_eq!(requests[0].risk, ToolRisk::Process);
        assert_eq!(requests[0].summary, "[scv-1 depth 1] Run rm -rf build");
        assert_eq!(
            json(&output)["reply"],
            if answer { "approved" } else { "denied" }
        );
    }
}

#[tokio::test]
async fn without_a_gate_nested_approvals_are_denied() {
    let dir = tempfile::tempdir().unwrap();
    let script = fake_scv(dir.path(), "approve");
    let tool = tool(&script, store(Duration::from_secs(3600)), None);
    let output = tool
        .execute(json!({"prompt":"clean up"}), context(dir.path(), None))
        .await
        .unwrap();
    assert_eq!(json(&output)["reply"], "denied");
}

#[tokio::test]
async fn a_child_ignoring_turn_cancel_is_killed_at_the_timeout() {
    let dir = tempfile::tempdir().unwrap();
    let script = fake_scv(dir.path(), "hang");
    let conversations = store(Duration::from_secs(3600));
    let tool = tool(&script, Arc::clone(&conversations), None);
    // Start the child first, so the one-second timeout covers the prompt
    // alone, not bash start-up and the handshake.
    warm_up(&tool, dir.path()).await;
    let output = tool
        .execute(
            json!({"prompt":"slow","session":"scv-1","timeout_seconds":1}),
            context(dir.path(), None),
        )
        .await
        .unwrap();
    let value = json(&output);
    assert_eq!(value["status"], "timeout");
    assert!(output.is_error());
    assert!(value["reply"].as_str().unwrap().contains("shut down"));
    assert!(
        dir.path().join("hang.cancels").exists(),
        "turn.cancel was not sent"
    );
    wait_gone(pid(dir.path(), "hang")).await;
    assert!(
        conversations.handles().is_empty(),
        "a dead child's conversation stays"
    );
}

#[tokio::test]
async fn a_timed_out_turn_that_settles_stays_resumable() {
    let dir = tempfile::tempdir().unwrap();
    let script = fake_scv(dir.path(), "cancellable");
    let conversations = store(Duration::from_secs(3600));
    let tool = tool(&script, Arc::clone(&conversations), None);
    warm_up(&tool, dir.path()).await;
    let output = tool
        .execute(
            json!({"prompt":"slow","session":"scv-1","timeout_seconds":1}),
            context(dir.path(), None),
        )
        .await
        .unwrap();
    assert_eq!(json(&output)["status"], "timeout");
    assert_eq!(json(&output)["session"], "scv-1");
    assert!(alive(pid(dir.path(), "cancellable")));
    assert_eq!(conversations.handles(), ["scv-1"]);
}

#[tokio::test]
async fn cancelling_the_call_cancels_the_nested_turn() {
    let dir = tempfile::tempdir().unwrap();
    let script = fake_scv(dir.path(), "cancellable");
    let tool = tool(&script, store(Duration::from_secs(3600)), None);
    let context = context(dir.path(), None);
    let cancel = context.cancellation.clone();
    let turns = dir.path().join("cancellable.turns");
    tokio::spawn(async move {
        // Cancel once the nested turn is running, however slowly it started.
        for _ in 0..400 {
            if turns.exists() {
                break;
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
        cancel.cancel();
    });
    let error = tool
        .execute(json!({"prompt":"slow"}), context)
        .await
        .unwrap_err();
    assert!(error.message.contains("cancelled"), "{error}");
    assert!(dir.path().join("cancellable.cancels").exists());
}

#[tokio::test]
async fn a_child_dying_mid_turn_fails_the_call_and_ends_the_conversation() {
    let dir = tempfile::tempdir().unwrap();
    let script = fake_scv(dir.path(), "die");
    let conversations = store(Duration::from_secs(3600));
    let tool = tool(&script, Arc::clone(&conversations), None);
    let output = tool
        .execute(json!({"prompt":"work"}), context(dir.path(), None))
        .await
        .unwrap();
    let value = json(&output);
    assert_eq!(value["status"], "failed");
    assert!(
        value["reply"].as_str().unwrap().contains("exited"),
        "{value}"
    );
    assert!(
        value["stderr_tail"].as_str().unwrap().contains("boom"),
        "{value}"
    );
    assert!(conversations.handles().is_empty());
    let error = tool
        .execute(
            json!({"prompt":"again","session":"scv-1"}),
            context(dir.path(), None),
        )
        .await
        .unwrap_err();
    assert!(error.message.contains("unknown"), "{error}");
}

#[tokio::test]
async fn idle_conversations_shut_their_child_down() {
    let dir = tempfile::tempdir().unwrap();
    let script = fake_scv(dir.path(), "echo");
    let conversations = store(Duration::from_millis(300));
    let tool = tool(&script, Arc::clone(&conversations), None);
    tool.execute(json!({"prompt":"one"}), context(dir.path(), None))
        .await
        .unwrap();
    let first = pid(dir.path(), "echo");
    tokio::time::sleep(Duration::from_millis(400)).await;
    // The next call forgets the idle conversation, which ends its child.
    tool.execute(json!({"prompt":"two"}), context(dir.path(), None))
        .await
        .unwrap();
    assert_ne!(pid(dir.path(), "echo"), first);
    wait_gone(first).await;
}

#[test]
fn arguments_are_checked_before_approval() {
    let dir = tempfile::tempdir().unwrap();
    let tool = tool(&dir.path().join("scv"), store(Duration::from_secs(1)), None);
    for (arguments, message) in [
        (json!({"prompt":"x","effort":"high"}), "effort"),
        (
            json!({"prompt":"x","session":"scv-1","model":"m"}),
            "new conversation",
        ),
        (
            json!({"prompt":"x","session":"0199a213-81c0"}),
            "not a conversation handle",
        ),
        (json!({"prompt":"x","timeout_seconds":999999}), "exceeds"),
    ] {
        let error = tool.risk(&arguments).unwrap_err();
        assert!(error.message.contains(message), "{arguments}: {error}");
    }
    let summary = tool
        .approval_summary(&json!({"prompt":"do it","cwd":"scv"}))
        .unwrap();
    assert!(summary.contains("new nested SCV"), "{summary}");
    assert!(summary.contains("come back here for approval"), "{summary}");
    let summary = tool
        .approval_summary(&json!({"prompt":"more","session":"scv-2"}))
        .unwrap();
    assert!(summary.contains("conversation scv-2"), "{summary}");
}

#[test]
fn the_registry_offers_agent_scv_only_below_the_depth_limit() {
    let dir = tempfile::tempdir().unwrap();
    let script = fake_scv(dir.path(), "echo");
    let adapter = crate::AgentAdapterConfig {
        command: script.display().to_string(),
        args: Vec::new(),
        prompt_args: Vec::new(),
        full_permission_args: None,
        model_args: Vec::new(),
        effort_args: Vec::new(),
        model_hint: String::new(),
        environment: Vec::new(),
        search_dirs: Vec::new(),
        output: crate::delegate::adapters::OutputFormat::Text,
        resume: crate::delegate::adapters::Resume::Unsupported,
        home: None,
        transport: crate::delegate::adapters::Transport::ScvProtocol,
        acp: None,
        use_for: None,
        model: None,
        effort: None,
    };
    let home = tempfile::tempdir().unwrap();
    for (depth, offered) in [(0, true), (1, true), (2, false)] {
        let config = crate::ToolsConfig {
            delegation: Some(DelegationContext {
                registry: Arc::new(DelegationRegistry::new(&scv_client::Layout::new(
                    home.path(),
                ))),
                session: "s".into(),
                depth,
            }),
            ..crate::ToolsConfig::default()
        };
        let registry = crate::builtin_registry(
            config,
            crate::SkillMap::new(),
            Vec::new(),
            1024,
            std::collections::HashMap::from([("agent_scv".to_owned(), adapter.clone())]),
        )
        .unwrap();
        assert_eq!(
            registry.get("agent_scv").is_some(),
            offered,
            "depth {depth}"
        );
        if let Some(tool) = registry.get("agent_scv") {
            let spec = tool.spec();
            assert!(spec.parameters["properties"]["session"].is_object());
            assert!(spec.parameters["properties"].get("effort").is_none());
        }
    }
}