Skip to main content

lean_ctx/core/hive/workers/
register.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Worker registration and the instance card on Hive (C0 2.0 §3.17.1,
3//! §3.18.1): E10 `POST /v1/workers` and E44 `PATCH /v1/instances/{id}/card`
4//! are signed by the instance key as `domain ‖ canonical_json(body)`;
5//! E11 `PATCH /v1/workers/{wkr}` rides on the instance token alone.
6
7use base64::Engine as _;
8use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64URL;
9use ed25519_dalek::Signer as _;
10use serde::{Deserialize, Serialize};
11use serde_json::{Value, json};
12
13use super::super::HiveError;
14use super::super::instance_key::InstanceKeys;
15use super::super::transport::HiveClient;
16use super::card::WorkerCard;
17use super::{WorkerAliasKey, alias_signing_key, check_name, key_id};
18
19pub const WORKER_DOMAIN: &str = "leanctx.hive.worker.v1\n";
20pub const INSTANCE_CARD_DOMAIN: &str = "leanctx.hive.instance_card.v1\n";
21
22/// Who is registered: the workspace worker, or its alias in one public
23/// vault or swarm (`place_ref` = `"{kind}:{id}"`).
24pub struct Registration<'a> {
25    pub instance_id: &'a str,
26    pub host_app: &'a str,
27    pub role: &'a str,
28    pub name: &'a str,
29    pub card: &'a WorkerCard,
30    pub alias_place: Option<&'a str>,
31}
32
33/// Add `key_id` and the instance signature over the body without them.
34fn sign(keys: &InstanceKeys, domain: &str, mut body: Value) -> Result<Value, HiveError> {
35    let signer = keys.signing_key();
36    body["key_id"] = key_id(signer).into();
37    let input = lean_ctx_protocol::hive::signing_input(domain, &body)
38        .map_err(|e| HiveError::Local(e.to_string()))?;
39    body["signature"] = hex::encode(signer.sign(&input).to_bytes()).into();
40    Ok(body)
41}
42
43/// The signed E10 body. The name passes the local rule first
44/// (`invalid_name`, SPEC-ENGINE §3.6).
45pub fn register_body(keys: &InstanceKeys, reg: &Registration<'_>) -> Result<Value, HiveError> {
46    let name = check_name(reg.name)
47        .map_err(|refusal| HiveError::Config(format!("invalid_name: {}", refusal.message())))?;
48    let card = serde_json::to_value(reg.card).map_err(|e| HiveError::Local(e.to_string()))?;
49    let mut body = json!({
50        "host_app": reg.host_app,
51        "role": reg.role,
52        "name": name,
53        "card": card,
54    });
55    match reg.alias_place {
56        None => {
57            body["worker_id"] =
58                super::workspace_worker_id(reg.instance_id, reg.host_app, reg.role).into();
59        }
60        Some(place) => {
61            let alias = WorkerAliasKey::of(keys);
62            body["worker_id"] = alias.worker_id(reg.host_app, reg.role, place).into();
63            body["place"] = place.into();
64            body["alias_pubkey"] = B64URL
65                .encode(alias_signing_key(keys, place).verifying_key().as_bytes())
66                .into();
67            body["hlc_node"] = alias.hlc_node(place).into();
68        }
69    }
70    sign(keys, WORKER_DOMAIN, body)
71}
72
73/// Consent channel the engine reports; the server derives the real one
74/// from the bound presence key and a card can only downgrade it.
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
76#[serde(rename_all = "snake_case")]
77pub enum ConsentChannel {
78    OsPresence,
79    TtyOnly,
80}
81
82/// The signed E44 body. `clear_presence_key` sends `presence_key: null`,
83/// which drops the bound key (e.g. after the helper was removed); a card
84/// can never set or replace one.
85pub fn instance_card_body(
86    keys: &InstanceKeys,
87    engine_version: &str,
88    consent_channel: ConsentChannel,
89    clear_presence_key: bool,
90) -> Result<Value, HiveError> {
91    let mut body = json!({
92        "engine_version": engine_version,
93        "consent_channel": consent_channel,
94    });
95    if clear_presence_key {
96        body["presence_key"] = Value::Null;
97    }
98    sign(keys, INSTANCE_CARD_DOMAIN, body)
99}
100
101/// E10 response: the worker as Hive stored it.
102#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
103pub struct RegisteredWorker {
104    pub id: String,
105    pub name: String,
106    pub place: Option<String>,
107    pub status: String,
108    pub registered_at: u64,
109}
110
111#[derive(Deserialize)]
112struct WorkerEnvelope {
113    worker: RegisteredWorker,
114}
115
116/// The bound presence key, as E44 returns it.
117#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
118pub struct PresenceKey {
119    pub alg: String,
120    pub key_id: String,
121    pub hardware: bool,
122    pub bound_at: u64,
123}
124
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct Account {
127    pub user_id: String,
128    /// C0 says string; a Hive that answers `null` for an account without
129    /// a handle must not stop the card from being read.
130    #[serde(default)]
131    pub handle: Option<String>,
132}
133
134#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
135pub struct CardState {
136    pub engine_version: String,
137    pub consent_channel: ConsentChannel,
138    pub updated_at: u64,
139}
140
141/// E44 response.
142#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
143pub struct InstanceCard {
144    pub card: CardState,
145    pub account: Account,
146    pub presence_key: Option<PresenceKey>,
147}
148
149/// Largest answer of these routes.
150const MAX_ANSWER: usize = 64 * 1024;
151
152/// A C0 2.0 refusal in the person's words (SPEC-ENGINE §3.6, WEB §4.4);
153/// `None` leaves it to the generic mapping.
154fn worded(code: &str, reason: &str) -> Option<String> {
155    Some(match (code, reason) {
156        (_, "confusable") => "This name mixes alphabets. Use one alphabet.".into(),
157        (_, "reserved") => {
158            "Names may not contain hive, thinkery, leanctx or moderator. Pick another name.".into()
159        }
160        ("worker_not_owned", _) => {
161            "worker_not_owned: Hive has bound this worker id to another engine.".into()
162        }
163        (_, "worker_cap_reached") => {
164            "worker_cap_reached: this engine already has 32 workers on Hive.".into()
165        }
166        (_, "presence_key_locked") => "The presence key can only be cleared here; bind a new one with `lean-ctx hive connect --bind-presence-key`.".into(),
167        _ => return None,
168    })
169}
170
171/// Send, then parse a 2xx answer or word the refusal.
172fn call<T: for<'de> Deserialize<'de>>(
173    client: &HiveClient,
174    method: &str,
175    path: &str,
176    body: &Value,
177    what: &str,
178) -> Result<T, HiveError> {
179    let (status, answer) = client.send_answer(method, path, Some(body), MAX_ANSWER)?;
180    if !(200..300).contains(&status) {
181        let code = answer["error"]["code"].as_str().unwrap_or_default();
182        let reason = answer["error"]["reason"].as_str().unwrap_or_default();
183        return Err(worded(code, reason).map_or_else(
184            || HiveError::from_response(status, &answer),
185            HiveError::Config,
186        ));
187    }
188    parse(answer, what)
189}
190
191fn parse<T: for<'de> Deserialize<'de>>(value: Value, what: &str) -> Result<T, HiveError> {
192    serde_json::from_value(value).map_err(|e| HiveError::Protocol(format!("{what}: {e}")))
193}
194
195/// E10.
196pub fn register(
197    client: &HiveClient,
198    keys: &InstanceKeys,
199    reg: &Registration<'_>,
200) -> Result<RegisteredWorker, HiveError> {
201    let body = register_body(keys, reg)?;
202    Ok(call::<WorkerEnvelope>(client, "POST", "/workers", &body, "worker registration")?.worker)
203}
204
205/// E44 for the enrolled instance, at `hive connect` and engine start.
206/// The engine reports `os_presence` only with a bound presence key
207/// (§3.8.4); the server derives the real channel.
208pub fn announce_instance(
209    session: &crate::core::hive::auth::Session,
210) -> Result<InstanceCard, HiveError> {
211    let keys = InstanceKeys::load(&session.store)?;
212    let channel =
213        if crate::core::hive::consent::broker::bound_presence_key(&session.store).is_some() {
214            ConsentChannel::OsPresence
215        } else {
216            ConsentChannel::TtyOnly
217        };
218    let exchanged = session.with_client(|client| {
219        let (status, answer) =
220            card_exchange(client, &keys, &session.instance.instance_id, channel, false)?;
221        if status == 401 {
222            // The session renews the token and asks once more.
223            return Err(HiveError::from_response(status, &answer));
224        }
225        Ok((status, answer))
226    });
227    // E44 exists only on a C0 2.0 Hive: its status (not the body, whose
228    // details may change) tells the relay which bus protocol to speak.
229    let speaks = match &exchanged {
230        Ok((status, _)) if (200..300).contains(status) => Some(true),
231        Ok((404, _)) | Err(HiveError::NotFound) => Some(false),
232        _ => None,
233    };
234    if let Some(v2) = speaks {
235        crate::core::hive::bus::relay_v2::record_protocol(&session.store, v2)?;
236    }
237    let result = exchanged.and_then(|(status, answer)| card_from(status, answer));
238    // The owner account web consents are checked against (§3.8.2 step 6).
239    if let Ok(card) = &result {
240        session.store.write_config(
241            crate::core::hive::consent::broker::ACCOUNT_FILE,
242            &card.account,
243        )?;
244    }
245    result
246}
247
248/// Register the worker a session attached to, once (E10 on the first
249/// event or bus post, SPEC-ENGINE §3.6), and remember it in the book.
250/// An already registered worker costs no request.
251pub fn ensure_registered(
252    session: &crate::core::hive::auth::Session,
253    attached: &super::attach::LocalWorker,
254    card: &WorkerCard,
255) -> Result<super::attach::LocalWorker, HiveError> {
256    if attached.registered_at.is_some() {
257        return Ok(attached.clone());
258    }
259    let keys = InstanceKeys::load(&session.store)?;
260    let instance = &session.instance;
261    let name = attached.name.clone().unwrap_or_else(|| {
262        super::default_name(
263            &instance.label,
264            &super::attach::host_display(&attached.host_app),
265            &attached.role,
266        )
267    });
268    let reg = Registration {
269        instance_id: &instance.instance_id,
270        host_app: &attached.host_app,
271        role: &attached.role,
272        name: &name,
273        card,
274        alias_place: None,
275    };
276    let worker = session.with_client(|client| register(client, &keys, &reg))?;
277    if worker.id != attached.worker_id {
278        return Err(HiveError::Protocol(format!(
279            "Hive registered {} for {}",
280            worker.id, attached.worker_id
281        )));
282    }
283    super::attach::update_book(&session.store, &instance.instance_id, |workers| {
284        let entry = workers.iter_mut().find(|w| w.worker_id == worker.id)?;
285        entry.registered_at = Some(worker.registered_at);
286        entry.name = Some(worker.name.clone());
287        Some(entry.clone())
288    })?
289    .ok_or_else(|| HiveError::Local(format!("{} left the worker book", worker.id)))
290}
291
292/// E11: rename and/or a new card.
293pub fn patch(
294    client: &HiveClient,
295    worker_id: &str,
296    name: Option<&str>,
297    card: Option<&WorkerCard>,
298) -> Result<RegisteredWorker, HiveError> {
299    if !crate::core::hive::bus::address::is_worker_id(worker_id) {
300        return Err(HiveError::Config(format!("{worker_id} is not a worker id")));
301    }
302    let mut body = json!({});
303    if let Some(name) = name {
304        body["name"] = check_name(name)
305            .map_err(|r| HiveError::Config(format!("invalid_name: {}", r.message())))?
306            .into();
307    }
308    if let Some(card) = card {
309        body["card"] = serde_json::to_value(card).map_err(|e| HiveError::Local(e.to_string()))?;
310    }
311    if body.as_object().is_none_or(serde_json::Map::is_empty) {
312        return Err(HiveError::Config("nothing to change".into()));
313    }
314    let path = format!("/workers/{worker_id}");
315    Ok(call::<WorkerEnvelope>(client, "PATCH", &path, &body, "worker update")?.worker)
316}
317
318/// E44.
319pub fn send_instance_card(
320    client: &HiveClient,
321    keys: &InstanceKeys,
322    instance_id: &str,
323    consent_channel: ConsentChannel,
324    clear_presence_key: bool,
325) -> Result<InstanceCard, HiveError> {
326    let (status, answer) = card_exchange(
327        client,
328        keys,
329        instance_id,
330        consent_channel,
331        clear_presence_key,
332    )?;
333    card_from(status, answer)
334}
335
336fn card_exchange(
337    client: &HiveClient,
338    keys: &InstanceKeys,
339    instance_id: &str,
340    consent_channel: ConsentChannel,
341    clear_presence_key: bool,
342) -> Result<(u16, Value), HiveError> {
343    let body = instance_card_body(
344        keys,
345        env!("CARGO_PKG_VERSION"),
346        consent_channel,
347        clear_presence_key,
348    )?;
349    let path = format!("/instances/{instance_id}/card");
350    client.send_answer("PATCH", &path, Some(&body), MAX_ANSWER)
351}
352
353fn card_from(status: u16, answer: Value) -> Result<InstanceCard, HiveError> {
354    if !(200..300).contains(&status) {
355        let code = answer["error"]["code"].as_str().unwrap_or_default();
356        let reason = answer["error"]["reason"].as_str().unwrap_or_default();
357        return Err(worded(code, reason).map_or_else(
358            || HiveError::from_response(status, &answer),
359            HiveError::Config,
360        ));
361    }
362    parse(answer, "instance card")
363}
364
365#[cfg(test)]
366mod tests {
367    use super::super::card::{Availability, Budget};
368    use super::*;
369
370    const FIXTURES: &str = concat!(
371        env!("CARGO_MANIFEST_DIR"),
372        "/crates/lean-ctx-protocol/tests/fixtures/hive-v2/"
373    );
374
375    fn fixture(name: &str) -> Value {
376        let text = std::fs::read_to_string(format!("{FIXTURES}{name}")).unwrap();
377        serde_json::from_str(&text).unwrap()
378    }
379
380    fn instance_a() -> InstanceKeys {
381        InstanceKeys::from_seeds([0x49; 32], [0x01; 32])
382    }
383
384    #[test]
385    fn workspace_registration_matches_the_fixture_byte_for_byte() {
386        let card = WorkerCard::new(
387            "claude-code",
388            Some("claude-opus-5-5"),
389            ["ctx_read", "ctx_search", "ctx_shell"].map(String::from),
390            Budget {
391                tasks_per_day: Some(20),
392                usd_cents_per_day: None,
393            },
394            Availability::Online,
395        );
396        let body = register_body(
397            &instance_a(),
398            &Registration {
399                instance_id: "6f2b9c4e-1a3d-4e5f-8a7b-0c1d2e3f4a5b",
400                host_app: "claude-code",
401                role: "backend",
402                name: "yves-mac · Claude Code · backend",
403                card: &card,
404                alias_place: None,
405            },
406        )
407        .unwrap();
408        assert_eq!(body, fixture("routes/worker_register.request.json"));
409    }
410
411    #[test]
412    fn alias_registration_matches_the_fixture_byte_for_byte() {
413        let card = WorkerCard::new(
414            "codex",
415            None,
416            Vec::new(),
417            Budget::default(),
418            Availability::Idle,
419        );
420        let body = register_body(
421            &instance_a(),
422            &Registration {
423                instance_id: "6f2b9c4e-1a3d-4e5f-8a7b-0c1d2e3f4a5b",
424                host_app: "codex",
425                role: "general",
426                name: "Codex · general",
427                card: &card,
428                alias_place: Some("swarm:9a4d7e21-6b3c-4f58-8e09-1d2c3b4a5f02"),
429            },
430        )
431        .unwrap();
432        let want = fixture("routes/worker_register.alias.request.json");
433        assert_eq!(body, want);
434        // Nothing in the alias body names the instance.
435        assert!(!body.to_string().contains("6f2b9c4e"));
436    }
437
438    #[test]
439    fn instance_cards_match_the_fixtures_and_can_only_clear() {
440        let keys = instance_a();
441        assert_eq!(
442            instance_card_body(&keys, "3.12.0", ConsentChannel::OsPresence, false).unwrap(),
443            fixture("routes/instance_card.request.json")
444        );
445        assert_eq!(
446            instance_card_body(&keys, "3.12.0", ConsentChannel::TtyOnly, true).unwrap(),
447            fixture("routes/instance_card.clear.request.json")
448        );
449        let card: InstanceCard =
450            parse(fixture("routes/instance_card.response.json"), "card").unwrap();
451        assert_eq!(card.presence_key.unwrap().key_id, "ef1bd9c792ccc768");
452        assert_eq!(card.account.handle.as_deref(), Some("yves"));
453        // An account without a handle (dogfood finding 25.10.) still reads,
454        // and only the status decides the protocol.
455        let mut nameless = fixture("routes/instance_card.response.json");
456        nameless["account"]["handle"] = Value::Null;
457        let card = card_from(200, nameless).unwrap();
458        assert_eq!(card.account.handle, None);
459        assert!(card_from(404, json!({"error": {"code": "not_found"}})).is_err());
460    }
461
462    #[test]
463    fn a_mixed_alphabet_name_is_refused_before_it_leaves() {
464        let card = WorkerCard::new(
465            "codex",
466            None,
467            Vec::new(),
468            Budget::default(),
469            Availability::Idle,
470        );
471        let err = register_body(
472            &instance_a(),
473            &Registration {
474                instance_id: "6f2b9c4e-1a3d-4e5f-8a7b-0c1d2e3f4a5b",
475                host_app: "codex",
476                role: "general",
477                name: "аdmin",
478                card: &card,
479                alias_place: None,
480            },
481        )
482        .unwrap_err();
483        assert!(err.to_string().contains("invalid_name"), "{err}");
484    }
485
486    #[test]
487    fn refusals_reach_the_person_in_their_words() {
488        let locked = fixture("routes/instance_card.error.presence_key_locked.json");
489        let text = worded(
490            locked["error"]["code"].as_str().unwrap(),
491            locked["error"]["reason"].as_str().unwrap(),
492        )
493        .unwrap();
494        assert!(text.contains("--bind-presence-key"), "{text}");
495        assert_eq!(
496            worded("invalid_request", "confusable").unwrap(),
497            "This name mixes alphabets. Use one alphabet."
498        );
499        assert!(
500            worded("worker_not_owned", "")
501                .unwrap()
502                .starts_with("worker_not_owned")
503        );
504        assert_eq!(worded("invalid_request", "other"), None);
505    }
506
507    #[test]
508    fn responses_parse() {
509        let w: WorkerEnvelope =
510            parse(fixture("routes/worker_register.response.json"), "w").unwrap();
511        assert_eq!(w.worker.id, "wkr_vk4oelpv5lzjmev44hun");
512        let p: WorkerEnvelope = parse(fixture("routes/worker_patch.response.json"), "p").unwrap();
513        assert!(p.worker.name.contains("payments"));
514    }
515}