kaish-tool-api 0.17.0

Stable plugin API for kaish tools: Tool/ToolCtx/KernelBackend traits, schema reflection
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
//! The `Tool` trait and argument validation.

use std::collections::HashSet;

use async_trait::async_trait;

use kaish_types::{ExecResult, ParamSchema, ToolArgs, ToolSchema, Value};

use crate::ctx::ToolCtx;
use crate::issue::{IssueCode, Severity, ValidationIssue};

/// A tool that can be executed.
///
/// Every kaish command — builtin or third-party — implements this trait. The
/// `execute` method receives a `&mut dyn ToolCtx`, the trimmed portable
/// context; tools needing deeper kernel state downcast via
/// [`ToolCtx::as_any_mut`](crate::ToolCtx::as_any_mut).
#[async_trait]
pub trait Tool: Send + Sync {
    /// The tool's name (used for lookup).
    fn name(&self) -> &str;

    /// Get the tool's schema.
    fn schema(&self) -> ToolSchema;

    /// Execute the tool with the given arguments and context.
    async fn execute(&self, args: ToolArgs, ctx: &mut dyn ToolCtx) -> ExecResult;

    /// Validate arguments without executing.
    ///
    /// Default implementation validates against the schema.
    /// Override this for semantic checks (regex validity, zero increment, etc.).
    fn validate(&self, args: &ToolArgs) -> Vec<ValidationIssue> {
        validate_against_schema(args, &self.schema())
    }
}

/// Validate arguments against a tool schema.
///
/// Splits `schema.params` into positional and named/flag groups so the
/// positional slot index never conflates with the struct-field index. With
/// clap-derived schemas, positionals sit *after* the flags in struct order;
/// the old single-index walk would have falsely failed `mkdir foo` because
/// the path slot lives at struct index 1+.
///
/// Checks:
/// - Required parameters are provided (positionals by slot, flags by name).
/// - Unknown flags (warning).
/// - Type compatibility for both positional and named args.
pub fn validate_against_schema(args: &ToolArgs, schema: &ToolSchema) -> Vec<ValidationIssue> {
    // A verbatim tool owns its grammar, and every check below reads a
    // decomposition it never receives — a required positional would look
    // missing on a subcommand path. One that wants checks overrides
    // `Tool::validate`.
    if args.words.is_some() {
        return Vec::new();
    }

    let mut issues = Vec::new();

    let positional_params: Vec<&ParamSchema> = schema.params.iter().filter(|p| p.positional).collect();
    let flag_params: Vec<&ParamSchema> = schema.params.iter().filter(|p| !p.positional).collect();

    // Required positionals: matched by slot among positional params only.
    for (slot, param) in positional_params.iter().enumerate() {
        if !param.required {
            continue;
        }
        let has_positional = args.positional.len() > slot;
        // A required positional can also be supplied as a named arg if the
        // caller knows the param name (e.g. `mkdir paths=foo`).
        let has_named = args.named.contains_key(&param.name);
        if !has_positional && !has_named {
            let code = IssueCode::MissingRequiredArg;
            issues.push(ValidationIssue {
                severity: code.default_severity(),
                code,
                message: format!("required parameter '{}' not provided", param.name),
                span: None,
                suggestion: Some(format!("add {} or {}=<value>", param.name, param.name)),
                command: Some(schema.name.clone()),
            });
        }
    }

    // Required flags: matched by name (or alias) against args.named / args.flags.
    for param in &flag_params {
        if !param.required {
            continue;
        }
        let has_named = args.named.contains_key(&param.name);
        let has_flag = param.param_type == "bool" && args.has_flag(&param.name);
        if !has_named && !has_flag {
            let code = IssueCode::MissingRequiredArg;
            issues.push(ValidationIssue {
                severity: code.default_severity(),
                code,
                message: format!("required parameter '{}' not provided", param.name),
                span: None,
                suggestion: Some(format!("add --{} <value>", param.name)),
                command: Some(schema.name.clone()),
            });
        }
    }

    // Check for unknown flags (only warn - tools may accept dynamic flags).
    // Only bool flags are gathered for the strict known-flag set; the
    // alias-fallback below catches value-taking flags via `matches_flag`.
    let known_flags: HashSet<&str> = flag_params
        .iter()
        .filter(|p| p.param_type == "bool")
        .flat_map(|p| {
            std::iter::once(p.name.as_str())
                .chain(p.aliases.iter().map(|a| a.as_str()))
        })
        .collect();

    for flag in &args.flags {
        // Strip leading dashes for comparison
        let flag_name = flag.trim_start_matches('-');
        // Global output flags are handled by the kernel, not the tool
        if is_global_output_flag(flag_name) {
            continue;
        }
        if !known_flags.contains(flag_name) && !known_flags.contains(flag.as_str()) {
            // Check if any flag param matches this flag via aliases
            let matches_alias = flag_params.iter().any(|p| p.matches_flag(flag));
            if !matches_alias {
                issues.push(ValidationIssue {
                    severity: Severity::Warning,
                    code: IssueCode::UnknownFlag,
                    message: format!("unknown flag '{}'", flag),
                    span: None,
                    suggestion: None,
                    command: Some(schema.name.clone()),
                });
            }
        }
    }

    // Type compatibility for named args (search the full schema — callers
    // may name either a positional or a flag param).
    for (key, value) in &args.named {
        if let Some(param) = schema.params.iter().find(|p| &p.name == key)
            && let Some(issue) = check_type_compatibility(key, value, &param.param_type, &schema.name) {
                issues.push(issue);
            }
    }

    // Type compatibility for positional args (matched by slot among
    // positional params). Extra positionals past the schema are ignored —
    // many builtins (cat, cp, mkdir) accept variadic positionals.
    for (slot, value) in args.positional.iter().enumerate() {
        if let Some(param) = positional_params.get(slot)
            && let Some(issue) = check_type_compatibility(&param.name, value, &param.param_type, &schema.name) {
                issues.push(issue);
            }
    }

    issues
}

