valkyria-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. valkyria_cli-0.1.0.dist-info/METADATA +117 -0
  2. valkyria_cli-0.1.0.dist-info/RECORD +55 -0
  3. valkyria_cli-0.1.0.dist-info/WHEEL +4 -0
  4. valkyria_cli-0.1.0.dist-info/entry_points.txt +3 -0
  5. valkyrie/__init__.py +5 -0
  6. valkyrie/auth/__init__.py +21 -0
  7. valkyrie/auth/account.py +245 -0
  8. valkyrie/auth/firebase_config.py +28 -0
  9. valkyrie/auth/login_page.py +177 -0
  10. valkyrie/auth/server.py +145 -0
  11. valkyrie/auth/tokens.py +196 -0
  12. valkyrie/chat/__init__.py +37 -0
  13. valkyrie/chat/clients.py +431 -0
  14. valkyrie/chat/commands.py +229 -0
  15. valkyrie/chat/engine.py +1458 -0
  16. valkyrie/chat/messages.py +108 -0
  17. valkyrie/chat/renderer.py +122 -0
  18. valkyrie/cli/__init__.py +2 -0
  19. valkyrie/cli/auth_commands.py +61 -0
  20. valkyrie/cli/chat_commands.py +139 -0
  21. valkyrie/cli/keys_commands.py +275 -0
  22. valkyrie/cli/main.py +179 -0
  23. valkyrie/cli/model_commands.py +334 -0
  24. valkyrie/cli/rag_commands.py +191 -0
  25. valkyrie/cli/session_commands.py +247 -0
  26. valkyrie/cli/setup_wizard.py +510 -0
  27. valkyrie/core/__init__.py +2 -0
  28. valkyrie/core/cards.py +55 -0
  29. valkyrie/core/config.py +84 -0
  30. valkyrie/core/console.py +122 -0
  31. valkyrie/core/paths.py +68 -0
  32. valkyrie/core/workspace.py +87 -0
  33. valkyrie/providers/__init__.py +23 -0
  34. valkyrie/providers/base.py +78 -0
  35. valkyrie/providers/gemini.py +141 -0
  36. valkyrie/providers/groq.py +102 -0
  37. valkyrie/providers/nvidia.py +95 -0
  38. valkyrie/providers/registry.py +233 -0
  39. valkyrie/rag/__init__.py +32 -0
  40. valkyrie/rag/chunker.py +75 -0
  41. valkyrie/rag/embeddings.py +227 -0
  42. valkyrie/rag/files.py +163 -0
  43. valkyrie/rag/pinecone_store.py +191 -0
  44. valkyrie/rag/pipeline.py +170 -0
  45. valkyrie/sessions/__init__.py +9 -0
  46. valkyrie/sessions/store.py +544 -0
  47. valkyrie/tools/__init__.py +6 -0
  48. valkyrie/tools/local_fs.py +423 -0
  49. valkyrie/tools/registry.py +100 -0
  50. valkyrie/tools/web_search.py +73 -0
  51. valkyrie/vault/__init__.py +26 -0
  52. valkyrie/vault/crypto.py +119 -0
  53. valkyrie/vault/prompt.py +77 -0
  54. valkyrie/vault/store.py +207 -0
  55. valkyrie/vault/sync.py +140 -0
