omp-app 0.1.0

Production command-line application and daemon for OMP inference
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
//! Command parsing and production dispatch for the `omp` executable.

use std::{
	collections::BTreeSet,
	path::{Path, PathBuf},
	sync::Arc,
	time::{SystemTime, UNIX_EPOCH},
};

use clap::{Args, Parser, Subcommand};
use futures::{StreamExt as _, stream};
use omp_core::Str;
use omp_llm_broker::cli::{self as broker_cli, AuthCli, AuthCommand};
use omp_llm_catalog::models::import_catalog_zstd;
use omp_llm_gateway::local::LocalEndpoint;
use omp_llm_local::{Embedded, Inference, TextModel, TextSelection};
use omp_llm_types::{
	Chat, ChatRequest, Item, ItemKind, Message, Part, Props, Role, StreamPartKind, Thread, TurnEvent,
};
use omp_proto::inference::v1::{
	TurnFrame, inference_client::InferenceClient, turn_event, turn_frame,
};
use tokio::io::AsyncWriteExt as _;

use crate::{
	auth_backend,
	daemon::{DaemonConfig, DaemonHandle},
	error::AppError,
};

/// Top-level parser for the production `omp` executable.
#[derive(Clone, Debug, Parser)]
#[command(name = "omp", version, about = "OMP inference and credential management")]
pub struct OmpCli {
	/// Operation to run.
	#[command(subcommand)]
	pub command: Command,
}

/// Production application commands.
#[derive(Clone, Debug, Subcommand)]
pub enum Command {
	/// Start the inference gateway on a platform-native local endpoint.
	Serve(ServeArgs),
	/// Run one stateless turn through a running gateway.
	Infer(InferArgs),
	/// Manage provider credentials in the local broker store.
	Auth(AuthArgs),
	/// Manage generated model-catalog data.
	Catalog(CatalogArgs),
	/// Run hardware-accelerated inference in this process.
	Local(LocalArgs),
}

/// Gateway serving options.
#[derive(Clone, Debug, Args)]
pub struct ServeArgs {
	/// Platform-local endpoint: a Unix socket path or Windows named-pipe name.
	#[arg(long = "endpoint", visible_aliases = ["uds", "pipe"], value_name = "LOCAL_ENDPOINT")]
	pub endpoint: LocalEndpoint,
	/// Override the directory containing daemon state.
	#[arg(long, value_name = "PATH")]
	pub data_dir: Option<PathBuf>,
}

/// Direct gateway inference options.
#[derive(Clone, Debug, Args)]
pub struct InferArgs {
	/// Platform-local endpoint of the running gateway.
	#[arg(long = "endpoint", visible_aliases = ["uds", "pipe"], value_name = "LOCAL_ENDPOINT")]
	pub endpoint: LocalEndpoint,
	/// Catalog model id, alias, or role.
	#[arg(long)]
	pub model:    Str,
	/// User prompt for the stateless turn.
	#[arg(long)]
	pub prompt:   Str,
}

/// Broker command and durable-state options.
#[derive(Clone, Debug, Args)]
pub struct AuthArgs {
	/// OMP data directory containing `broker.db`.
	#[arg(long, value_name = "PATH")]
	pub data_dir: Option<PathBuf>,
	/// Authentication operation.
	#[command(subcommand)]
	pub command:  AuthCommand,
}

/// Model-catalog command tree.
#[derive(Clone, Debug, Args)]
pub struct CatalogArgs {
	/// Catalog operation.
	#[command(subcommand)]
	pub command: CatalogCommand,
}

/// Model-catalog operations.
#[derive(Clone, Debug, Subcommand)]
pub enum CatalogCommand {
	/// Normalize and compress a generated source catalog.
	Import(CatalogImportArgs),
}

/// Catalog import paths.
#[derive(Clone, Debug, Args)]
pub struct CatalogImportArgs {
	/// Generated source JSON.
	#[arg(long, value_name = "JSON")]
	pub source:      PathBuf,
	/// Destination zstd catalog payload.
	#[arg(long, value_name = "ZST")]
	pub destination: PathBuf,
}

/// In-process local inference command tree.
#[derive(Clone, Debug, Args)]
pub struct LocalArgs {
	/// Local inference operation.
	#[command(subcommand)]
	pub command: LocalCommand,
}

/// Local inference operations.
#[derive(Clone, Debug, Subcommand)]
pub enum LocalCommand {
	/// Generate one complete local response.
	Infer(LocalInferArgs),
}

/// In-process text generation options.
#[derive(Clone, Debug, Args)]
pub struct LocalInferArgs {
	/// Backend selection: `auto`, `foundation`, or a local GGUF path.
	#[arg(long, default_value = "auto", value_name = "BACKEND_OR_GGUF")]
	pub model:  Str,
	/// User prompt.
	#[arg(long)]
	pub prompt: Str,
}

#[cfg(test)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum DispatchTarget {
	Serve,
	Infer,
	Auth,
	CatalogImport,
	LocalInfer,
}

