emelex 1.1.1

Apple Silicon local inference toolkit powered by MLX
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
//! High-level Emelex invocation facade.

use std::{
	path::{Path, PathBuf},
	sync::Arc,
};

use once_cell::sync::OnceCell;

use crate::{
	config::{Config, ConfigError, ConfigSources},
	home::{EmelexHome, HomeError},
	hub::{HubClient, HubCredentials, HubError},
	memory::{MemoryError, MemorySnapshotReferenceGuard, MemoryStore},
	model::{WorkloadError, WorkloadProfile},
	models::ModelManager,
	runtime::{self, RuntimeError},
};

/// One resolved Emelex invocation.
pub struct Emelex {
	home: EmelexHome,
	invocation_root: PathBuf,
	config: Config,
	config_sources: ConfigSources,
	hub: OnceCell<HubClient>,
	models: OnceCell<ModelManager>,
	memory: OnceCell<MemoryStore>,
	metal_budget_bytes: OnceCell<u64>,
	metal_budget_override: Option<u64>,
	hub_credentials: Option<HubCredentials>,
}

impl Emelex {
	/// Start configuring an invocation.
	pub fn builder() -> EmelexBuilder {
		EmelexBuilder::default()
	}

	/// Resolve defaults for the current directory.
	///
	/// # Errors
	///
	/// Returns home, working-directory, or configuration errors.
	pub fn current() -> Result<Self, ToolkitError> {
		Self::builder().build()
	}

	/// Selected Emelex Home.
	pub const fn home(&self) -> &EmelexHome {
		&self.home
	}

	/// Canonical directory from which this invocation started.
	pub fn invocation_root(&self) -> &Path {
		&self.invocation_root
	}

	/// Fully resolved immutable configuration.
	pub const fn config(&self) -> &Config {
		&self.config
	}

	/// Configuration files that contributed to this snapshot.
	pub const fn config_sources(&self) -> &ConfigSources {
		&self.config_sources
	}

	/// Static Hugging Face discovery client.
	///
	/// # Errors
	///
	/// Returns Hub-client initialization failures. This facet makes no
	/// machine-fit claim and does not query Metal.
	pub fn hub(&self) -> Result<&HubClient, ToolkitError> {
		self.hub.get_or_try_init(|| {
			Ok(match &self.hub_credentials {
				Some(credentials) => {
					HubClient::with_credentials(self.config.hub.clone(), credentials.clone())?
				}
				None => HubClient::new(self.config.hub.clone())?,
			})
		})
	}

	/// Owned-snapshot and external-link model manager.
	///
	/// # Errors
	///
	/// Returns Hub, workload, Metal budget, or model-policy initialization
	/// failures.
	pub fn models(&self) -> Result<&ModelManager, ToolkitError> {
		self.models.get_or_try_init(|| {
			let workload = WorkloadProfile::new(1, self.config.inference.context_tokens)?;
			let metal_budget_bytes = self.metal_budget_bytes()?;
			let hub = HubClient::with_local_search_profile(
				self.config.hub.clone(),
				workload,
				metal_budget_bytes,
				self.home.temp_dir(),
				self.hub_credentials.clone(),
			)?;
			Ok(ModelManager::new(
				self.home.clone(),
				self.config.clone(),
				hub,
				metal_budget_bytes,
			)?
			.with_reference_guard(Arc::new(MemorySnapshotReferenceGuard::new(&self.home))))
		})
	}

	/// Durable Sessions and workspace Knowledge.
	///
	/// # Errors
	///
	/// Returns durable-store initialization or migration failures.
	pub fn memory(&self) -> Result<&MemoryStore, ToolkitError> {
		self.memory
			.get_or_try_init(|| Ok(MemoryStore::open(&self.home)?))
	}

	/// Metal recommended working-set maximum used for fit reports.
	///
	/// # Errors
	///
	/// Returns an error when no supported Metal device is available.
	pub fn metal_budget_bytes(&self) -> Result<u64, ToolkitError> {
		self.metal_budget_bytes
			.get_or_try_init(|| {
				self.metal_budget_override.map_or_else(
					|| runtime::recommended_max_working_set_size().map_err(Into::into),
					Ok,
				)
			})
			.copied()
	}
}

/// Builder for one resolved Emelex invocation.
#[derive(Debug, Clone)]
pub struct EmelexBuilder {
	home: Option<PathBuf>,
	invocation_root: Option<PathBuf>,
	load_project_config: bool,
	metal_budget_bytes: Option<u64>,
	hub_credentials: HubCredentialSelection,
}

