supercode-core 0.1.0

A lightweight, fully-customizable AI coding agent SDK in Rust. Talks to any model via OpenRouter or any OpenAI-compatible endpoint.
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
//! Tests for built-in tools (P5 capability parity).

use supercode::tools::{
    ApplyPatchTool, PersistentShellTool, SandboxPolicy, Tool, ToolContext, WriteFileTool,
};

fn ctx() -> (ToolContext, std::path::PathBuf) {
    use std::sync::atomic::{AtomicU64, Ordering};
    static N: AtomicU64 = AtomicU64::new(0);
    let dir = std::env::temp_dir().join(format!(
        "sc-tools-{}-{}",
        std::process::id(),
        N.fetch_add(1, Ordering::SeqCst)
    ));
    std::fs::create_dir_all(&dir).unwrap();
    (ToolContext::new(dir.clone()), dir)
}

#[tokio::test]
async fn apply_patch_add_update_delete_move() {
    let (ctx, dir) = ctx();
    let tool = ApplyPatchTool;

    // Seed a file to update and one to delete.
    std::fs::write(dir.join("keep.rs"), "fn main() {\n    old();\n}\n").unwrap();
    std::fs::write(dir.join("gone.txt"), "bye").unwrap();

    let patch = "\
*** Begin Patch
*** Add File: src/new.rs
+pub fn added() -> u8 {
+    42
+}
*** Update File: keep.rs
@@
 fn main() {
-    old();
+    fresh();
 }
*** Delete File: gone.txt
*** End Patch
";

    let out = tool
        .execute(serde_json::json!({ "patch": patch }), &ctx)
        .await
        .unwrap();
    assert!(out.contains("A src/new.rs"), "{out}");
    assert!(out.contains("U keep.rs"), "{out}");
    assert!(out.contains("D gone.txt"), "{out}");

    // Add wrote the new file.
    let added = std::fs::read_to_string(dir.join("src/new.rs")).unwrap();
    assert!(added.contains("pub fn added") && added.contains("42"));
    // Update replaced the hunk, preserving context.
    let updated = std::fs::read_to_string(dir.join("keep.rs")).unwrap();
    assert!(updated.contains("fresh();") && !updated.contains("old();"));
    assert!(updated.contains("fn main()"));
    // Delete removed the file.
    assert!(!dir.join("gone.txt").exists());

    // A rename via Move to.
    let mv = "\
*** Begin Patch
*** Update File: keep.rs
*** Move to: renamed.rs
@@
-    fresh();
+    fresher();
*** End Patch
";
    let out = tool
        .execute(serde_json::json!({ "patch": mv }), &ctx)
        .await
        .unwrap();
    assert!(out.contains("M keep.rs -> renamed.rs"), "{out}");
    assert!(!dir.join("keep.rs").exists());
    assert!(std::fs::read_to_string(dir.join("renamed.rs"))
        .unwrap()
        .contains("fresher();"));

    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn apply_patch_reports_unmatched_hunk() {
    let (ctx, dir) = ctx();
    std::fs::write(dir.join("f.txt"), "hello world").unwrap();
    let tool = ApplyPatchTool;
    let patch = "\
*** Begin Patch
*** Update File: f.txt
@@
-not present
+replacement
*** End Patch
";
    let err = tool
        .execute(serde_json::json!({ "patch": patch }), &ctx)
        .await
        .unwrap_err()
        .to_string();
    assert!(err.contains("did not match"), "{err}");
    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn apply_patch_is_registered_as_a_builtin() {
    use supercode::ToolRegistry;
    let reg = ToolRegistry::with_builtins();
    assert!(
        reg.get("apply_patch").is_some(),
        "apply_patch must be a built-in tool"
    );
    assert!(
        reg.get("shell").is_some(),
        "persistent shell must be a built-in tool"
    );
}

#[tokio::test]
async fn persistent_shell_keeps_state_across_calls() {
    let (ctx, dir) = ctx();
    let sh = PersistentShellTool::default();

    // State set in one call is visible in the next (env var + cwd persist).
    let r = sh
        .execute(serde_json::json!({"command": "MYVAR=hello123"}), &ctx)
        .await
        .unwrap();
    assert!(r.contains("exit code: 0"), "{r}");

    let r = sh
        .execute(serde_json::json!({"command": "echo $MYVAR"}), &ctx)
        .await
        .unwrap();
    assert!(r.contains("hello123"), "env var did not persist: {r}");

    // cd persists across calls — the key difference from one-shot bash.
    std::fs::create_dir_all(dir.join("sub")).unwrap();
    sh.execute(serde_json::json!({"command": "cd sub"}), &ctx)
        .await
        .unwrap();
    let r = sh
        .execute(serde_json::json!({"command": "pwd"}), &ctx)
        .await
        .unwrap();
    assert!(r.contains("/sub"), "cwd did not persist: {r}");

    // Exit code is reported.
    let r = sh
        .execute(serde_json::json!({"command": "false"}), &ctx)
        .await
        .unwrap();
    assert!(r.contains("exit code: 1"), "{r}");

    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn sandbox_read_only_and_workspace_write() {
    let (mut ctx, dir) = ctx();
    let w = WriteFileTool;

    // read-only: every write is denied.
    ctx.sandbox = SandboxPolicy::ReadOnly;
    let err = w
        .execute(serde_json::json!({"path": "a.txt", "content": "x"}), &ctx)
        .await
        .unwrap_err()
        .to_string();
    assert!(err.contains("read-only"), "{err}");
    assert!(!dir.join("a.txt").exists());

    // workspace-write: inside the workspace is allowed…
    ctx.sandbox = SandboxPolicy::WorkspaceWrite;
    w.execute(
        serde_json::json!({"path": "inside.txt", "content": "ok"}),
        &ctx,
    )
    .await
    .unwrap();
    assert_eq!(
        std::fs::read_to_string(dir.join("inside.txt")).unwrap(),
        "ok"
    );

    // …but writing outside the workspace (absolute escape or `..`) is denied.
    let outside = std::env::temp_dir().join(format!("sc-escape-{}.txt", std::process::id()));
    let err = w
        .execute(
            serde_json::json!({"path": outside.to_string_lossy(), "content": "no"}),
            &ctx,
        )
        .await
        .unwrap_err()
        .to_string();
    assert!(err.contains("outside the workspace"), "{err}");
    assert!(!outside.exists());

    let err = w
        .execute(
            serde_json::json!({"path": "../escape.txt", "content": "no"}),
            &ctx,
        )
        .await
        .unwrap_err()
        .to_string();
    assert!(err.contains("outside the workspace"), "{err}");

    // danger-full-access (default): writing outside is allowed.
    ctx.sandbox = SandboxPolicy::DangerFullAccess;
    w.execute(
        serde_json::json!({"path": outside.to_string_lossy(), "content": "yes"}),
        &ctx,
    )
    .await
    .unwrap();
    assert!(outside.exists());
    std::fs::remove_file(&outside).ok();

    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn sandbox_blocks_apply_patch_writes() {
    let (mut ctx, dir) = ctx();
    ctx.sandbox = SandboxPolicy::ReadOnly;
    let tool = ApplyPatchTool;
    let patch = "*** Begin Patch\n*** Add File: blocked.rs\n+x\n*** End Patch\n";
    let err = tool
        .execute(serde_json::json!({"patch": patch}), &ctx)
        .await
        .unwrap_err()
        .to_string();
    assert!(err.contains("read-only"), "{err}");
    assert!(!dir.join("blocked.rs").exists());
    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn persistent_shell_write_stdin() {
    let (ctx, dir) = ctx();
    let sh = PersistentShellTool::default();
    // The shell reads commands from its stdin, so raw stdin input is executed.
    let out = sh
        .execute(
            serde_json::json!({"write_stdin": "echo from_stdin_pipe\n"}),
            &ctx,
        )
        .await
        .unwrap();
    assert!(out.contains("from_stdin_pipe"), "write_stdin output: {out}");
    std::fs::remove_dir_all(&dir).ok();
}

#[tokio::test]
async fn update_plan_tool() {
    use supercode::tools::UpdatePlanTool;
    let (ctx, dir) = ctx();
    let tool = UpdatePlanTool::default();
    let out = tool
        .execute(
            serde_json::json!({"plan": [
                {"step": "read code", "status": "completed"},
                {"step": "fix bug", "status": "in_progress"},
                {"step": "add test"}
            ]}),
            &ctx,
        )
        .await
        .unwrap();
    assert!(out.contains("[x] read code"));
    assert!(out.contains("[~] fix bug"));
    assert!(out.contains("[ ] add test"));
    assert_eq!(tool.current().len(), 3);
    std::fs::remove_dir_all(&dir).ok();
}

#[cfg(target_os = "macos")]
#[tokio::test]
async fn bash_os_sandbox_blocks_writes() {
    use supercode::tools::BashTool;
    let (mut ctx, dir) = ctx();
    let tool = BashTool::default();

    // read-only: a subprocess write is blocked by the OS sandbox.
    ctx.sandbox = SandboxPolicy::ReadOnly;
    let out = tool
        .execute(
            serde_json::json!({"command": "echo hi > blocked.txt; echo done"}),
            &ctx,
        )
        .await
        .unwrap();
    assert!(
        !dir.join("blocked.txt").exists(),
        "read-only sandbox must block the write: {out}"
    );

    // workspace-write: writing inside the workspace succeeds…
    ctx.sandbox = SandboxPolicy::WorkspaceWrite;
    tool.execute(serde_json::json!({"command": "echo hi > inside.txt"}), &ctx)
        .await
        .unwrap();
    assert!(
        dir.join("inside.txt").exists(),
        "workspace-write must allow writes inside cwd"
    );

    // …but writing outside the workspace is blocked.
    let outside = std::env::temp_dir().join(format!("sc-bash-escape-{}.txt", std::process::id()));
    let _ = std::fs::remove_file(&outside);
    let cmd = format!("echo hi > {}", outside.display());
    tool.execute(serde_json::json!({"command": cmd}), &ctx)
        .await
        .unwrap();
    assert!(
        !outside.exists(),
        "workspace-write must block writes outside cwd"
    );

    // full access (default): unsandboxed, the write goes through.
    ctx.sandbox = SandboxPolicy::DangerFullAccess;
    tool.execute(serde_json::json!({"command": "echo hi > free.txt"}), &ctx)
        .await
        .unwrap();
    assert!(dir.join("free.txt").exists());

    std::fs::remove_dir_all(&dir).ok();
}

// The persistent `shell` tool must honor the same OS sandbox as `bash`, or it
// becomes an unsandboxed escape hatch around the policy.
#[cfg(target_os = "macos")]
#[tokio::test]
async fn persistent_shell_os_sandbox_blocks_writes() {
    let (mut ctx, dir) = ctx();
    ctx.sandbox = SandboxPolicy::ReadOnly;
    let sh = PersistentShellTool::default();
    let out = sh
        .execute(
            serde_json::json!({"command": "echo hi > shell_blocked.txt; echo done"}),
            &ctx,
        )
        .await
        .unwrap();
    assert!(
        !dir.join("shell_blocked.txt").exists(),
        "read-only sandbox must block the persistent shell's write: {out}"
    );
    std::fs::remove_dir_all(&dir).ok();
}

// The `@@` header anchors a hunk: it disambiguates which of several identical
// blocks to edit, and gives a pure insertion a real location.
#[tokio::test]
async fn apply_patch_at_at_anchor_disambiguates_and_locates_insertions() {
    let (ctx, dir) = ctx();
    let tool = ApplyPatchTool;
    std::fs::write(
        dir.join("a.py"),
        "def foo():\n    return 1\n\ndef bar():\n    return 1\n",
    )
    .unwrap();

    // Anchor on `bar` so the *second* `return 1` is the one changed.
    let patch = "\
*** Begin Patch
*** Update File: a.py
@@ def bar():
-    return 1
+    return 2
*** End Patch
";
    tool.execute(serde_json::json!({ "patch": patch }), &ctx)
        .await
        .unwrap();
    let after = std::fs::read_to_string(dir.join("a.py")).unwrap();
    assert_eq!(
        after, "def foo():\n    return 1\n\ndef bar():\n    return 2\n",
        "anchor must target bar, leaving foo untouched: {after:?}"
    );

    // Anchored pure insertion lands right after the anchor line, not at EOF.
    let ins = "\
*** Begin Patch
*** Update File: a.py
@@ def foo():
+    # hello
*** End Patch
";
    tool.execute(serde_json::json!({ "patch": ins }), &ctx)
        .await
        .unwrap();
    let after = std::fs::read_to_string(dir.join("a.py")).unwrap();
    assert!(
        after.starts_with("def foo():\n    # hello\n    return 1\n"),
        "insertion must follow the anchor line, not append at EOF: {after:?}"
    );

    // A missing anchor is a hard error, not a silent misapply.
    let bad = "\
*** Begin Patch
*** Update File: a.py
@@ def nope():
-    return 1
+    return 9
*** End Patch
";
    assert!(tool
        .execute(serde_json::json!({ "patch": bad }), &ctx)
        .await
        .is_err());

    std::fs::remove_dir_all(&dir).ok();
}