#[cfg(test)]
const fn dispatch_target(command: &Command) -> DispatchTarget {
	match command {
		Command::Serve(_) => DispatchTarget::Serve,
		Command::Infer(_) => DispatchTarget::Infer,
		Command::Auth(_) => DispatchTarget::Auth,
		Command::Catalog(CatalogArgs { command: CatalogCommand::Import(_) }) => {
			DispatchTarget::CatalogImport
		},
		Command::Local(LocalArgs { command: LocalCommand::Infer(_) }) => DispatchTarget::LocalInfer,
	}
}

/// Dispatches one parsed command to its production implementation.
pub async fn dispatch(cli: OmpCli) -> crate::Result<()> {
	match cli.command {
		Command::Serve(args) => serve(args).await,
		Command::Infer(args) => infer(args).await,
		Command::Auth(args) => auth(args).await,
		Command::Catalog(CatalogArgs { command: CatalogCommand::Import(args) }) => {
			catalog_import(&args)
		},
		Command::Local(LocalArgs { command: LocalCommand::Infer(args) }) => local_infer(args).await,
	}
}

async fn serve(args: ServeArgs) -> crate::Result<()> {
	let config = match args.data_dir {
		Some(data_dir) => DaemonConfig::local(args.endpoint).with_data_dir(data_dir),
		None => DaemonConfig::local(args.endpoint),
	};
	let handle = DaemonHandle::start(config).await?;
	handle.wait().await?;
	Ok(())
}

async fn infer(args: InferArgs) -> crate::Result<()> {
	let channel = omp_llm_gateway::local::connect(&args.endpoint)
		.await
		.map_err(|source| AppError::ConnectGateway { endpoint: args.endpoint.clone(), source })?;
	omp_rpc::handshake(channel.clone(), "omp-cli", &["inference"]).await?;
	let request = ChatRequest::builder()
		.model(args.model)
		.thread(
			Thread::builder()
				.items(vec![user_item(args.prompt)])
				.build(),
		)
		.tools(Vec::new())
		.build();
	let mut open: omp_proto::inference::v1::TurnRequest = request.into();
	open.turn_id = turn_id();
	let frame = TurnFrame { frame: Some(turn_frame::Frame::Open(open)) };
	let mut events = InferenceClient::new(channel)
		.turn(stream::iter([frame]))
		.await?
		.into_inner();
	let mut terminal = false;
	let mut stdout = tokio::io::stdout();
	while let Some(event) = events.next().await {
		match event?.event {
			Some(turn_event::Event::PartDelta(delta)) => stdout.write_all(&delta.chunk).await?,
			Some(turn_event::Event::Outcome(_)) => terminal = true,
			Some(turn_event::Event::Error(error)) => {
				return Err(AppError::InferenceFailed { detail: Str::from(error.detail) });
			},
			_ => {},
		}
	}
	if !terminal {
		return Err(AppError::InferenceStreamUnterminated);
	}
	stdout.write_all(b"\n").await?;
	stdout.flush().await?;
	Ok(())
}

fn user_item(prompt: Str) -> Item {
	Item::builder()
		.seq(0)
		.kind(ItemKind::Message(
			Message::builder()
				.role(Role::User)
				.parts(vec![Part::Text(prompt)])
				.build(),
		))
		.props(Props::default())
		.build()
}

fn turn_id() -> String {
	let now = SystemTime::now()
		.duration_since(UNIX_EPOCH)
		.unwrap_or_default()
		.as_nanos();
	format!("cli-{}-{now}", std::process::id())
}

async fn auth(args: AuthArgs) -> crate::Result<()> {
	validate_auth(&args.command)?;
	let database = data_dir(args.data_dir)?.join("broker.db");
	let backend = auth_backend::open(&database)?;
	let output = broker_cli::run(&backend, &AuthCli { command: args.command }).await?;
	println!("{output}");
	Ok(())
}

const fn validate_auth(command: &AuthCommand) -> crate::Result<()> {
	if let AuthCommand::Migrate(args) = command
		&& args.sqlite.is_none()
		&& args.json_file.is_none()
	{
		return Err(AppError::AuthMigrateArgsRequired);
	}
	Ok(())
}

fn data_dir(explicit: Option<PathBuf>) -> crate::Result<PathBuf> {
	if let Some(path) = explicit {
		return Ok(path);
	}
	if let Some(path) = std::env::var_os("OMP_DATA_DIR") {
		return Ok(path.into());
	}
	let home = std::env::var_os("HOME").ok_or(AppError::DataDirNotConfigured)?;
	Ok(PathBuf::from(home).join(".local/share/omp"))
}

fn catalog_import(args: &CatalogImportArgs) -> crate::Result<()> {
	if same_path(&args.source, &args.destination) {
		return Err(AppError::SameCatalogSourceAndDestination);
	}
	let input = std::fs::read(&args.source)
		.map_err(|source| AppError::ReadCatalogSource { path: args.source.clone(), source })?;
	let payload = import_catalog_zstd(&input)?;
	if let Some(parent) = args.destination.parent()
		&& !parent.as_os_str().is_empty()
	{
		std::fs::create_dir_all(parent)?;
	}
	std::fs::write(&args.destination, payload).map_err(|source| {
		AppError::WriteCatalogDestination { path: args.destination.clone(), source }
	})?;
	Ok(())
}