// ============================================================
// Global Output Flags (--json)
// ============================================================
//
// `--json` is declared per-builtin via `GlobalFlags` flatten
// (`crate::global_flags`). Builtins parse it inside execute() and write the
// output format via `ToolCtx::set_output_format`; the kernel applies the
// format after execute() returns.

/// Check if a flag name is the kernel-owned `--json` flag.
///
/// External commands (no schema) bypass clap entirely and the kernel
/// doesn't touch their argv — `cargo --json` and similar work as
/// expected.
///
/// Every binder asks this before deciding the flag is the kernel's: the
/// typed, `raw_argv`, and verbatim arms in the kernel, both arms of the
/// validator's binder, and scatter/gather's early-error path. A tool that
/// declares its own value-taking `--json` would have its value taken by
/// them; `schema_from_clap` skips the name for exactly that reason.
pub fn is_global_output_flag(name: &str) -> bool {
    name == "json"
}

/// Check if a value is compatible with a type.
fn check_type_compatibility(
    name: &str,
    value: &Value,
    expected_type: &str,
    command: &str,
) -> Option<ValidationIssue> {
    let compatible = match expected_type {
        "any" => true,
        "string" => true, // Everything can be a string
        "int" => matches!(value, Value::Int(_) | Value::String(_)),
        "float" => matches!(value, Value::Float(_) | Value::Int(_) | Value::String(_)),
        "bool" => matches!(value, Value::Bool(_) | Value::String(_)),
        "array" => matches!(value, Value::String(_)), // Arrays are passed as strings in kaish
        "object" => matches!(value, Value::String(_)), // Objects are JSON strings
        _ => true, // Unknown types pass
    };

    if compatible {
        None
    } else {
        let code = IssueCode::InvalidArgType;
        Some(ValidationIssue {
            severity: code.default_severity(),
            code,
            message: format!(
                "argument '{}' has type {:?}, expected {}",
                name, value, expected_type
            ),
            span: None,
            suggestion: None,
            command: Some(command.to_string()),
        })
    }
}

#[cfg(test)]
mod validate_tests {
    use super::*;
    use kaish_types::{ParamSchema, ToolSchema};

    fn schema_with_positionals_after_flags() -> ToolSchema {
        // Mirrors clap-derived order: flag fields first, positionals last.
        ToolSchema::new("demo", "demo")
            .param(
                ParamSchema::new("verbose", "bool")
                    .with_default(Some(Value::Bool(false)))
                    .with_aliases(["v"]),
            )
            .param(ParamSchema::new("lines", "int").with_aliases(["n"]))
            .param(
                ParamSchema::new("path", "string")
                    .with_required(true)
                    .positional(),
            )
    }

    /// Regression for the clap-migration index-mismatch: `cat foo.txt` should
    /// satisfy the required positional `path` even though `path` is at struct
    /// index 2 (after `verbose`/`lines`). The old code matched positional[0]
    /// against `verbose` and required positional[2] to exist.
    #[test]
    fn required_positional_satisfied_when_positional_sits_after_flags() {
        let schema = schema_with_positionals_after_flags();
        let mut args = ToolArgs::new();
        args.positional.push(Value::String("foo.txt".into()));

        let issues = validate_against_schema(&args, &schema);
        assert!(
            !issues.iter().any(|i| i.code == IssueCode::MissingRequiredArg),
            "required positional should be satisfied by positional[0]; got {:?}",
            issues
        );
    }

    #[test]
    fn required_positional_missing_when_no_positional_given() {
        let schema = schema_with_positionals_after_flags();
        let mut args = ToolArgs::new();
        args.flags.insert("verbose".into());

        let issues = validate_against_schema(&args, &schema);
        assert!(
            issues.iter().any(|i| i.code == IssueCode::MissingRequiredArg),
            "missing required positional should error; got {:?}",
            issues
        );
    }

