Skip to main content

kernel_apis/
lib.rs

1//! Host operations behind the thin Python kernel APIs, served as one [`kernel::HostHandler`]:
2//!
3//! - `skills.*`: the version-pinned skill catalog (refresh, list, select, load, why; invoke is validated but needs
4//!   task spawning) and code skills (propose_code / propose_policy with test gating in a fresh kernel, rollback,
5//!   code_list, code_history), ported from `ultron/skills.ts` and `ultron/code-skills.ts`;
6//! - `memory.*`: prepare / propose / correct / get / forget / why / list over a Hindsight-shaped backend, ported from
7//!   `ultron/memory.ts` and the dispatch of `ultron/worker-services.ts`;
8//! - `images.*`: image generation through the OpenRouter images API, saved to files ([`images`]);
9//! - `sessions.*`: stored sessions listed, grepped and read as spans, read-only ([`sessions`]);
10//! - `hints.*`: per-lane hint mutes (`ultron/rlm/hints.ts`), and [`cell_hints`], the situational hints a cell's
11//!   result ends with;
12//! - `tools.*`: extension tool calls from the REPL, detached after `yield_after` (`ultron/rlm/extension-tools.ts`);
13//! - `schedules.*`, `goals.*` and `goal.*` as durable work: the schedule tick, goal recovery over the task journal,
14//!   and [`DurableWork`], the entry point a composition root opens and closes.
15//!
16//! Modules are [`ApiModule`]s, matched by request-type prefix as TS host modules are; every other request goes to
17//! the inner handler. Modules start once, on the first request of any type. Requests carry the calling lane, the
18//! task that owns it (from the [`TaskHost`]) and the host's task operations.
19
20pub mod artifacts;
21pub mod cell_hints;
22pub mod code_skills;
23pub mod context_control;
24pub mod durable_work;
25pub mod family;
26pub mod goal;
27pub mod hints;
28pub mod images;
29pub mod instances;
30pub mod memory;
31pub mod memory_import;
32pub mod memory_pointers;
33pub mod memory_records;
34pub mod progress;
35pub mod prompt_schedule;
36pub mod schedule_tick;
37pub mod schedules;
38pub mod sessions;
39pub mod skills;
40pub mod store;
41pub mod tasks;
42pub mod tool_calls;
43pub mod util;
44
45use kernel::{HostHandler, Signal};
46use serde_json::{Map, Value};
47use std::sync::{Arc, Mutex};
48
49pub use artifacts::{FileKeyedDocuments, KeyedDocuments, MemoryKeyedDocuments};
50pub use code_skills::{CodeSkillKind, CodeSkills, CodeSkillsOptions};
51pub use context_control::{ContextBranches, ContextControl};
52pub use durable_work::{DurableWork, DurableWorkOptions, Recovered};
53pub use family::{FamilyModule, FamilyOptions};
54pub use goal::{GoalDriver, GoalJobs, JobState, TaskGoalJobs};
55pub use hints::HintsModule;
56pub use images::{ImagesConfig, ImagesModule};
57pub use instances::InstancesModule;
58pub use memory::{MemoryApi, MemoryBackend, MemoryError, MemoryService, worker_gate};
59pub use progress::ProgressModule;
60pub use schedule_tick::{ManualTickClock, ScheduleTicker, TickClock};
61pub use schedules::SchedulesModule;
62pub use sessions::SessionsModule;
63pub use skills::{PinnedSkill, SkillLoader, SkillSource, SkillsModule};
64pub use tasks::{RootOnly, TaskHost};
65pub use tool_calls::{ToolCallEnd, ToolCalls, ToolInfo, ToolRunner};
66
67/// One host request as a module sees it (TS `HostModuleRequest` plus the `NativeHostApi`).
68pub struct Request<'a> {
69    pub kind: &'a str,
70    pub payload: &'a Map<String, Value>,
71    /// Lane whose kernel sent the request; the root agent is "main".
72    pub lane: &'a str,
73    /// Task that owns the lane, `None` for the root lane.
74    pub caller_task: Option<&'a str>,
75    pub host: &'a dyn TaskHost,
76    /// Aborted when the requesting cell ends.
77    pub signal: &'a Signal,
78}
79
80/// A host module: owns every request type that starts with one of its prefixes.
81pub trait ApiModule: Send + Sync {
82    fn prefixes(&self) -> &[&str];
83    /// Called once before the first request is served.
84    fn start(&self, _host: &dyn TaskHost) -> Result<(), String> {
85        Ok(())
86    }
87    fn handle(&self, request: &Request<'_>) -> Result<Value, String>;
88}
89
90pub struct KernelApis {
91    inner: Arc<dyn HostHandler>,
92    host: Arc<dyn TaskHost>,
93    lane: String,
94    modules: Vec<Arc<dyn ApiModule>>,
95    /// The outcome of starting the modules, kept like TS keeps its start promise.
96    started: Mutex<Option<Result<(), String>>>,
97}
98
99impl KernelApis {
100    /// Serves the root lane ("main") of a host without a task runtime; see [`KernelApis::with_host`].
101    pub fn new(inner: Arc<dyn HostHandler>) -> Self {
102        Self {
103            inner,
104            host: Arc::new(RootOnly {
105                now: util::system_clock(),
106            }),
107            lane: kernel::ROOT_LANE.into(),
108            modules: Vec::new(),
109            started: Mutex::new(None),
110        }
111    }
112
113    /// The task operations modules use, and the lane whose kernel this handler serves.
114    pub fn with_host(mut self, host: Arc<dyn TaskHost>, lane: impl Into<String>) -> Self {
115        self.host = host;
116        self.lane = lane.into();
117        self
118    }
119
120    pub fn with(mut self, module: Arc<dyn ApiModule>) -> Self {
121        self.modules.push(module);
122        self
123    }
124
125    fn start(&self) -> Result<(), String> {
126        let mut started = jsrt::sync::lock(&self.started);
127        started
128            .get_or_insert_with(|| {
129                self.modules
130                    .iter()
131                    .try_for_each(|module| module.start(self.host.as_ref()))
132            })
133            .clone()
134    }
135}
136
137impl HostHandler for KernelApis {
138    fn handle(&self, kind: &str, payload: Map<String, Value>, signal: &Signal) -> Result<Value, String> {
139        self.start()?;
140        let module = self
141            .modules
142            .iter()
143            .find(|module| module.prefixes().iter().any(|prefix| kind.starts_with(prefix)));
144        let Some(module) = module else {
145            return self.inner.handle(kind, payload, signal);
146        };
147        let caller = self.host.caller_task_id(&self.lane);
148        module.handle(&Request {
149            kind,
150            payload: &payload,
151            lane: &self.lane,
152            caller_task: caller.as_deref(),
153            host: self.host.as_ref(),
154            signal,
155        })
156    }
157}