1use std::collections::{BTreeMap, BTreeSet};
22use std::path::{Path, PathBuf};
23
24use serde_json::{Map, Value};
25
26use crate::adapters::adapter;
27use crate::adapters::caps::{Caps, FieldSet};
28use crate::apply::render::native_to_template;
29use crate::error::{CoreError, ErrorCode};
30use crate::fs::Fs;
31use crate::model::clients::{ClientSelection, NATIVE_NAME_KEY};
32use crate::model::ids::{self, IdKind};
33use crate::model::server::{Enable, Meta, Server, ToolFilter, Transport};
34use crate::secrets::classify::{classify_import, find_in_text};
35use crate::secrets::extract::{Aliases, Extraction, Extractor};
36
37pub const DIR: &str = ".skilldock";
39pub const LEGACY_DIR: &str = ".skillm";
42pub const ORIGIN: &str = "migrated:skilldock";
44
45pub const MCP_FILES: [&str; 3] = [
47 "~/.skilldock/config/mcp-servers.json",
48 "~/.skilldock/mcp-servers.json",
49 "~/.skillm/mcp-servers.json",
50];
51pub const SETTINGS_FILES: [&str; 2] = [
53 "~/.skilldock/config/settings.json",
54 "~/.skilldock/settings.json",
55];
56pub const STATE_FILES: [&str; 2] = ["~/.skilldock/data/state.json", "~/.skilldock/state.json"];
58pub const TAG_FILES: [&str; 2] = [
60 "~/.skilldock/data/skill-tags.json",
61 "~/.skilldock/skill-tags.json",
62];
63pub const SKILLS_DIR: &str = "~/.skilldock/skills";
65pub const GITHUB_CREDENTIAL: &str = "~/.skilldock/credentials/github.json";
67pub const BACKUP_REPO: &str = "~/.skilldock/backup/repo";
69
70pub fn resolve(home: &Path, display: &str) -> PathBuf {
72 let rest = display.strip_prefix("~/").unwrap_or(display);
73 rest.split('/')
74 .fold(home.to_path_buf(), |path, part| path.join(part))
75}
76
77pub fn first_existing(fs: &dyn Fs, home: &Path, candidates: &[&str]) -> Option<(String, PathBuf)> {
79 candidates.iter().find_map(|display| {
80 let path = resolve(home, display);
81 fs.exists(&path).then(|| ((*display).to_owned(), path))
82 })
83}
84
85pub fn read_json(fs: &dyn Fs, path: &Path, display: &str) -> Result<Value, CoreError> {
88 let text = fs.read_to_string(path).map_err(|err| {
89 CoreError::new(ErrorCode::IoError, format!("cannot read {display}: {err}"))
90 })?;
91 let text = text.strip_prefix('\u{feff}').unwrap_or(&text);
92 serde_json::from_str(text).map_err(|err| {
93 CoreError::new(
94 ErrorCode::ParseError,
95 format!("{display} is not valid JSON (line {})", err.line()),
96 )
97 })
98}
99
100#[derive(Debug, Clone, PartialEq)]
102pub struct Record {
103 pub id: String,
105 pub name: String,
106 pub server: Value,
108 pub description: String,
109 pub source_url: String,
110 pub enabled_app_ids: Vec<String>,
111 pub imported_from_app_ids: Vec<String>,
112 pub managed_app_ids: Vec<String>,
113 pub tools: Vec<(String, bool)>,
115 pub lifecycle_source: String,
117 pub owner_plugin_name: String,
118 pub renamed: Vec<(String, String)>,
121}
122
123impl Record {
124 pub fn plugin_owned(&self) -> bool {
127 self.lifecycle_source == "plugin" || !self.owner_plugin_name.is_empty()
128 }
129}
130
131fn text(map: &Map<String, Value>, key: &str) -> String {
132 map.get(key)
133 .and_then(Value::as_str)
134 .map(str::trim)
135 .unwrap_or_default()
136 .to_owned()
137}
138
139fn texts(map: &Map<String, Value>, key: &str) -> Vec<String> {
140 let mut out: Vec<String> = Vec::new();
141 for item in map.get(key).and_then(Value::as_array).into_iter().flatten() {
142 if let Some(item) = item.as_str().map(str::trim).filter(|s| !s.is_empty())
143 && !out.iter().any(|known| known == item)
144 {
145 out.push(item.to_owned());
146 }
147 }
148 out
149}
150
151pub const APP_RENAMES: [(&str, &str); 1] = [("github-copilot", "copilot")];
155
156fn app_ids(
158 map: &Map<String, Value>,
159 key: &str,
160 renamed: &mut Vec<(String, String)>,
161) -> Vec<String> {
162 let mut out: Vec<String> = Vec::new();
163 for id in texts(map, key) {
164 let id = match APP_RENAMES.iter().find(|(from, _)| *from == id) {
165 Some((from, to)) => {
166 if !renamed.iter().any(|(known, _)| known == from) {
167 renamed.push(((*from).to_owned(), (*to).to_owned()));
168 }
169 (*to).to_owned()
170 }
171 None => id,
172 };
173 if !out.contains(&id) {
174 out.push(id);
175 }
176 }
177 out
178}
179
180pub fn parse_records(doc: &Value) -> Result<Vec<Result<Record, CoreError>>, CoreError> {
184 let items = match doc {
185 Value::Array(items) => items,
186 Value::Object(map) => match map.get("servers") {
187 Some(Value::Array(items)) => items,
188 None => return Ok(Vec::new()),
189 Some(_) => {
190 return Err(CoreError::new(
191 ErrorCode::UnexpectedShape,
192 "`servers` is not a list",
193 ));
194 }
195 },
196 _ => {
197 return Err(CoreError::new(
198 ErrorCode::UnexpectedShape,
199 "the MCP registry is not an object",
200 ));
201 }
202 };
203 Ok(items
204 .iter()
205 .enumerate()
206 .map(|(index, item)| {
207 let map = item.as_object().ok_or_else(|| {
208 CoreError::new(
209 ErrorCode::UnexpectedShape,
210 format!("record {} is not an object", index + 1),
211 )
212 })?;
213 let id = text(map, "id");
214 let name = text(map, "name");
215 let id = if id.is_empty() { name.clone() } else { id };
216 if id.is_empty() {
217 return Err(CoreError::new(
218 ErrorCode::MissingField,
219 format!("record {} has no id or name", index + 1),
220 ));
221 }
222 let tools = map
223 .get("tools")
224 .and_then(Value::as_array)
225 .into_iter()
226 .flatten()
227 .filter_map(|tool| {
228 let tool = tool.as_object()?;
229 let name = text(tool, "name");
230 let enabled = tool
231 .get("isEnabled")
232 .and_then(Value::as_bool)
233 .unwrap_or(true);
234 (!name.is_empty()).then_some((name, enabled))
235 })
236 .collect();
237 let mut renamed = Vec::new();
238 Ok(Record {
239 name: if name.is_empty() { id.clone() } else { name },
240 id,
241 server: map.get("server").cloned().unwrap_or(Value::Null),
242 description: text(map, "description"),
243 source_url: text(map, "sourceUrl"),
244 enabled_app_ids: app_ids(map, "enabledAppIds", &mut renamed),
245 imported_from_app_ids: app_ids(map, "importedFromAppIds", &mut renamed),
246 managed_app_ids: app_ids(map, "managedAppIds", &mut renamed),
247 tools,
248 lifecycle_source: text(map, "lifecycleSource"),
249 owner_plugin_name: text(map, "ownerPluginName"),
250 renamed,
251 })
252 })
253 .collect())
254}
255
256fn folder_of(path: &str) -> Option<String> {
259 path.trim()
260 .trim_end_matches(['/', '\\'])
261 .rsplit(['/', '\\'])
262 .next()
263 .map(str::trim)
264 .filter(|name| !name.is_empty())
265 .map(str::to_owned)
266}
267
268fn names_skill(name: &str, folder: Option<&str>, folder_name: &str, names: &[&str]) -> bool {
272 match folder {
273 Some(folder) => folder.eq_ignore_ascii_case(folder_name),
274 None => names.iter().any(|n| n.trim().to_lowercase() == name),
275 }
276}
277
278#[derive(Debug, Clone, PartialEq, Eq)]
283pub struct TagEntry {
284 pub name: String,
286 pub folder: Option<String>,
288 pub tag: String,
289}
290
291impl TagEntry {
292 pub fn matches(&self, folder_name: &str, names: &[&str]) -> bool {
294 names_skill(&self.name, self.folder.as_deref(), folder_name, names)
295 }
296}
297
298pub fn parse_tags(doc: &Value, into: &mut Vec<TagEntry>) {
300 let Some(tags) = doc.get("skillTags").and_then(Value::as_object) else {
301 return;
302 };
303 for (key, tag) in tags {
304 let Some(tag) = tag.as_str().map(str::trim).filter(|tag| !tag.is_empty()) else {
305 continue;
306 };
307 let (name, folder) = match key.split_once('\n') {
308 Some((name, path)) => (name, folder_of(path)),
309 None => (key.as_str(), None),
310 };
311 push_tag(
312 into,
313 TagEntry {
314 name: name.trim().to_lowercase(),
315 folder,
316 tag: tag.to_owned(),
317 },
318 );
319 }
320}
321
322fn push_tag(into: &mut Vec<TagEntry>, entry: TagEntry) {
323 if !into.contains(&entry) {
324 into.push(entry);
325 }
326}
327
328#[derive(Debug, Clone, Default, PartialEq, Eq)]
330pub struct InstalledSkill {
331 pub name: String,
333 pub folder: Option<String>,
335 pub source_type: String,
336 pub source_url: String,
337 pub branch: String,
338 pub tag: String,
340}
341
342impl InstalledSkill {
343 pub fn matches(&self, folder_name: &str, names: &[&str]) -> bool {
345 names_skill(&self.name, self.folder.as_deref(), folder_name, names)
346 }
347}
348
349pub fn parse_installed(doc: &Value, tags: &mut Vec<TagEntry>) -> Vec<InstalledSkill> {
352 let mut out = Vec::new();
353 for item in doc
354 .get("installedSkills")
355 .and_then(Value::as_array)
356 .into_iter()
357 .flatten()
358 {
359 let Some(map) = item.as_object() else {
360 continue;
361 };
362 let name = text(map, "name").to_lowercase();
363 if name.is_empty() {
364 continue;
365 }
366 let canonical = text(map, "canonicalPath");
367 let path = if canonical.is_empty() {
368 text(map, "localPath")
369 } else {
370 canonical
371 };
372 let skill = InstalledSkill {
373 name,
374 folder: folder_of(&path),
375 source_type: text(map, "sourceType"),
376 source_url: text(map, "sourceUrl"),
377 branch: text(map, "branch"),
378 tag: text(map, "tag"),
379 };
380 if !skill.tag.is_empty() {
381 push_tag(
382 tags,
383 TagEntry {
384 name: skill.name.clone(),
385 folder: skill.folder.clone(),
386 tag: skill.tag.clone(),
387 },
388 );
389 }
390 out.push(skill);
391 }
392 out
393}
394
395#[derive(Debug, Clone)]
397pub struct Mapped {
398 pub server: Server,
399 pub unwrapped: Option<&'static str>,
402 pub extractions: Vec<Extraction>,
403 pub machine_path: bool,
405 pub dropped: Vec<String>,
407 pub unknown_clients: Vec<String>,
409 pub notes: Vec<String>,
411 pub review: Vec<String>,
413}
414
415#[derive(Debug, Clone, Default, PartialEq)]
417struct Raw {
418 transport: Option<Transport>,
419 command: Option<String>,
420 args: Vec<String>,
421 cwd: Option<String>,
422 url: Option<String>,
423 env: BTreeMap<String, String>,
424 headers: BTreeMap<String, String>,
425 allow: Vec<String>,
427 deny: Vec<String>,
429 unused_env: Vec<String>,
432}
433
434fn substitute(text: &str, env: &BTreeMap<String, String>, used: &mut BTreeSet<String>) -> String {
438 let mut out = String::new();
439 let mut rest = text;
440 while let Some(start) = rest.find("${") {
441 let after = &rest[start + 2..];
442 match after.find('}') {
443 Some(end) if env.contains_key(&after[..end]) => {
444 let name = &after[..end];
445 out.push_str(&rest[..start]);
446 out.push_str(&env[name]);
447 used.insert(name.to_owned());
448 rest = &after[end + 1..];
449 }
450 _ => {
451 out.push_str(&rest[..start + 2]);
452 rest = after;
453 }
454 }
455 }
456 out.push_str(rest);
457 out
458}
459
460fn is_filter(arg: &str) -> bool {
461 arg == "mcp-filter" || arg.ends_with("/mcp-filter") || arg.starts_with("mcp-filter@")
462}
463
464fn is_remote(arg: &str) -> bool {
465 arg == "mcp-remote" || arg.starts_with("mcp-remote@") || arg.ends_with("/mcp-remote")
466}
467
468pub fn wrapper_kind(command: Option<&str>, args: &[String]) -> Option<&'static str> {
471 let command = command?;
472 let program = command
473 .rsplit(['/', '\\'])
474 .next()
475 .unwrap_or(command)
476 .trim_end_matches(".cmd")
477 .trim_end_matches(".exe");
478 if program != "npx" {
479 return None;
480 }
481 let first = args.iter().take(3).find(|arg| !arg.starts_with('-'))?;
482 if is_filter(first) {
483 Some("mcp-filter")
484 } else if is_remote(first) {
485 Some("mcp-remote")
486 } else {
487 None
488 }
489}
490
491fn unwrap(raw: &Raw) -> Option<(Raw, &'static str)> {
494 let kind = wrapper_kind(raw.command.as_deref(), &raw.args)?;
495 let args = &raw.args;
496 let start = args.iter().position(|arg| !arg.starts_with('-'))? + 1;
497 match kind {
498 "mcp-filter" => {
499 let delimiter = args.iter().position(|arg| arg == "--")?;
500 let command = args.get(delimiter + 1)?.trim();
501 if command.is_empty() || delimiter < start {
502 return None;
503 }
504 let mut allow = Vec::new();
505 let mut index = start;
506 while index < delimiter {
507 if args[index] == "--include"
508 && let Some(tool) = args.get(index + 1).map(|t| t.trim())
509 {
510 if !tool.is_empty() && !allow.iter().any(|known| known == tool) {
511 allow.push(tool.to_owned());
512 }
513 index += 2;
514 } else {
515 index += 1;
516 }
517 }
518 Some((
519 Raw {
520 transport: Some(Transport::Stdio),
521 command: Some(command.to_owned()),
522 args: args[delimiter + 2..].to_vec(),
523 cwd: raw.cwd.clone(),
524 env: raw.env.clone(),
525 allow,
526 ..Raw::default()
527 },
528 kind,
529 ))
530 }
531 _ => {
532 let url = args.get(start)?.trim();
533 if !(url.starts_with("http://") || url.starts_with("https://")) {
534 return None;
535 }
536 let mut inner = Raw {
537 transport: Some(Transport::Http),
538 url: Some(url.to_owned()),
539 ..Raw::default()
540 };
541 let mut index = start + 1;
542 while index < args.len() {
543 let value = args.get(index + 1);
544 match (args[index].as_str(), value) {
545 ("--transport", Some(mode)) => {
546 inner.transport = Some(match mode.as_str() {
547 "sse-only" | "sse-first" => Transport::Sse,
548 _ => Transport::Http,
549 });
550 index += 2;
551 }
552 ("--header", Some(header)) => {
553 let (name, value) = header.split_once(':')?;
554 inner
555 .headers
556 .insert(name.trim().to_owned(), value.trim().to_owned());
557 index += 2;
558 }
559 ("--ignore-tool", Some(tool)) => {
560 if !inner.deny.iter().any(|known| known == tool) {
561 inner.deny.push(tool.clone());
562 }
563 index += 2;
564 }
565 ("--allow-http", _) => index += 1,
566 _ => return None,
567 }
568 }
569 let mut used = BTreeSet::new();
572 inner.url = inner.url.map(|url| substitute(&url, &raw.env, &mut used));
573 for value in inner.headers.values_mut() {
574 *value = substitute(value, &raw.env, &mut used);
575 }
576 inner.unused_env = raw
577 .env
578 .keys()
579 .filter(|k| !used.contains(*k))
580 .cloned()
581 .collect();
582 Some((inner, kind))
583 }
584 }
585}
586
587const KNOWN_KEYS: [&str; 7] = ["type", "command", "args", "env", "url", "headers", "cwd"];
588
589fn read_raw(server: &Value, dropped: &mut Vec<String>) -> Result<Raw, CoreError> {
590 let map = server.as_object().ok_or_else(|| {
591 CoreError::new(
592 ErrorCode::UnexpectedShape,
593 "the server definition is not an object",
594 )
595 })?;
596 let shape = |field: &str, expected: &str| {
597 CoreError::new(
598 ErrorCode::UnexpectedShape,
599 format!("`{field}` is not {expected}"),
600 )
601 };
602 let string = |key: &str| -> Result<Option<String>, CoreError> {
603 match map.get(key) {
604 None | Some(Value::Null) => Ok(None),
605 Some(Value::String(text)) if text.trim().is_empty() => Ok(None),
606 Some(Value::String(text)) => Ok(Some(text.clone())),
607 Some(_) => Err(shape(key, "a string")),
608 }
609 };
610 let string_map = |key: &str| -> Result<BTreeMap<String, String>, CoreError> {
611 match map.get(key) {
612 None | Some(Value::Null) => Ok(BTreeMap::new()),
613 Some(Value::Object(items)) => items
614 .iter()
615 .map(|(name, value)| match value {
616 Value::String(text) => Ok((name.clone(), text.clone())),
617 Value::Number(_) | Value::Bool(_) => Ok((name.clone(), value.to_string())),
618 _ => Err(shape(&format!("{key}.{name}"), "a string")),
619 })
620 .collect(),
621 Some(_) => Err(shape(key, "an object")),
622 }
623 };
624 let args = match map.get("args") {
625 None | Some(Value::Null) => Vec::new(),
626 Some(Value::Array(items)) => items
627 .iter()
628 .map(|item| match item {
629 Value::String(text) => Ok(text.clone()),
630 Value::Number(_) | Value::Bool(_) => Ok(item.to_string()),
631 _ => Err(shape("args", "a list of strings")),
632 })
633 .collect::<Result<_, _>>()?,
634 Some(_) => return Err(shape("args", "a list")),
635 };
636 let command = string("command")?;
637 let url = string("url")?;
638 let transport = match string("type")?.as_deref() {
639 Some("stdio") => Some(Transport::Stdio),
640 Some("http" | "streamable-http" | "streamableHttp" | "streamable_http") => {
641 Some(Transport::Http)
642 }
643 Some("sse") => Some(Transport::Sse),
644 Some(other) => {
645 return Err(CoreError::new(
646 ErrorCode::UnsupportedTransport,
647 format!("transport {other:?} has no store equivalent"),
648 ));
649 }
650 None if command.is_some() => Some(Transport::Stdio),
651 None if url.is_some() => Some(Transport::Http),
652 None => None,
653 };
654 for key in map.keys() {
655 if !KNOWN_KEYS.contains(&key.as_str()) {
656 dropped.push(key.clone());
657 }
658 }
659 Ok(Raw {
660 transport,
661 command,
662 args,
663 cwd: string("cwd")?,
664 url,
665 env: string_map("env")?,
666 headers: string_map("headers")?,
667 allow: Vec::new(),
668 deny: Vec::new(),
669 unused_env: Vec::new(),
670 })
671}
672
673pub fn is_machine_path(command: &str) -> bool {
677 let bytes = command.as_bytes();
678 command.starts_with('/')
679 || command.starts_with('~')
680 || command.starts_with("\\\\")
681 || (bytes.len() > 2
682 && bytes[0].is_ascii_alphabetic()
683 && bytes[1] == b':'
684 && matches!(bytes[2], b'\\' | b'/'))
685}
686
687pub fn map_record(record: &Record, id: &str, aliases: &mut Aliases) -> Result<Mapped, CoreError> {
691 ids::check(IdKind::Server, id)?;
692 let mut dropped = Vec::new();
693 let raw = read_raw(&record.server, &mut dropped)?;
694 let (raw, unwrapped) = match unwrap(&raw) {
695 Some((inner, kind)) => (inner, Some(kind)),
696 None if wrapper_kind(raw.command.as_deref(), &raw.args).is_some() => {
697 return Err(CoreError::new(
698 ErrorCode::UnexpectedShape,
699 "a SkillDock wrapper whose arguments cannot be read back",
700 ));
701 }
702 None => (raw, None),
703 };
704 let Some(transport) = raw.transport else {
705 return Err(CoreError::new(
706 ErrorCode::MissingField,
707 "the definition has neither `command` nor `url`",
708 ));
709 };
710 let caps = &adapter(crate::adapters::claude_code::ID)
711 .and_then(|spec| spec.mcp.as_ref())
712 .expect("Claude Code has MCP")
713 .caps;
714 let mut extractor = Extractor::new(id, aliases);
715 let mut server = Server::new(id);
716 let body = &mut server.body;
717 body.transport = Some(transport);
718 if let Some(command) = &raw.command {
719 body.command = Some(convert(caps, command, FieldSet::COMMAND)?);
720 }
721 if !raw.args.is_empty() {
722 let args = raw
723 .args
724 .iter()
725 .map(|arg| convert(caps, arg, FieldSet::ARGS))
726 .collect::<Result<Vec<_>, _>>()?;
727 body.args = Some(extractor.args(args));
728 }
729 if let Some(cwd) = &raw.cwd {
730 body.cwd = Some(convert(caps, cwd, FieldSet::CWD)?);
731 }
732 if let Some(url) = &raw.url {
733 let url = convert(caps, url, FieldSet::URL)?;
734 body.url = Some(extractor.url(url)?);
735 }
736 for (field, source, label) in [
737 (FieldSet::ENV, &raw.env, "env"),
738 (FieldSet::HEADERS, &raw.headers, "headers"),
739 ] {
740 let mut map = BTreeMap::new();
741 for (name, value) in source {
742 map.insert(name.clone(), convert(caps, value, field)?);
743 }
744 let map = extractor.map(label, map);
745 let map = (!map.is_empty()).then_some(map);
746 match label {
747 "env" => body.env = map,
748 _ => body.headers = map,
749 }
750 }
751 let extractions: Vec<Extraction> = extractor
753 .finish()
754 .into_iter()
755 .map(|extracted| extracted.extraction)
756 .collect();
757 let disabled: Vec<String> = record
758 .tools
759 .iter()
760 .filter(|(_, enabled)| !enabled)
761 .map(|(name, _)| name.clone())
762 .collect();
763 let mut deny = raw.deny.clone();
764 for tool in disabled {
765 if !deny.contains(&tool) {
766 deny.push(tool);
767 }
768 }
769 deny.sort();
770 let mut allow = raw.allow.clone();
771 allow.sort();
772 if !deny.is_empty() || !allow.is_empty() {
773 body.tools = Some(ToolFilter {
774 allow: (deny.is_empty() && !allow.is_empty()).then_some(allow),
776 deny: (!deny.is_empty()).then_some(deny),
777 extra: toml::Table::new(),
778 });
779 }
780 if record.name != id {
781 body.display_name = Some(record.name.clone());
782 }
783 if !record.description.is_empty() {
784 body.description = Some(record.description.clone());
785 }
786 let mut notes = Vec::new();
787 let mut review = Vec::new();
788 for (from, to) in &record.renamed {
789 notes.push(format!("SkillDock's {from} is {to}"));
790 }
791 if !raw.unused_env.is_empty() {
792 review.push(format!(
793 "the wrapper's env keys its headers did not use were dropped: {}",
794 raw.unused_env.join(", ")
795 ));
796 }
797 let homepage = (!record.source_url.is_empty()).then(|| record.source_url.clone());
800 let homepage = match homepage {
801 Some(url) if classify_import(None, &url).is_some() || !find_in_text(&url).is_empty() => {
802 review.push(
803 "the source URL may hold a credential and was left out of meta.homepage".to_owned(),
804 );
805 None
806 }
807 other => other,
808 };
809 body.meta = Some(Meta {
810 homepage,
811 origin: Some(ORIGIN.to_owned()),
812 ..Meta::default()
813 });
814 let mut unknown_clients = Vec::new();
815 for client in &record.enabled_app_ids {
816 if adapter(client).is_none() {
817 unknown_clients.push(client.clone());
818 }
819 }
820 if record.id != id {
821 let mut clients = BTreeMap::new();
823 for client in record
824 .enabled_app_ids
825 .iter()
826 .chain(&record.managed_app_ids)
827 .chain(&record.imported_from_app_ids)
828 {
829 if adapter(client).is_some() {
830 let mut table = toml::Table::new();
831 table.insert(
832 NATIVE_NAME_KEY.to_owned(),
833 toml::Value::String(record.id.clone()),
834 );
835 clients.insert(client.clone(), table);
836 }
837 }
838 body.client = (!clients.is_empty()).then_some(clients);
839 }
840 if !record.enabled_app_ids.is_empty() {
841 server.enable = Some(Enable {
842 clients: Some(ClientSelection::List(record.enabled_app_ids.clone())),
843 extra: toml::Table::new(),
844 });
845 }
846 if let Some(err) = server.validate(Some(id)).first_error(None) {
847 return Err(err);
848 }
849 let machine_path = server.body.command.as_deref().is_some_and(is_machine_path);
850 Ok(Mapped {
851 server,
852 unwrapped,
853 extractions,
854 machine_path,
855 dropped,
856 unknown_clients,
857 notes,
858 review,
859 })
860}
861
862fn convert(caps: &Caps, text: &str, field: FieldSet) -> Result<String, CoreError> {
863 native_to_template(text, caps, field).ok_or_else(|| {
864 CoreError::new(
865 ErrorCode::UnsupportedField,
866 "a value uses a variable form the store cannot express (`${NAME:-default}`)",
867 )
868 })
869}
870
871#[derive(Debug, Clone, Default, PartialEq)]
874pub struct SkillDockSettings {
875 pub fields: Map<String, Value>,
876}
877
878impl SkillDockSettings {
879 pub fn parse(doc: &Value) -> Result<Self, CoreError> {
880 match doc {
881 Value::Object(fields) => Ok(Self {
882 fields: fields.clone(),
883 }),
884 _ => Err(CoreError::new(
885 ErrorCode::UnexpectedShape,
886 "settings are not an object",
887 )),
888 }
889 }
890
891 pub fn text(&self, key: &str) -> Option<&str> {
892 self.fields
893 .get(key)
894 .and_then(Value::as_str)
895 .map(str::trim)
896 .filter(|value| !value.is_empty())
897 }
898
899 pub fn bool(&self, key: &str) -> Option<bool> {
900 self.fields.get(key).and_then(Value::as_bool)
901 }
902}