Skip to main content

nibkeep_node/library/
agents.rs

1//! AI agents on the user's own replica ([technical design: AI agents]): the person's
2//! consent, which `nib mcp enable` gives, and a key for each AI client, kept in this
3//! replica's folder sealed with its storage key, which signs the client's changes while the
4//! library acts as it.
5//!
6//! The record of each key is like a paired AI agent's replica's, on this replica's device,
7//! with no endpoint and no folder of its own: every replica treats its changes as a paired
8//! AI agent's, and nothing in the log's rules is new.
9//!
10//! [technical design: AI agents]: ../../../docs/Technical-design.md#14-ai-agents
11
12use std::fs::{self, File};
13use std::io;
14
15use nibkeep_base::cbor::{self, FromCbor, ToCbor, Value};
16use nibkeep_base::{EntityId, SpaceId};
17use nibkeep_crypto::rand_core::CryptoRng;
18use nibkeep_crypto::{DecryptionKey, Envelope, SigningKey, Zeroizing};
19use nibkeep_governance::{Listing, NewAgentKey, add_agent_key, replica_record};
20
21use super::Library;
22use crate::NodeError;
23use crate::info::write_file;
24
25/// The file, in a replica's folder, of the AI agents that the person allows on it.
26pub(crate) const AGENTS: &str = "agents.cbor";
27
28/// The lock that programs take while they read and change [`AGENTS`], so that two sessions
29/// of one client never make two keys.
30const AGENTS_LOCK: &str = "agents.lock";
31
32/// What the key that seals [`AGENTS`] is derived from the storage key with.
33const AGENTS_CONTEXT: &str = "nibkeep 2026-11 ai agents";
34
35/// What the file's envelope is bound to.
36const AGENTS_AAD: &[u8] = b"nibkeep 2026-11 ai agents file";
37
38/// The key that the library acts as, while an AI client works on it: its changes are signed
39/// with it.
40pub(crate) struct Acting {
41	/// The AI client's name.
42	pub(crate) name: String,
43	/// Its signing key.
44	pub(crate) signing: SigningKey,
45}
46
47/// An AI agent's key that this replica made.
48struct AgentKey {
49	name: String,
50	signing: SigningKey,
51	decryption: DecryptionKey,
52}
53
54/// What the file holds: whether the person allows AI agents here, and the keys made.
55#[derive(Default)]
56struct Agents {
57	allowed: bool,
58	keys: Vec<AgentKey>,
59}
60
61impl ToCbor for Agents {
62	fn to_cbor(&self) -> Value {
63		Value::Array(vec![
64			1u8.to_cbor(),
65			Value::Bool(self.allowed),
66			Value::Array(
67				self.keys
68					.iter()
69					.map(|key| {
70						Value::Array(vec![
71							key.name.to_cbor(),
72							Value::Bytes(key.signing.expose_bytes().to_vec()),
73							Value::Bytes(key.decryption.expose_seed().to_vec()),
74						])
75					})
76					.collect(),
77			),
78		])
79	}
80}
81
82impl FromCbor for Agents {
83	fn from_cbor(value: &Value) -> Result<Self, cbor::Error> {
84		const EXPECTED: &str = "AI agents: [1, allowed, [[name, signing, decryption], …]]";
85		let wrong = || cbor::Error::Expected(EXPECTED);
86		let Value::Array(items) = value else {
87			return Err(wrong());
88		};
89		let [suite, allowed, keys] = items.as_slice() else {
90			return Err(wrong());
91		};
92		if u8::from_cbor(suite) != Ok(1) {
93			return Err(wrong());
94		}
95		let Value::Array(keys) = keys else {
96			return Err(wrong());
97		};
98		let keys = keys
99			.iter()
100			.map(|key| {
101				let Value::Array(parts) = key else {
102					return Err(wrong());
103				};
104				let [name, Value::Bytes(signing), Value::Bytes(decryption)] = parts.as_slice()
105				else {
106					return Err(wrong());
107				};
108				let signing: [u8; 32] = signing.as_slice().try_into().map_err(|_| wrong())?;
109				let decryption: [u8; 32] = decryption.as_slice().try_into().map_err(|_| wrong())?;
110				Ok(AgentKey {
111					name: String::from_cbor(name)?,
112					signing: SigningKey::from_bytes(&signing),
113					decryption: DecryptionKey::from_seed(&decryption),
114				})
115			})
116			.collect::<Result<_, _>>()?;
117		Ok(Self {
118			allowed: bool::from_cbor(allowed)?,
119			keys,
120		})
121	}
122}
123
124impl Library {
125	/// Whether the person allowed AI agents on this replica, with `nib mcp enable`.
126	///
127	/// # Errors
128	///
129	/// Returns an error if the file of AI agents cannot be read.
130	pub fn ai_agents_enabled(&self) -> Result<bool, NodeError> {
131		Ok(self.read_agents()?.allowed)
132	}
133
134	/// Allows AI agents on this replica, as the person's consent: AI clients on this
135	/// computer may then work on it, each with a key of its own, in the personal space.
136	/// Keys of clients that were revoked since are forgotten, so that a client named as one
137	/// of them gets a new key.
138	///
139	/// # Errors
140	///
141	/// Returns [`NodeError::AiAgentMayNot`] if the library acts as an AI agent, and an error
142	/// if the file cannot be written.
143	pub fn enable_ai_agents(&mut self, rng: &mut impl CryptoRng) -> Result<(), NodeError> {
144		self.check_not_ai_agent("allow AI agents")?;
145		self.change_agents(rng, |library, agents| {
146			agents.allowed = true;
147			let personal = library.info.personal;
148			let mut kept = Vec::new();
149			for key in std::mem::take(&mut agents.keys) {
150				if !library.key_revoked(personal, &key.signing)? {
151					kept.push(key);
152				}
153			}
154			agents.keys = kept;
155			Ok(())
156		})
157	}
158
159	/// Withdraws the person's consent to AI agents on this replica, and revokes every key
160	/// that it made for them. Returns the names of the clients whose keys it revoked.
161	///
162	/// # Errors
163	///
164	/// Returns [`NodeError::AiAgentMayNot`] if the library acts as an AI agent, and an error
165	/// if a key cannot be revoked or the file written.
166	pub fn disable_ai_agents(
167		&mut self,
168		wall_millis: u64,
169		rng: &mut impl CryptoRng,
170	) -> Result<Vec<String>, NodeError> {
171		self.check_not_ai_agent("withdraw AI agents")?;
172		let personal = self.info.personal;
173		// Held throughout, so that no key made meanwhile is forgotten unrevoked.
174		let lock = self.lock_agents()?;
175		let agents = self.read_agents()?;
176		let mut revoking = Vec::new();
177		let mut names = Vec::new();
178		for key in &agents.keys {
179			if !self.key_revoked(personal, &key.signing)? {
180				revoking.push(replica_record(personal, &key.signing.verifying_key()));
181				names.push(key.name.clone());
182			}
183		}
184		if !revoking.is_empty() {
185			self.revoke(&revoking, wall_millis, rng)?;
186		}
187		self.write_agents(&Agents::default(), rng)?;
188		drop(lock);
189		Ok(names)
190	}
191
192	/// Acts as the AI client named `name` from now on, for as long as the library is open:
193	/// its key signs every change, the library refuses what an AI agent may not do, and it
194	/// keeps only the personal space, so that nothing reads another. The client's key is made
195	/// the first time, and listed by this replica.
196	///
197	/// # Errors
198	///
199	/// Returns [`NodeError::AiAgentsNotAllowedHere`] if the person did not allow AI agents here,
200	/// [`NodeError::AiAgentRevoked`] if the client's key was revoked, and an error if the key
201	/// cannot be made or listed.
202	pub fn act_as_ai_agent(
203		&mut self,
204		name: &str,
205		wall_millis: u64,
206		rng: &mut impl CryptoRng,
207	) -> Result<(), NodeError> {
208		if name.trim().is_empty() {
209			return Err(NodeError::AiAgentMayNot("go without a name"));
210		}
211		self.check_not_ai_agent("act as another AI agent")?;
212		let personal = self.info.personal;
213		let lock = self.lock_agents()?;
214		let mut agents = self.read_agents()?;
215		if !agents.allowed {
216			return Err(NodeError::AiAgentsNotAllowedHere);
217		}
218		let found = agents.keys.iter().position(|key| key.name == name);
219		if let Some(at) = found
220			&& self.key_revoked(personal, &agents.keys[at].signing)?
221		{
222			return Err(NodeError::AiAgentRevoked(name.to_owned()));
223		}
224		let at = found.unwrap_or_else(|| {
225			agents.keys.push(AgentKey {
226				name: name.to_owned(),
227				signing: SigningKey::generate(rng),
228				decryption: DecryptionKey::generate(rng),
229			});
230			agents.keys.len() - 1
231		});
232		if found.is_none() {
233			// Kept before it is listed, so that a listed key is never lost.
234			self.write_agents(&agents, rng)?;
235		}
236		let key = &agents.keys[at];
237		let signing = SigningKey::from_bytes(key.signing.expose_bytes());
238		// Listed unless it is already: also a key kept by a call whose listing failed.
239		if !self.key_listed(personal, &signing)? {
240			let encryption = key.decryption.encryption_key();
241			let listing =
242				Listing::sign(&signing, &encryption, personal, (self.info.user, true)).to_text();
243			let (_, mut operations, ordinary) = add_agent_key(
244				&NewAgentKey {
245					space: personal,
246					user: self.info.user,
247					signing: &signing.verifying_key(),
248					encryption: &encryption,
249					device: self.info.device,
250					name,
251					listing: &listing,
252				},
253				rng,
254			);
255			operations.extend(ordinary);
256			self.commit(personal, operations, wall_millis, rng)?;
257		}
258		drop(lock);
259		self.spaces.retain(|&space, _| space == personal);
260		self.chosen = None;
261		self.acting = Some(Acting {
262			name: name.to_owned(),
263			signing,
264		});
265		Ok(())
266	}
267
268	/// The name of the AI client that the library acts as, if it does.
269	#[must_use]
270	pub fn acting_as(&self) -> Option<&str> {
271		self.acting.as_ref().map(|acting| acting.name.as_str())
272	}
273
274	/// The key that signs this library's changes: the AI client's that it acts as, or else
275	/// this replica's own.
276	pub(crate) fn author_key(&self) -> &SigningKey {
277		self.acting
278			.as_ref()
279			.map_or(&self.replica.signing, |acting| &acting.signing)
280	}
281
282	/// Whether a counting change lists `key` in `space`.
283	fn key_listed(&self, space: SpaceId, key: &SigningKey) -> Result<bool, NodeError> {
284		let open = self.space(space)?;
285		Ok(open
286			.stored
287			.log()
288			.is_listed(&key.verifying_key(), &open.keys)?)
289	}
290
291	/// Whether `key` was revoked in `space`.
292	fn key_revoked(&self, space: SpaceId, key: &SigningKey) -> Result<bool, NodeError> {
293		let open = self.space(space)?;
294		Ok(open
295			.stored
296			.log()
297			.is_revoked(&key.verifying_key(), &open.keys)?)
298	}
299
300	/// The record of the key of the AI client named `name`, if this replica made one.
301	///
302	/// # Errors
303	///
304	/// Returns an error if the file of AI agents cannot be read.
305	pub fn ai_agent_record(&self, name: &str) -> Result<Option<EntityId>, NodeError> {
306		let personal = self.info.personal;
307		Ok(self
308			.read_agents()?
309			.keys
310			.iter()
311			.find(|key| key.name == name)
312			.map(|key| replica_record(personal, &key.signing.verifying_key())))
313	}
314
315	/// Takes the lock on the file of AI agents, which closing the returned file lets go of.
316	fn lock_agents(&self) -> Result<File, NodeError> {
317		let path = self.directory.join(AGENTS_LOCK);
318		let lock = File::options()
319			.create(true)
320			.truncate(false)
321			.write(true)
322			.open(&path)
323			.map_err(NodeError::file(&path))?;
324		lock.lock().map_err(NodeError::file(&path))?;
325		Ok(lock)
326	}
327
328	/// Changes the file of AI agents under its lock.
329	fn change_agents(
330		&mut self,
331		rng: &mut impl CryptoRng,
332		change: impl FnOnce(&mut Self, &mut Agents) -> Result<(), NodeError>,
333	) -> Result<(), NodeError> {
334		let lock = self.lock_agents()?;
335		let mut agents = self.read_agents()?;
336		change(self, &mut agents)?;
337		self.write_agents(&agents, rng)?;
338		drop(lock);
339		Ok(())
340	}
341
342	/// The file of AI agents, or none allowed where there is no file.
343	fn read_agents(&self) -> Result<Agents, NodeError> {
344		let path = self.directory.join(AGENTS);
345		let bytes = match fs::read(&path) {
346			Ok(bytes) => bytes,
347			Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Agents::default()),
348			Err(error) => return Err(NodeError::file(&path)(error)),
349		};
350		let unreadable = || {
351			NodeError::file(&path)(io::Error::new(
352				io::ErrorKind::InvalidData,
353				"the file of AI agents does not read",
354			))
355		};
356		let envelope: Envelope = cbor::from_slice(&bytes).map_err(|_| unreadable())?;
357		let plain: Zeroizing<Vec<u8>> = envelope
358			.open(&self.derived_key(AGENTS_CONTEXT), AGENTS_AAD)
359			.map_err(|_| unreadable())?;
360		cbor::from_slice(&plain).map_err(|_| unreadable())
361	}
362
363	/// Writes the file of AI agents, sealed with a key derived from the storage key.
364	fn write_agents(&self, agents: &Agents, rng: &mut impl CryptoRng) -> Result<(), NodeError> {
365		let plain = Zeroizing::new(cbor::to_vec(agents));
366		let envelope = Envelope::seal(&self.derived_key(AGENTS_CONTEXT), &plain, AGENTS_AAD, rng);
367		write_file(&self.directory.join(AGENTS), &cbor::to_vec(&envelope))
368	}
369}