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,145 @@
1
+ """
2
+ Local OAuth server — serves the login page and receives the token callback.
3
+
4
+ Spins up a minimal HTTP server on localhost to:
5
+ 1. Serve the Google sign-in page at /
6
+ 2. Receive the POST callback with Firebase tokens at /callback
7
+ 3. Shut down after successful auth
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import threading
14
+ from http.server import BaseHTTPRequestHandler, HTTPServer
15
+ from typing import Any
16
+
17
+ from valkyrie.auth.firebase_config import (
18
+ OAUTH_CALLBACK_HOST,
19
+ OAUTH_CALLBACK_PATH,
20
+ OAUTH_CALLBACK_PORT,
21
+ )
22
+ from valkyrie.auth.login_page import get_login_page_html
23
+
24
+
25
+ class _AuthResult:
26
+ """Thread-safe container for the auth result."""
27
+
28
+ def __init__(self) -> None:
29
+ self.data: dict[str, Any] | None = None
30
+ self.error: str | None = None
31
+ self.event = threading.Event()
32
+
33
+
34
+ _result = _AuthResult()
35
+
36
+
37
+ class _OAuthHTTPServer(HTTPServer):
38
+ """HTTPServer carrying per-run OAuth options."""
39
+
40
+ def __init__(
41
+ self,
42
+ server_address: tuple[str, int],
43
+ handler_class: type[BaseHTTPRequestHandler],
44
+ *,
45
+ select_account: bool = False,
46
+ ) -> None:
47
+ self.select_account = select_account
48
+ super().__init__(server_address, handler_class)
49
+
50
+
51
+ class _OAuthHandler(BaseHTTPRequestHandler):
52
+ """HTTP handler for the local OAuth server."""
53
+
54
+ server: _OAuthHTTPServer
55
+
56
+ def log_message(self, format: str, *args: Any) -> None: # noqa: A002
57
+ """Suppress default logging."""
58
+ pass
59
+
60
+ def do_GET(self) -> None: # noqa: N802
61
+ """Serve the login page."""
62
+ if self.path == "/" or self.path == "/login":
63
+ select_account = getattr(self.server, "select_account", False)
64
+ html = get_login_page_html(select_account=select_account)
65
+ self.send_response(200)
66
+ self.send_header("Content-Type", "text/html; charset=utf-8")
67
+ self.send_header("Cache-Control", "no-store")
68
+ self.end_headers()
69
+ self.wfile.write(html.encode("utf-8"))
70
+ else:
71
+ self.send_response(404)
72
+ self.end_headers()
73
+
74
+ def do_POST(self) -> None: # noqa: N802
75
+ """Handle the token callback from the login page."""
76
+ if self.path == OAUTH_CALLBACK_PATH:
77
+ content_length = int(self.headers.get("Content-Length", 0))
78
+ body = self.rfile.read(content_length)
79
+
80
+ try:
81
+ data = json.loads(body)
82
+ _result.data = data
83
+ _result.event.set()
84
+
85
+ # Send success response with CORS headers for the local page
86
+ self.send_response(200)
87
+ self.send_header("Content-Type", "application/json")
88
+ self.send_header("Access-Control-Allow-Origin", "*")
89
+ self.end_headers()
90
+ self.wfile.write(json.dumps({"status": "ok"}).encode())
91
+
92
+ except (json.JSONDecodeError, KeyError) as e:
93
+ _result.error = str(e)
94
+ _result.event.set()
95
+ self.send_response(400)
96
+ self.send_header("Access-Control-Allow-Origin", "*")
97
+ self.end_headers()
98
+ else:
99
+ self.send_response(404)
100
+ self.end_headers()
101
+
102
+ def do_OPTIONS(self) -> None: # noqa: N802
103
+ """Handle CORS preflight."""
104
+ self.send_response(200)
105
+ self.send_header("Access-Control-Allow-Origin", "*")
106
+ self.send_header("Access-Control-Allow-Methods", "POST, OPTIONS")
107
+ self.send_header("Access-Control-Allow-Headers", "Content-Type")
108
+ self.end_headers()
109
+
110
+
111
+ def run_auth_server(
112
+ timeout: float = 300.0,
113
+ *,
114
+ select_account: bool = False,
115
+ ) -> dict[str, Any] | None:
116
+ """
117
+ Start the local OAuth server, wait for auth, and return the result.
118
+
119
+ Args:
120
+ timeout: Seconds to wait for the user to complete sign-in.
121
+ select_account: Whether to prompt Google's account chooser.
122
+
123
+ Returns:
124
+ Dict with auth data (idToken, refreshToken, uid, email, etc.)
125
+ or None if timed out or errored.
126
+ """
127
+ global _result
128
+ _result = _AuthResult()
129
+
130
+ server = _OAuthHTTPServer(
131
+ (OAUTH_CALLBACK_HOST, OAUTH_CALLBACK_PORT),
132
+ _OAuthHandler,
133
+ select_account=select_account,
134
+ )
135
+ server_thread = threading.Thread(target=server.serve_forever, daemon=True)
136
+ server_thread.start()
137
+
138
+ try:
139
+ # Wait for the callback
140
+ _result.event.wait(timeout=timeout)
141
+ return _result.data
142
+ finally:
143
+ server.shutdown()
144
+ server_thread.join(timeout=2.0)
145
+
@@ -0,0 +1,196 @@
1
+ """
2
+ Token management — store, load, refresh Firebase auth tokens.
3
+
4
+ Tokens are stored in ~/.valkyrie/auth.json. The refresh token is used
5
+ to obtain new ID tokens when they expire (Firebase ID tokens last 1 hour).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import time
12
+ from dataclasses import dataclass
13
+ from typing import TYPE_CHECKING, Any
14
+
15
+ import httpx
16
+
17
+ from valkyrie.auth.firebase_config import (
18
+ FIREBASE_AUTH_BASE,
19
+ FIREBASE_CONFIG,
20
+ FIREBASE_TOKEN_BASE,
21
+ )
22
+ from valkyrie.core.paths import get_auth_path
23
+
24
+ if TYPE_CHECKING:
25
+ from pathlib import Path
26
+
27
+
28
+ @dataclass
29
+ class AuthUser:
30
+ """Authenticated user info."""
31
+
32
+ uid: str
33
+ email: str
34
+ display_name: str | None
35
+ photo_url: str | None
36
+ id_token: str
37
+ refresh_token: str
38
+ expires_at: float # Unix timestamp
39
+
40
+ @property
41
+ def is_expired(self) -> bool:
42
+ """Check if the ID token has expired (with 5-minute buffer)."""
43
+ return time.time() >= (self.expires_at - 300)
44
+
45
+ def to_dict(self) -> dict[str, Any]:
46
+ """Serialize to dict for storage."""
47
+ return {
48
+ "uid": self.uid,
49
+ "email": self.email,
50
+ "display_name": self.display_name,
51
+ "photo_url": self.photo_url,
52
+ "id_token": self.id_token,
53
+ "refresh_token": self.refresh_token,
54
+ "expires_at": self.expires_at,
55
+ }
56
+
57
+ @classmethod
58
+ def from_dict(cls, data: dict[str, Any]) -> AuthUser:
59
+ """Deserialize from dict."""
60
+ return cls(
61
+ uid=data["uid"],
62
+ email=data["email"],
63
+ display_name=data.get("display_name"),
64
+ photo_url=data.get("photo_url"),
65
+ id_token=data["id_token"],
66
+ refresh_token=data["refresh_token"],
67
+ expires_at=data.get("expires_at", 0),
68
+ )
69
+
70
+ @classmethod
71
+ def from_oauth_callback(cls, data: dict[str, Any]) -> AuthUser:
72
+ """Create from the OAuth callback data."""
73
+ return cls(
74
+ uid=data["uid"],
75
+ email=data["email"],
76
+ display_name=data.get("displayName"),
77
+ photo_url=data.get("photoURL"),
78
+ id_token=data["idToken"],
79
+ refresh_token=data["refreshToken"],
80
+ # Firebase ID tokens last 3600 seconds
81
+ expires_at=time.time() + 3600,
82
+ )
83
+
84
+
85
+ def save_auth(user: AuthUser) -> Path:
86
+ """Save auth data to disk. Returns the file path."""
87
+ path = get_auth_path()
88
+ path.parent.mkdir(parents=True, exist_ok=True)
89
+ path.write_text(json.dumps(user.to_dict(), indent=2) + "\n")
90
+ # Restrict permissions (owner read/write only)
91
+ path.chmod(0o600)
92
+ return path
93
+
94
+
95
+ def load_auth() -> AuthUser | None:
96
+ """Load auth data from disk. Returns None if not found."""
97
+ path = get_auth_path()
98
+ if not path.exists():
99
+ return None
100
+ try:
101
+ data = json.loads(path.read_text())
102
+ return AuthUser.from_dict(data)
103
+ except (json.JSONDecodeError, KeyError):
104
+ return None
105
+
106
+
107
+ def clear_auth() -> None:
108
+ """Delete the auth file."""
109
+ path = get_auth_path()
110
+ if path.exists():
111
+ path.unlink()
112
+
113
+
114
+ def refresh_id_token(user: AuthUser) -> AuthUser | None:
115
+ """
116
+ Use the refresh token to get a new ID token from Firebase.
117
+
118
+ Returns updated AuthUser or None on failure.
119
+ """
120
+ url = f"{FIREBASE_TOKEN_BASE}/token?key={FIREBASE_CONFIG['apiKey']}"
121
+
122
+ try:
123
+ response = httpx.post(
124
+ url,
125
+ data={
126
+ "grant_type": "refresh_token",
127
+ "refresh_token": user.refresh_token,
128
+ },
129
+ timeout=15.0,
130
+ )
131
+ response.raise_for_status()
132
+ data = response.json()
133
+
134
+ user.id_token = data["id_token"]
135
+ user.refresh_token = data["refresh_token"]
136
+ user.expires_at = time.time() + int(data.get("expires_in", 3600))
137
+ save_auth(user)
138
+ return user
139
+
140
+ except (httpx.HTTPError, KeyError):
141
+ return None
142
+
143
+
144
+ def get_valid_user() -> AuthUser | None:
145
+ """
146
+ Load auth and refresh if needed. Returns a user with a valid ID token,
147
+ or None if not authenticated.
148
+ """
149
+ user = load_auth()
150
+ if user is None:
151
+ return None
152
+
153
+ if user.is_expired:
154
+ user = refresh_id_token(user)
155
+
156
+ return user
157
+
158
+
159
+ def delete_firebase_account(id_token: str) -> tuple[bool, str]:
160
+ """
161
+ Permanently delete the Firebase Auth account for the given ID token.
162
+
163
+ Returns (success, detail_message).
164
+ """
165
+ url = f"{FIREBASE_AUTH_BASE}/accounts:delete?key={FIREBASE_CONFIG['apiKey']}"
166
+ try:
167
+ response = httpx.post(
168
+ url,
169
+ json={"idToken": id_token},
170
+ timeout=15.0,
171
+ )
172
+ if response.status_code == 200:
173
+ return True, "Account deleted from Firebase Authentication."
174
+
175
+ detail = ""
176
+ try:
177
+ err_data = response.json()
178
+ detail = str(err_data.get("error", {}).get("message", ""))
179
+ except ValueError:
180
+ detail = response.text[:200]
181
+
182
+ if "CREDENTIAL_TOO_OLD_LOGIN_REQUIRED" in detail:
183
+ return (
184
+ False,
185
+ "Firebase requires a recent sign-in before deleting an account. "
186
+ "Run '/account switch' (or 'valkyrie auth switch') to re-authenticate, "
187
+ "then retry.",
188
+ )
189
+ return (
190
+ False,
191
+ f"Firebase account deletion failed ({response.status_code}): "
192
+ f"{detail or 'unknown error'}",
193
+ )
194
+ except httpx.HTTPError as exc:
195
+ return False, f"Network error during account deletion: {exc}"
196
+
@@ -0,0 +1,37 @@
1
+ """Chat engine — message protocol, streaming clients, renderer, and REPL."""
2
+
3
+ from valkyrie.chat.clients import ChatStreamError, StreamChunk, stream_chat_completion
4
+ from valkyrie.chat.commands import SlashCommand, SlashCommandRegistry, ValkyrieCompleter
5
+ from valkyrie.chat.engine import (
6
+ ChatEngine,
7
+ build_command_registry,
8
+ build_system_prompt,
9
+ run_chat_repl,
10
+ )
11
+ from valkyrie.chat.messages import (
12
+ ChatMessage,
13
+ ContextBudget,
14
+ MessageRole,
15
+ TokenUsage,
16
+ estimate_messages_tokens,
17
+ estimate_tokens,
18
+ )
19
+
20
+ __all__ = [
21
+ "ChatEngine",
22
+ "ChatMessage",
23
+ "ChatStreamError",
24
+ "ContextBudget",
25
+ "MessageRole",
26
+ "SlashCommand",
27
+ "SlashCommandRegistry",
28
+ "StreamChunk",
29
+ "TokenUsage",
30
+ "ValkyrieCompleter",
31
+ "build_command_registry",
32
+ "build_system_prompt",
33
+ "estimate_messages_tokens",
34
+ "estimate_tokens",
35
+ "run_chat_repl",
36
+ "stream_chat_completion",
37
+ ]