cairnkit 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cairnkit/curator.py ADDED
@@ -0,0 +1,217 @@
1
+ # Adapted from hermes-agent v0.22.2 (d923a5e): agent/curator.py
2
+ # Copyright (c) 2025 Nous Research. MIT License.
3
+ """Curator: background maintenance of skills a host lets people (or agents) add.
4
+
5
+ Kept from Hermes:
6
+ * **Idle-triggered, no scheduler.** :func:`should_run` says yes only when the last run is
7
+ older than ``interval_hours`` and nobody has used the agents for ``min_idle_hours``. Hosts
8
+ call it from whatever quiet moment they have (a page load, the end of a request).
9
+ * **Lifecycle from activity.** A skill unused for ``stale_after_days`` becomes *stale*; one
10
+ unused for ``archive_after_days`` is *archived*; using a stale skill makes it *active*
11
+ again. A never-used skill younger than the stale window is left alone (no evidence is not
12
+ staleness), and its clock starts at creation.
13
+ * **Never delete, only archive.** Archiving is reversible. **Pinned** skills and skills the
14
+ host marks as built-in are never touched.
15
+ * **Optional consolidation** by a model (off by default) that may only *propose* archiving
16
+ or rewriting skills, as a report; nothing it says is applied automatically.
17
+
18
+ Changed: transitions are returned as a plan instead of written to files, so a host can
19
+ apply them, or turn the archive steps into proposals someone approves first.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import re
26
+ from dataclasses import dataclass, field
27
+ from datetime import UTC, datetime, timedelta
28
+ from typing import Literal
29
+
30
+ from cairnkit.llm.base import ChatModel
31
+
32
+ SkillState = Literal["active", "stale", "archived"]
33
+
34
+
35
+ @dataclass
36
+ class CuratorPolicy:
37
+ enabled: bool = False # hosts decide; this project ships it switched off
38
+ interval_hours: float = 24 * 7
39
+ min_idle_hours: float = 2
40
+ stale_after_days: int = 14
41
+ archive_after_days: int = 30
42
+ consolidate: bool = False # ask a model for merge / rewrite / archive suggestions
43
+
44
+ def __post_init__(self) -> None:
45
+ self.interval_hours = max(1.0, float(self.interval_hours))
46
+ self.min_idle_hours = max(0.0, float(self.min_idle_hours))
47
+ self.stale_after_days = max(1, int(self.stale_after_days))
48
+ self.archive_after_days = max(self.stale_after_days + 1, int(self.archive_after_days))
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class SkillActivity:
53
+ name: str
54
+ state: SkillState = "active"
55
+ pinned: bool = False
56
+ built_in: bool = False # shipped with the code: never curated
57
+ use_count: int = 0
58
+ last_used_at: datetime | None = None
59
+ created_at: datetime | None = None
60
+ description: str = ""
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class Transition:
65
+ name: str
66
+ from_state: SkillState
67
+ to_state: SkillState
68
+ reason: str
69
+
70
+
71
+ @dataclass(frozen=True)
72
+ class Suggestion:
73
+ """A model's consolidation idea. Never applied without a person."""
74
+
75
+ action: Literal["archive", "rewrite"]
76
+ skills: list[str]
77
+ reason: str
78
+ new_description: str | None = None
79
+ new_body: str | None = None
80
+
81
+
82
+ @dataclass
83
+ class CuratorReport:
84
+ checked: int = 0
85
+ transitions: list[Transition] = field(default_factory=list)
86
+ suggestions: list[Suggestion] = field(default_factory=list)
87
+ skipped: list[str] = field(default_factory=list) # pinned / built-in
88
+ error: str | None = None
89
+
90
+
91
+ def should_run(
92
+ policy: CuratorPolicy,
93
+ *,
94
+ last_run_at: datetime | None,
95
+ last_activity_at: datetime | None,
96
+ now: datetime | None = None,
97
+ ) -> bool:
98
+ if not policy.enabled:
99
+ return False
100
+ now = now or datetime.now(UTC)
101
+ if last_run_at and now - _aware(last_run_at) < timedelta(hours=policy.interval_hours):
102
+ return False
103
+ return not (
104
+ last_activity_at and now - _aware(last_activity_at) < timedelta(hours=policy.min_idle_hours)
105
+ )
106
+
107
+
108
+ def plan_transitions(
109
+ skills: list[SkillActivity], policy: CuratorPolicy, now: datetime | None = None
110
+ ) -> CuratorReport:
111
+ """Hermes ``apply_automatic_transitions`` as a pure function."""
112
+ now = now or datetime.now(UTC)
113
+ stale_cutoff = now - timedelta(days=policy.stale_after_days)
114
+ archive_cutoff = now - timedelta(days=policy.archive_after_days)
115
+ report = CuratorReport()
116
+ for skill in skills:
117
+ report.checked += 1
118
+ if skill.pinned or skill.built_in:
119
+ report.skipped.append(skill.name)
120
+ continue
121
+ if skill.state == "archived":
122
+ continue
123
+ anchor = _aware(skill.last_used_at or skill.created_at or now)
124
+ if skill.use_count == 0 and anchor > stale_cutoff:
125
+ if skill.state == "stale":
126
+ report.transitions.append(
127
+ Transition(skill.name, "stale", "active", "too new to judge")
128
+ )
129
+ continue
130
+ idle = (now - anchor).days
131
+ if anchor <= archive_cutoff:
132
+ report.transitions.append(
133
+ Transition(skill.name, skill.state, "archived", f"unused for {idle} days")
134
+ )
135
+ elif anchor <= stale_cutoff and skill.state == "active":
136
+ report.transitions.append(
137
+ Transition(skill.name, "active", "stale", f"unused for {idle} days")
138
+ )
139
+ elif anchor > stale_cutoff and skill.state == "stale":
140
+ report.transitions.append(Transition(skill.name, "stale", "active", "used again"))
141
+ return report
142
+
143
+
144
+ CONSOLIDATION_PROMPT = """You maintain a library of skills (instructions an AI assistant reads
145
+ on demand). Review the list below and suggest consolidation: skills that overlap and should
146
+ be merged into one rewrite, and skills that are obsolete and should be archived. Archiving is
147
+ reversible; nothing you suggest is applied until a person approves it. Be conservative: no
148
+ suggestion is a fine answer. Never suggest touching a skill marked pinned.
149
+
150
+ Answer with JSON only:
151
+ {{"suggestions": [{{"action": "archive" | "rewrite", "skills": ["name", ...], "reason": "...",
152
+ "new_description": "<= 60 chars, rewrite only", "new_body": "full text, rewrite only"}}]}}
153
+
154
+ Skills:
155
+ {skills}"""
156
+
157
+
158
+ async def suggest_consolidation(
159
+ model: ChatModel,
160
+ skills: list[SkillActivity],
161
+ bodies: dict[str, str],
162
+ *,
163
+ max_chars: int = 60_000,
164
+ ) -> list[Suggestion]:
165
+ """Ask a model for consolidation ideas (Hermes' optional LLM pass, report-only)."""
166
+ rows, used = [], 0
167
+ for s in skills:
168
+ if s.state == "archived" or s.built_in:
169
+ continue
170
+ row = (
171
+ f"### {s.name}{' (pinned)' if s.pinned else ''}\n{s.description}\n"
172
+ f"uses: {s.use_count}\n{bodies.get(s.name, '')[:4_000]}"
173
+ )
174
+ if used + len(row) > max_chars:
175
+ break
176
+ rows.append(row)
177
+ used += len(row)
178
+ if len(rows) < 2:
179
+ return []
180
+ response = await model.complete(
181
+ [{"role": "user", "content": CONSOLIDATION_PROMPT.format(skills="\n\n".join(rows))}],
182
+ max_tokens=4_000,
183
+ )
184
+ return parse_suggestions(response.content or "", {s.name for s in skills if not s.pinned})
185
+
186
+
187
+ def parse_suggestions(text: str, allowed: set[str]) -> list[Suggestion]:
188
+ match = re.search(r"\{.*\}", text, re.DOTALL)
189
+ if not match:
190
+ return []
191
+ try:
192
+ data = json.loads(match.group(0))
193
+ except ValueError:
194
+ return []
195
+ out: list[Suggestion] = []
196
+ for item in data.get("suggestions", []) if isinstance(data, dict) else []:
197
+ if not isinstance(item, dict) or item.get("action") not in ("archive", "rewrite"):
198
+ continue
199
+ names = [n for n in item.get("skills", []) if isinstance(n, str)]
200
+ if not names or any(n not in allowed for n in names):
201
+ continue # unknown or pinned skills: drop the whole suggestion
202
+ out.append(
203
+ Suggestion(
204
+ action=item["action"],
205
+ skills=names,
206
+ reason=str(item.get("reason", ""))[:500],
207
+ new_description=(
208
+ str(item["new_description"])[:60] if item.get("new_description") else None
209
+ ),
210
+ new_body=str(item["new_body"]) if item.get("new_body") else None,
211
+ )
212
+ )
213
+ return out
214
+
215
+
216
+ def _aware(value: datetime) -> datetime:
217
+ return value if value.tzinfo else value.replace(tzinfo=UTC)
cairnkit/delegate.py ADDED
@@ -0,0 +1,99 @@
1
+ # Adapted from hermes-agent v0.22.2 (d923a5e): tools/delegate_tool.py
2
+ # Copyright (c) 2025 Nous Research. MIT License. Single-level, sequential delegation.
3
+ """Hand a focused task to a child agent.
4
+
5
+ The child starts a fresh conversation with its own focused system prompt and its own
6
+ (narrower) tools. The parent only ever sees the delegation call and the child's final
7
+ answer, never the child's intermediate tool calls (Hermes contract). Children cannot
8
+ delegate further, and each parent turn may delegate a bounded number of times.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections.abc import Callable
14
+ from typing import TYPE_CHECKING, Any
15
+
16
+ from cairnkit.tools import ToolContext, ToolError, ToolSpec, tool_result
17
+
18
+ if TYPE_CHECKING:
19
+ from cairnkit.loop import Agent, RunResult
20
+
21
+ ChildRunHook = Callable[["Agent", "RunResult", ToolContext], None]
22
+ """Called after each finished child run with the child, its result and the parent's context."""
23
+
24
+ DEPTH_KEY = "_delegation_depth"
25
+ COUNT_KEY = "_delegations"
26
+
27
+
28
+ def make_delegate_tool(
29
+ children: dict[str, Agent],
30
+ *,
31
+ name: str = "delegate_task",
32
+ max_per_turn: int = 3,
33
+ roles: set[str] | None = None,
34
+ on_child_run: ChildRunHook | None = None,
35
+ ) -> ToolSpec:
36
+ """``on_child_run`` sees every finished child run, e.g. to bill its usage (the parent's
37
+ ``RunResult.usage`` covers only the parent's own model calls)."""
38
+ if not children:
39
+ raise ValueError("at least one child agent is required")
40
+ catalog = "; ".join(f"'{n}': {a.spec.description}" for n, a in children.items())
41
+
42
+ async def handler(args: dict[str, Any], ctx: ToolContext) -> str:
43
+ if int(ctx.scope.get(DEPTH_KEY, 0)) >= 1:
44
+ raise ToolError("delegated agents cannot delegate again; do the task yourself")
45
+ counter = ctx.scope.get(COUNT_KEY)
46
+ if isinstance(counter, list):
47
+ if len(counter) >= max_per_turn:
48
+ raise ToolError(
49
+ f"this turn already delegated {len(counter)} times (limit "
50
+ f"{max_per_turn}); finish with the results you have"
51
+ )
52
+ counter.append(args.get("agent"))
53
+ child = children.get(str(args.get("agent", "")))
54
+ if child is None:
55
+ raise ToolError(f"agent must be one of {', '.join(children)}")
56
+ goal = str(args.get("goal") or "").strip()
57
+ if not goal:
58
+ raise ToolError("goal is required: say exactly what the child should find or produce")
59
+ context = str(args.get("context") or "").strip()
60
+ child_ctx = ToolContext(
61
+ principal=ctx.principal,
62
+ roles=ctx.roles,
63
+ scope={**ctx.scope, DEPTH_KEY: 1, COUNT_KEY: []},
64
+ )
65
+ message = f"Goal: {goal}" + (
66
+ f"\n\nContext from the requester:\n{context}" if context else ""
67
+ )
68
+ result = await child.run(message, child_ctx)
69
+ if on_child_run is not None:
70
+ on_child_run(child, result, ctx)
71
+ return tool_result(
72
+ agent=child.spec.name,
73
+ answer=result.text or "",
74
+ stop_reason=result.stop_reason,
75
+ tool_calls=len(result.tool_records),
76
+ )
77
+
78
+ return ToolSpec(
79
+ name=name,
80
+ description=(
81
+ "Give a focused task to a specialist agent and get back only its final answer. "
82
+ f"Use it for self-contained lookups or drafting. Agents: {catalog}."
83
+ ),
84
+ access="read",
85
+ roles=frozenset(roles) if roles else None,
86
+ handler=handler,
87
+ parameters={
88
+ "type": "object",
89
+ "properties": {
90
+ "agent": {"type": "string", "enum": list(children)},
91
+ "goal": {"type": "string", "description": "What the specialist must deliver."},
92
+ "context": {
93
+ "type": "string",
94
+ "description": "Facts it needs; it cannot see this chat.",
95
+ },
96
+ },
97
+ "required": ["agent", "goal"],
98
+ },
99
+ )