    /// Positional type check must look up the positional slot, not the
    /// struct-field index. Here we have a string positional at slot 0; the
    /// old code would have type-checked positional[0] against the int param
    /// `lines` (struct index 1) and emit nothing — but now an int positional
    /// against the string slot must be accepted, and a string positional
    /// against an int positional slot would error.
    #[test]
    fn positional_type_check_targets_positional_slot_not_struct_index() {
        let mut schema = ToolSchema::new("demo", "demo");
        // Two positionals: count (int) then name (string).
        schema = schema
            .param(ParamSchema::new("verbose", "bool").with_default(Some(Value::Bool(false))))
            .param(
                ParamSchema::new("count", "int")
                    .with_required(true)
                    .positional(),
            )
            .param(
                ParamSchema::new("name", "string")
                    .with_required(true)
                    .positional(),
            );

        let mut args = ToolArgs::new();
        args.positional.push(Value::Int(5));
        args.positional.push(Value::String("widget".into()));

        let issues = validate_against_schema(&args, &schema);
        assert!(
            !issues.iter().any(|i| matches!(i.code, IssueCode::InvalidArgType)),
            "int->int and string->string slots should validate clean; got {:?}",
            issues
        );
    }

    /// Required *flag* (non-positional) must still fire MissingRequiredArg
    /// when absent — separating the loops shouldn't silently drop the check.
    #[test]
    fn required_flag_still_errors_when_missing() {
        let schema = ToolSchema::new("demo", "demo").param(
            ParamSchema::new("output", "string")
                .with_required(true)
                .with_aliases(["o"]),
        );

        let args = ToolArgs::new();
        let issues = validate_against_schema(&args, &schema);
        assert!(
            issues.iter().any(|i| i.code == IssueCode::MissingRequiredArg),
            "required flag should error when missing; got {:?}",
            issues
        );
    }

    /// The schema always names the command being checked, so every issue
    /// `validate_against_schema` raises should carry it — a caller that
    /// calls `Tool::validate` directly (no walker in between) still gets a
    /// structured command name, not just message text.
    #[test]
    fn missing_required_positional_carries_command_name() {
        let schema = schema_with_positionals_after_flags();
        let args = ToolArgs::new();

        let issues = validate_against_schema(&args, &schema);
        let issue = issues
            .iter()
            .find(|i| i.code == IssueCode::MissingRequiredArg)
            .expect("expected a MissingRequiredArg issue");
        assert_eq!(issue.command.as_deref(), Some("demo"));
    }

    /// The positional and flag branches are two separate loops in
    /// `validate_against_schema` (see `required_flag_still_errors_when_missing`
    /// above) — both push the same `IssueCode::MissingRequiredArg` from their
    /// own `ValidationIssue { .. }` literal, so the field has to be pinned on
    /// each independently. The positional branch is covered by
    /// `missing_required_positional_carries_command_name`; this is the flag one.
    #[test]
    fn missing_required_flag_carries_command_name() {
        let schema = ToolSchema::new("demo", "demo").param(
            ParamSchema::new("output", "string")
                .with_required(true)
                .with_aliases(["o"]),
        );

        let args = ToolArgs::new();
        let issues = validate_against_schema(&args, &schema);
        let issue = issues
            .iter()
            .find(|i| i.code == IssueCode::MissingRequiredArg)
            .expect("expected a MissingRequiredArg issue");
        assert_eq!(issue.command.as_deref(), Some("demo"));
    }

    /// `UnknownFlag` is its own `ValidationIssue { .. }` literal in the
    /// unknown-flags loop, not shared with either `MissingRequiredArg` branch
    /// — it needs its own pin.
    #[test]
    fn unknown_flag_carries_command_name() {
        let schema = ToolSchema::new("demo", "demo").param(
            ParamSchema::new("verbose", "bool").with_default(Some(Value::Bool(false))),
        );
        let mut args = ToolArgs::new();
        args.flags.insert("bogus".to_string());

        let issues = validate_against_schema(&args, &schema);
        let issue = issues
            .iter()
            .find(|i| i.code == IssueCode::UnknownFlag)
            .expect("expected an UnknownFlag issue");
        assert_eq!(issue.command.as_deref(), Some("demo"));
    }

    #[test]
    fn invalid_arg_type_carries_command_name() {
        let schema = ToolSchema::new("demo", "demo").param(
            ParamSchema::new("count", "int").with_required(true).positional(),
        );
        let mut args = ToolArgs::new();
        // Bool is not int-compatible per check_type_compatibility.
        args.positional.push(Value::Bool(true));

        let issues = validate_against_schema(&args, &schema);
        let issue = issues
            .iter()
            .find(|i| i.code == IssueCode::InvalidArgType)
            .expect("expected an InvalidArgType issue");
        assert_eq!(issue.command.as_deref(), Some("demo"));
    }
}