fn same_path(left: &Path, right: &Path) -> bool {
	left == right
		|| left
			.canonicalize()
			.ok()
			.zip(right.canonicalize().ok())
			.is_some_and(|(left, right)| left == right)
}

async fn local_infer(args: LocalInferArgs) -> crate::Result<()> {
	let selection = match args.model.as_str() {
		"auto" => TextSelection::Auto,
		"foundation" => TextSelection::FoundationModels,
		path => TextSelection::Gguf(TextModel::Local(PathBuf::from(path))),
	};
	let inference = Arc::new(Inference::builder().text(selection).build().await?);
	let embedded = Embedded::new(Arc::clone(&inference));
	let request = ChatRequest::builder()
		.model(Str::new_static("local/default"))
		.thread(
			Thread::builder()
				.items(vec![user_item(args.prompt)])
				.build(),
		)
		.tools(Vec::new())
		.build();
	let mut events = embedded.turn(request, None).await?;
	let mut text_parts = BTreeSet::new();
	let mut terminal = false;
	let mut stdout = tokio::io::stdout();
	while let Some(event) = events.next().await {
		match event {
			TurnEvent::PartStart { index, kind: StreamPartKind::Text, .. } => {
				text_parts.insert(index);
			},
			TurnEvent::PartDelta { index, chunk } if text_parts.contains(&index) => {
				stdout.write_all(&chunk).await?;
			},
			TurnEvent::PartEnd { index, .. } => {
				text_parts.remove(&index);
			},
			TurnEvent::Outcome(_) => terminal = true,
			TurnEvent::Error(error) => {
				return Err(AppError::InferenceFailed { detail: error.detail });
			},
			_ => {},
		}
	}
	if !terminal {
		return Err(AppError::LocalInferenceStreamUnterminated);
	}
	stdout.write_all(b"\n").await?;
	stdout.flush().await?;
	inference.shutdown().await?;
	Ok(())
}

#[cfg(test)]
mod tests {
	use clap::error::ErrorKind;

	use super::*;

	fn parse(arguments: &[&str]) -> OmpCli {
		OmpCli::try_parse_from(arguments).expect("valid command")
	}

	#[cfg(unix)]
	const TEST_ENDPOINT: &str = "/tmp/omp.sock";
	#[cfg(windows)]
	const TEST_ENDPOINT: &str = r"\\.\pipe\omp-cli-test";

	#[test]
	fn parses_every_dispatch_branch() {
		let cases = [
			(&["omp", "serve", "--endpoint", TEST_ENDPOINT][..], DispatchTarget::Serve),
			(
				&["omp", "infer", "--endpoint", TEST_ENDPOINT, "--model", "slow", "--prompt", "hello"]
					[..],
				DispatchTarget::Infer,
			),
			(&["omp", "auth", "list"][..], DispatchTarget::Auth),
			(
				&[
					"omp",
					"catalog",
					"import",
					"--source",
					"models.json",
					"--destination",
					"models.json.zst",
				][..],
				DispatchTarget::CatalogImport,
			),
			(&["omp", "local", "infer", "--prompt", "hello"][..], DispatchTarget::LocalInfer),
		];
		for (arguments, expected) in cases {
			assert_eq!(dispatch_target(&parse(arguments).command), expected);
		}
	}

	#[cfg(windows)]
	#[test]
	fn parses_windows_named_pipe_alias_and_uri() {
		for arguments in [
			&["omp", "serve", "--pipe", r"\\.\pipe\omp-cli-test"][..],
			&["omp", "serve", "--endpoint", "npipe://./pipe/omp-cli-test"][..],
		] {
			let Command::Serve(args) = parse(arguments).command else {
				panic!("serve command");
			};
			assert_eq!(args.endpoint.as_path(), Path::new(r"\\.\pipe\omp-cli-test"));
		}
	}

	#[test]
	fn rejects_incomplete_and_conflicting_commands() {
		for arguments in [
			&["omp", "serve"][..],
			&["omp", "infer", "--model", "slow", "--prompt", "hello"][..],
			&["omp", "local", "infer"][..],
			&["omp", "catalog", "import", "--source", "models.json"][..],
		] {
			assert_eq!(
				OmpCli::try_parse_from(arguments)
					.expect_err("command must be rejected")
					.kind(),
				ErrorKind::MissingRequiredArgument
			);
		}
	}

	#[test]
	fn catalog_import_rejects_overwriting_its_source() {
		let args =
			CatalogImportArgs { source: "models.json".into(), destination: "models.json".into() };
		assert!(catalog_import(&args).is_err());
	}

	#[test]
	fn auth_migrate_rejects_an_empty_source_set() {
		let command = parse(&["omp", "auth", "migrate"]).command;
		let Command::Auth(args) = command else {
			panic!("auth command");
		};
		assert!(validate_auth(&args.command).is_err());
	}
}