#[derive(Debug, Clone, Default)]
enum HubCredentialSelection {
	#[default]
	StoredFallback,
	Explicit(HubCredentials),
	Anonymous,
}

impl Default for EmelexBuilder {
	fn default() -> Self {
		Self {
			home: None,
			invocation_root: None,
			load_project_config: true,
			metal_budget_bytes: None,
			hub_credentials: HubCredentialSelection::StoredFallback,
		}
	}
}

impl EmelexBuilder {
	/// Select the sole storage root.
	#[must_use]
	pub fn home(mut self, path: impl Into<PathBuf>) -> Self {
		self.home = Some(path.into());
		self
	}

	/// Select the tool/configuration invocation directory.
	#[must_use]
	pub fn invocation_root(mut self, path: impl Into<PathBuf>) -> Self {
		self.invocation_root = Some(path.into());
		self
	}

	/// Enable or disable nearest-Git-root `.emelex.toml` loading.
	#[must_use]
	pub const fn project_config(mut self, enabled: bool) -> Self {
		self.load_project_config = enabled;
		self
	}

	/// Override Metal fit budget, primarily for deterministic embedding/tests.
	#[must_use]
	pub const fn metal_budget_bytes(mut self, bytes: u64) -> Self {
		self.metal_budget_bytes = Some(bytes);
		self
	}

	/// Use explicit Hugging Face credentials for this invocation's Hub facets.
	///
	/// Explicit credentials override any token in the global configuration.
	/// No environment variable is read by the library. Separate builders may
	/// therefore carry distinct credentials in the same process.
	#[must_use]
	pub fn hub_credentials(mut self, credentials: HubCredentials) -> Self {
		self.hub_credentials = HubCredentialSelection::Explicit(credentials);
		self
	}

	/// Suppress any global Hugging Face token for this invocation.
	#[must_use]
	pub fn anonymous_hub(mut self) -> Self {
		self.hub_credentials = HubCredentialSelection::Anonymous;
		self
	}

	/// Resolve invocation directory, storage root, and configuration.
	///
	/// Hub, Metal, model management, memory, and MLX remain uninitialized until
	/// their corresponding accessors or model operations are used.
	///
	/// # Errors
	///
	/// Returns home, directory, or configuration errors.
	pub fn build(self) -> Result<Emelex, ToolkitError> {
		let home = EmelexHome::resolve(self.home.as_deref())?;
		let invocation_root = if let Some(path) = self.invocation_root {
			std::fs::canonicalize(&path)
				.map_err(|source| ToolkitError::Directory { path, source })?
		} else {
			let current = std::env::current_dir().map_err(|source| ToolkitError::Directory {
				path: PathBuf::from("."),
				source,
			})?;
			std::fs::canonicalize(&current).map_err(|source| ToolkitError::Directory {
				path: current,
				source,
			})?
		};
		if !invocation_root.is_dir() {
			return Err(ToolkitError::Directory {
				path: invocation_root,
				source: std::io::Error::new(
					std::io::ErrorKind::InvalidInput,
					"invocation root is not a directory",
				),
			});
		}
		let loaded = Config::load_for_emelex(&home, &invocation_root, self.load_project_config)?;
		let hub_credentials = match self.hub_credentials {
			HubCredentialSelection::StoredFallback => loaded.hub_credentials,
			HubCredentialSelection::Explicit(credentials) => Some(credentials),
			HubCredentialSelection::Anonymous => None,
		};
		let config = loaded.config;
		let config_sources = loaded.sources;
		if self.metal_budget_bytes == Some(0) {
			return Err(ToolkitError::Configuration(
				"Metal budget override must be positive".to_string(),
			));
		}
		let metal_budget_override = self.metal_budget_bytes;
		Ok(Emelex {
			home,
			invocation_root,
			config,
			config_sources,
			hub: OnceCell::new(),
			models: OnceCell::new(),
			memory: OnceCell::new(),
			metal_budget_bytes: OnceCell::new(),
			metal_budget_override,
			hub_credentials,
		})
	}
}

