1#![allow(clippy::print_stdout, clippy::print_stderr)]
4#![allow(deprecated)]
8
9use crate::services::event_network::ensure_event_origin_for_profile;
10#[cfg(feature = "experimental")]
11use crate::storage::GitRef;
12use crate::storage::ModelRef;
13use anyhow::{bail, Result};
14use hyprstream_rpc::events::EventSubscriber;
15use hyprstream_rpc::prelude::*;
16use hyprstream_rpc::streaming::StreamPayload;
17use hyprstream_rpc_std::inference_client::ChatMessage;
18use hyprstream_rpc_std::inference_client::GenerationRequest;
19use hyprstream_rpc_std::model_client::ChatTemplateRequest;
20use hyprstream_rpc_std::model_client::{
21 LoadModelRequest, ModelClient, StatusRequest, UnloadModelRequest,
22};
23#[cfg(feature = "experimental")]
24use hyprstream_rpc_std::registry_client::FileChangeType;
25use hyprstream_rpc_std::registry_client::RegistryClient;
26use hyprstream_rpc_std::registry_client::{
27 BranchRequest, CheckoutRequest, CloneRequest, CreateWorktreeRequest, RemoveWorktreeRequest,
28 UpdateRequest,
29};
30use std::io::{self, Write};
31use std::path::PathBuf;
32use tracing::{debug, info, warn};
33
34pub async fn handle_branch(
36 registry: &RegistryClient,
37 model: &str,
38 branch_name: &str,
39 from_ref: Option<String>,
40 policy_template: Option<String>,
41) -> Result<()> {
42 info!("Creating branch {} for model {}", branch_name, model);
43
44 let tracked = registry
45 .get_by_name(model)
46 .await
47 .map_err(|e| anyhow::anyhow!("Failed to get repository client: {}", e))?;
48 let repo_client = registry.repo(&tracked.id);
49
50 repo_client
52 .create_branch(&BranchRequest {
53 branch_name: branch_name.to_owned(),
54 start_point: from_ref.as_deref().unwrap_or("").to_owned(),
55 })
56 .await
57 .map_err(|e| anyhow::anyhow!("Failed to create branch '{}': {}", branch_name, e))?;
58
59 println!("✓ Created branch {branch_name}");
60
61 if let Some(ref from) = from_ref {
62 println!(" Branch created from: {from}");
63 }
64
65 repo_client
67 .create_worktree(&CreateWorktreeRequest {
68 branch: branch_name.to_owned(),
69 })
70 .await
71 .map_err(|e| anyhow::anyhow!("Failed to create worktree: {}", e))?;
72 println!("✓ Created worktree for branch {branch_name}");
73
74 if let Some(ref template_name) = policy_template {
76 apply_policy_template_to_model(registry, model, template_name).await?;
77 }
78
79 println!("\n→ Next steps:");
81 println!(" hyprstream worktree info {model} {branch_name}");
82 println!(" hyprstream status {model}:{branch_name}");
83 println!(" hyprstream lt {model}:{branch_name} --adapter my-adapter");
84
85 Ok(())
86}
87
88pub async fn handle_checkout(
90 registry: &RegistryClient,
91 model_ref_str: &str,
92 create_branch: bool,
93 force: bool,
94) -> Result<()> {
95 let model_ref = ModelRef::parse(model_ref_str)?;
97
98 info!(
99 "Checking out {} for model {}",
100 model_ref.git_ref.to_string(),
101 model_ref.model
102 );
103
104 let tracked = registry
106 .get_by_name(&model_ref.model)
107 .await
108 .map_err(|e| anyhow::anyhow!("Failed to get repository client: {}", e))?;
109 let repo_client = registry.repo(&tracked.id);
110
111 if !force {
113 let status = repo_client
114 .status()
115 .await
116 .map_err(|e| anyhow::anyhow!("Failed to get status: {}", e))?;
117 if !status.is_clean {
118 println!("Warning: Model has uncommitted changes");
119 println!("Use --force to discard changes, or commit them first");
120 return Ok(());
121 }
122 }
123
124 let previous_oid = repo_client
126 .get_head()
127 .await
128 .unwrap_or_else(|_| "unknown".to_owned());
129
130 let ref_spec = match &model_ref.git_ref {
132 crate::storage::GitRef::Branch(name) => name.clone(),
133 crate::storage::GitRef::Tag(name) => format!("refs/tags/{name}"),
134 crate::storage::GitRef::Commit(oid) => oid.to_string(),
135 crate::storage::GitRef::DefaultBranch => "HEAD".to_owned(),
136 crate::storage::GitRef::Revspec(spec) => spec.clone(),
137 };
138
139 if create_branch {
141 if let crate::storage::GitRef::Branch(name) = &model_ref.git_ref {
142 repo_client
143 .create_branch(&BranchRequest {
144 branch_name: name.to_owned(),
145 start_point: previous_oid.clone(),
146 })
147 .await
148 .map_err(|e| anyhow::anyhow!("Failed to create branch: {}", e))?;
149 }
150 }
151
152 let worktree_name = match &model_ref.git_ref {
155 crate::storage::GitRef::Branch(name) => name.clone(),
156 _ => tracked.tracking_ref.clone(),
157 };
158 repo_client
159 .worktree(&worktree_name)
160 .checkout(&CheckoutRequest {
161 ref_name: ref_spec.clone(),
162 create_branch: false,
163 })
164 .await
165 .map_err(|e| anyhow::anyhow!("Failed to checkout '{}': {}", ref_spec, e))?;
166
167 let new_oid = repo_client
169 .get_head()
170 .await
171 .unwrap_or_else(|_| "unknown".to_owned());
172
173 let ref_display = model_ref.git_ref.to_string();
175 println!(
176 "✓ Switched to {} ({})",
177 ref_display,
178 &new_oid[..8.min(new_oid.len())]
179 );
180
181 if force {
182 println!(" ⚠️ Forced checkout - local changes discarded");
183 }
184
185 Ok(())
186}
187
188pub async fn handle_status(
190 registry: &RegistryClient,
191 model: Option<String>,
192 verbose: bool,
193) -> Result<()> {
194 if let Some(model_ref_str) = model {
195 let model_ref = ModelRef::parse(&model_ref_str)?;
197 let tracked = registry
198 .get_by_name(&model_ref.model)
199 .await
200 .map_err(|e| anyhow::anyhow!("Failed to get repository client: {}", e))?;
201 let repo_client = registry.repo(&tracked.id);
202 let status = repo_client
203 .status()
204 .await
205 .map_err(|e| anyhow::anyhow!("Failed to get status: {}", e))?;
206 print_model_status(&model_ref.model, &status, verbose);
207 } else {
208 let repos = registry
210 .list()
211 .await
212 .map_err(|e| anyhow::anyhow!("Failed to list repositories: {}", e))?;
213
214 if repos.is_empty() {
215 println!("No models found");
216 return Ok(());
217 }
218
219 for tracked in repos {
220 if !tracked.name.is_empty() {
221 let name = &tracked.name;
222 let repo_client = registry.repo(&tracked.id);
223 if let Ok(status) = repo_client.status().await {
224 print_model_status(name, &status, verbose);
225 println!(); }
227 }
228 }
229 }
230
231 Ok(())
232}
233
234#[cfg(feature = "experimental")]
238fn status_char(s: FileChangeType) -> char {
239 match s {
240 FileChangeType::None => ' ',
241 FileChangeType::Added => 'A',
242 FileChangeType::Modified => 'M',
243 FileChangeType::Deleted => 'D',
244 FileChangeType::Renamed => 'R',
245 FileChangeType::Untracked => '?',
246 FileChangeType::TypeChanged => 'T',
247 FileChangeType::Conflicted => 'U',
248 }
249}
250
251#[cfg(feature = "experimental")]
253pub async fn handle_commit(
254 registry: &RegistryClient,
255 model_ref_str: &str,
256 message: &str,
257 all: bool,
258 all_untracked: bool,
259 amend: bool,
260 author: Option<String>,
261 author_name: Option<String>,
262 author_email: Option<String>,
263 allow_empty: bool,
264 dry_run: bool,
265 verbose: bool,
266) -> Result<()> {
267 info!("Committing changes to model {}", model_ref_str);
268
269 let model_ref = ModelRef::parse(model_ref_str)?;
271
272 let tracked = registry
274 .get_by_name(&model_ref.model)
275 .await
276 .map_err(|e| anyhow::anyhow!("Failed to get repository client: {}", e))?;
277 let repo_client = registry.repo(&tracked.id);
278
279 let branch_name = match &model_ref.git_ref {
281 crate::storage::GitRef::Branch(name) => name.clone(),
282 crate::storage::GitRef::DefaultBranch => repo_client
283 .get_head()
284 .await
285 .map_err(|e| anyhow::anyhow!("Failed to get default branch: {}", e))?,
286 crate::storage::GitRef::Tag(tag) => {
287 anyhow::bail!(
288 "Cannot commit to a tag reference. Tags are immutable.\nTag: {}\nUse a branch instead: {}:main",
289 tag, model_ref.model
290 );
291 }
292 crate::storage::GitRef::Commit(oid) => {
293 anyhow::bail!(
294 "Cannot commit to a detached HEAD (commit reference).\nCommit: {}\nCheckout a branch first: hyprstream checkout {}:main",
295 oid, model_ref.model
296 );
297 }
298 crate::storage::GitRef::Revspec(spec) => {
299 anyhow::bail!(
300 "Cannot commit to a revspec reference. Revspecs are for querying history.\nRevspec: {}\nUse a branch instead: {}:main",
301 spec, model_ref.model
302 );
303 }
304 };
305
306 let wts = repo_client.list_worktrees().await?;
308 if !wts.iter().any(|wt| wt.branch_name == branch_name) {
309 anyhow::bail!(
310 "Worktree '{}' does not exist for model '{}'.\n\nCreate it first with:\n hyprstream branch {} {}",
311 branch_name, model_ref.model, model_ref.model, branch_name
312 );
313 }
314
315 let detailed_status = repo_client.detailed_status().await?;
317 let has_changes = !detailed_status.files.is_empty();
318
319 if !allow_empty && !amend && !has_changes && !all_untracked {
320 println!(
321 "No changes to commit for {}:{}",
322 model_ref.model, branch_name
323 );
324 println!("\nUse --allow-empty to create a commit without changes");
325 return Ok(());
326 }
327
328 if verbose || dry_run {
330 println!("\n→ Changes to be committed:");
331
332 if all || all_untracked {
333 for file in &detailed_status.files {
335 println!(
336 " {}{} {}",
337 status_char(file.index_status),
338 status_char(file.worktree_status),
339 file.path
340 );
341 }
342 } else {
343 for file in detailed_status
345 .files
346 .iter()
347 .filter(|f| !matches!(f.index_status, FileChangeType::None))
348 {
349 println!(" {} {}", status_char(file.index_status), file.path);
350 }
351 }
352 println!();
353 }
354
355 if dry_run {
357 println!("→ Dry run mode - no commit will be created\n");
358 println!("Would commit to: {}:{}", model_ref.model, branch_name);
359 println!("Message: {}", message);
360
361 if let Some(ref auth) = author {
362 println!("Author: {}", auth);
363 } else if author_name.is_some() || author_email.is_some() {
364 println!(
365 "Author: {} <{}>",
366 author_name.as_deref().unwrap_or("default"),
367 author_email.as_deref().unwrap_or("default")
368 );
369 }
370
371 if amend {
372 println!("Mode: Amend previous commit");
373 }
374
375 return Ok(());
376 }
377
378 let wt = repo_client.worktree(&branch_name);
380
381 if all_untracked {
383 info!("Staging all files including untracked");
385 wt.stage_all_including_untracked().await?;
386 } else if all {
387 info!("Staging all tracked files");
389 wt.stage_all().await?;
390 }
391
392 let commit_oid = if amend {
394 info!("Amending previous commit");
395 wt.amend_commit(message).await?
396 } else if author.is_some() || author_name.is_some() || author_email.is_some() {
397 let (name, email) = if let Some(author_str) = author {
399 let re = regex::Regex::new(r"^(.+?)\s*<(.+?)>$")?;
400 if let Some(captures) = re.captures(&author_str) {
401 let name = captures
402 .get(1)
403 .ok_or_else(|| anyhow::anyhow!("Invalid author format: missing name"))?
404 .as_str()
405 .trim()
406 .to_owned();
407 let email = captures
408 .get(2)
409 .ok_or_else(|| anyhow::anyhow!("Invalid author format: missing email"))?
410 .as_str()
411 .trim()
412 .to_owned();
413 (name, email)
414 } else {
415 anyhow::bail!(
416 "Invalid author format. Expected: \"Name <email>\"\nGot: {}",
417 author_str
418 );
419 }
420 } else {
421 let name = author_name.ok_or_else(|| {
422 anyhow::anyhow!("--author-name required when using --author-email")
423 })?;
424 let email = author_email.ok_or_else(|| {
425 anyhow::anyhow!("--author-email required when using --author-name")
426 })?;
427 (name, email)
428 };
429
430 wt.commit_with_author(message, &name, &email).await?
431 } else {
432 wt.stage_all().await?;
434 wt.commit(message).await?
435 };
436
437 println!("✓ Committed changes to {}:{}", model_ref.model, branch_name);
439 println!(" Message: {}", message);
440 println!(" Commit: {}", commit_oid);
441
442 if amend {
443 println!(" ⚠️ Previous commit amended");
444 }
445
446 Ok(())
447}
448
449#[cfg(feature = "experimental")]
462pub async fn handle_promote(
463 registry: &RegistryClient,
464 model_ref_str: &str,
465 branch: &str,
466 author_name: Option<String>,
467 author_email: Option<String>,
468) -> Result<()> {
469 use crate::git::promote::{promote, PromoteAuthor, PromoteError, PromoteLeaseTable};
470 use std::sync::Arc;
471
472 info!("Promoting {} (branch {})", model_ref_str, branch);
473
474 let model_ref = ModelRef::parse(model_ref_str)?;
475 let tracked = registry
476 .get_by_name(&model_ref.model)
477 .await
478 .map_err(|e| anyhow::anyhow!("Failed to get repository client: {}", e))?;
479 let repo_client = registry.repo(&tracked.id);
480 let wt = repo_client.worktree(branch);
481
482 let author = PromoteAuthor {
483 name: author_name.unwrap_or_else(|| "hyprstream".to_owned()),
484 email: author_email.unwrap_or_else(|| "promote@hyprstream.local".to_owned()),
485 };
486
487 let lease_table = Arc::new(PromoteLeaseTable::new());
491
492 match promote(&model_ref.model, branch, &wt, &author, &lease_table).await {
493 Ok(outcome) => {
494 println!("✓ Promoted {} ({})", model_ref_str, branch);
495 println!(" Commit: {}", outcome.commit_oid);
496 if outcome.pointer_advanced {
497 println!(" atproto pointer advanced");
498 }
499 Ok(())
500 }
501 Err(PromoteError::LeaseHeld(_)) => {
502 anyhow::bail!(
503 "another promote is in progress for {}/{}",
504 model_ref.model,
505 branch
506 )
507 }
508 Err(PromoteError::LocalCommit(e)) => {
509 anyhow::bail!("promote failed during local commit: {e}")
510 }
511 Err(PromoteError::PointerStale(e)) => {
512 warn!(
514 model = %model_ref.model, branch, error = %e,
515 "promote: content committed but atproto pointer is stale; next promote will advance it"
516 );
517 println!(
518 "⚠ Promoted {} ({}) — content committed, pointer stale",
519 model_ref_str, branch
520 );
521 println!(" The atproto pointer will advance on the next successful promote.");
522 Ok(())
523 }
524 }
525}
526
527fn print_model_status(
529 model_name: &str,
530 status: &hyprstream_rpc_std::registry_client::RepositoryStatus,
531 verbose: bool,
532) {
533 println!("Model: {model_name}");
534
535 if !status.branch.is_empty() {
537 if !status.head_oid.is_empty() {
538 println!("Current ref: {} ({})", status.branch, status.head_oid);
539 } else {
540 println!("Current ref: {}", status.branch);
541 }
542 } else if !status.head_oid.is_empty() {
543 println!("Current ref: detached HEAD ({})", status.head_oid);
544 } else {
545 println!("Current ref: unknown");
546 }
547
548 if status.ahead > 0 || status.behind > 0 {
550 println!("Tracking: ahead {}, behind {}", status.ahead, status.behind);
551 }
552
553 if !status.is_clean {
555 println!("Status: modified (uncommitted changes)");
556
557 if verbose || !status.modified_files.is_empty() {
558 println!("\n Modified files:");
559 for file in &status.modified_files {
560 println!(" M {}", file);
561 }
562 }
563 } else {
564 println!("Status: clean");
565 }
566}
567
568pub fn parse_filters(raw: &[String]) -> Result<Vec<(String, regex::Regex)>> {
576 const VALID_KEYS: &[&str] = &["name", "domains", "access", "ref", "commit", "size"];
577 let mut out = Vec::with_capacity(raw.len());
578 for s in raw {
579 let (k, v) = s
580 .split_once('=')
581 .ok_or_else(|| anyhow::anyhow!("--filter '{}': expected KEY=REGEX format", s))?;
582 let key = k.to_lowercase();
583 if key == "status" {
584 anyhow::bail!(
585 "--filter '{}': 'status' cannot be used with --filter. Use --status/-s instead (e.g. -s loaded,loading)",
586 s
587 );
588 }
589 if !VALID_KEYS.contains(&key.as_str()) {
590 anyhow::bail!(
591 "--filter '{}': unknown column '{}'. Valid columns: {}",
592 s,
593 key,
594 VALID_KEYS.join(", ")
595 );
596 }
597 let re = regex::Regex::new(v).map_err(|e| {
598 anyhow::anyhow!("--filter '{}': invalid regex pattern '{}': {}", s, v, e)
599 })?;
600 out.push((key, re));
601 }
602 Ok(out)
603}
604
605pub fn parse_status_filter(raw: &[String]) -> Result<std::collections::HashSet<String>> {
612 const VALID: &[&str] = &["loaded", "loading", "unloaded"];
613 let mut out = std::collections::HashSet::new();
614 for s in raw {
615 for part in s.split(',') {
616 let val = part.trim().to_lowercase();
617 if val.is_empty() {
618 continue;
619 }
620 if !VALID.contains(&val.as_str()) {
621 anyhow::bail!(
622 "--status '{}': unknown status '{}'. Valid values: {}",
623 s,
624 val,
625 VALID.join(", ")
626 );
627 }
628 out.insert(val);
629 }
630 }
631 Ok(out)
632}
633
634pub async fn handle_list(
635 registry: &RegistryClient,
636 model_client: ModelClient,
637 filters: &[(String, regex::Regex)],
638 status_filter: &std::collections::HashSet<String>,
639) -> Result<()> {
640 info!("Listing models");
641
642 let all_status_req = StatusRequest {
644 model_ref: String::new(),
645 };
646 let (repos_result, status_result) =
647 tokio::join!(registry.list(), model_client.status(&all_status_req),);
648
649 let repos = repos_result.map_err(|e| anyhow::anyhow!("Failed to list repositories: {}", e))?;
650
651 if repos.is_empty() {
652 println!("No models found.");
653 println!("Try: hyprstream clone https://huggingface.co/Qwen/Qwen3-0.6B");
654 return Ok(());
655 }
656
657 let status_map: std::collections::HashMap<String, String> = match status_result {
659 Ok(entries) => entries
660 .into_iter()
661 .map(|e| (e.model_ref, e.status))
662 .collect(),
663 Err(e) => {
664 warn!("Model service unavailable for status: {}", e);
665 std::collections::HashMap::new()
666 }
667 };
668
669 struct RowInfo {
670 display_name: String,
671 domains_str: String,
672 access_str: String,
673 git_ref: String,
674 commit: String,
675 load_status: String,
676 size_str: String,
677 }
678
679 let mut rows = Vec::new();
680
681 for tracked in repos {
682 if tracked.name.is_empty() {
683 continue;
684 }
685 let name = &tracked.name;
686
687 for wt in &tracked.worktrees {
688 let branch_name = if wt.branch_name.is_empty() {
689 "detached".to_owned()
690 } else {
691 wt.branch_name.clone()
692 };
693 let display_name = format!("{}:{}", name, branch_name);
694 let commit = wt.head_oid.chars().take(7).collect::<String>();
695
696 let domains_str = if wt.capabilities.is_empty() {
698 "n/a".to_owned()
699 } else {
700 wt.capabilities.join(",")
701 };
702 let access_str = domains_str.clone();
704
705 let model_ref = format!("{}:{}", name, branch_name);
707 let load_status = status_map
708 .get(&model_ref)
709 .cloned()
710 .unwrap_or_else(|| "unloaded".to_owned());
711
712 let size_str = "n/a".to_owned();
713
714 rows.push(RowInfo {
715 display_name,
716 domains_str,
717 access_str,
718 git_ref: branch_name,
719 commit,
720 load_status,
721 size_str,
722 });
723 }
724 }
725
726 let rows: Vec<_> = if status_filter.is_empty() {
728 rows
729 } else {
730 rows.into_iter()
731 .filter(|r| status_filter.contains(r.load_status.as_str()))
732 .collect()
733 };
734
735 let rows: Vec<_> = rows
737 .into_iter()
738 .filter(|r| {
739 filters.iter().all(|(key, re)| {
740 let haystack = match key.as_str() {
741 "name" => &r.display_name,
742 "domains" => &r.domains_str,
743 "access" => &r.access_str,
744 "ref" => &r.git_ref,
745 "commit" => &r.commit,
746 "size" => &r.size_str,
747 _ => return true,
748 };
749 re.is_match(haystack)
750 })
751 })
752 .collect();
753
754 if rows.is_empty() {
755 println!("No models match the given filters.");
756 return Ok(());
757 }
758
759 println!(
760 "{:<35} {:<16} {:<15} {:<8} {:<10}",
761 "MODEL NAME", "DOMAINS", "REF", "COMMIT", "STATUS"
762 );
763 println!("{}", "-".repeat(90));
764
765 for r in &rows {
766 println!(
767 "{:<35} {:<16} {:<15} {:<8} {:<10}",
768 r.display_name, r.domains_str, r.git_ref, r.commit, r.load_status
769 );
770 }
771
772 Ok(())
773}
774
775#[allow(clippy::too_many_arguments)]
777pub async fn handle_clone(
778 registry: &RegistryClient,
779 repo_url: &str,
780 name: Option<String>,
781 branch: Option<String>,
782 depth: u32,
783 full: bool,
784 quiet: bool,
785 verbose: bool,
786 policy_template: Option<String>,
787) -> Result<()> {
788 if !quiet {
789 info!("Cloning model from {}", repo_url);
790 println!("📦 Cloning model from: {repo_url}");
791
792 if let Some(ref b) = branch {
793 println!(" Branch: {b}");
794 }
795
796 if full {
797 println!(" Mode: Full history");
798 } else if depth > 0 {
799 println!(" Depth: {depth} commits");
800 }
801
802 if verbose {
803 println!(" Verbose output enabled");
804 }
805 }
806
807 let model_name = if let Some(n) = name {
809 n
810 } else {
811 let extracted = repo_url
812 .split('/')
813 .next_back()
814 .unwrap_or("")
815 .trim_end_matches(".git")
816 .to_owned();
817
818 if extracted.is_empty() {
819 anyhow::bail!(
820 "Cannot derive model name from URL '{}'. Please provide --name.",
821 repo_url
822 );
823 }
824 extracted
825 };
826
827 let shallow = !full;
829 let clone_depth = if full { 0 } else { depth };
830
831 let clone_result = clone_with_streaming(
833 registry,
834 repo_url,
835 &model_name,
836 shallow,
837 clone_depth,
838 branch.as_deref(),
839 quiet,
840 verbose,
841 )
842 .await;
843
844 if let Err(e) = clone_result {
846 if verbose {
847 warn!(
848 "Streaming clone failed, falling back to non-streaming: {}",
849 e
850 );
851 }
852 registry
853 .clone(&CloneRequest {
854 url: repo_url.to_owned(),
855 name: model_name.clone(),
856 shallow,
857 depth: clone_depth,
858 branch: branch.as_deref().unwrap_or("").to_owned(),
859 })
860 .await
861 .map_err(|e| anyhow::anyhow!("Failed to clone model: {}", e))?;
862 }
863
864 let tracked = registry
866 .get_by_name(&model_name)
867 .await
868 .map_err(|e| anyhow::anyhow!("Failed to get repository client: {}", e))?;
869 let repo_client = registry.repo(&tracked.id);
870
871 let worktree_branch = if let Some(ref b) = branch {
874 b.clone()
875 } else if !tracked.tracking_ref.is_empty() {
876 tracked.tracking_ref.clone()
877 } else {
878 "main".to_owned()
879 };
880
881 if !quiet {
882 println!(" Creating worktree for branch: {worktree_branch}");
883 }
884 repo_client
885 .create_worktree(&CreateWorktreeRequest {
886 branch: worktree_branch.clone(),
887 })
888 .await
889 .map_err(|e| anyhow::anyhow!("Failed to create worktree: {}", e))?;
890
891 if !quiet {
892 println!("✅ Model '{}' cloned successfully!", model_name);
893 println!("✓ Worktree: {model_name}:{worktree_branch}");
894 }
895
896 if let Some(ref template_name) = policy_template {
898 apply_policy_template_to_model(registry, &model_name, template_name).await?;
899 }
900
901 Ok(())
902}
903
904#[allow(clippy::too_many_arguments)]
908async fn clone_with_streaming(
909 registry: &RegistryClient,
910 repo_url: &str,
911 model_name: &str,
912 shallow: bool,
913 depth: u32,
914 branch: Option<&str>,
915 quiet: bool,
916 verbose: bool,
917) -> Result<()> {
918 use hyprstream_rpc_std::registry_client::RegistryRpc;
919 let mut stream_handle = RegistryRpc::clone_stream(
920 registry,
921 &CloneRequest {
922 url: repo_url.to_owned(),
923 name: model_name.to_owned(),
924 shallow,
925 depth,
926 branch: branch.unwrap_or("").to_owned(),
927 },
928 )
929 .await
930 .map_err(|e| anyhow::anyhow!("Failed to start streaming clone: {}", e))?;
931
932 if !quiet {
933 print!(" Progress: ");
934 io::stdout().flush()?;
935 }
936
937 let mut current_stage = String::new();
939 loop {
940 match stream_handle.recv_next().await? {
941 Some(StreamPayload::Data(data)) => {
942 if let Ok(text) = String::from_utf8(data) {
944 if !quiet {
945 let parts: Vec<&str> = text.split(':').collect();
947 if parts.len() >= 3 {
948 let stage = parts[0];
949 let current = parts[1];
950 let total = parts[2];
951
952 let is_transition = stage != current_stage;
954 if is_transition {
955 if !current_stage.is_empty() && !verbose {
956 println!();
957 }
958 let stage_label = match stage {
959 "fetch" => "Fetching objects",
960 "indexing" => "Indexing",
961 "smudge" => "Downloading model files",
962 "lfs" => "Downloading LFS files",
963 other => other,
964 };
965 current_stage = stage.to_owned();
966 if verbose {
967 println!(" {stage_label}...");
968 } else {
969 print!(" {stage_label}...");
970 io::stdout().flush()?;
971 }
972 }
973
974 if verbose && !is_transition {
975 if total == "0" {
976 println!(" {}: {} files", stage, current);
978 } else {
979 println!(" {}: {}/{}", stage, current, total);
980 }
981 } else if !verbose {
982 print!(".");
983 io::stdout().flush()?;
984 }
985 } else {
986 if verbose {
988 println!("\r {}", text);
989 }
990 }
991 }
992 }
993 }
994 Some(StreamPayload::Complete(_metadata)) => {
995 if !quiet {
996 println!(" done");
997 }
998 break;
999 }
1000 Some(StreamPayload::Error(message)) => {
1001 if !quiet {
1002 println!(" error");
1003 }
1004 return Err(anyhow::anyhow!("Clone stream error: {}", message));
1005 }
1006 Some(StreamPayload::Tagged { .. }) => {
1007 }
1009 None => {
1010 if !quiet {
1012 println!(" done");
1013 }
1014 break;
1015 }
1016 }
1017 }
1018
1019 Ok(())
1020}
1021
1022pub async fn handle_info(
1026 registry: &RegistryClient,
1027 model: &str,
1028 verbose: bool,
1029 adapters_only: bool,
1030) -> Result<()> {
1031 info!("Getting info for model {}", model);
1032
1033 let model_ref = ModelRef::parse(model)?;
1034
1035 let tracked_repo = registry
1037 .get_by_name(&model_ref.model)
1038 .await
1039 .map_err(|e| anyhow::anyhow!("Failed to get repository client: {}", e))?;
1040 let repo_client = registry.repo(&tracked_repo.id);
1041
1042 let repo_metadata = {
1044 let remotes = repo_client.list_remotes().await.ok();
1046 let url = remotes
1047 .as_ref()
1048 .and_then(|r| r.iter().find(|remote| remote.name == "origin"))
1049 .map(|remote| remote.url.clone())
1050 .unwrap_or_else(|| "unknown".to_owned());
1051
1052 let current_oid = repo_client.get_head().await.ok();
1054
1055 Some((
1056 Some(model_ref.model.clone()),
1057 url,
1058 model_ref.git_ref.to_string(),
1059 current_oid,
1060 ))
1061 };
1062
1063 let branch_name = match &model_ref.git_ref {
1065 crate::storage::GitRef::DefaultBranch => repo_client
1066 .get_head()
1067 .await
1068 .unwrap_or_else(|_| "main".to_owned()),
1069 crate::storage::GitRef::Branch(b) => b.clone(),
1070 _ => "main".to_owned(),
1071 };
1072
1073 let storage_paths = crate::storage::StoragePaths::new()?;
1075 let model_path = storage_paths
1076 .worktree_path(&model_ref.model, &branch_name)
1077 .unwrap_or_else(|_| PathBuf::from("."));
1078
1079 if !adapters_only {
1081 println!("Model: {}", model_ref.model);
1082
1083 if let Some((name, url, tracking_ref, current_oid)) = &repo_metadata {
1085 if let Some(n) = name {
1086 if n != &model_ref.model {
1087 println!(" Registry name: {n}");
1088 }
1089 }
1090 println!(" Origin URL: {url}");
1091 println!(" Tracking ref: {tracking_ref}");
1092 if let Some(oid) = current_oid {
1093 println!(" Current OID: {}", &oid[..8.min(oid.len())]);
1094 }
1095 }
1096
1097 let display_ref = match &model_ref.git_ref {
1099 crate::storage::GitRef::DefaultBranch => repo_client
1100 .get_head()
1101 .await
1102 .unwrap_or_else(|_| "unknown".to_owned()),
1103 _ => model_ref.git_ref.to_string(),
1104 };
1105
1106 println!("Reference: {display_ref}");
1107 println!("Path: {}", model_path.display());
1108
1109 let archetype_registry = crate::archetypes::global_registry();
1111 let detected = archetype_registry.detect(&model_path);
1112
1113 if !detected.is_empty() {
1114 println!("\nArchetypes:");
1115 for archetype in &detected.archetypes {
1116 println!(" - {archetype}");
1117 }
1118 println!("Capabilities: {}", detected.capabilities);
1119 } else {
1120 println!("\nArchetypes: None detected");
1121 }
1122 }
1123
1124 println!("\nRepository Information:");
1126
1127 if let Ok(remotes) = repo_client.list_remotes().await {
1129 if !remotes.is_empty() {
1130 for remote in remotes {
1131 println!(" Remote '{}': {}", remote.name, remote.url);
1132 }
1133 }
1134 }
1135
1136 if let Ok(branches) = repo_client.list_branches().await {
1138 if !branches.is_empty() {
1139 println!(" Local branches: {}", branches.join(", "));
1140 }
1141 }
1142
1143 if let Ok(tags) = repo_client.list_tags().await {
1145 if !tags.is_empty() {
1146 println!(" Tags: {}", tags.join(", "));
1147 }
1148 }
1149
1150 let bare_repo_path = storage_paths.models_dir().ok().map(|d| {
1152 d.join(&model_ref.model)
1153 .join(format!("{}.git", model_ref.model))
1154 });
1155
1156 if let Some(ref bare_repo_path) = bare_repo_path {
1157 if bare_repo_path.exists() {
1158 if let Ok(metadata) = std::fs::metadata(bare_repo_path) {
1159 if metadata.is_dir() {
1160 let mut total_size = 0u64;
1161 if let Ok(entries) = walkdir::WalkDir::new(bare_repo_path)
1162 .into_iter()
1163 .collect::<std::result::Result<Vec<_>, _>>()
1164 {
1165 for entry in entries {
1166 if entry.file_type().is_file() {
1167 if let Ok(meta) = entry.metadata() {
1168 total_size += meta.len();
1169 }
1170 }
1171 }
1172 }
1173 println!(
1174 " Repository size: {:.2} MB",
1175 total_size as f64 / 1_048_576.0
1176 );
1177 }
1178 }
1179 }
1180 }
1181
1182 println!("\nWorktree Status:");
1184
1185 match repo_client.status().await {
1186 Ok(status) => {
1187 println!(
1188 " Current branch/ref: {}",
1189 if status.branch.is_empty() {
1190 "detached"
1191 } else {
1192 &status.branch
1193 }
1194 );
1195
1196 if !status.head_oid.is_empty() {
1197 println!(
1198 " HEAD commit: {}",
1199 &status.head_oid[..8.min(status.head_oid.len())]
1200 );
1201 }
1202
1203 if !status.is_clean {
1204 println!(" Working tree: dirty");
1205 println!(" Modified files: {}", status.modified_files.len());
1206 if verbose {
1207 for file in &status.modified_files {
1210 println!(" M {}", file);
1211 }
1212 }
1213 } else {
1214 println!(" Working tree: clean");
1215 }
1216 }
1217 Err(e) => {
1218 println!(" Unable to get status: {e}");
1219 debug!("Status error details: {:?}", e);
1220 }
1221 }
1222
1223 if let Ok(metadata) = std::fs::metadata(&model_path) {
1225 if metadata.is_dir() {
1226 let mut total_size = 0u64;
1228 let mut file_count = 0u32;
1229
1230 if let Ok(entries) = std::fs::read_dir(&model_path) {
1231 for entry in entries.flatten() {
1232 if let Ok(meta) = entry.metadata() {
1233 if meta.is_file() {
1234 total_size += meta.len();
1235 file_count += 1;
1236 }
1237 }
1238 }
1239 }
1240
1241 println!("\nModel Size:");
1242 println!(" Files: {file_count}");
1243 println!(" Total size: {:.2} MB", total_size as f64 / 1_048_576.0);
1244 }
1245 }
1246
1247 let adapter_manager = crate::storage::AdapterManager::new(&model_path);
1249
1250 match adapter_manager.list_adapters() {
1251 Ok(adapters) => {
1252 if adapters.is_empty() {
1253 println!("\nAdapters: None");
1254 } else {
1255 println!("\nAdapters: {}", adapters.len());
1256
1257 let mut sorted_adapters = adapters;
1259 sorted_adapters.sort_by_key(|a| a.index);
1260
1261 for adapter in &sorted_adapters {
1262 let size_kb = adapter.size as f64 / 1024.0;
1263 print!(" [{}] {} ({:.1} KB)", adapter.index, adapter.name, size_kb);
1264
1265 if let (true, Some(config_path)) = (verbose, adapter.config_path.as_ref()) {
1267 if let Ok(config_content) = std::fs::read_to_string(config_path) {
1268 if let Ok(config) = serde_json::from_str::<crate::storage::AdapterConfig>(
1269 &config_content,
1270 ) {
1271 print!(
1272 " - rank: {}, alpha: {}, lr: {:.0e}",
1273 config.rank, config.alpha, config.learning_rate
1274 );
1275 }
1276 }
1277 }
1278 println!();
1279 }
1280
1281 if verbose {
1282 println!("\nAdapter Details:");
1283 for adapter in &sorted_adapters {
1284 println!(" [{}] {}", adapter.index, adapter.name);
1285 println!(" File: {}", adapter.filename);
1286 println!(" Path: {}", adapter.path.display());
1287 println!(" Size: {:.1} KB", adapter.size as f64 / 1024.0);
1288
1289 if let Some(config_path) = &adapter.config_path {
1290 println!(" Config: {}", config_path.display());
1291 if let Ok(config_content) = std::fs::read_to_string(config_path) {
1292 if let Ok(config) =
1293 serde_json::from_str::<crate::storage::AdapterConfig>(
1294 &config_content,
1295 )
1296 {
1297 println!(" Rank: {}", config.rank);
1298 println!(" Alpha: {}", config.alpha);
1299 println!(" Learning Rate: {:.2e}", config.learning_rate);
1300 println!(" Created: {}", config.created_at);
1301 }
1302 }
1303 } else {
1304 println!(" Config: Not found");
1305 }
1306 println!();
1307 }
1308 }
1309 }
1310 }
1311 Err(e) => {
1312 if verbose {
1313 println!("\nAdapters: Error listing adapters: {e}");
1314 } else {
1315 println!("\nAdapters: Unable to list");
1316 }
1317 }
1318 }
1319
1320 Ok(())
1321}
1322
1323pub async fn apply_policy_template_to_model(
1328 registry: &RegistryClient,
1329 model: &str,
1330 template_name: &str,
1331) -> Result<()> {
1332 use crate::auth::PolicyManager;
1333 use crate::cli::policy_handlers::get_template;
1334 use std::process::Command;
1335
1336 let template = get_template(template_name)
1337 .ok_or_else(|| anyhow::anyhow!(
1338 "Unknown policy template: '{}'. Available templates: local, public-inference, public-read",
1339 template_name
1340 ))?;
1341
1342 let _tracked = registry
1344 .get_by_name(model)
1345 .await
1346 .map_err(|e| anyhow::anyhow!("Failed to get repository: {}", e))?;
1347
1348 let storage_paths = crate::storage::StoragePaths::new()?;
1350 let models_dir = storage_paths.models_dir()?;
1351
1352 let registry_path = models_dir.join(".registry");
1353 let policies_dir = registry_path.join("policies");
1354
1355 if !policies_dir.exists() {
1357 tokio::fs::create_dir_all(&policies_dir).await?;
1358 }
1359
1360 let policy_path = policies_dir.join("policy.csv");
1361
1362 let existing_content = if policy_path.exists() {
1364 tokio::fs::read_to_string(&policy_path).await?
1365 } else {
1366 default_policy_header().to_owned()
1367 };
1368
1369 let rules = template.to_csv();
1371 if existing_content.contains(rules.trim()) {
1372 println!("✓ Policy template '{template_name}' already applied");
1373 return Ok(());
1374 }
1375
1376 let new_content = format!("{}\n{}", existing_content.trim_end(), rules);
1378
1379 crate::auth::write_policy_file(&policy_path, &new_content)
1381 .await
1382 .map_err(|e| anyhow::anyhow!("Failed to write policy: {}", e))?;
1383
1384 let policy_manager = PolicyManager::new(&policies_dir)
1386 .await
1387 .map_err(|e| anyhow::anyhow!("Failed to validate policy: {}", e))?;
1388
1389 if let Err(e) = policy_manager.reload().await {
1391 let _ = crate::auth::write_policy_file(&policy_path, &existing_content).await;
1393 bail!("Policy validation failed: {}. Template not applied.", e);
1394 }
1395
1396 let commit_msg = format!("policy: apply {template_name} template for model {model}");
1398
1399 Command::new("git")
1400 .current_dir(®istry_path)
1401 .args(["add", "policies/"])
1402 .output()
1403 .ok();
1404
1405 Command::new("git")
1406 .current_dir(®istry_path)
1407 .args(["commit", "-m", &commit_msg])
1408 .output()
1409 .ok();
1410
1411 println!("✓ Applied policy template: {template_name}");
1412 println!(" {}", template.description);
1413
1414 Ok(())
1415}
1416
1417fn default_policy_header() -> &'static str {
1419 r#"# Hyprstream Access Control Policy
1420# Format: p, subject, resource, action
1421#
1422# Subjects: user names or role names
1423# Resources: model:<name>, data:<name>, or * for all
1424# Actions: infer, train, query, write, serve, manage, or * for all
1425"#
1426}
1427
1428#[allow(clippy::too_many_arguments)]
1440pub async fn handle_infer(
1441 model_ref_str: &str,
1442 prompt: &str,
1443 image_path: Option<String>,
1444 max_tokens: Option<usize>,
1445 temperature: Option<f32>,
1446 top_p: Option<f32>,
1447 top_k: Option<usize>,
1448 repeat_penalty: Option<f32>,
1449 seed: Option<u32>,
1450 sync: bool,
1451 signing_key: SigningKey,
1452) -> Result<()> {
1453 info!(
1454 "Running inference via ModelService: model={}, prompt_len={}",
1455 model_ref_str,
1456 prompt.len()
1457 );
1458
1459 let _ = ModelRef::parse(model_ref_str)?;
1461
1462 let model_client = ModelClient::from_provider(
1464 &hyprstream_discovery::ProductionRpcClientProvider,
1465 signing_key.clone(),
1466 None,
1467 )?;
1468
1469 let messages = vec![ChatMessage {
1471 role: "user".to_owned(),
1472 content: prompt.to_owned(),
1473 tool_calls: vec![],
1474 tool_call_id: String::new(),
1475 }];
1476
1477 let formatted_prompt = match model_client
1478 .infer(model_ref_str)
1479 .apply_chat_template(&ChatTemplateRequest {
1480 messages: messages.clone(),
1481 add_generation_prompt: true,
1482 tools_json: Some(String::new()),
1483 max_tokens: None,
1484 enable_thinking: None,
1485 template_vars_json: None,
1486 })
1487 .await
1488 {
1489 Ok(prompt_str) => crate::config::TemplatedPrompt::new(prompt_str),
1490 Err(e) => {
1491 tracing::warn!("Could not apply chat template: {}. Using raw prompt.", e);
1492 crate::config::TemplatedPrompt::new(prompt.to_owned())
1493 }
1494 };
1495
1496 let mut request = GenerationRequest {
1498 prompt: formatted_prompt.into_inner(),
1499 max_tokens: Some(max_tokens.unwrap_or(2048) as u32),
1500 temperature,
1501 top_p,
1502 top_k: top_k.map(|v| v as u32),
1503 repeat_penalty,
1504 seed,
1505 ..Default::default()
1506 };
1507
1508 if let Some(img_path) = image_path {
1510 info!("Using image: {}", img_path);
1511 let img_bytes = std::fs::read(&img_path)
1512 .map_err(|e| anyhow::anyhow!("Failed to read image {}: {}", img_path, e))?;
1513 request.images = Some(vec![img_bytes]);
1514 }
1515
1516 info!(
1517 "Generating response: max_tokens={:?}, temperature={:?}, top_p={:?}, top_k={:?}, repeat_penalty={:?}",
1518 request.max_tokens, request.temperature, request.top_p, request.top_k, request.repeat_penalty
1519 );
1520
1521 if !sync {
1523 use hyprstream_rpc_std::model_client::InferRpc;
1525 let mut stream_handle =
1526 InferRpc::generate_stream(&model_client.infer(model_ref_str), &request).await?;
1527
1528 println!();
1529
1530 loop {
1532 match stream_handle.recv_next().await? {
1533 Some(StreamPayload::Data(data)) => {
1534 if let Ok(text) = String::from_utf8(data) {
1536 print!("{text}");
1537 io::stdout().flush()?;
1538 }
1539 }
1540 Some(StreamPayload::Complete(_metadata)) => {
1541 break;
1543 }
1544 Some(StreamPayload::Error(message)) => {
1545 warn!("Stream error: {}", message);
1546 bail!("Inference stream error: {}", message);
1547 }
1548 Some(StreamPayload::Tagged { .. }) => {
1549 }
1551 None => {
1552 break;
1554 }
1555 }
1556 }
1557
1558 println!();
1559 } else {
1560 use hyprstream_rpc_std::model_client::InferRpc;
1562 let mut handle =
1563 InferRpc::generate_stream(&model_client.infer(model_ref_str), &request).await?;
1564
1565 let mut text = String::new();
1566 loop {
1567 match handle.recv_next().await? {
1568 Some(payload) => match payload {
1569 StreamPayload::Data(data) => {
1570 text.push_str(&String::from_utf8_lossy(&data));
1571 }
1572 StreamPayload::Complete(meta) => {
1573 let stats: crate::services::rpc_types::InferenceComplete =
1574 serde_json::from_slice(&meta).unwrap_or_else(|e| {
1575 warn!("Failed to parse InferenceComplete: {e}");
1576 crate::services::rpc_types::InferenceComplete::empty()
1577 });
1578 println!("\n{}", text);
1579 info!(
1580 "Generated {} tokens in {}ms ({:.2} tokens/sec overall)",
1581 stats.tokens_generated,
1582 stats.generation_time_ms,
1583 stats.tokens_per_second
1584 );
1585 info!(
1586 " Prefill: {} tokens in {}ms ({:.2} tokens/sec)",
1587 stats.prefill_tokens,
1588 stats.prefill_time_ms,
1589 stats.prefill_tokens_per_sec
1590 );
1591 info!(
1592 " Inference: {} tokens in {}ms ({:.2} tokens/sec)",
1593 stats.inference_tokens,
1594 stats.inference_time_ms,
1595 stats.inference_tokens_per_sec
1596 );
1597 break;
1598 }
1599 StreamPayload::Error(msg) => {
1600 bail!("Generation error: {msg}");
1601 }
1602 StreamPayload::Tagged { .. } => {}
1603 },
1604 None => {
1605 bail!("Stream ended without completion");
1606 }
1607 }
1608 }
1609 }
1610
1611 Ok(())
1612}
1613
1614pub async fn handle_load(
1619 model_ref_str: &str,
1620 max_context: Option<usize>,
1621 kv_quant: hyprstream_rpc_std::model_client::KVQuantType,
1622 wait: Option<u64>,
1623 signing_key: SigningKey,
1624) -> Result<()> {
1625 use crate::events::{EventEnvelope, EventPayload};
1626
1627 info!("Loading model: {}", model_ref_str);
1628 let _model_ref = ModelRef::parse(model_ref_str)?;
1629 let load_max_context = max_context.map(|v| v as u32);
1630 let load_kv_quant = if kv_quant == hyprstream_rpc_std::model_client::KVQuantType::None {
1631 None
1632 } else {
1633 Some(kv_quant)
1634 };
1635
1636 let model_client = ModelClient::from_provider(
1638 &hyprstream_discovery::ProductionRpcClientProvider,
1639 signing_key.clone(),
1640 None,
1641 )?;
1642 match model_client
1643 .load(&LoadModelRequest {
1644 model_ref: model_ref_str.to_owned(),
1645 max_context: load_max_context,
1646 kv_quant: load_kv_quant
1647 .filter(|q| *q != hyprstream_rpc_std::model_client::KVQuantType::None),
1648 })
1649 .await
1650 {
1651 Ok(_) => debug!("Load RPC accepted for {}", model_ref_str),
1652 Err(e) => warn!("Load RPC failed for {}: {}", model_ref_str, e),
1653 }
1654
1655 println!("Load initiated for model: {}", model_ref_str);
1656 if let Some(max_ctx) = max_context {
1657 println!(" Max context: {}", max_ctx);
1658 }
1659 if kv_quant != hyprstream_rpc_std::model_client::KVQuantType::None {
1660 println!(" KV quantization: {:?}", kv_quant);
1661 }
1662
1663 if let Some(timeout_secs) = wait {
1675 println!("Waiting for model to load (timeout: {}s)...", timeout_secs);
1676 ensure_event_origin_for_profile()?;
1677 let mut subscriber = EventSubscriber::new()?;
1678 subscriber.subscribe("model")?;
1679
1680 use crate::services::model::ModelLoadTerminal;
1681 use hyprstream_rpc::latch::{
1682 read_then_subscribe, AllowAllTerminalAuthz, Terminal, TerminalStore,
1683 };
1684
1685 let store: TerminalStore<String, ModelLoadTerminal> = TerminalStore::new();
1688 let mut fast_path = false;
1689 match model_client
1690 .status(&StatusRequest {
1691 model_ref: model_ref_str.to_owned(),
1692 })
1693 .await
1694 {
1695 Ok(entries) => {
1696 let already_loaded = entries.iter().any(|e| {
1697 e.status == "loaded"
1698 && (e.model_ref.contains(model_ref_str)
1699 || model_ref_str.contains(e.model_ref.as_str()))
1700 });
1701 if already_loaded {
1702 let _ = store.latch(
1706 model_ref_str.to_owned(),
1707 Terminal {
1708 value: ModelLoadTerminal::Loaded {
1709 endpoint: String::new(),
1710 },
1711 latched_by: "cli-status".to_owned(),
1712 },
1713 );
1714 fast_path = true;
1715 }
1716 }
1717 Err(e) => debug!("model status probe failed (will wait on live edge): {e}"),
1718 }
1719
1720 let classify_ref = model_ref_str.to_owned();
1724 let classify = move |_topic: &str, payload: &[u8]| -> Option<ModelLoadTerminal> {
1725 let event: EventEnvelope = match serde_json::from_slice(payload) {
1726 Ok(e) => e,
1727 Err(_) => return None,
1728 };
1729 match &event.payload {
1730 EventPayload::ModelLoaded {
1731 model_ref: mr,
1732 endpoint,
1733 } if mr.contains(classify_ref.as_str()) || classify_ref.contains(mr.as_str()) => {
1734 Some(ModelLoadTerminal::Loaded {
1735 endpoint: endpoint.clone(),
1736 })
1737 }
1738 EventPayload::ModelFailed {
1739 model_ref: mr,
1740 error,
1741 } if mr.contains(classify_ref.as_str()) || classify_ref.contains(mr.as_str()) => {
1742 Some(ModelLoadTerminal::LoadFailed {
1743 error: error.clone(),
1744 })
1745 }
1746 _ => None,
1747 }
1748 };
1749
1750 let watcher = "cli-load-wait".to_owned();
1751 let deadline = std::time::Duration::from_secs(timeout_secs);
1752 let outcome = match tokio::time::timeout(
1753 deadline,
1754 read_then_subscribe(
1755 &store,
1756 &mut subscriber,
1757 &AllowAllTerminalAuthz,
1758 &watcher,
1759 model_ref_str.to_owned(),
1760 classify,
1761 ),
1762 )
1763 .await
1764 {
1765 Err(_) => Err(anyhow::anyhow!(
1766 "Timeout waiting for model load notification ({}s elapsed)",
1767 timeout_secs
1768 )),
1769 Ok(Err(e)) => Err(anyhow::anyhow!("Model load wait failed: {e}")),
1770 Ok(Ok(terminal)) => match terminal.value {
1771 ModelLoadTerminal::Loaded { endpoint } => {
1772 println!(
1773 "\u{2713} Model {} loaded{}",
1774 model_ref_str,
1775 if fast_path { " (already loaded)" } else { "" }
1776 );
1777 if !endpoint.is_empty() {
1778 println!(" Endpoint: {}", endpoint);
1779 }
1780 Ok(())
1781 }
1782 ModelLoadTerminal::LoadFailed { error } => Err(anyhow::anyhow!(
1783 "Model {} failed to load: {}",
1784 model_ref_str,
1785 error
1786 )),
1787 },
1788 };
1789 outcome?;
1790 }
1791
1792 Ok(())
1793}
1794
1795pub async fn handle_notify_command(
1796 command: crate::cli::quick::NotifyCommand,
1797 signing_key: SigningKey,
1798) -> Result<()> {
1799 use crate::cli::quick::NotifyCommand;
1800
1801 match command {
1802 NotifyCommand::Probe { timeout } => {
1803 crate::services::event_network::probe_event_network(std::time::Duration::from_secs(
1804 timeout,
1805 ))
1806 .await
1807 }
1808 NotifyCommand::Subscribe {
1809 pattern,
1810 json,
1811 timeout,
1812 count,
1813 } => handle_notify_subscribe(&pattern, json, timeout, count, signing_key).await,
1814 }
1815}
1816
1817async fn handle_notify_subscribe(
1819 pattern: &str,
1820 json_output: bool,
1821 timeout_secs: u64,
1822 max_count: u64,
1823 _signing_key: SigningKey,
1824) -> Result<()> {
1825 use crate::events::EventEnvelope;
1826
1827 ensure_event_origin_for_profile()?;
1833 let mut subscriber = EventSubscriber::new()?;
1834 subscriber.subscribe(pattern)?;
1835
1836 eprintln!("Subscribed to: {}", pattern);
1837
1838 let deadline = if timeout_secs > 0 {
1839 Some(tokio::time::Instant::now() + std::time::Duration::from_secs(timeout_secs))
1840 } else {
1841 None
1842 };
1843 let mut received = 0u64;
1844
1845 loop {
1846 if max_count > 0 && received >= max_count {
1847 break;
1848 }
1849 let (topic, payload) = if let Some(dl) = deadline {
1850 match tokio::time::timeout_at(dl, subscriber.recv()).await {
1851 Ok(Ok(tp)) => tp,
1852 Ok(Err(e)) => {
1853 debug!("event recv: {e}");
1854 break;
1855 }
1856 Err(_) => {
1857 eprintln!("Timeout reached");
1858 break;
1859 }
1860 }
1861 } else {
1862 match subscriber.recv().await {
1863 Ok(tp) => tp,
1864 Err(e) => {
1865 debug!("event recv: {e}");
1866 break;
1867 }
1868 }
1869 };
1870 if json_output {
1871 if let Ok(s) = String::from_utf8(payload) {
1872 println!("{}", s);
1873 }
1874 } else {
1875 match serde_json::from_slice::<EventEnvelope>(&payload) {
1876 Ok(event) => {
1877 println!(
1878 "[{}] {} (source: {})",
1879 event.timestamp.format("%H:%M:%S"),
1880 topic,
1881 event.source
1882 );
1883 println!(" {:?}", event.payload);
1884 }
1885 Err(_) => {
1886 if let Ok(s) = String::from_utf8(payload) {
1887 println!("{}", s);
1888 }
1889 }
1890 }
1891 }
1892 received += 1;
1893 }
1894 eprintln!("Received {} events", received);
1895 Ok(())
1896}
1897
1898pub async fn handle_unload(model_ref_str: &str, signing_key: SigningKey) -> Result<()> {
1900 info!("Unloading model: {}", model_ref_str);
1901
1902 let _ = ModelRef::parse(model_ref_str)?;
1904
1905 let model_client = ModelClient::from_provider(
1906 &hyprstream_discovery::ProductionRpcClientProvider,
1907 signing_key,
1908 None,
1909 )?;
1910
1911 model_client
1912 .unload(&UnloadModelRequest {
1913 model_ref: model_ref_str.to_owned(),
1914 })
1915 .await?;
1916
1917 println!("✓ Model {} unloaded", model_ref_str);
1918
1919 Ok(())
1920}
1921
1922#[cfg(feature = "experimental")]
1926pub async fn handle_push(
1927 registry: &RegistryClient,
1928 model: &str,
1929 remote: Option<String>,
1930 branch: Option<String>,
1931 set_upstream: bool,
1932 force: bool,
1933) -> Result<()> {
1934 info!("Pushing model {} to remote", model);
1935
1936 let remote_name = remote.as_deref().unwrap_or("origin");
1937 let model_ref = ModelRef::new(model.to_string());
1938
1939 let tracked = registry
1941 .get_by_name(&model_ref.model)
1942 .await
1943 .map_err(|e| anyhow::anyhow!("Failed to get repository client: {}", e))?;
1944 let repo_client = registry.repo(&tracked.id);
1945
1946 let push_branch = if let Some(b) = &branch {
1948 b.clone()
1949 } else {
1950 repo_client.get_head().await?
1952 };
1953
1954 let refspec = format!("refs/heads/{}:refs/heads/{}", push_branch, push_branch);
1956
1957 repo_client.push(remote_name, &refspec, force).await?;
1959
1960 println!("✓ Pushed model {} to {}", model, remote_name);
1961 println!(" Branch: {}", push_branch);
1962 if force {
1963 println!(" ⚠️ Force push");
1964 }
1965 if set_upstream {
1966 println!(" Note: Upstream tracking is automatically configured by git");
1967 }
1968
1969 Ok(())
1970}
1971
1972pub async fn handle_pull(
1980 registry: &RegistryClient,
1981 model: &str,
1982 remote: Option<String>,
1983 branch: Option<String>,
1984 rebase: bool,
1985) -> Result<()> {
1986 info!("Pulling model {} from remote", model);
1987
1988 let remote_name = remote.as_deref().unwrap_or("origin");
1989 let model_ref = ModelRef::new(model.to_owned());
1990
1991 let tracked = registry
1993 .get_by_name(&model_ref.model)
1994 .await
1995 .map_err(|e| anyhow::anyhow!("Failed to get repository client: {}", e))?;
1996 let repo_client = registry.repo(&tracked.id);
1997
1998 let refspec = branch
2000 .as_ref()
2001 .map(|branch_name| format!("refs/heads/{branch_name}"));
2002
2003 repo_client
2006 .update(&UpdateRequest {
2007 refspec: refspec.as_deref().unwrap_or("").to_owned(),
2008 })
2009 .await?;
2010
2011 println!("✓ Pulled latest changes for model {model}");
2012 println!(" Remote: {remote_name}");
2013 if let Some(ref b) = branch {
2014 println!(" Branch: {b}");
2015 }
2016 if rebase {
2017 println!(" Strategy: rebase (note: currently performs merge)");
2018 warn!("Rebase strategy not yet implemented at service layer");
2019 } else {
2020 println!(" Strategy: merge");
2021 }
2022
2023 Ok(())
2024}
2025
2026#[cfg(feature = "experimental")]
2030pub struct MergeOptions {
2031 pub ff: bool,
2032 pub no_ff: bool,
2033 pub ff_only: bool,
2034 pub no_commit: bool,
2035 pub squash: bool,
2036 pub message: Option<String>,
2037 pub abort: bool,
2038 pub continue_merge: bool,
2039 pub quit: bool,
2040 pub no_stat: bool,
2041 pub quiet: bool,
2042 pub verbose: bool,
2043 pub strategy: Option<String>,
2044 pub strategy_option: Vec<String>,
2045 pub allow_unrelated_histories: bool,
2046 pub no_verify: bool,
2047}
2048
2049#[cfg(feature = "experimental")]
2055pub async fn handle_merge(
2056 registry: &RegistryClient,
2057 target: &str,
2058 source: &str,
2059 options: MergeOptions,
2060) -> Result<()> {
2061 if options.abort || options.continue_merge || options.quit {
2063 return handle_merge_conflict_resolution(registry, target, options).await;
2064 }
2065
2066 let target_ref = ModelRef::parse(target)?;
2068
2069 if !options.quiet {
2070 info!("Merging '{}' into '{}'", source, target_ref);
2071 }
2072
2073 let tracked = registry
2075 .get_by_name(&target_ref.model)
2076 .await
2077 .map_err(|e| anyhow::anyhow!("Failed to get repository client: {}", e))?;
2078 let repo_client = registry.repo(&tracked.id);
2079
2080 let message = if let Some(msg) = &options.message {
2082 Some(msg.as_str())
2083 } else {
2084 None
2085 };
2086
2087 let target_branch = match &target_ref.git_ref {
2089 crate::storage::GitRef::Branch(b) => b.clone(),
2090 crate::storage::GitRef::DefaultBranch => repo_client
2091 .get_head()
2092 .await
2093 .unwrap_or_else(|_| "main".to_owned()),
2094 _ => anyhow::bail!("Merge target must be a branch reference"),
2095 };
2096
2097 let merge_result = repo_client
2099 .worktree(&target_branch)
2100 .merge(source, message)
2101 .await;
2102
2103 match merge_result {
2104 Ok(merge_oid) => {
2105 if !options.quiet {
2106 println!("✓ Merged '{}' into '{}'", source, target_ref);
2107
2108 if !options.no_stat {
2110 if options.ff_only {
2111 println!(" Strategy: fast-forward only");
2112 } else if options.no_ff {
2113 println!(" Strategy: no fast-forward (merge commit created)");
2114 } else {
2115 println!(" Strategy: auto (fast-forward if possible)");
2116 }
2117
2118 if options.verbose {
2120 println!(" Commit: {}", &merge_oid[..8.min(merge_oid.len())]);
2121 }
2122 }
2123 }
2124
2125 Ok(())
2126 }
2127 Err(e) => {
2128 let err_msg = e.to_string();
2130 if err_msg.contains("conflict") || err_msg.contains("Conflict") {
2131 eprintln!("✗ Merge conflict detected");
2132 eprintln!("\nResolve conflicts in the repository");
2133 eprintln!("\nThen run:");
2134 eprintln!(" hyprstream merge {} --continue", target);
2135 eprintln!("\nOr abort the merge:");
2136 eprintln!(" hyprstream merge {} --abort", target);
2137 bail!("Merge conflicts must be resolved manually");
2138 } else {
2139 Err(e.into())
2140 }
2141 }
2142 }
2143}
2144
2145#[cfg(feature = "experimental")]
2149async fn handle_merge_conflict_resolution(
2150 registry: &RegistryClient,
2151 target: &str,
2152 options: MergeOptions,
2153) -> Result<()> {
2154 let target_ref = ModelRef::parse(target)?;
2155
2156 let tracked = registry
2158 .get_by_name(&target_ref.model)
2159 .await
2160 .map_err(|e| anyhow::anyhow!("Failed to get repository client: {}", e))?;
2161 let repo_client = registry.repo(&tracked.id);
2162
2163 let target_branch = match &target_ref.git_ref {
2165 GitRef::Branch(b) => b.clone(),
2166 GitRef::DefaultBranch => repo_client.get_head().await?,
2167 _ => bail!("Target must be a branch reference"),
2168 };
2169
2170 let wts = repo_client.list_worktrees().await?;
2172 if !wts.iter().any(|wt| wt.branch_name == target_branch) {
2173 bail!("Worktree not found for branch {}", target_branch);
2174 }
2175
2176 let wt = repo_client.worktree(&target_branch);
2178
2179 if options.abort {
2180 if !options.quiet {
2182 println!("→ Aborting merge...");
2183 }
2184
2185 wt.abort_merge().await?;
2186
2187 if !options.quiet {
2188 println!("✓ Merge aborted, restored pre-merge state");
2189 }
2190 } else if options.continue_merge {
2191 if !options.quiet {
2193 println!("→ Continuing merge...");
2194 }
2195
2196 let merge_oid = wt.continue_merge(options.message.as_deref()).await?;
2197
2198 if !options.quiet {
2199 println!("✓ Merge completed successfully");
2200 if options.verbose {
2201 println!(" Commit: {}", &merge_oid[..8.min(merge_oid.len())]);
2202 }
2203 }
2204 } else if options.quit {
2205 if !options.quiet {
2207 println!("→ Quitting merge (keeping changes)...");
2208 }
2209
2210 wt.quit_merge().await?;
2211
2212 if !options.quiet {
2213 println!("✓ Merge state removed, changes retained");
2214 println!(" Use 'hyprstream status {}' to see modified files", target);
2215 }
2216 }
2217
2218 Ok(())
2219}
2220
2221pub async fn handle_remove(
2226 registry: &RegistryClient,
2227 model: &str,
2228 force: bool,
2229 _registry_only: bool,
2230 _files_only: bool,
2231) -> Result<()> {
2232 info!("Removing model {}", model);
2233
2234 let model_ref = ModelRef::parse(model)?;
2236
2237 let is_worktree_removal = !matches!(model_ref.git_ref, crate::storage::GitRef::DefaultBranch);
2239
2240 if is_worktree_removal {
2241 let branch = model_ref.git_ref.display_name();
2243 info!("Removing worktree {} for model {}", branch, model_ref.model);
2244
2245 let tracked = registry
2246 .get_by_name(&model_ref.model)
2247 .await
2248 .map_err(|e| anyhow::anyhow!("Failed to get repository client: {}", e))?;
2249 let repo_client = registry.repo(&tracked.id);
2250
2251 let worktrees = repo_client
2253 .list_worktrees()
2254 .await
2255 .map_err(|e| anyhow::anyhow!("Failed to list worktrees: {}", e))?;
2256
2257 let wt = match worktrees.iter().find(|wt| wt.branch_name == branch) {
2258 Some(wt) => wt,
2259 None => {
2260 println!(
2261 "❌ Worktree '{}' not found for model '{}'",
2262 branch, model_ref.model
2263 );
2264 return Ok(());
2265 }
2266 };
2267
2268 println!("Worktree '{}:{}' removal plan:", model_ref.model, branch);
2270 println!(" Remove worktree for branch: {}", wt.branch_name);
2271
2272 if !force {
2274 print!(
2275 "Are you sure you want to remove worktree '{}:{}'? [y/N]: ",
2276 model_ref.model, branch
2277 );
2278 io::stdout().flush()?;
2279
2280 let mut input = String::new();
2281 io::stdin().read_line(&mut input)?;
2282 let input = input.trim().to_lowercase();
2283
2284 if input != "y" && input != "yes" {
2285 println!("Removal cancelled");
2286 return Ok(());
2287 }
2288 }
2289
2290 repo_client
2292 .remove_worktree(&RemoveWorktreeRequest {
2293 branch: wt.branch_name.clone(),
2294 force: false,
2295 })
2296 .await
2297 .map_err(|e| anyhow::anyhow!("Failed to remove worktree: {}", e))?;
2298
2299 println!(
2300 "✓ Worktree '{}:{}' removed successfully",
2301 model_ref.model, branch
2302 );
2303 return Ok(());
2304 }
2305
2306 let tracked = match registry.get_by_name(&model_ref.model).await {
2309 Ok(t) => t,
2310 Err(e) => {
2311 let err_msg = e.to_string();
2312 if err_msg.contains("not found") || err_msg.contains("Not found") {
2313 println!("❌ Model '{}' not found in registry", model_ref.model);
2314 return Ok(());
2315 }
2316 return Err(anyhow::anyhow!("Failed to query registry: {}", e));
2317 }
2318 };
2319
2320 println!("Model '{}' removal plan:", model_ref.model);
2322 println!(" 🗂️ Remove from registry and all associated files");
2323
2324 if !force {
2326 print!(
2327 "Are you sure you want to remove model '{}'? [y/N]: ",
2328 model_ref.model
2329 );
2330 io::stdout().flush()?;
2331
2332 let mut input = String::new();
2333 io::stdin().read_line(&mut input)?;
2334 let input = input.trim().to_lowercase();
2335
2336 if input != "y" && input != "yes" {
2337 println!("Removal cancelled");
2338 return Ok(());
2339 }
2340 }
2341
2342 registry
2344 .remove(&tracked.id)
2345 .await
2346 .map_err(|e| anyhow::anyhow!("Failed to remove model: {}", e))?;
2347
2348 println!("✓ Model '{}' removed successfully", model_ref.model);
2349 Ok(())
2350}