opencode_rs 0.4.0

Rust SDK for OpenCode (HTTP-first hybrid with SSE streaming)
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
//! Integration tests for `opencode_rs`.
//!
//! These tests run against a real `OpenCode` server and are gated by environment variables.
//!
//! To run:
//!   `OPENCODE_INTEGRATION=1` cargo test --test integration -- --ignored
//!
//! Optional environment variables:
//!   `OPENCODE_BASE_URL` - Base URL of the `OpenCode` server (default: <http://127.0.0.1:4096>)
//!   `OPENCODE_DIRECTORY` - Directory context for requests (default: current directory)

// Integration tests are allowed to use unwrap/expect for test assertions
#![allow(clippy::unwrap_used, clippy::expect_used)]

// Include submodule tests from integration/ directory
#[path = "integration/mod.rs"]
mod typed_tests;

use opencode_rs::ClientBuilder;
use opencode_rs::types::event::Event;
use opencode_rs::types::message::PromptPart;
use opencode_rs::types::message::PromptRequest;
use opencode_rs::types::session::CreateSessionRequest;
use std::time::Duration;

/// Check if integration tests should run.
fn should_run() -> bool {
    std::env::var("OPENCODE_INTEGRATION").is_ok()
}

/// Get the base URL for the `OpenCode` server.
fn base_url() -> String {
    std::env::var("OPENCODE_BASE_URL").unwrap_or_else(|_| "http://127.0.0.1:4096".to_string())
}

/// Get the directory context.
fn directory() -> String {
    std::env::var("OPENCODE_DIRECTORY").unwrap_or_else(|_| {
        std::env::current_dir()
            .map_or_else(|_| "/tmp".to_string(), |p| p.to_string_lossy().to_string())
    })
}

/// Build a client for integration tests.
fn build_client() -> opencode_rs::Client {
    ClientBuilder::new()
        .base_url(base_url())
        .directory(directory())
        .timeout_secs(300)
        .build()
        .unwrap()
}

/// Test server health endpoint.
#[tokio::test]
#[ignore = "requires: opencode serve"]
async fn test_server_health() {
    if !should_run() {
        return;
    }

    let client = build_client();
    let health = client.misc().health().await.expect("Failed to get health");
    assert!(health.healthy, "Server should be healthy");
}

/// Test full session lifecycle: create -> list -> get -> delete.
#[tokio::test]
#[ignore = "requires: opencode serve"]
async fn test_session_lifecycle() {
    if !should_run() {
        return;
    }

    let client = build_client();

    // Create session
    let session = client
        .sessions()
        .create(&CreateSessionRequest {
            title: Some("Integration Test Session".into()),
            ..Default::default()
        })
        .await
        .expect("Failed to create session");
    assert!(!session.id.is_empty());

    // Get session to verify it exists
    let fetched = client
        .sessions()
        .get(&session.id)
        .await
        .expect("Failed to get session");
    assert_eq!(fetched.id, session.id);

    // List sessions (our session should be there, but don't fail if not)
    match client.sessions().list().await {
        Ok(sessions) => {
            println!("Found {} sessions", sessions.len());
        }
        Err(e) => {
            println!("List sessions failed: {e:?}");
        }
    }

    // Cleanup - delete session
    client
        .sessions()
        .delete(&session.id)
        .await
        .expect("Failed to delete session");
}