@@ -0,0 +1,108 @@
1
+ """
2
+ Chat message protocol and context window accounting.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from dataclasses import dataclass, field
8
+ from datetime import UTC, datetime
9
+ from enum import StrEnum
10
+ from typing import Any
11
+
12
+
13
+ class MessageRole(StrEnum):
14
+ """Supported roles in the chat message protocol."""
15
+
16
+ SYSTEM = "system"
17
+ USER = "user"
18
+ ASSISTANT = "assistant"
19
+ TOOL = "tool"
20
+
21
+
22
+ @dataclass
23
+ class TokenUsage:
24
+ """Token counts for a single completion turn."""
25
+
26
+ prompt_tokens: int = 0
27
+ completion_tokens: int = 0
28
+ estimated: bool = False
29
+
30
+ @property
31
+ def total_tokens(self) -> int:
32
+ return self.prompt_tokens + self.completion_tokens
33
+
34
+
35
+ @dataclass
36
+ class ChatMessage:
37
+ """Single message in a conversation."""
38
+
39
+ role: MessageRole
40
+ content: str
41
+ model: str | None = None
42
+ name: str | None = None
43
+ tool_call_id: str | None = None
44
+ tool_calls: list[dict[str, Any]] | None = None
45
+ usage: TokenUsage | None = None
46
+ created_at: str = field(default_factory=lambda: datetime.now(UTC).isoformat())
47
+
48
+ def to_openai_dict(self) -> dict[str, Any]:
49
+ """Serialize to OpenAI-compatible chat message payload."""
50
+ payload: dict[str, Any] = {
51
+ "role": self.role.value,
52
+ "content": self.content,
53
+ }
54
+ if self.name:
55
+ payload["name"] = self.name
56
+ if self.tool_call_id:
57
+ payload["tool_call_id"] = self.tool_call_id
58
+ if self.tool_calls:
59
+ payload["tool_calls"] = self.tool_calls
60
+ return payload
61
+
62
+
63
+ def estimate_tokens(text: str) -> int:
64
+ """Fast heuristic token estimate (~4 chars per token) when exact counts are absent."""
65
+ if not text:
66
+ return 0
67
+ return max(1, len(text) // 4 + 1)
68
+
69
+
70
+ def estimate_messages_tokens(messages: list[ChatMessage]) -> int:
71
+ """Estimate total prompt tokens for a list of messages."""
72
+ return sum(estimate_tokens(m.content) + 4 for m in messages)
73
+
74
+
75
+ @dataclass
76
+ class ContextBudget:
77
+ """Tracks current conversation context usage against the active model limit."""
78
+
79
+ used_tokens: int
80
+ context_window: int | None
81
+ total_prompt_tokens: int = 0
82
+ total_completion_tokens: int = 0
83
+
84
+ @property
85
+ def remaining_tokens(self) -> int | None:
86
+ if self.context_window is None:
87
+ return None
88
+ return max(0, self.context_window - self.used_tokens)
89
+
90
+ @property
91
+ def utilization_pct(self) -> float | None:
92
+ if not self.context_window:
93
+ return None
94
+ return min(100.0, (self.used_tokens / self.context_window) * 100.0)
95
+
96
+ def fits(self, target_window: int | None, reserve_output: int = 1024) -> bool:
97
+ """Check whether current context fits within a target model's context window."""
98
+ if target_window is None:
99
+ return True
100
+ return self.used_tokens + reserve_output <= target_window
101
+
102
+ def format_summary(self) -> str:
103
+ """Human-readable budget summary, showing 'unknown' when window limit is unknown."""
104
+ if self.context_window is None:
105
+ return f"~{self.used_tokens:,} tokens / unknown limit"
106
+ pct = self.utilization_pct or 0.0
107
+ return f"{self.used_tokens:,} / {self.context_window:,} tokens ({pct:.0f}%)"
108
+
@@ -0,0 +1,122 @@
1
+ """
2
+ Streaming Markdown renderer — live thinking indicator, Markdown streaming, and tool capture.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import time
8
+ from typing import TYPE_CHECKING
9
+
10
+ from rich.live import Live
11
+ from rich.markdown import Markdown
12
+ from rich.spinner import Spinner
13
+ from rich.text import Text
14
+
15
+ from valkyrie.chat.messages import TokenUsage, estimate_messages_tokens, estimate_tokens
16
+ from valkyrie.core.console import console
17
+
18
+ if TYPE_CHECKING:
19
+ from collections.abc import AsyncIterator
20
+
21
+ from valkyrie.chat.clients import StreamChunk, ToolCall
22
+ from valkyrie.chat.messages import ChatMessage
23
+
24
+
25
+ async def render_agent_stream(
26
+ chunks: AsyncIterator[StreamChunk],
27
+ *,
28
+ qualified_model: str,
29
+ prompt_messages: list[ChatMessage],
30
+ ) -> tuple[str, TokenUsage, list[ToolCall]]:
31
+ """
32
+ Stream chunks to the terminal as live-rendered Markdown, collecting any tool calls.
33
+
34
+ Returns (full_response_text, token_usage, tool_calls).
35
+ """
36
+ provider, _, model_name = qualified_model.partition("/")
37
+ header = Text()
38
+ header.append(" ┃ ", style="bright_cyan")
39
+ header.append("◆ ", style="bold bright_magenta")
40
+ if model_name:
41
+ header.append(f"{provider}", style="bold bright_blue")
42
+ header.append("/", style="grey50")
43
+ header.append(model_name, style="bold bright_magenta")
44
+ else:
45
+ header.append(qualified_model, style="bold bright_magenta")
46
+ header.append(" · ", style="grey42")
47
+ header.append("hosted stream", style="grey62")
48
+
49
+ console.print()
50
+ console.print(header)
51
+
52
+ buffer: list[str] = []
53
+ tool_calls: list[ToolCall] = []
54
+ final_usage: TokenUsage | None = None
55
+ started_at = time.perf_counter()
56
+
57
+ spinner = Spinner(
58
+ "dots",
59
+ text=Text(" routing & thinking…", style="grey62"),
60
+ style="bright_cyan",
61
+ )
62
+ with Live(
63
+ spinner,
64
+ console=console,
65
+ refresh_per_second=14,
66
+ transient=False,
67
+ ) as live:
68
+ async for chunk in chunks:
69
+ if chunk.delta:
70
+ buffer.append(chunk.delta)
71
+ live.update(Markdown("".join(buffer)))
72
+ if chunk.tool_calls:
73
+ tool_calls.extend(chunk.tool_calls)
74
+ if chunk.usage is not None:
75
+ final_usage = chunk.usage
76
+
77
+ full_text = "".join(buffer)
78
+ if not full_text and tool_calls:
79
+ names = ", ".join(tc.name for tc in tool_calls)
80
+ live.update(Text(f" ▸ invoking tools: {names}", style="bright_cyan"))
81
+ elif not full_text:
82
+ live.update(Text(" (empty response)", style="muted"))
83
+
84
+ elapsed = max(0.01, time.perf_counter() - started_at)
85
+
86
+ if final_usage is None:
87
+ final_usage = TokenUsage(
88
+ prompt_tokens=estimate_messages_tokens(prompt_messages),
89
+ completion_tokens=estimate_tokens(full_text),
90
+ estimated=True,
91
+ )
92
+
93
+ approx = "~" if final_usage.estimated else ""
94
+ tps = final_usage.completion_tokens / elapsed if final_usage.completion_tokens > 0 else 0.0
95
+ tps_part = f" · {tps:.0f} tok/s" if tps >= 1.0 else ""
96
+
97
+ footer = Text()
98
+ footer.append(" └─ ", style="grey35")
99
+ footer.append(
100
+ f"{approx}{final_usage.prompt_tokens:,} in · "
101
+ f"{approx}{final_usage.completion_tokens:,} out · "
102
+ f"{elapsed:.2f}s{tps_part}",
103
+ style="grey62",
104
+ )
105
+ console.print(footer)
106
+ console.print()
107
+ return full_text, final_usage, tool_calls
108
+
109
+
110
+ async def render_stream(
111
+ chunks: AsyncIterator[StreamChunk],
112
+ *,
113
+ qualified_model: str,
114
+ prompt_messages: list[ChatMessage],
115
+ ) -> tuple[str, TokenUsage]:
116
+ """Stream text response without returning tool_calls (backwards-compatible wrapper)."""
117
+ text, usage, _ = await render_agent_stream(
118
+ chunks,
119
+ qualified_model=qualified_model,
120
+ prompt_messages=prompt_messages,
121
+ )
122
+ return text, usage
@@ -0,0 +1,2 @@
1
+ """CLI command group and entry point."""
2
+
@@ -0,0 +1,61 @@
1
+ """
2
+ Auth CLI commands — login, switch, delete, logout, and status.
3
+ """
4
+
5
+ import click
6
+
7
+ from valkyrie.auth.account import (
8
+ delete_account,
9
+ login_account,
10
+ logout_account,
11
+ show_account_status,
12
+ switch_account,
13
+ )
14
+
15
+
16
+ @click.group()
17
+ def auth() -> None:
18
+ """Manage authentication and account lifecycle."""
19
+ pass
20
+
21
+
22
+ @auth.command()
23
+ def login() -> None:
24
+ """Sign in with Google via browser handoff."""
25
+ user = login_account(select_account=False)
26
+ if user is None:
27
+ raise SystemExit(1)
28
+
29
+
30
+ @auth.command()
31
+ def switch() -> None:
32
+ """Switch to another Google account via browser selector."""
33
+ user = switch_account(interactive=True)
34
+ if user is None:
35
+ raise SystemExit(1)
36
+
37
+
38
+ @auth.command()
39
+ @click.option("--yes", is_flag=True, help="Skip confirmation prompts.")
40
+ @click.option(
41
+ "--purge-local",
42
+ is_flag=True,
43
+ help="Also delete the local encrypted key vault (vault.enc).",
44
+ )
45
+ def delete(yes: bool, purge_local: bool) -> None:
46
+ """Permanently delete the signed-in account and remote synced vault."""
47
+ if not delete_account(assume_yes=yes, purge_local=purge_local):
48
+ raise SystemExit(1)
49
+
50
+
51
+ @auth.command()
52
+ def logout() -> None:
53
+ """Sign out and clear stored credentials."""
54
+ logout_account()
55
+
56
+
57
+ @auth.command(name="status")
58
+ def auth_status() -> None:
59
+ """Show current authentication state."""
60
+ show_account_status()
61
+
@@ -0,0 +1,139 @@
1
+ """
2
+ Chat CLI command — launch or resume a durable multi-model terminal chat session.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import click
8
+
9
+ from valkyrie.chat.engine import ChatEngine, build_system_prompt, run_chat_repl
10
+ from valkyrie.chat.messages import ChatMessage, MessageRole
11
+ from valkyrie.core.config import ValkyrieConfig
12
+ from valkyrie.core.console import console, print_error, print_info, print_rule
13
+ from valkyrie.core.workspace import detect_workspace_root
14
+ from valkyrie.providers.registry import PROVIDERS, ModelRegistry
15
+ from valkyrie.sessions.store import SessionStore
16
+ from valkyrie.vault.prompt import verify_and_prompt
17
+ from valkyrie.vault.store import get_key, vault_exists
18
+
19
+
20
+ @click.command()
21
+ @click.option(
22
+ "--model",
23
+ "model_override",
24
+ default=None,
25
+ help="Override chat model (<provider>/<model_id>).",
26
+ )
27
+ @click.option(
28
+ "--new",
29
+ "force_new",
30
+ is_flag=True,
31
+ default=False,
32
+ help="Start a new session instead of resuming the latest one.",
33
+ )
34
+ @click.option(
35
+ "--session",
36
+ "session_id",
37
+ default=None,
38
+ help="Resume a specific session by ID (or unique prefix).",
39
+ )
40
+ def chat(model_override: str | None, force_new: bool, session_id: str | None) -> None:
41
+ """Start or resume an interactive chat session."""
42
+ config = ValkyrieConfig.load()
43
+ registry = ModelRegistry.load_cache()
44
+ store = SessionStore()
45
+ ws_root = detect_workspace_root()
46
+ workspace = str(ws_root)
47
+
48
+ # Resolve target session (explicit ID -> latest for workspace -> new)
49
+ existing_session = None
50
+ if session_id is not None:
51
+ existing_session = store.get_session(session_id)
52
+ if existing_session is None:
53
+ print_error(f"Session '{session_id}' not found.")
54
+ raise SystemExit(1)
55
+ elif not force_new:
56
+ existing_session = store.get_latest_session(workspace_root=workspace)
57
+
58
+ selected_model = model_override or (
59
+ existing_session.active_model if existing_session else config.models.chat
60
+ )
61
+ if not selected_model:
62
+ console.print()
63
+ print_rule("Chat")
64
+ print_error("No chat model configured.")
65
+ print_info(
66
+ "Run [bold]valkyrie setup[/bold] or "
67
+ "[bold]valkyrie model set chat <provider>/<model>[/bold]."
68
+ )
69
+ console.print()
70
+ raise SystemExit(1)
71
+
72
+ if "/" not in selected_model:
73
+ print_error("Model must be in <provider>/<model_id> format.")
74
+ raise SystemExit(1)
75
+
76
+ if not vault_exists():
77
+ print_error("No key vault found. Run [bold]valkyrie keys add[/bold] first.")
78
+ raise SystemExit(1)
79
+
80
+ console.print()
81
+ print_info("Unlock vault to start chat session.")
82
+ password = verify_and_prompt(action="unlock API keys for chat")
83
+ if password is None:
84
+ raise SystemExit(1)
85
+
86
+ api_keys: dict[str, str] = {}
87
+ for pkey in PROVIDERS:
88
+ key = get_key(password, pkey)
89
+ if key:
90
+ api_keys[pkey] = key
91
+
92
+ provider_key, _ = selected_model.split("/", 1)
93
+ if provider_key not in api_keys:
94
+ print_error(f"No API key found in vault for provider '{provider_key}'.")
95
+ raise SystemExit(1)
96
+
97
+ if existing_session is not None:
98
+ loaded_messages = store.load_messages(existing_session.id)
99
+ if model_override and model_override != existing_session.active_model:
100
+ store.update_active_model(existing_session.id, model_override)
101
+ print_info(
102
+ f"Resuming session [bold]{existing_session.title}[/bold] "
103
+ f"([dim]{existing_session.id}[/dim], {existing_session.message_count} messages)"
104
+ )
105
+ engine = ChatEngine(
106
+ config=config,
107
+ registry=registry,
108
+ api_keys=api_keys,
109
+ initial_model=selected_model,
110
+ session_store=store,
111
+ session_id=existing_session.id,
112
+ initial_messages=loaded_messages,
113
+ total_prompt_tokens=existing_session.total_prompt_tokens,
114
+ total_completion_tokens=existing_session.total_completion_tokens,
115
+ workspace_root=ws_root,
116
+ )
117
+ else:
118
+ sys_msg = ChatMessage(
119
+ role=MessageRole.SYSTEM,
120
+ content=build_system_prompt(config, ws_root),
121
+ )
122
+ created = store.create_session(
123
+ active_model=selected_model,
124
+ workspace_root=workspace,
125
+ initial_messages=[sys_msg],
126
+ )
127
+ print_info(f"Started new session [dim]{created.id}[/dim]")
128
+ engine = ChatEngine(
129
+ config=config,
130
+ registry=registry,
131
+ api_keys=api_keys,
132
+ initial_model=selected_model,
133
+ session_store=store,
134
+ session_id=created.id,
135
+ initial_messages=[sys_msg],
136
+ workspace_root=ws_root,
137
+ )
138
+
139
+ run_chat_repl(engine)
@@ -0,0 +1,275 @@
1
+ """
2
+ Keys CLI commands — manage provider API keys in the encrypted vault.
3
+ """
4
+
5
+ import click
6
+
7
+ from valkyrie.core.console import (
8
+ console,
9
+ print_error,
10
+ print_info,
11
+ print_rule,
12
+ print_success,
13
+ print_warning,
14
+ )
15
+ from valkyrie.vault.store import SERVICE_KEYS, SUPPORTED_PROVIDERS
16
+
17
+
18
+ @click.group()
19
+ def keys() -> None:
20
+ """Manage provider API keys."""
21
+ pass
22
+
23
+
24
+ @keys.command()
25
+ @click.argument("provider", required=False)
26
+ def add(provider: str | None) -> None:
27
+ """Add or update an API key for a provider."""
28
+ from valkyrie.vault.prompt import prompt_master_password
29
+ from valkyrie.vault.store import add_key
30
+
31
+ console.print()
32
+ print_rule("Add Provider Key")
33
+ console.print()
34
+
35
+ # If no provider specified, show options
36
+ if provider is None:
37
+ print_info("Available services:")
38
+ console.print()
39
+ for pid, pinfo in SERVICE_KEYS.items():
40
+ console.print(f" [accent]{pid:<10}[/accent] {pinfo['description']}")
41
+ console.print()
42
+ provider = click.prompt(" Service", type=click.Choice(list(SERVICE_KEYS.keys())))
43
+
44
+ provider = provider.lower()
45
+ if provider not in SERVICE_KEYS:
46
+ print_error(f"Unknown service: {provider}")
47
+ print_info(f"Supported: {', '.join(SERVICE_KEYS.keys())}")
48
+ raise SystemExit(1)
49
+
50
+ pinfo = SERVICE_KEYS[provider]
51
+ console.print()
52
+ print_info(f"Adding key for [accent]{pinfo['name']}[/accent]")
53
+ print_info(f"Get your key at: [dim]{pinfo['url']}[/dim]")
54
+ console.print()
55
+
56
+ # Get the master password (create vault if first time)
57
+ password = prompt_master_password()
58
+ if password is None:
59
+ return
60
+
61
+ # Get the API key (masked input)
62
+ api_key = click.prompt(
63
+ f" {pinfo['name']} API key",
64
+ hide_input=True,
65
+ prompt_suffix=": ",
66
+ )
67
+
68
+ if not api_key.strip():
69
+ print_error("API key cannot be empty.")
70
+ return
71
+
72
+ # Validate key format hint (non-blocking)
73
+ expected_prefix = pinfo.get("prefix", "")
74
+ if expected_prefix and not api_key.startswith(expected_prefix):
75
+ print_warning(
76
+ f"Key doesn't start with '{expected_prefix}'. "
77
+ f"It may still work — saving anyway."
78
+ )
79
+
80
+ # Store it
81
+ add_key(password, provider, api_key.strip())
82
+
83
+ # Record model provider in config (skip vector DB entries like pinecone)
84
+ if provider in SUPPORTED_PROVIDERS:
85
+ from valkyrie.core.config import ProviderConfig, ValkyrieConfig
86
+
87
+ config = ValkyrieConfig.load()
88
+ config.providers[provider] = ProviderConfig(name=pinfo["name"], enabled=True)
89
+ config.save()
90
+
91
+ console.print()
92
+ print_success(f"{pinfo['name']} key saved to encrypted vault.")
93
+ if provider in SUPPORTED_PROVIDERS:
94
+ print_info("Run [bold]valkyrie model refresh[/bold] to discover available models.")
95
+
96
+ # Offer to sync
97
+ _offer_sync(password)
98
+
99
+ console.print()
100
+
101
+
102
+ @keys.command(name="list")
103
+ def list_cmd() -> None:
104
+ """List stored provider keys (masked)."""
105
+ from valkyrie.vault.store import vault_exists
106
+
107
+ console.print()
108
+ print_rule("Provider Keys")
109
+ console.print()
110
+
111
+ if not vault_exists():
112
+ print_info("No vault found. Run [bold]valkyrie keys add[/bold] to add your first key.")
113
+ console.print()
114
+ return
115
+
116
+ from valkyrie.vault.prompt import verify_and_prompt
117
+ from valkyrie.vault.store import list_keys
118
+
119
+ password = verify_and_prompt(action="list your keys")
120
+ if password is None:
121
+ console.print()
122
+ return
123
+
124
+ stored_keys = list_keys(password)
125
+
126
+ if not stored_keys:
127
+ print_info("Vault is empty. Run [bold]valkyrie keys add[/bold] to add a key.")
128
+ else:
129
+ console.print()
130
+ for provider, data in stored_keys.items():
131
+ pinfo = SERVICE_KEYS.get(provider, {"name": provider})
132
+ name = pinfo["name"] if isinstance(pinfo, dict) else provider
133
+ console.print(f" [accent]{name:<18}[/accent] [dim]{data['masked_key']}[/dim]")
134
+
135
+ console.print()
136
+
137
+
138
+ @keys.command()
139
+ @click.argument("provider")
140
+ def remove(provider: str) -> None:
141
+ """Remove a provider key from the vault."""
142
+ from valkyrie.vault.store import vault_exists
143
+
144
+ provider = provider.lower()
145
+
146
+ console.print()
147
+ print_rule("Remove Key")
148
+ console.print()
149
+
150
+ if not vault_exists():
151
+ print_error("No vault found.")
152
+ console.print()
153
+ return
154
+
155
+ if provider not in SERVICE_KEYS:
156
+ print_warning(f"Unknown service '{provider}', checking vault anyway.")
157
+
158
+ pinfo = SERVICE_KEYS.get(provider, {"name": provider})
159
+ name = pinfo["name"] if isinstance(pinfo, dict) else provider
160
+
161
+ if not click.confirm(f" Remove {name} key?", default=False):
162
+ print_info("Cancelled.")
163
+ console.print()
164
+ return
165
+
166
+ from valkyrie.vault.prompt import verify_and_prompt
167
+ from valkyrie.vault.store import remove_key
168
+
169
+ password = verify_and_prompt(action="remove a key")
170
+ if password is None:
171
+ console.print()
172
+ return
173
+
174
+ if remove_key(password, provider):
175
+ from valkyrie.core.config import ValkyrieConfig
176
+
177
+ config = ValkyrieConfig.load()
178
+ config.providers.pop(provider, None)
179
+ config.save()
180
+ print_success(f"{name} key removed.")
181
+ _offer_sync(password)
182
+ else:
183
+ print_info(f"No key found for {name}.")
184
+
185
+ console.print()
186
+
187
+
188
+ @keys.command()
189
+ def sync() -> None:
190
+ """Sync the encrypted vault to/from Firebase."""
191
+ from valkyrie.vault.store import vault_exists
192
+
193
+ console.print()
194
+ print_rule("Vault Sync")
195
+ console.print()
196
+
197
+ if not vault_exists():
198
+ # Try pulling from remote
199
+ _pull_from_remote()
200
+ return
201
+
202
+ from valkyrie.vault.prompt import verify_and_prompt
203
+
204
+ password = verify_and_prompt(action="sync your vault")
205
+ if password is None:
206
+ console.print()
207
+ return
208
+
209
+ _do_sync(password)
210
+ console.print()
211
+
212
+
213
+ # ── Sync helpers ────────────────────────────────────────────────────────────
214
+
215
+
216
+ def _offer_sync(password: str) -> None:
217
+ """Offer to sync after a vault change."""
218
+ from valkyrie.auth.tokens import get_valid_user
219
+
220
+ user = get_valid_user()
221
+ if user is None:
222
+ return
223
+
224
+ if click.confirm("\n Sync vault to Firebase?", default=True):
225
+ _do_sync(password)
226
+
227
+
228
+ def _do_sync(password: str) -> None:
229
+ """Push local vault to Firebase."""
230
+ from valkyrie.auth.tokens import get_valid_user
231
+ from valkyrie.vault.store import get_vault_blob
232
+ from valkyrie.vault.sync import push_vault
233
+
234
+ user = get_valid_user()
235
+ if user is None:
236
+ print_warning("Not signed in. Sign in first to sync.")
237
+ return
238
+
239
+ blob = get_vault_blob()
240
+ if blob is None:
241
+ print_info("No vault to sync.")
242
+ return
243
+
244
+ print_info("Pushing encrypted vault to Firebase...")
245
+ if push_vault(user.id_token, user.uid, blob):
246
+ print_success("Vault synced to Firebase.")
247
+ else:
248
+ print_error("Sync failed. Check your connection and try again.")
249
+
250
+
251
+ def _pull_from_remote() -> None:
252
+ """Pull vault from Firebase when no local vault exists."""
253
+ from valkyrie.auth.tokens import get_valid_user
254
+ from valkyrie.vault.store import save_vault_blob
255
+ from valkyrie.vault.sync import pull_vault
256
+
257
+ user = get_valid_user()
258
+ if user is None:
259
+ print_info("Not signed in. Run [bold]valkyrie auth login[/bold] first.")
260
+ console.print()
261
+ return
262
+
263
+ print_info("No local vault. Checking Firebase for a synced vault...")
264
+ blob = pull_vault(user.id_token, user.uid)
265
+
266
+ if blob is None:
267
+ print_info(
268
+ "No remote vault found either. Run [bold]valkyrie keys add[/bold] to create one."
269
+ )
270
+ else:
271
+ save_vault_blob(blob)
272
+ print_success("Vault downloaded from Firebase. Unlock it with your master password.")
273
+
274
+ console.print()
275
+