kaynine-core 0.1.0

Core agent loop, messages, events, policies, and provider abstractions for Kaynine
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
//! Skills (SPEC §9.3): name/description/instructions/source units the model
//! discovers via a catalog layer and reads via the built-in `activate_skill`
//! tool.

use crate::error::{PromptError, ToolError};
use crate::prompt::{PromptContext, PromptFragment, PromptLayer};
use crate::tool::{
    Concurrency, PreparedToolCall, Tool, ToolContext, ToolExecutionContext, ToolOutput, ToolSpec,
};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::{hash_map::DefaultHasher, BTreeMap, HashMap};
use std::hash::{Hash, Hasher};
use std::path::Path;
use std::sync::{Arc, Mutex};

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Skill {
    pub name: String,
    pub description: String,
    pub instructions: String,
    pub source: String,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SkillSummary {
    pub name: String,
    pub description: String,
}

/// Deterministic (BTreeMap-ordered) skill registry.
pub struct SkillRegistry {
    skills: BTreeMap<String, Skill>,
}

impl Default for SkillRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl SkillRegistry {
    pub fn new() -> Self {
        Self {
            skills: BTreeMap::new(),
        }
    }

    /// Registers a skill, replacing any existing entry with the same name.
    pub fn register(&mut self, skill: Skill) {
        self.skills.insert(skill.name.clone(), skill);
    }

    pub fn get(&self, name: &str) -> Option<Skill> {
        self.skills.get(name).cloned()
    }

    /// Deterministic summaries in BTreeMap (name) order.
    pub fn summaries(&self) -> Vec<SkillSummary> {
        self.skills
            .values()
            .map(|skill| SkillSummary {
                name: skill.name.clone(),
                description: skill.description.clone(),
            })
            .collect()
    }

    /// Loads skills from a trusted directory: each subdirectory containing a
    /// `SKILL.md` becomes a skill (description = first non-empty line with
    /// leading `#` trimmed; instructions = full file content; source = dir
    /// path). Subdirectories without `SKILL.md` are skipped; a missing root
    /// directory yields an empty registry.
    pub fn from_directory(path: &Path) -> std::io::Result<Self> {
        let mut registry = Self::new();
        let entries = match std::fs::read_dir(path) {
            Ok(entries) => entries,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(registry),
            Err(error) => return Err(error),
        };
        for entry in entries {
            let entry = entry?;
            let dir = entry.path();
            if !dir.is_dir() {
                continue;
            }
            let skill_md = dir.join("SKILL.md");
            if !skill_md.is_file() {
                continue;
            }
            let instructions = std::fs::read_to_string(&skill_md)?;
            let description = instructions
                .lines()
                .find(|line| !line.trim().is_empty())
                .map(|line| line.trim().trim_start_matches('#').trim().to_string())
                .unwrap_or_default();
            let name = entry.file_name().to_string_lossy().to_string();
            registry.register(Skill {
                name: name.clone(),
                description,
                instructions,
                source: dir.to_string_lossy().to_string(),
            });
        }
        Ok(registry)
    }
}

/// Per-run activation state: skill name → hash of the instructions that were
/// activated. A different hash (skill version change) forces a fresh
/// full-instruction activation (SPEC §9.3).
pub struct SkillActivationState {
    activated: Mutex<HashMap<String, u64>>,
}

impl Default for SkillActivationState {
    fn default() -> Self {
        Self::new()
    }
}

impl SkillActivationState {
    pub fn new() -> Self {
        Self {
            activated: Mutex::new(HashMap::new()),
        }
    }

    fn is_activated(&self, name: &str, hash: u64) -> bool {
        self.activated
            .lock()
            .expect("skill activation mutex poisoned")
            .get(name)
            .is_some_and(|&h| h == hash)
    }

    fn mark(&self, name: &str, hash: u64) {
        self.activated
            .lock()
            .expect("skill activation mutex poisoned")
            .insert(name.to_string(), hash);
    }
}

/// Built-in, side-effect-free `activate_skill` tool (SPEC §9.3). First
/// activation (or a version change) returns the full instructions; a
/// repeat activation of the same version returns a short confirmation.
pub struct ActivateSkillTool {
    registry: Arc<SkillRegistry>,
    state: Arc<SkillActivationState>,
}

/// Convenience constructor wiring the tool with its registry and per-run state.
pub fn activate_skill_tool(
    registry: Arc<SkillRegistry>,
    state: Arc<SkillActivationState>,
) -> Arc<ActivateSkillTool> {
    Arc::new(ActivateSkillTool { registry, state })
}

fn instructions_hash(instructions: &str) -> u64 {
    let mut hasher = DefaultHasher::new();
    instructions.hash(&mut hasher);
    hasher.finish()
}

#[async_trait]
impl Tool for ActivateSkillTool {
    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: "activate_skill".into(),
            description: "读取一个 Skill 的完整指令".into(),
            parameters_schema: serde_json::json!({
                "type": "object",
                "properties": {"name": {"type": "string"}},
                "required": ["name"],
            }),
            concurrency: Concurrency::Sequential,
        }
    }

    async fn prepare(
        &self,
        arguments: serde_json::Value,
        context: &ToolContext,
    ) -> Result<PreparedToolCall, ToolError> {
        let name = arguments
            .get("name")
            .and_then(|v| v.as_str())
            .ok_or_else(|| ToolError::InvalidArguments("missing name".into()))?
            .to_string();
        if self.registry.get(&name).is_none() {
            return Err(ToolError::InvalidArguments(format!(
                "unknown skill: {name}"
            )));
        }
        Ok(PreparedToolCall {
            call_id: context.call_id.clone(),
            name: self.spec().name,
            arguments,
            capabilities: Vec::new(),
        })
    }

    async fn execute(
        &self,
        call: PreparedToolCall,
        _context: ToolExecutionContext,
    ) -> Result<ToolOutput, ToolError> {
        let name = call
            .arguments
            .get("name")
            .and_then(|v| v.as_str())
            .ok_or_else(|| ToolError::InvalidArguments("missing name".into()))?;
        let skill = self
            .registry
            .get(name)
            .ok_or_else(|| ToolError::InvalidArguments(format!("unknown skill: {name}")))?;
        let hash = instructions_hash(&skill.instructions);
        if self.state.is_activated(name, hash) {
            return Ok(ToolOutput {
                is_error: false,
                text: format!("已激活: {name}"),
            });
        }
        self.state.mark(name, hash);
        Ok(ToolOutput {
            is_error: false,
            text: format!("Skill instructions for {name}:\n\n{}", skill.instructions),
        })
    }
}