/// Test session with prompt and SSE streaming.
#[tokio::test]
#[ignore = "requires: opencode serve"]
async fn test_session_prompt_and_stream() {
    if !should_run() {
        return;
    }

    let client = build_client();

    // Create session
    let session = client
        .sessions()
        .create(&CreateSessionRequest::default())
        .await
        .expect("Failed to create session");

    // Subscribe to events BEFORE sending prompt
    let mut subscription = client
        .subscribe_session(&session.id)
        .expect("Failed to subscribe");

    // Send a simple prompt
    let prompt_result = client
        .messages()
        .prompt(
            &session.id,
            &PromptRequest {
                parts: vec![PromptPart::Text {
                    text: "Say 'hello' and nothing else.".into(),
                    synthetic: None,
                    ignored: None,
                    metadata: None,
                }],
                message_id: None,
                model: None,
                agent: None,
                no_reply: None,
                system: None,
                variant: None,
            },
        )
        .await;

    if prompt_result.is_err() {
        // Prompt may fail if no provider is configured
        println!("Prompt failed (no provider?): {:?}", prompt_result.err());
        subscription.close();
        let _ = client.sessions().delete(&session.id).await;
        return;
    }

    // Wait for events with timeout (shorter timeout for CI)
    let timeout = Duration::from_secs(30);
    let start = std::time::Instant::now();
    let mut got_any_event = false;

    while start.elapsed() < timeout {
        tokio::select! {
            event = subscription.recv() => {
                match event {
                    Some(Event::SessionIdle { .. } | Event::SessionError { .. }) => {
                        got_any_event = true;
                        break;
                    }
                    Some(_) => {
                        // Any other event (MessagePartUpdated, ServerHeartbeat, etc.)
                        got_any_event = true;
                    }
                    None => break,
                }
            }
            () = tokio::time::sleep(Duration::from_millis(100)) => {}
        }
    }

    // Just verify we connected and received some events
    // The actual content depends on provider configuration
    println!(
        "Streaming test: got_any_event={}, elapsed={:?}",
        got_any_event,
        start.elapsed()
    );

    // Cleanup
    subscription.close();
    client
        .sessions()
        .delete(&session.id)
        .await
        .expect("Failed to delete session");
}

/// Test session abort.
#[tokio::test]
#[ignore = "requires: opencode serve"]
async fn test_session_abort() {
    if !should_run() {
        return;
    }

    let client = build_client();

    // Create session
    let session = client
        .sessions()
        .create(&CreateSessionRequest::default())
        .await
        .expect("Failed to create session");

    // Abort should succeed even on idle session
    let result = client.sessions().abort(&session.id).await;
    // Abort may fail if session is already idle, that's OK
    if let Err(e) = &result {
        // Check it's not a 404
        assert!(!e.is_not_found(), "Session should exist");
    }

    // Cleanup
    client
        .sessions()
        .delete(&session.id)
        .await
        .expect("Failed to delete session");
}

/// Test permissions API.
#[tokio::test]
#[ignore = "requires: opencode serve"]
async fn test_permissions_list() {
    if !should_run() {
        return;
    }

    let client = build_client();

    // List permissions (may be empty, that's fine)
    let permissions = client
        .permissions()
        .list()
        .await
        .expect("Failed to list permissions");

    // Just verify we got a list (could be empty, that's OK)
    let _ = permissions.len();
}

/// Test files API.
#[tokio::test]
#[ignore = "requires: opencode serve"]
async fn test_files_list() {
    if !should_run() {
        return;
    }

    let client = build_client();

    // List files in project
    // Note: This endpoint may require specific project context or return 400
    // if not properly configured
    match client.files().list().await {
        Ok(files) => {
            // Should have some files in a project directory
            let _ = files.len();
        }
        Err(e) => {
            // Some OpenCode configurations may not support this endpoint
            println!("Files list not available: {e:?}");
        }
    }
}

/// Test file status.
#[tokio::test]
#[ignore = "requires: opencode serve"]
async fn test_files_status() {
    if !should_run() {
        return;
    }

    let client = build_client();

    // Get file status (VCS status)
    let status = client
        .files()
        .status()
        .await
        .expect("Failed to get file status");

    // Just verify we got a response
    let _ = status.len();
}

/// Test project API.
#[tokio::test]
#[ignore = "requires: opencode serve"]
async fn test_project_list() {
    if !should_run() {
        return;
    }

    let client = build_client();

    // List projects
    let projects = client
        .project()
        .list()
        .await
        .expect("Failed to list projects");

    // Should have at least one project
    assert!(!projects.is_empty(), "Should have at least one project");
}

/// Test current project.
#[tokio::test]
#[ignore = "requires: opencode serve"]
async fn test_project_current() {
    if !should_run() {
        return;
    }

    let client = build_client();

    // Get current project
    let project = client
        .project()
        .current()
        .await
        .expect("Failed to get current project");

    assert!(!project.id.is_empty(), "Project should have an ID");
}

