acorn-lib 0.1.70

ACORN library
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
//! OpenCode synchronization configuration types
//!
//! When syncing ACORN models to OpenCode, the sync command creates or updates
//! a custom provider entry that points to the local llama-swap instance.
//! Each model is registered as a keyed entry in the provider's model map.
use super::{Options, RenderedOutput, SyncTarget};
use crate::io::{home_directory, read_file, ApiResult, CstValue, PathConversion};
use crate::prelude::{current_dir, Path, PathBuf};
use crate::schema::agent::opencode;
use crate::util::constants::app::DEFAULT_OPENCODE_CONFIG_PATH;
use alloc::collections::{BTreeMap, BTreeSet};
use alloc::string::String;
use alloc::string::ToString;
use color_eyre::eyre::eyre;
use core::{fmt, iter::once};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use serde_with::skip_serializing_none;
use validator::Validate;

#[derive(Clone, Debug, Serialize)]
#[serde(untagged)]
enum Entry {
    Provider {
        npm: String,
        name: String,
        options: BTreeMap<String, String>,
    },
    Model {
        name: String,
    },
}
/// Configuration for synchronizing models into OpenCode
#[skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Serialize, Validate)]
#[serde(rename_all = "camelCase")]
pub struct Config {
    /// Path to the OpenCode configuration file on disk
    #[serde(skip_serializing)]
    #[validate(length(min = 1))]
    pub path: Option<String>,
    /// Base URL for the OpenAI-compatible endpoint (e.g., `http://localhost:8080/v1`)
    #[serde(default = "default_base_url")]
    #[validate(length(min = 1))]
    pub base_url: String,
    /// Provider identifier in the OpenCode configuration
    #[serde(default = "default_provider_id")]
    #[validate(length(min = 1))]
    pub provider_id: String,
    /// Human-readable provider display name
    #[serde(default = "default_provider_name")]
    #[validate(length(min = 1))]
    pub provider_name: String,
    /// Default model to use when none is specified
    #[validate(length(min = 1))]
    pub default_model: Option<String>,
}
impl Default for Config {
    fn default() -> Self {
        Self {
            path: None,
            base_url: default_base_url(),
            provider_id: default_provider_id(),
            provider_name: default_provider_name(),
            default_model: None,
        }
    }
}
impl fmt::Display for Config {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.provider_id.fmt(formatter)
    }
}
impl SyncTarget for Config {
    const COMMAND: &'static str = "opencode";
    fn merge(self, overrides: Self) -> Self {
        Self {
            path: overrides.path.or(self.path),
            base_url: overrides.base_url,
            provider_id: overrides.provider_id,
            provider_name: overrides.provider_name,
            default_model: overrides.default_model.or(self.default_model),
        }
    }
    fn merge_cli_overrides(self, overrides: Self) -> Self {
        Self {
            path: overrides.path.or(self.path),
            ..self
        }
    }
    fn resolve_path(explicit: Option<&str>) -> ApiResult<PathBuf> {
        match explicit {
            | Some(path) => Ok(PathBuf::from(Path::new(path).cross_platform_display())),
            | None => current_dir()
                .map_err(|why| eyre!("Failed to get ACORN calling directory — {why}"))
                .and_then(|directory| home_directory(DEFAULT_OPENCODE_CONFIG_PATH).map(|user_config| Self::discover_path(&directory, user_config))),
        }
    }
    fn render(&self, options: Options<'_>) -> ApiResult<RenderedOutput> {
        Self::resolve_path(self.path.as_deref()).and_then(|path| {
            let models = options
                .models
                .iter()
                .filter_map(|model| model.name.as_ref().or(model.id.as_ref()))
                .map(|name| (name.clone(), name.clone()))
                .collect::<Vec<_>>();
            path.is_file()
                .then(|| read_file(path.clone()))
                .transpose()
                .map(|content| content.unwrap_or_default())
                .and_then(|before| {
                    match path.is_file() {
                        | true => opencode::Config::from_path(&path),
                        | false => Ok(opencode::Config::default()),
                    }
                    .and_then(|existing| self.upsert(&existing, &models, options.prune))
                    .and_then(|opencode| Config::render(self, &opencode))
                    .map(|content| RenderedOutput {
                        target: "OpenCode",
                        path,
                        before,
                        content,
                    })
                })
        })
    }
}
impl Config {
    /// Build the JSON structure for a model entry.
    pub fn model_entry(&self, display_name: &str) -> Value {
        serde_json::to_value(Entry::Model {
            name: display_name.to_string(),
        })
        .unwrap_or(Value::Null)
    }
    /// Build the JSON structure for an OpenCode provider entry.
    pub fn provider_entry(&self) -> Value {
        serde_json::to_value(Entry::Provider {
            npm: "@ai-sdk/openai-compatible".to_string(),
            name: self.provider_name.clone(),
            options: once(("baseURL".to_string(), self.base_url.clone())).collect(),
        })
        .unwrap_or(Value::Null)
    }
    fn discover_path(calling_directory: &Path, user_config: PathBuf) -> PathBuf {
        [
            calling_directory.join("opencode.jsonc"),
            calling_directory.join("opencode.json"),
            user_config.clone(),
            user_config.with_extension("json"),
        ]
        .into_iter()
        .find(|path| path.is_file())
        .unwrap_or(user_config)
    }
    /// Render an updated OpenCode configuration while preserving JSONC comments outside the managed provider
    pub fn render(&self, config: &opencode::Config) -> ApiResult<String> {
        match &config.cst {
            | Some(cst) => config
                .provider
                .as_ref()
                .and_then(|providers| providers.get(&self.provider_id))
                .ok_or_else(|| eyre!("Managed OpenCode provider '{self}' is missing"))
                .map(|provider| {
                    let root = cst.object_value_or_set();
                    let providers = root.object_value_or_set("provider");
                    match providers.get(&self.provider_id) {
                        | Some(property) => property.set_value(CstValue(provider).into()),
                        | None => {
                            providers.append(&self.provider_id, CstValue(provider).into());
                        }
                    }
                    if let Some(model) = config.model.as_ref() {
                        match root.get("model") {
                            | Some(property) => property.set_value(model.clone().into()),
                            | None => {
                                root.append("model", model.clone().into());
                            }
                        }
                    }
                    cst.to_string()
                })
                .and_then(|content| {
                    opencode::Config::parse_jsonc(&content)
                        .map(|_| content)
                        .map_err(|why| eyre!("Generated OpenCode JSONC is invalid — {why}"))
                }),
            | None => serde_json::to_string_pretty(config)
                .map_err(|why| eyre!("Failed to serialize OpenCode config — {why}"))
                .and_then(|content| {
                    serde_json::from_str::<opencode::Config>(&content)
                        .map(|_| content)
                        .map_err(|why| eyre!("Generated OpenCode JSON is invalid — {why}"))
                }),
        }
    }
    /// Upsert the managed provider into an existing OpenCode `Config`
    ///
    /// Returns the modified config with the llama-swap provider and its models
    /// upserted, preserving all other existing configuration.
    pub fn upsert(&self, existing: &opencode::Config, model_ids: &[(String, String)], prune: bool) -> ApiResult<opencode::Config> {
        let current_ids = model_ids.iter().map(|(identifier, _)| identifier.as_str()).collect::<BTreeSet<_>>();
        let existing_provider = existing
            .provider
            .as_ref()
            .and_then(|providers| providers.get(&self.provider_id))
            .and_then(Value::as_object)
            .cloned()
            .unwrap_or_default();
        let existing_models = existing_provider.get("models").and_then(Value::as_object).cloned().unwrap_or_default();
        let models = existing_models
            .into_iter()
            .filter(|(identifier, _)| !prune || current_ids.contains(identifier.as_str()))
            .chain(model_ids.iter().map(|(identifier, name)| (identifier.clone(), self.model_entry(name))))
            .collect::<serde_json::Map<_, _>>();
        let options = existing_provider
            .get("options")
            .and_then(Value::as_object)
            .into_iter()
            .flat_map(|options| options.iter())
            .map(|(key, value)| (key.clone(), value.clone()))
            .chain(once(("baseURL".to_string(), Value::String(self.base_url.clone()))))
            .collect::<serde_json::Map<_, _>>();
        let provider = existing_provider
            .into_iter()
            .chain([
                ("npm".to_string(), Value::String("@ai-sdk/openai-compatible".to_string())),
                ("name".to_string(), Value::String(self.provider_name.clone())),
                ("options".to_string(), Value::Object(options)),
                ("models".to_string(), Value::Object(models)),
            ])
            .collect::<serde_json::Map<_, _>>();
        let providers = existing
            .provider
            .as_ref()
            .into_iter()
            .flat_map(|providers| providers.iter())
            .map(|(identifier, value)| (identifier.clone(), value.clone()))
            .chain(once((self.provider_id.clone(), Value::Object(provider))))
            .collect::<BTreeMap<_, _>>();
        let root_model = existing
            .model
            .as_ref()
            .and_then(|model| model.split_once('/'))
            .filter(|(provider, _)| *provider == self.provider_id);
        match (prune, root_model, self.default_model.as_ref()) {
            | (true, Some((_, model)), None) if !current_ids.contains(model) => Err(eyre!(
                "Root model '{self}/{model}' points to a removed entry without a configured defaultModel"
            )),
            | _ => Ok(opencode::Config {
                model: self
                    .default_model
                    .as_ref()
                    .map(|model| format!("{}/{model}", self.provider_id))
                    .or_else(|| existing.model.clone()),
                provider: Some(providers),
                ..existing.clone()
            }),
        }
    }
}
fn default_base_url() -> String {
    "http://localhost:8080/v1".to_string()
}
fn default_provider_id() -> String {
    "llama-swap".to_string()
}
fn default_provider_name() -> String {
    "Local (llama-swap)".to_string()
}
#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
    use super::*;
    use crate::prelude::{create_dir_all, remove_dir_all, write};
    use crate::test::utils::temp_dir;

    #[test]
    fn test_default_values() {
        let config = Config::default();
        assert_eq!(config.base_url, "http://localhost:8080/v1");
        assert_eq!(config.provider_id, "llama-swap");
        assert_eq!(config.provider_name, "Local (llama-swap)");
        assert_eq!(config.to_string(), "llama-swap");
    }
    #[test]
    fn test_resolve_path_uses_discovered_or_default_config() {
        let calling_directory = current_dir().unwrap();
        let user_config = home_directory(DEFAULT_OPENCODE_CONFIG_PATH).unwrap();
        let expected = [
            calling_directory.join("opencode.jsonc"),
            calling_directory.join("opencode.json"),
            user_config.clone(),
            user_config.with_extension("json"),
        ]
        .into_iter()
        .find(|path| path.is_file())
        .unwrap_or(user_config);
        assert_eq!(Config::resolve_path(None).unwrap(), expected);
    }
    #[test]
    fn test_resolve_path_prefers_explicit_path() {
        let explicit = PathBuf::from(Path::new("custom/opencode.json").cross_platform_display());
        assert_eq!(Config::resolve_path(Some("custom/opencode.json")).unwrap(), explicit);
    }
    #[test]
    fn test_discover_path_prefers_calling_directory_jsonc_then_json() {
        let dir = temp_dir("opencode-calling-directory");
        let user_config = dir.join("user").join("opencode.jsonc");
        create_dir_all(user_config.parent().unwrap()).unwrap();
        write(&user_config, "{}").unwrap();
        let project_json = dir.join("opencode.json");
        write(&project_json, "{}").unwrap();
        assert_eq!(Config::discover_path(&dir, user_config.clone()), project_json);
        let project_jsonc = dir.join("opencode.jsonc");
        write(&project_jsonc, "not valid jsonc").unwrap();
        assert_eq!(Config::discover_path(&dir, user_config), project_jsonc);
        let _ = remove_dir_all(dir);
    }
    #[test]
    fn test_model_json_structure() {
        let json = Config::default().model_entry("Qwen GGUF");
        assert_eq!(json.get("name").unwrap().as_str().unwrap(), "Qwen GGUF");
    }
    #[test]
    fn test_provider_json_structure() {
        let config = Config::default();
        let json = config.provider_entry();
        assert_eq!(json.get("npm").unwrap().as_str().unwrap(), "@ai-sdk/openai-compatible");
        assert_eq!(json.get("name").unwrap().as_str().unwrap(), "Local (llama-swap)");
        let options = json.get("options").unwrap();
        assert_eq!(options.get("baseURL").unwrap().as_str().unwrap(), "http://localhost:8080/v1");
    }
    #[test]
    fn test_render_preserves_jsonc_comments_outside_managed_provider() {
        let existing = opencode::Config::parse_jsonc(
            r#"{
  // root comment
  "username": "acorn",
  "provider": {
    // unrelated provider comment
    "other": {"options": {"baseURL": "https://example.test"}},
    "llama-swap": {"models": {"stale": {"name": "Stale"}}}
  }
}"#,
        )
        .unwrap();
        let config = Config::default();
        let updated = config.upsert(&existing, &[("qwen".to_string(), "Qwen".to_string())], false).unwrap();
        let rendered = config.render(&updated).unwrap();
        assert!(rendered.contains("// root comment"));
        assert!(rendered.contains("// unrelated provider comment"));
        assert!(rendered.contains("\"stale\""));
        assert!(rendered.contains("\"qwen\""));
        assert_eq!(rendered, config.render(&updated).unwrap());
    }
    #[test]
    fn test_upsert_is_additive_unless_pruned() {
        let existing = opencode::Config {
            username: Some("acorn".to_string()),
            provider: Some(
                [
                    ("other".to_string(), serde_json::json!({"options": {"baseURL": "https://example.test"}})),
                    (
                        "llama-swap".to_string(),
                        serde_json::json!({
                            "custom": true,
                            "options": {"apiKey": "secret"},
                            "models": {"stale": {"name": "Stale"}}
                        }),
                    ),
                ]
                .into_iter()
                .collect(),
            ),
            ..Default::default()
        };
        let config = Config::default();
        let models = [("qwen".to_string(), "Qwen".to_string())];
        let additive = config.upsert(&existing, &models, false).unwrap();
        let provider = additive.provider.as_ref().unwrap().get("llama-swap").unwrap();
        assert!(provider.pointer("/models/stale").is_some());
        assert!(provider.pointer("/models/qwen").is_some());
        assert_eq!(provider.get("custom"), Some(&Value::Bool(true)));
        assert_eq!(provider.pointer("/options/apiKey").and_then(Value::as_str), Some("secret"));
        assert!(additive.provider.as_ref().unwrap().contains_key("other"));
        assert_eq!(additive.username.as_deref(), Some("acorn"));
        let pruned = config.upsert(&existing, &models, true).unwrap();
        let provider = pruned.provider.as_ref().unwrap().get("llama-swap").unwrap();
        assert!(provider.pointer("/models/stale").is_none());
        assert!(provider.pointer("/models/qwen").is_some());
    }
    #[test]
    fn test_upsert_protects_pruned_root_model() {
        let existing = opencode::Config {
            model: Some("llama-swap/stale".to_string()),
            provider: Some(
                [("llama-swap".to_string(), serde_json::json!({"models": {"stale": {"name": "Stale"}}}))]
                    .into_iter()
                    .collect(),
            ),
            ..Default::default()
        };
        let models = [("qwen".to_string(), "Qwen".to_string())];
        assert!(Config::default().upsert(&existing, &models, true).is_err());
        let replacement = Config {
            default_model: Some("qwen".to_string()),
            ..Default::default()
        }
        .upsert(&existing, &models, true)
        .unwrap();
        assert_eq!(replacement.model.as_deref(), Some("llama-swap/qwen"));
    }
}