agnix-lsp 0.2.0

Language Server Protocol implementation for agnix
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
//! Hover documentation provider for LSP.
//!
//! Provides contextual documentation when hovering over fields
//! in agent configuration files.

use tower_lsp::lsp_types::{Hover, HoverContents, MarkupContent, MarkupKind, Position};

/// Field documentation for hover support.
///
/// Contains the field name pattern and its documentation.
struct FieldDoc {
    /// Field name to match (e.g., "name", "version", "model")
    field: &'static str,
    /// Markdown documentation to display on hover
    docs: &'static str,
}

/// Static documentation for common skill/agent fields.
const FIELD_DOCS: &[FieldDoc] = &[
    FieldDoc {
        field: "name",
        docs: r#"**name** (required)

The skill identifier. Must be lowercase alphanumeric with hyphens.

Example: `my-skill`, `code-review`

Rules: AS-004, CC-SK-001"#,
    },
    FieldDoc {
        field: "version",
        docs: r#"**version** (required)

Semantic version string for the skill.

Format: `MAJOR.MINOR.PATCH` (e.g., `1.0.0`, `2.3.1`)

Rules: AS-005, CC-SK-002"#,
    },
    FieldDoc {
        field: "model",
        docs: r#"**model** (required)

The AI model to use for this skill.

Common values: `sonnet`, `opus`, `haiku`

Rules: AS-006, CC-SK-003"#,
    },
    FieldDoc {
        field: "description",
        docs: r#"**description** (optional)

Human-readable description of what this skill does.

Best practices:
- Keep it concise (1-2 sentences)
- Explain the primary use case
- Mention any prerequisites"#,
    },
    FieldDoc {
        field: "tools",
        docs: r#"**tools** (optional)

List of MCP tools this skill can use.

Format: Array of tool names or tool configurations.

Example:
```yaml
tools:
  - read_file
  - write_file
  - execute_command
```

Rules: CC-SK-TL-001"#,
    },
    FieldDoc {
        field: "allowed_tools",
        docs: r#"**allowed_tools** (optional)

Restricts which tools this skill can access.

This provides a security boundary for skill execution.

Example:
```yaml
allowed_tools:
  - read_file
  - list_directory
```"#,
    },
    FieldDoc {
        field: "triggers",
        docs: r#"**triggers** (optional)

Patterns that activate this skill automatically.

Example:
```yaml
triggers:
  - pattern: "review.*code"
    description: "Code review requests"
```

Rules: CC-HK-001"#,
    },
    FieldDoc {
        field: "hooks",
        docs: r#"**hooks** (optional)

Lifecycle hooks for skill execution.

Available hooks:
- `pre_invoke`: Run before skill starts
- `post_invoke`: Run after skill completes
- `on_error`: Run if skill fails

Rules: CC-HK-002"#,
    },
    FieldDoc {
        field: "memory",
        docs: r#"**memory** (optional)

Memory configuration for the skill.

Controls how context is managed across invocations.

Rules: AS-MEM-001"#,
    },
    FieldDoc {
        field: "context",
        docs: r#"**context** (optional)

Additional context files to include.

Example:
```yaml
context:
  - path: "./docs/api.md"
    description: "API documentation"
```"#,
    },
    FieldDoc {
        field: "prompt",
        docs: r#"**prompt** (optional)

System prompt or instructions for the skill.

Can be inline text or a file reference."#,
    },
    FieldDoc {
        field: "mcpServers",
        docs: r#"**mcpServers** (MCP configuration)

Defines MCP server connections.

Example:
```json
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem"]
    }
  }
}
```

Rules: MCP-001"#,
    },
    FieldDoc {
        field: "command",
        docs: r#"**command** (MCP server)

The command to launch an MCP server.

Common values: `npx`, `node`, `python`

Rules: MCP-002"#,
    },
    FieldDoc {
        field: "args",
        docs: r#"**args** (MCP server)

Arguments passed to the MCP server command.

Example:
```json
"args": ["-y", "@modelcontextprotocol/server-filesystem"]
```

Rules: MCP-003"#,
    },
    FieldDoc {
        field: "env",
        docs: r#"**env** (MCP server)

Environment variables for the MCP server.

Example:
```json
"env": {
  "API_KEY": "${API_KEY}"
}
```

Rules: MCP-004"#,
    },
];

/// Get the field name at a position in YAML content.
///
/// Looks for patterns like `field:` or `  field:` and returns
/// the field name if the position is on that line.
///
/// # Arguments
///
/// * `content` - The document content
/// * `position` - The cursor position
///
/// # Returns
///
/// The field name if found, or None if the position is not on a field.
pub fn get_field_at_position(content: &str, position: Position) -> Option<String> {
    let line_idx = position.line as usize;
    let line = content.lines().nth(line_idx)?;

    let trimmed = line.trim_start();
    if let Some(colon_pos) = trimmed.find(':') {
        let field = trimmed[..colon_pos].trim();
        if !field.is_empty()
            && field
                .chars()
                .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
        {
            let char_pos = position.character as usize;
            let leading_spaces = line.len() - trimmed.len();
            let field_end = leading_spaces + colon_pos;

            if char_pos <= field_end {
                return Some(field.to_string());
            }
        }
    }

    if let Some(first_quote) = trimmed.find('"') {
        let after_first_quote = &trimmed[first_quote + 1..];
        if let Some(second_quote) = after_first_quote.find('"') {
            let field = &after_first_quote[..second_quote];
            let after_field = &after_first_quote[second_quote + 1..];
            let after_ws = after_field.trim_start();
            if after_ws.starts_with(':') {
                let char_pos = position.character as usize;
                let leading_spaces = line.len() - trimmed.len();
                let colon_offset = trimmed.len() - after_ws.len();
                let field_end = leading_spaces + colon_offset;

                if char_pos <= field_end {
                    return Some(field.to_string());
                }
            }
        }
    }

    None
}