/// Test providers API.
#[tokio::test]
#[ignore = "requires: opencode serve"]
async fn test_providers_list() {
    if !should_run() {
        return;
    }

    let client = build_client();

    // List providers - returns ProviderListResponse with all/default/connected
    let response = client
        .providers()
        .list()
        .await
        .expect("Failed to list providers");

    // Should have some providers in the 'all' field
    // Note: List may be empty if no providers are configured
    for provider in &response.all {
        assert!(!provider.id.is_empty(), "Provider should have an ID");
        assert!(!provider.name.is_empty(), "Provider should have a name");
    }

    // The response also includes default models and connected providers
    println!(
        "Found {} providers, {} defaults, {} connected",
        response.all.len(),
        response.default.len(),
        response.connected.len()
    );
}

/// Test MCP status.
#[tokio::test]
#[ignore = "requires: opencode serve"]
async fn test_mcp_status() {
    if !should_run() {
        return;
    }

    let client = build_client();

    // Get MCP status
    let status = client
        .mcp()
        .status()
        .await
        .expect("Failed to get MCP status");

    // Just verify we got a response
    let _ = status.servers.len();
}

/// Test config API.
#[tokio::test]
#[ignore = "requires: opencode serve"]
async fn test_config_get() {
    if !should_run() {
        return;
    }

    let client = build_client();

    // Get config
    let config = client.config().get().await.expect("Failed to get config");

    // Just verify we got a config response
    // The specific fields depend on OpenCode's config structure
    assert!(config.extra.is_object() || config.extra.is_null());
}

/// Test tools/agents API.
#[tokio::test]
#[ignore = "requires: opencode serve"]
async fn test_agents_list() {
    if !should_run() {
        return;
    }

    let client = build_client();

    // List agents
    let agents = client
        .tools()
        .agents()
        .await
        .expect("Failed to list agents");

    // Should have at least one agent
    assert!(!agents.is_empty(), "Should have at least one agent");
}

/// Test commands list.
#[tokio::test]
#[ignore = "requires: opencode serve"]
async fn test_commands_list() {
    if !should_run() {
        return;
    }

    let client = build_client();

    // List commands
    let commands = client
        .tools()
        .commands()
        .await
        .expect("Failed to list commands");

    // May or may not have commands
    let _ = commands.len();
}