/// High-level invocation construction failure.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ToolkitError {
	/// Home resolution/preparation failed.
	#[error(transparent)]
	Home(#[from] HomeError),
	/// Invocation directory failed validation.
	#[error("cannot use invocation directory {path:?}: {source}")]
	Directory {
		/// Requested path.
		path: PathBuf,
		/// Underlying error.
		#[source]
		source: std::io::Error,
	},
	/// Strict configuration failed.
	#[error(transparent)]
	Config(#[from] ConfigError),
	/// Hub client construction failed.
	#[error(transparent)]
	Hub(#[from] HubError),
	/// Durable memory initialization failed.
	#[error(transparent)]
	Memory(#[from] MemoryError),
	/// Model-manager policy was invalid.
	#[error(transparent)]
	Models(#[from] crate::models::ModelsError),
	/// Workload assumptions were invalid.
	#[error(transparent)]
	Workload(#[from] WorkloadError),
	/// Metal budget query failed.
	#[error(transparent)]
	Runtime(#[from] RuntimeError),
	/// Builder override was invalid.
	#[error("invalid Emelex builder configuration: {0}")]
	Configuration(String),
}

#[cfg(test)]
mod tests {
	#![allow(clippy::expect_used)]

	use super::*;

	#[test]
	fn facade_construction_and_static_hub_leave_memory_and_metal_lazy() {
		let directory = tempfile::tempdir().expect("temporary invocation root");
		let requested_home = directory.path().join("home");
		let emelex = Emelex::builder()
			.home(&requested_home)
			.invocation_root(directory.path())
			.metal_budget_bytes(123_456)
			.build()
			.expect("build invocation facade");
		let database = emelex.home().database_file();

		assert!(!database.exists());
		let _ = emelex.hub().expect("initialize static Hub client");
		assert!(!database.exists());
		assert_eq!(
			emelex
				.metal_budget_bytes()
				.expect("configured Metal budget"),
			123_456
		);
		assert!(!database.exists());

		let first = emelex.memory().expect("initialize memory");
		let second = emelex.memory().expect("reuse memory");
		assert!(std::ptr::eq(first, second));
		assert!(database.exists());
	}

	#[test]
	fn explicit_credentials_reach_both_lazy_hub_clients() {
		let directory = tempfile::tempdir().expect("temporary invocation root");
		let emelex = Emelex::builder()
			.home(directory.path().join("home"))
			.invocation_root(directory.path())
			.metal_budget_bytes(123_456)
			.hub_credentials(HubCredentials::bearer_token("hf_example").expect("valid credentials"))
			.build()
			.expect("build authenticated invocation facade");

		assert!(
			emelex
				.hub()
				.expect("initialize static Hub client")
				.is_authenticated()
		);
		assert!(
			emelex
				.models()
				.expect("initialize model manager")
				.hub()
				.is_authenticated()
		);
	}

	#[test]
	fn stored_global_credentials_reach_both_lazy_hub_clients() {
		let directory = tempfile::tempdir().expect("temporary invocation root");
		let home = EmelexHome::prepare(&directory.path().join("home")).expect("prepare home");
		Config::write_global_hub_token(&home, Some("hf_stored")).expect("store token");
		let emelex = Emelex::builder()
			.home(home.root())
			.invocation_root(directory.path())
			.metal_budget_bytes(123_456)
			.build()
			.expect("build authenticated invocation facade");

		assert!(
			emelex
				.hub()
				.expect("initialize static Hub client")
				.is_authenticated()
		);
		assert!(
			emelex
				.models()
				.expect("initialize model manager")
				.hub()
				.is_authenticated()
		);
	}

	#[test]
	fn explicit_anonymous_hub_suppresses_stored_credentials() {
		let directory = tempfile::tempdir().expect("temporary invocation root");
		let home = EmelexHome::prepare(&directory.path().join("home")).expect("prepare home");
		Config::write_global_hub_token(&home, Some("hf_stored")).expect("store token");
		let emelex = Emelex::builder()
			.home(home.root())
			.invocation_root(directory.path())
			.metal_budget_bytes(123_456)
			.anonymous_hub()
			.build()
			.expect("build anonymous invocation facade");

		assert!(
			!emelex
				.hub()
				.expect("initialize static Hub client")
				.is_authenticated()
		);
		assert!(
			!emelex
				.models()
				.expect("initialize model manager")
				.hub()
				.is_authenticated()
		);
	}

	#[test]
	fn builder_debug_redacts_explicit_credentials() {
		let token = "hf_builder_secret";
		let builder = Emelex::builder()
			.hub_credentials(HubCredentials::bearer_token(token).expect("valid credentials"));

		assert!(!format!("{builder:?}").contains(token));
	}

	#[test]
	fn zero_budget_override_fails_before_any_facet_activation() {
		let directory = tempfile::tempdir().expect("temporary invocation root");
		let error = Emelex::builder()
			.home(directory.path().join("home"))
			.invocation_root(directory.path())
			.metal_budget_bytes(0)
			.build()
			.err()
			.expect("zero budget must fail");
		assert!(matches!(error, ToolkitError::Configuration(_)));
	}
}