/// PromptLayer (priority 400) rendering the model-visible skill catalog.
/// Empty catalog renders nothing.
pub struct SkillCatalogLayer {
    registry: Arc<SkillRegistry>,
}

impl SkillCatalogLayer {
    pub fn new(registry: Arc<SkillRegistry>) -> Self {
        Self { registry }
    }
}

#[async_trait]
impl PromptLayer for SkillCatalogLayer {
    fn id(&self) -> &str {
        "skill-catalog"
    }

    fn priority(&self) -> i32 {
        400
    }

    async fn render(
        &self,
        _context: &PromptContext,
    ) -> Result<Option<PromptFragment>, PromptError> {
        let summaries = self.registry.summaries();
        if summaries.is_empty() {
            return Ok(None);
        }
        let mut lines = vec!["可用 Skills(使用 activate_skill 工具获取完整指令):".to_string()];
        for summary in summaries {
            lines.push(format!("- {}: {}", summary.name, summary.description));
        }
        Ok(Some(PromptFragment {
            content: lines.join("\n"),
        }))
    }
}

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

    fn tool_context() -> ToolContext {
        ToolContext {
            session_id: crate::ids::SessionId::from("s"),
            run_id: crate::ids::RunId::from("r"),
            turn_id: crate::ids::TurnId::from("t"),
            call_id: crate::ids::ToolCallId::from("c1"),
        }
    }

    fn exec_context() -> ToolExecutionContext {
        let (tx, _rx) = tokio::sync::mpsc::channel(4);
        ToolExecutionContext {
            cancel: tokio_util::sync::CancellationToken::new(),
            progress: tx,
        }
    }

    struct TempDir(std::path::PathBuf);

    impl TempDir {
        fn new() -> Self {
            let path = std::env::temp_dir().join(format!("kaynine-skill-{}", uuid::Uuid::new_v4()));
            std::fs::create_dir_all(&path).unwrap();
            Self(path)
        }

        fn write(&self, skill: &str, markdown: &str) {
            let dir = self.0.join(skill);
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(dir.join("SKILL.md"), markdown).unwrap();
        }
    }

    impl Drop for TempDir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    #[test]
    fn from_directory_parses_skills_and_skips_missing_skill_md() {
        let dir = TempDir::new();
        dir.write("alpha", "# Alpha skill\nDo alpha things.");
        dir.write("beta", "# Beta skill\nDo beta things.");
        std::fs::create_dir_all(dir.0.join("empty")).unwrap();

        let registry = SkillRegistry::from_directory(&dir.0).unwrap();
        let summaries = registry.summaries();
        assert_eq!(summaries.len(), 2);
        let alpha = registry.get("alpha").unwrap();
        assert_eq!(alpha.description, "Alpha skill");
        assert_eq!(alpha.instructions, "# Alpha skill\nDo alpha things.");
        assert!(alpha.source.contains("alpha"));
    }

    #[test]
    fn summaries_are_in_name_order() {
        let mut registry = SkillRegistry::new();
        for name in ["zeta", "alpha", "mid"] {
            registry.register(Skill {
                name: name.into(),
                description: format!("{name} desc"),
                instructions: "x".into(),
                source: "test".into(),
            });
        }
        let names: Vec<String> = registry.summaries().into_iter().map(|s| s.name).collect();
        assert_eq!(names, vec!["alpha", "mid", "zeta"]);
    }

    #[tokio::test]
    async fn activate_returns_full_then_short_confirmation() {
        let mut registry = SkillRegistry::new();
        registry.register(Skill {
            name: "alpha".into(),
            description: "d".into(),
            instructions: "full instructions".into(),
            source: "test".into(),
        });
        let registry = Arc::new(registry);
        let state = Arc::new(SkillActivationState::new());
        let tool = activate_skill_tool(registry, state);
        let args = serde_json::json!({"name": "alpha"});
        let first = tool
            .execute(
                tool.prepare(args.clone(), &tool_context()).await.unwrap(),
                exec_context(),
            )
            .await
            .unwrap();
        assert!(!first.is_error);
        assert_eq!(
            first.text,
            "Skill instructions for alpha:\n\nfull instructions"
        );
        let second = tool
            .execute(
                tool.prepare(args, &tool_context()).await.unwrap(),
                exec_context(),
            )
            .await
            .unwrap();
        assert_eq!(second.text, "已激活: alpha");
    }

    #[tokio::test]
    async fn version_change_rereturns_full_instructions() {
        let mut registry = SkillRegistry::new();
        registry.register(Skill {
            name: "alpha".into(),
            description: "d".into(),
            instructions: "v1".into(),
            source: "test".into(),
        });
        let registry = Arc::new(registry);
        let state = Arc::new(SkillActivationState::new());
        let tool = activate_skill_tool(registry.clone(), state.clone());
        let args = serde_json::json!({"name": "alpha"});
        let first = tool
            .execute(
                tool.prepare(args.clone(), &tool_context()).await.unwrap(),
                exec_context(),
            )
            .await
            .unwrap();
        assert!(first.text.contains("v1"));

        // Same name, new instructions (version change).
        let mut updated = SkillRegistry::new();
        updated.register(Skill {
            name: "alpha".into(),
            description: "d".into(),
            instructions: "v2".into(),
            source: "test".into(),
        });
        let tool = activate_skill_tool(Arc::new(updated), state);
        let second = tool
            .execute(
                tool.prepare(args, &tool_context()).await.unwrap(),
                exec_context(),
            )
            .await
            .unwrap();
        assert!(second.text.contains("v2"));
    }

    #[tokio::test]
    async fn unknown_skill_is_invalid_arguments() {
        let registry = Arc::new(SkillRegistry::new());
        let tool = activate_skill_tool(registry, Arc::new(SkillActivationState::new()));
        let result = tool
            .prepare(serde_json::json!({"name": "nope"}), &tool_context())
            .await;
        assert!(matches!(
            result,
            Err(ToolError::InvalidArguments(msg)) if msg.contains("unknown skill")
        ));
        let missing = tool.prepare(serde_json::json!({}), &tool_context()).await;
        assert!(matches!(missing, Err(ToolError::InvalidArguments(_))));
    }
}