/// Test VCS info.
#[tokio::test]
#[ignore = "requires: opencode serve"]
async fn test_vcs_info() {
    if !should_run() {
        return;
    }

    let client = build_client();

    // Get VCS info - the .expect() validates we got a successful response
    let vcs = client.misc().vcs().await.expect("Failed to get VCS info");

    // Log the VCS type for debugging (type is optional as this could be non-git)
    println!("VCS type: {:?}", vcs.r#type);
}

/// Test path info.
#[tokio::test]
#[ignore = "requires: opencode serve"]
async fn test_path_info() {
    if !should_run() {
        return;
    }

    let client = build_client();

    // Get path info
    let path = client.misc().path().await.expect("Failed to get path info");

    assert!(!path.directory.is_empty(), "Directory should not be empty");
}

/// Test `OpenAPI` doc endpoint.
#[tokio::test]
#[ignore = "requires: opencode serve"]
async fn test_openapi_doc() {
    if !should_run() {
        return;
    }

    let client = build_client();

    // Get OpenAPI doc
    let doc = client
        .misc()
        .doc()
        .await
        .expect("Failed to get OpenAPI doc");

    // Should be a valid OpenAPI document
    assert!(doc.spec.is_object(), "Doc should be a JSON object");
    assert!(
        doc.spec.get("openapi").is_some() || doc.spec.get("swagger").is_some(),
        "Should be an OpenAPI/Swagger document"
    );
}

/// Test session fork.
#[tokio::test]
#[ignore = "requires: opencode serve"]
async fn test_session_fork() {
    if !should_run() {
        return;
    }

    let client = build_client();

    // Create parent session
    let parent = client
        .sessions()
        .create(&CreateSessionRequest {
            title: Some("Parent Session".into()),
            ..Default::default()
        })
        .await
        .expect("Failed to create parent session");

    // Fork session
    let forked = client
        .sessions()
        .fork(&parent.id)
        .await
        .expect("Failed to fork session");

    assert_ne!(forked.id, parent.id, "Forked session should have new ID");
    // Note: parent_id field may not be set in all OpenCode versions

    // Cleanup
    client
        .sessions()
        .delete(&forked.id)
        .await
        .expect("Failed to delete forked session");
    client
        .sessions()
        .delete(&parent.id)
        .await
        .expect("Failed to delete parent session");
}

/// Test session children.
#[tokio::test]
#[ignore = "requires: opencode serve"]
async fn test_session_children() {
    if !should_run() {
        return;
    }

    let client = build_client();

    // Create parent session
    let parent = client
        .sessions()
        .create(&CreateSessionRequest {
            title: Some("Parent Session".into()),
            ..Default::default()
        })
        .await
        .expect("Failed to create parent session");

    // Fork to create a child
    let child = client
        .sessions()
        .fork(&parent.id)
        .await
        .expect("Failed to fork session");

    // Get children - this may or may not include the forked session
    // depending on OpenCode version and how forking is tracked
    let children = client
        .sessions()
        .children(&parent.id)
        .await
        .expect("Failed to get children");

    // Just verify we got a response (children list may be empty in some versions)
    let _ = children.len();

    // Cleanup
    client
        .sessions()
        .delete(&child.id)
        .await
        .expect("Failed to delete child session");
    client
        .sessions()
        .delete(&parent.id)
        .await
        .expect("Failed to delete parent session");
}

/// Test session diff.
#[tokio::test]
#[ignore = "requires: opencode serve"]
async fn test_session_diff() {
    if !should_run() {
        return;
    }

    let client = build_client();

    // Create session
    let session = client
        .sessions()
        .create(&CreateSessionRequest::default())
        .await
        .expect("Failed to create session");

    // Get diff (may be empty for new session)
    // Note: Response format may vary - could be object or array
    match client.sessions().diff(&session.id).await {
        Ok(diff) => {
            // Just verify we got a response
            let _ = diff.files.len();
        }
        Err(e) => {
            // Some versions return different format
            println!("Diff returned unexpected format: {e:?}");
        }
    }

    // Cleanup
    client
        .sessions()
        .delete(&session.id)
        .await
        .expect("Failed to delete session");
}

/// Test session todos.
#[tokio::test]
#[ignore = "requires: opencode serve"]
async fn test_session_todos() {
    if !should_run() {
        return;
    }

    let client = build_client();

    // Create session
    let session = client
        .sessions()
        .create(&CreateSessionRequest::default())
        .await
        .expect("Failed to create session");

    // Get todos (may be empty)
    let todos = client
        .sessions()
        .todo(&session.id)
        .await
        .expect("Failed to get todos");

    // Just verify we got a list
    let _ = todos.len();

    // Cleanup
    client
        .sessions()
        .delete(&session.id)
        .await
        .expect("Failed to delete session");
}

/// Test global event subscription.
#[tokio::test]
#[ignore = "requires: opencode serve"]
async fn test_global_events() {
    if !should_run() {
        return;
    }

    let client = build_client();

    // Subscribe to global events
    let mut subscription = client
        .subscribe_global()
        .expect("Failed to subscribe to global events");

    // Wait briefly for any events (heartbeat, etc.)
    let timeout = Duration::from_secs(5);
    let start = std::time::Instant::now();
    let mut got_event = false;

    while start.elapsed() < timeout {
        tokio::select! {
            event = subscription.recv() => {
                match event {
                    Some(_) => {
                        got_event = true;
                        break;
                    }
                    None => break,
                }
            }
            () = tokio::time::sleep(Duration::from_millis(100)) => {}
        }
    }

    // May or may not get an event depending on server activity
    // Just verify we could subscribe
    subscription.close();

    // This is informational - we successfully subscribed
    if got_event {
        println!("Received global event");
    } else {
        println!("No global events received within timeout (this is OK)");
    }
}