/// Get hover information for a field.
///
/// # Arguments
///
/// * `field` - The field name to look up
///
/// # Returns
///
/// A Hover with markdown documentation if the field is known.
pub fn get_hover_info(field: &str) -> Option<Hover> {
    // Look up the field in our documentation
    let doc = FIELD_DOCS.iter().find(|d| d.field == field)?;

    Some(Hover {
        contents: HoverContents::Markup(MarkupContent {
            kind: MarkupKind::Markdown,
            value: doc.docs.to_string(),
        }),
        range: None,
    })
}

/// Get hover information for a position in a document.
///
/// Combines field detection and documentation lookup.
///
/// # Arguments
///
/// * `content` - The document content
/// * `position` - The cursor position
///
/// # Returns
///
/// A Hover if there's documentation for the field at the position.
pub fn hover_at_position(content: &str, position: Position) -> Option<Hover> {
    let field = get_field_at_position(content, position)?;
    get_hover_info(&field)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_get_field_at_position_yaml() {
        let content = "---\nname: test-skill\nversion: 1.0.0\n---";

        // On "name" field
        let pos = Position {
            line: 1,
            character: 0,
        };
        assert_eq!(
            get_field_at_position(content, pos),
            Some("name".to_string())
        );

        // On "version" field
        let pos = Position {
            line: 2,
            character: 3,
        };
        assert_eq!(
            get_field_at_position(content, pos),
            Some("version".to_string())
        );
    }

    #[test]
    fn test_get_field_at_position_after_colon() {
        let content = "name: test-skill";

        // After the colon (on the value)
        let pos = Position {
            line: 0,
            character: 10,
        };
        assert_eq!(get_field_at_position(content, pos), None);
    }

    #[test]
    fn test_get_field_at_position_indented() {
        let content = "root:\n  nested: value";

        let pos = Position {
            line: 1,
            character: 4,
        };
        assert_eq!(
            get_field_at_position(content, pos),
            Some("nested".to_string())
        );
    }

    #[test]
    fn test_get_field_at_position_json() {
        let content = r#"{"name": "test"}"#;

        let pos = Position {
            line: 0,
            character: 2,
        };
        assert_eq!(
            get_field_at_position(content, pos),
            Some("name".to_string())
        );
    }

    #[test]
    fn test_get_field_at_position_out_of_bounds() {
        let content = "name: test";

        let pos = Position {
            line: 5,
            character: 0,
        };
        assert_eq!(get_field_at_position(content, pos), None);
    }

    #[test]
    fn test_get_hover_info_known_field() {
        let hover = get_hover_info("name");
        assert!(hover.is_some());

        let hover = hover.unwrap();
        match hover.contents {
            HoverContents::Markup(markup) => {
                assert_eq!(markup.kind, MarkupKind::Markdown);
                assert!(markup.value.contains("name"));
                assert!(markup.value.contains("required"));
            }
            _ => panic!("Expected Markup content"),
        }
    }

    #[test]
    fn test_get_hover_info_unknown_field() {
        let hover = get_hover_info("unknown_field_xyz");
        assert!(hover.is_none());
    }

    #[test]
    fn test_hover_at_position_found() {
        let content = "---\nname: test\nversion: 1.0.0\n---";

        let pos = Position {
            line: 1,
            character: 2,
        };
        let hover = hover_at_position(content, pos);

        assert!(hover.is_some());
    }

    #[test]
    fn test_hover_at_position_not_found() {
        let content = "---\nunknown_xyz: test\n---";

        let pos = Position {
            line: 1,
            character: 0,
        };
        let hover = hover_at_position(content, pos);

        assert!(hover.is_none());
    }

    #[test]
    fn test_all_documented_fields_have_hover() {
        let fields = [
            "name",
            "version",
            "model",
            "description",
            "tools",
            "mcpServers",
            "command",
            "args",
            "env",
        ];

        for field in fields {
            let hover = get_hover_info(field);
            assert!(
                hover.is_some(),
                "Field '{}' should have documentation",
                field
            );
        }
    }

    #[test]
    fn test_hover_content_format() {
        // All hovers should be markdown and contain the field name
        for doc in FIELD_DOCS {
            let hover = get_hover_info(doc.field).unwrap();
            match hover.contents {
                HoverContents::Markup(markup) => {
                    assert_eq!(markup.kind, MarkupKind::Markdown);
                    assert!(
                        markup.value.contains(doc.field),
                        "Hover for '{}' should contain field name",
                        doc.field
                    );
                }
                _ => panic!("Expected Markup content for field '{}'", doc.field),
            }
        }
    }
}