glaip-sdk 0.6.5b3__py3-none-any.whl → 0.7.17__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 (145) hide show
  1. glaip_sdk/__init__.py +42 -5
  2. glaip_sdk/agents/base.py +362 -39
  3. glaip_sdk/branding.py +113 -2
  4. glaip_sdk/cli/account_store.py +15 -0
  5. glaip_sdk/cli/auth.py +14 -8
  6. glaip_sdk/cli/commands/accounts.py +1 -1
  7. glaip_sdk/cli/commands/agents/__init__.py +116 -0
  8. glaip_sdk/cli/commands/agents/_common.py +562 -0
  9. glaip_sdk/cli/commands/agents/create.py +155 -0
  10. glaip_sdk/cli/commands/agents/delete.py +64 -0
  11. glaip_sdk/cli/commands/agents/get.py +89 -0
  12. glaip_sdk/cli/commands/agents/list.py +129 -0
  13. glaip_sdk/cli/commands/agents/run.py +264 -0
  14. glaip_sdk/cli/commands/agents/sync_langflow.py +72 -0
  15. glaip_sdk/cli/commands/agents/update.py +112 -0
  16. glaip_sdk/cli/commands/common_config.py +15 -12
  17. glaip_sdk/cli/commands/configure.py +2 -3
  18. glaip_sdk/cli/commands/mcps/__init__.py +94 -0
  19. glaip_sdk/cli/commands/mcps/_common.py +459 -0
  20. glaip_sdk/cli/commands/mcps/connect.py +82 -0
  21. glaip_sdk/cli/commands/mcps/create.py +152 -0
  22. glaip_sdk/cli/commands/mcps/delete.py +73 -0
  23. glaip_sdk/cli/commands/mcps/get.py +212 -0
  24. glaip_sdk/cli/commands/mcps/list.py +69 -0
  25. glaip_sdk/cli/commands/mcps/tools.py +235 -0
  26. glaip_sdk/cli/commands/mcps/update.py +190 -0
  27. glaip_sdk/cli/commands/models.py +2 -4
  28. glaip_sdk/cli/commands/shared/__init__.py +21 -0
  29. glaip_sdk/cli/commands/shared/formatters.py +91 -0
  30. glaip_sdk/cli/commands/tools/__init__.py +69 -0
  31. glaip_sdk/cli/commands/tools/_common.py +80 -0
  32. glaip_sdk/cli/commands/tools/create.py +228 -0
  33. glaip_sdk/cli/commands/tools/delete.py +61 -0
  34. glaip_sdk/cli/commands/tools/get.py +103 -0
  35. glaip_sdk/cli/commands/tools/list.py +69 -0
  36. glaip_sdk/cli/commands/tools/script.py +49 -0
  37. glaip_sdk/cli/commands/tools/update.py +102 -0
  38. glaip_sdk/cli/commands/transcripts/__init__.py +90 -0
  39. glaip_sdk/cli/commands/transcripts/_common.py +9 -0
  40. glaip_sdk/cli/commands/transcripts/clear.py +5 -0
  41. glaip_sdk/cli/commands/transcripts/detail.py +5 -0
  42. glaip_sdk/cli/commands/{transcripts.py → transcripts_original.py} +2 -1
  43. glaip_sdk/cli/commands/update.py +163 -17
  44. glaip_sdk/cli/config.py +1 -0
  45. glaip_sdk/cli/core/output.py +12 -7
  46. glaip_sdk/cli/entrypoint.py +20 -0
  47. glaip_sdk/cli/main.py +127 -39
  48. glaip_sdk/cli/pager.py +3 -3
  49. glaip_sdk/cli/resolution.py +2 -1
  50. glaip_sdk/cli/slash/accounts_controller.py +112 -32
  51. glaip_sdk/cli/slash/agent_session.py +5 -2
  52. glaip_sdk/cli/slash/prompt.py +11 -0
  53. glaip_sdk/cli/slash/remote_runs_controller.py +3 -1
  54. glaip_sdk/cli/slash/session.py +375 -25
  55. glaip_sdk/cli/slash/tui/__init__.py +28 -1
  56. glaip_sdk/cli/slash/tui/accounts.tcss +97 -6
  57. glaip_sdk/cli/slash/tui/accounts_app.py +1107 -126
  58. glaip_sdk/cli/slash/tui/clipboard.py +195 -0
  59. glaip_sdk/cli/slash/tui/context.py +92 -0
  60. glaip_sdk/cli/slash/tui/indicators.py +341 -0
  61. glaip_sdk/cli/slash/tui/keybind_registry.py +235 -0
  62. glaip_sdk/cli/slash/tui/layouts/__init__.py +14 -0
  63. glaip_sdk/cli/slash/tui/layouts/harlequin.py +184 -0
  64. glaip_sdk/cli/slash/tui/loading.py +43 -21
  65. glaip_sdk/cli/slash/tui/remote_runs_app.py +152 -20
  66. glaip_sdk/cli/slash/tui/terminal.py +407 -0
  67. glaip_sdk/cli/slash/tui/theme/__init__.py +15 -0
  68. glaip_sdk/cli/slash/tui/theme/catalog.py +79 -0
  69. glaip_sdk/cli/slash/tui/theme/manager.py +112 -0
  70. glaip_sdk/cli/slash/tui/theme/tokens.py +55 -0
  71. glaip_sdk/cli/slash/tui/toast.py +388 -0
  72. glaip_sdk/cli/transcript/history.py +1 -1
  73. glaip_sdk/cli/transcript/viewer.py +5 -3
  74. glaip_sdk/cli/tui_settings.py +125 -0
  75. glaip_sdk/cli/update_notifier.py +215 -7
  76. glaip_sdk/cli/validators.py +1 -1
  77. glaip_sdk/client/__init__.py +2 -1
  78. glaip_sdk/client/_schedule_payloads.py +89 -0
  79. glaip_sdk/client/agents.py +290 -16
  80. glaip_sdk/client/base.py +25 -0
  81. glaip_sdk/client/hitl.py +136 -0
  82. glaip_sdk/client/main.py +7 -5
  83. glaip_sdk/client/mcps.py +44 -13
  84. glaip_sdk/client/payloads/agent/__init__.py +23 -0
  85. glaip_sdk/client/{_agent_payloads.py → payloads/agent/requests.py} +28 -48
  86. glaip_sdk/client/payloads/agent/responses.py +43 -0
  87. glaip_sdk/client/run_rendering.py +414 -3
  88. glaip_sdk/client/schedules.py +439 -0
  89. glaip_sdk/client/tools.py +57 -26
  90. glaip_sdk/config/constants.py +22 -2
  91. glaip_sdk/guardrails/__init__.py +80 -0
  92. glaip_sdk/guardrails/serializer.py +89 -0
  93. glaip_sdk/hitl/__init__.py +48 -0
  94. glaip_sdk/hitl/base.py +64 -0
  95. glaip_sdk/hitl/callback.py +43 -0
  96. glaip_sdk/hitl/local.py +121 -0
  97. glaip_sdk/hitl/remote.py +523 -0
  98. glaip_sdk/models/__init__.py +47 -1
  99. glaip_sdk/models/_provider_mappings.py +101 -0
  100. glaip_sdk/models/_validation.py +97 -0
  101. glaip_sdk/models/agent.py +2 -1
  102. glaip_sdk/models/agent_runs.py +2 -1
  103. glaip_sdk/models/constants.py +141 -0
  104. glaip_sdk/models/model.py +170 -0
  105. glaip_sdk/models/schedule.py +224 -0
  106. glaip_sdk/payload_schemas/agent.py +1 -0
  107. glaip_sdk/payload_schemas/guardrails.py +34 -0
  108. glaip_sdk/registry/tool.py +273 -66
  109. glaip_sdk/runner/__init__.py +76 -0
  110. glaip_sdk/runner/base.py +84 -0
  111. glaip_sdk/runner/deps.py +115 -0
  112. glaip_sdk/runner/langgraph.py +1055 -0
  113. glaip_sdk/runner/logging_config.py +77 -0
  114. glaip_sdk/runner/mcp_adapter/__init__.py +13 -0
  115. glaip_sdk/runner/mcp_adapter/base_mcp_adapter.py +43 -0
  116. glaip_sdk/runner/mcp_adapter/langchain_mcp_adapter.py +257 -0
  117. glaip_sdk/runner/mcp_adapter/mcp_config_builder.py +116 -0
  118. glaip_sdk/runner/tool_adapter/__init__.py +18 -0
  119. glaip_sdk/runner/tool_adapter/base_tool_adapter.py +44 -0
  120. glaip_sdk/runner/tool_adapter/langchain_tool_adapter.py +242 -0
  121. glaip_sdk/schedules/__init__.py +22 -0
  122. glaip_sdk/schedules/base.py +291 -0
  123. glaip_sdk/tools/base.py +67 -14
  124. glaip_sdk/utils/__init__.py +1 -0
  125. glaip_sdk/utils/a2a/__init__.py +34 -0
  126. glaip_sdk/utils/a2a/event_processor.py +188 -0
  127. glaip_sdk/utils/agent_config.py +8 -2
  128. glaip_sdk/utils/bundler.py +138 -2
  129. glaip_sdk/utils/import_resolver.py +43 -11
  130. glaip_sdk/utils/rendering/renderer/base.py +58 -0
  131. glaip_sdk/utils/runtime_config.py +120 -0
  132. glaip_sdk/utils/sync.py +31 -11
  133. glaip_sdk/utils/tool_detection.py +301 -0
  134. glaip_sdk/utils/tool_storage_provider.py +140 -0
  135. {glaip_sdk-0.6.5b3.dist-info → glaip_sdk-0.7.17.dist-info}/METADATA +49 -38
  136. glaip_sdk-0.7.17.dist-info/RECORD +224 -0
  137. {glaip_sdk-0.6.5b3.dist-info → glaip_sdk-0.7.17.dist-info}/WHEEL +2 -1
  138. glaip_sdk-0.7.17.dist-info/entry_points.txt +2 -0
  139. glaip_sdk-0.7.17.dist-info/top_level.txt +1 -0
  140. glaip_sdk/cli/commands/agents.py +0 -1509
  141. glaip_sdk/cli/commands/mcps.py +0 -1356
  142. glaip_sdk/cli/commands/tools.py +0 -576
  143. glaip_sdk/cli/utils.py +0 -263
  144. glaip_sdk-0.6.5b3.dist-info/RECORD +0 -145
  145. glaip_sdk-0.6.5b3.dist-info/entry_points.txt +0 -3
@@ -0,0 +1,407 @@
1
+ """Terminal capability detection for TUI applications.
2
+
3
+ This module provides terminal capability detection including TTY status, ANSI support,
4
+ OSC 52 clipboard support, mouse support, truecolor support, and OSC 11 background
5
+ color detection for automatic theme selection.
6
+
7
+ Authors:
8
+ Raymond Christopher (raymond.christopher@gdplabs.id)
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import os
15
+ import re
16
+ import select
17
+ import sys
18
+ import time
19
+ from dataclasses import dataclass
20
+ from typing import Literal
21
+
22
+ # Windows compatibility: termios and tty may not be available
23
+ try:
24
+ import termios
25
+ import tty
26
+
27
+ _TERMIOS_AVAILABLE = True
28
+ except ImportError: # pragma: no cover
29
+ # Platform-specific: Windows doesn't have termios/tty modules
30
+ # This exception is only raised on Windows or systems without termios support
31
+ # Testing would require complex module reloading and platform-specific test setup
32
+ _TERMIOS_AVAILABLE = False
33
+
34
+
35
+ @dataclass
36
+ class TerminalCapabilities:
37
+ """Terminal feature detection results.
38
+
39
+ Attributes:
40
+ tty: Whether stdout is a TTY.
41
+ ansi: Whether ANSI escape sequences are supported.
42
+ osc52: Whether OSC 52 (clipboard) is supported.
43
+ osc11_bg: Raw RGB color string from OSC 11 query, or None if not detected.
44
+ mouse: Whether mouse support is available.
45
+ truecolor: Whether truecolor (24-bit) color is supported.
46
+ """
47
+
48
+ tty: bool
49
+ ansi: bool
50
+ osc52: bool
51
+ osc11_bg: str | None
52
+ mouse: bool
53
+ truecolor: bool
54
+
55
+ @property
56
+ def background_mode(self) -> Literal["light", "dark"]:
57
+ """Derive light/dark mode from OSC 11 background color.
58
+
59
+ Returns:
60
+ "light" if luminance > 0.5, "dark" otherwise. Defaults to "dark"
61
+ if osc11_bg is None.
62
+ """
63
+ if self.osc11_bg is None:
64
+ return "dark"
65
+
66
+ rgb = _parse_color_response(self.osc11_bg)
67
+ if rgb is None:
68
+ return "dark"
69
+
70
+ luminance = _calculate_luminance(rgb[0], rgb[1], rgb[2])
71
+ return "light" if luminance > 0.5 else "dark"
72
+
73
+ @classmethod
74
+ async def detect(cls, *, detect_osc11: bool = True) -> TerminalCapabilities:
75
+ """Detect terminal capabilities asynchronously with fast timeout.
76
+
77
+ This method performs capability detection including OSC 11 background
78
+ color detection with a 100ms timeout. The method completes quickly
79
+ (< 100ms) as required by the roadmap. OSC 11 detection may return None
80
+ if the terminal doesn't respond within the timeout; use
81
+ detect_terminal_background() for full 1-second timeout when needed.
82
+
83
+ Args:
84
+ detect_osc11: When False, skip OSC 11 background detection.
85
+
86
+ Returns:
87
+ TerminalCapabilities instance with detected capabilities.
88
+ """
89
+ tty_available = sys.stdout.isatty()
90
+ term = os.environ.get("TERM", "")
91
+ colorterm = os.environ.get("COLORTERM", "")
92
+
93
+ # Basic capability detection
94
+ ansi = tty_available and term not in ("dumb", "")
95
+ osc52 = detect_osc52_support()
96
+ mouse = tty_available and term not in ("dumb", "")
97
+ truecolor = colorterm in ("truecolor", "24bit")
98
+
99
+ osc11_bg: str | None = None
100
+ if detect_osc11 and tty_available and sys.stdin.isatty():
101
+ # OSC 11 detection: use fast path (<100ms timeout)
102
+ osc11_bg = await _detect_osc11_fast()
103
+
104
+ return cls(
105
+ tty=tty_available,
106
+ ansi=ansi,
107
+ osc52=osc52,
108
+ osc11_bg=osc11_bg,
109
+ mouse=mouse,
110
+ truecolor=truecolor,
111
+ )
112
+
113
+
114
+ async def detect_terminal_background() -> str | None:
115
+ """Detect terminal background color using OSC 11 with full timeout.
116
+
117
+ This function can be called separately to await OSC 11 detection with the
118
+ full 1-second timeout. Useful for theme initialization where a slight delay
119
+ is acceptable.
120
+
121
+ Returns:
122
+ Raw RGB color string from terminal, or None if detection fails or times out.
123
+ """
124
+ if not sys.stdout.isatty() or not sys.stdin.isatty():
125
+ return None
126
+
127
+ if not _TERMIOS_AVAILABLE:
128
+ return None
129
+
130
+ return await _detect_osc11_full()
131
+
132
+
133
+ async def _detect_osc11_fast() -> str | None:
134
+ """Fast-path OSC 11 detection (used by detect())."""
135
+ return await _detect_osc11_impl(timeout=0.1)
136
+
137
+
138
+ async def _detect_osc11_full() -> str | None:
139
+ """Full-timeout OSC 11 detection (used by detect_terminal_background())."""
140
+ return await _detect_osc11_impl(timeout=1.0)
141
+
142
+
143
+ def _read_osc11_char_with_timeout(start_time: float, timeout_seconds: float) -> str | None:
144
+ """Read a single character from stdin with timeout.
145
+
146
+ Args:
147
+ start_time: Start time for timeout calculation.
148
+ timeout_seconds: Maximum time to wait.
149
+
150
+ Returns:
151
+ Character read or None on timeout/error.
152
+ """
153
+ elapsed = time.time() - start_time
154
+ if elapsed >= timeout_seconds:
155
+ return None
156
+
157
+ try:
158
+ remaining = timeout_seconds - elapsed
159
+ ready, _, _ = select.select([sys.stdin], [], [], min(0.1, remaining))
160
+ if not ready:
161
+ return None
162
+
163
+ char = sys.stdin.read(1)
164
+ return char if char else None
165
+ except (OSError, ValueError):
166
+ return None
167
+
168
+
169
+ def _check_osc11_complete(response_text: str, response_length: int) -> str | None:
170
+ """Check if OSC 11 response is complete.
171
+
172
+ Args:
173
+ response_text: Current response text.
174
+ response_length: Length of response characters.
175
+
176
+ Returns:
177
+ Matched color string if complete, None otherwise.
178
+ """
179
+ match = _match_osc11_response(response_text)
180
+ if match:
181
+ return match
182
+
183
+ # If we see BEL (\x07) terminator, check one more time then give up
184
+ if "\x07" in response_text and response_length >= 10:
185
+ return None
186
+
187
+ return None
188
+
189
+
190
+ def _read_osc11_response_sync(timeout_seconds: float) -> str | None:
191
+ """Synchronously read OSC 11 response from stdin.
192
+
193
+ This runs in a thread to avoid blocking the event loop.
194
+
195
+ Args:
196
+ timeout_seconds: Maximum time to wait.
197
+
198
+ Returns:
199
+ Color string or None.
200
+ """
201
+ response_chars: list[str] = []
202
+ start_time = time.time()
203
+ max_chars = 200 # Reasonable limit to prevent infinite loops
204
+
205
+ while len(response_chars) < max_chars:
206
+ elapsed = time.time() - start_time
207
+ if elapsed >= timeout_seconds:
208
+ return None
209
+
210
+ char = _read_osc11_char_with_timeout(start_time, timeout_seconds)
211
+ if char is None:
212
+ # Check timeout again after failed read
213
+ if time.time() - start_time >= timeout_seconds:
214
+ return None
215
+ continue
216
+
217
+ response_chars.append(char)
218
+ response_text = "".join(response_chars)
219
+
220
+ result = _check_osc11_complete(response_text, len(response_chars))
221
+ if result is not None:
222
+ return result
223
+
224
+ return None
225
+
226
+
227
+ async def _detect_osc11_impl(timeout: float) -> str | None:
228
+ """Internal OSC 11 detection implementation.
229
+
230
+ Args:
231
+ timeout: Maximum time to wait for terminal response in seconds.
232
+
233
+ Returns:
234
+ Raw RGB color string, or None on timeout/error.
235
+ """
236
+ if not _TERMIOS_AVAILABLE:
237
+ return None
238
+
239
+ old_settings = None
240
+ try:
241
+ # Save terminal settings
242
+ old_settings = termios.tcgetattr(sys.stdin)
243
+ tty.setraw(sys.stdin.fileno())
244
+
245
+ # Send OSC 11 query
246
+ sys.stdout.write("\x1b]11;?\x07")
247
+ sys.stdout.flush()
248
+
249
+ # Read response in a thread to avoid blocking
250
+ try:
251
+ result = await asyncio.wait_for(asyncio.to_thread(_read_osc11_response_sync, timeout), timeout=timeout)
252
+ return result
253
+ except TimeoutError:
254
+ return None
255
+
256
+ except Exception:
257
+ return None
258
+ finally:
259
+ # Restore terminal settings
260
+ if old_settings is not None:
261
+ try:
262
+ termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
263
+ except Exception:
264
+ pass
265
+
266
+
267
+ def _match_osc11_response(text: str) -> str | None:
268
+ """Extract OSC 11 color response from text.
269
+
270
+ Args:
271
+ text: Raw text from stdin.
272
+
273
+ Returns:
274
+ Color string (e.g., "rgb:RRRR/GGGG/BBBB") or None if not found.
275
+ """
276
+ # Match OSC 11 response: \x1b]11;...\x07
277
+ match = re.search(r"\x1b\]11;([^\x07\x1b]+)", text)
278
+ if match:
279
+ return match.group(1)
280
+ return None
281
+
282
+
283
+ def _parse_color_response(color_str: str) -> tuple[int, int, int] | None:
284
+ """Parse RGB color from various terminal color formats.
285
+
286
+ Supports:
287
+ - rgb:RRRR/GGGG/BBBB (16-bit per channel)
288
+ - rgb:RR/GG/BB (8-bit per channel)
289
+ - #RRGGBB (hex)
290
+ - rgb(R,G,B) (decimal)
291
+
292
+ Args:
293
+ color_str: Color string from terminal.
294
+
295
+ Returns:
296
+ Tuple of (R, G, B) values in 0-255 range, or None if parsing fails.
297
+ """
298
+ if not color_str:
299
+ return None
300
+
301
+ try:
302
+ if color_str.startswith("rgb:"):
303
+ # Format: rgb:RRRR/GGGG/BBBB (16-bit) or rgb:RR/GG/BB (8-bit)
304
+ parts = color_str[4:].split("/")
305
+ if len(parts) == 3:
306
+ r_val = int(parts[0], 16)
307
+ g_val = int(parts[1], 16)
308
+ b_val = int(parts[2], 16)
309
+
310
+ # Convert 16-bit to 8-bit: if hex string has 4 digits, it's 16-bit
311
+ # and we take the high byte (>> 8). If 2 digits, it's already 8-bit.
312
+ if len(parts[0]) == 4: # 16-bit format
313
+ r_val = r_val >> 8
314
+ if len(parts[1]) == 4: # 16-bit format
315
+ g_val = g_val >> 8
316
+ if len(parts[2]) == 4: # 16-bit format
317
+ b_val = b_val >> 8
318
+
319
+ return (r_val, g_val, b_val)
320
+
321
+ elif color_str.startswith("#"):
322
+ # Format: #RRGGBB
323
+ if len(color_str) == 7:
324
+ r = int(color_str[1:3], 16)
325
+ g = int(color_str[3:5], 16)
326
+ b = int(color_str[5:7], 16)
327
+ return (r, g, b)
328
+
329
+ elif color_str.startswith("rgb("):
330
+ # Format: rgb(R,G,B)
331
+ parts = color_str[4:-1].split(",")
332
+ if len(parts) == 3:
333
+ r = int(parts[0].strip())
334
+ g = int(parts[1].strip())
335
+ b = int(parts[2].strip())
336
+ return (r, g, b)
337
+
338
+ except (ValueError, IndexError):
339
+ pass
340
+
341
+ return None
342
+
343
+
344
+ def _calculate_luminance(r: int, g: int, b: int) -> float:
345
+ """Calculate relative luminance from RGB values.
346
+
347
+ Uses the relative luminance formula from WCAG:
348
+ L = 0.299*R + 0.587*G + 0.114*B
349
+
350
+ Args:
351
+ r: Red component (0-255).
352
+ g: Green component (0-255).
353
+ b: Blue component (0-255).
354
+
355
+ Returns:
356
+ Luminance value normalized to 0.0-1.0 range.
357
+ """
358
+ return (0.299 * r + 0.587 * g + 0.114 * b) / 255.0
359
+
360
+
361
+ def _check_terminal_in_env(env_value: str, terminals: list[str]) -> bool:
362
+ """Check if any terminal name appears in environment value.
363
+
364
+ Args:
365
+ env_value: Environment variable value to check.
366
+ terminals: List of terminal names to search for.
367
+
368
+ Returns:
369
+ True if any terminal name is found in env_value.
370
+ """
371
+ return any(terminal in env_value for terminal in terminals)
372
+
373
+
374
+ def detect_osc52_support() -> bool:
375
+ """Check if terminal likely supports OSC 52 (clipboard).
376
+
377
+ Returns:
378
+ True if terminal name suggests OSC 52 support.
379
+ """
380
+ term = os.environ.get("TERM", "").lower()
381
+ term_program = os.environ.get("TERM_PROGRAM", "").lower()
382
+ term_program_version = os.environ.get("TERM_PROGRAM_VERSION", "").lower()
383
+
384
+ # Known terminals that support OSC 52
385
+ osc52_terminals = [
386
+ "iterm",
387
+ "kitty",
388
+ "alacritty",
389
+ "wezterm",
390
+ "vscode",
391
+ "windows terminal",
392
+ "mintty", # Windows terminal emulator
393
+ ]
394
+
395
+ # Check TERM_PROGRAM first (most reliable)
396
+ if term_program and _check_terminal_in_env(term_program, osc52_terminals):
397
+ return True
398
+
399
+ # Check TERM_PROGRAM_VERSION (VS Code uses this)
400
+ if term_program_version and _check_terminal_in_env(term_program_version, osc52_terminals):
401
+ return True
402
+
403
+ # Check TERM (less reliable but sometimes works)
404
+ if term and _check_terminal_in_env(term, osc52_terminals):
405
+ return True
406
+
407
+ return False
@@ -0,0 +1,15 @@
1
+ """Theme system primitives for Textual TUIs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from glaip_sdk.cli.slash.tui.theme.catalog import get_builtin_theme, list_builtin_themes
6
+ from glaip_sdk.cli.slash.tui.theme.manager import ThemeManager, ThemeMode
7
+ from glaip_sdk.cli.slash.tui.theme.tokens import ThemeTokens
8
+
9
+ __all__ = [
10
+ "ThemeManager",
11
+ "ThemeMode",
12
+ "ThemeTokens",
13
+ "get_builtin_theme",
14
+ "list_builtin_themes",
15
+ ]
@@ -0,0 +1,79 @@
1
+ """Built-in theme catalog for TUI applications.
2
+
3
+ This module implements Phase 2 of the TUI Theme System spec, providing a foundational
4
+ set of 12 color tokens (primary, secondary, accent, background, background_panel, text,
5
+ text_muted, success, warning, error, info). Additional tokens (e.g., diff.added,
6
+ syntax.*, backgroundElevated, textDim) will be added in future phases per the spec's
7
+ "100+ color tokens" requirement.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from glaip_sdk.cli.slash.tui.theme.tokens import ThemeModeLiteral, ThemeTokens
13
+
14
+ _BUILTIN_THEMES: dict[str, ThemeTokens] = {
15
+ "gl-dark": ThemeTokens(
16
+ name="gl-dark",
17
+ mode="dark",
18
+ primary="#6EA8FE",
19
+ secondary="#ADB5BD",
20
+ accent="#C77DFF",
21
+ background="#0B0F19",
22
+ background_panel="#111827",
23
+ text="#E5E7EB",
24
+ text_muted="#9CA3AF",
25
+ success="#34D399",
26
+ warning="#FBBF24",
27
+ error="#F87171",
28
+ info="#60A5FA",
29
+ ),
30
+ "gl-light": ThemeTokens(
31
+ name="gl-light",
32
+ mode="light",
33
+ primary="#1D4ED8",
34
+ secondary="#4B5563",
35
+ accent="#7C3AED",
36
+ background="#FFFFFF",
37
+ background_panel="#F3F4F6",
38
+ text="#111827",
39
+ text_muted="#4B5563",
40
+ success="#059669",
41
+ warning="#B45309",
42
+ error="#B91C1C",
43
+ info="#1D4ED8",
44
+ ),
45
+ "gl-high-contrast": ThemeTokens(
46
+ name="gl-high-contrast",
47
+ mode="dark",
48
+ # High-contrast theme uses uniform colors (#FFFFFF on #000000) to maximize
49
+ # contrast for accessibility. Semantic distinctions (success/warning/error)
50
+ # are intentionally uniform to prioritize maximum readability over color
51
+ # coding, per accessibility best practices for high-contrast modes.
52
+ primary="#FFFFFF",
53
+ secondary="#FFFFFF",
54
+ accent="#FFFFFF",
55
+ background="#000000",
56
+ background_panel="#000000",
57
+ text="#FFFFFF",
58
+ text_muted="#FFFFFF",
59
+ success="#FFFFFF",
60
+ warning="#FFFFFF",
61
+ error="#FFFFFF",
62
+ info="#FFFFFF",
63
+ ),
64
+ }
65
+
66
+
67
+ def get_builtin_theme(name: str) -> ThemeTokens | None:
68
+ """Return a built-in theme by name."""
69
+ return _BUILTIN_THEMES.get(name)
70
+
71
+
72
+ def list_builtin_themes() -> list[str]:
73
+ """List available built-in theme names."""
74
+ return sorted(_BUILTIN_THEMES)
75
+
76
+
77
+ def default_theme_name_for_mode(mode: ThemeModeLiteral) -> str:
78
+ """Return the default theme name for the given light/dark mode."""
79
+ return "gl-light" if mode == "light" else "gl-dark"
@@ -0,0 +1,112 @@
1
+ """Theme manager for TUI applications."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from enum import Enum
7
+ from typing import Literal
8
+
9
+ from glaip_sdk.cli.account_store import AccountStore, AccountStoreError
10
+ from glaip_sdk.cli.slash.tui.terminal import TerminalCapabilities
11
+ from glaip_sdk.cli.slash.tui.theme.catalog import default_theme_name_for_mode, get_builtin_theme
12
+ from glaip_sdk.cli.slash.tui.theme.tokens import ThemeTokens
13
+ from glaip_sdk.cli.tui_settings import persist_tui_theme
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class ThemeMode(str, Enum):
19
+ """User-selectable theme mode."""
20
+
21
+ AUTO = "auto"
22
+ LIGHT = "light"
23
+ DARK = "dark"
24
+
25
+
26
+ class ThemeManager:
27
+ """Resolve active theme tokens from terminal state and user preferences."""
28
+
29
+ def __init__(
30
+ self,
31
+ terminal: TerminalCapabilities,
32
+ *,
33
+ mode: ThemeMode | str = ThemeMode.AUTO,
34
+ theme: str | None = None,
35
+ settings_store: AccountStore | None = None,
36
+ ) -> None:
37
+ """Initialize the theme manager."""
38
+ self._terminal = terminal
39
+ self._mode = self._coerce_mode(mode)
40
+ self._theme = self._normalize_theme_name(theme)
41
+ self._settings_store = settings_store
42
+
43
+ @property
44
+ def mode(self) -> ThemeMode:
45
+ """Return configured mode (auto/light/dark)."""
46
+ return self._mode
47
+
48
+ @property
49
+ def effective_mode(self) -> Literal["light", "dark"]:
50
+ """Return resolved light/dark mode."""
51
+ if self._mode == ThemeMode.AUTO:
52
+ return self._terminal.background_mode
53
+ return "light" if self._mode == ThemeMode.LIGHT else "dark"
54
+
55
+ @property
56
+ def theme_name(self) -> str:
57
+ """Return resolved theme name."""
58
+ return self._theme or default_theme_name_for_mode(self.effective_mode)
59
+
60
+ @property
61
+ def tokens(self) -> ThemeTokens:
62
+ """Return tokens for the resolved theme."""
63
+ chosen = get_builtin_theme(self.theme_name)
64
+ if chosen is not None:
65
+ return chosen
66
+
67
+ fallback_name = default_theme_name_for_mode(self.effective_mode)
68
+ fallback = get_builtin_theme(fallback_name)
69
+ if fallback is None:
70
+ raise RuntimeError(f"Missing default theme: {fallback_name}")
71
+
72
+ return fallback
73
+
74
+ def set_mode(self, mode: ThemeMode | str) -> None:
75
+ """Set auto/light/dark mode."""
76
+ self._mode = self._coerce_mode(mode)
77
+ self._persist_preferences()
78
+
79
+ def set_theme(self, theme: str | None) -> None:
80
+ """Set explicit theme name (or None to use the default)."""
81
+ self._theme = self._normalize_theme_name(theme)
82
+ self._persist_preferences()
83
+
84
+ def _coerce_mode(self, mode: ThemeMode | str) -> ThemeMode:
85
+ """Coerce a mode value to ThemeMode enum, defaulting to AUTO on invalid input."""
86
+ if isinstance(mode, ThemeMode):
87
+ return mode
88
+ try:
89
+ return ThemeMode(mode)
90
+ except ValueError:
91
+ logger.warning(f"Invalid theme mode '{mode}', defaulting to AUTO")
92
+ return ThemeMode.AUTO
93
+
94
+ def _persist_preferences(self) -> None:
95
+ if self._settings_store is None:
96
+ return
97
+ try:
98
+ persist_tui_theme(mode=self._mode.value, name=self._theme, store=self._settings_store)
99
+ except (OSError, AccountStoreError) as exc:
100
+ # Log recoverable errors (permissions, I/O) as warnings
101
+ logger.warning(f"Failed to persist TUI theme preferences: {exc}")
102
+ except Exception as exc:
103
+ # Log unexpected errors at error level for debugging
104
+ logger.error(f"Unexpected error persisting TUI theme preferences: {exc}", exc_info=True)
105
+
106
+ def _normalize_theme_name(self, theme: str | None) -> str | None:
107
+ if not isinstance(theme, str):
108
+ return None
109
+ cleaned = theme.strip()
110
+ if not cleaned or cleaned.lower() == "default":
111
+ return None
112
+ return cleaned
@@ -0,0 +1,55 @@
1
+ """Theme token definitions for TUI applications."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Literal
7
+
8
+ ThemeModeLiteral = Literal["light", "dark"]
9
+
10
+
11
+ @dataclass(frozen=True, slots=True)
12
+ class ThemeTokens:
13
+ """Color token set for a built-in theme."""
14
+
15
+ name: str
16
+ mode: ThemeModeLiteral
17
+
18
+ primary: str
19
+ secondary: str
20
+ accent: str
21
+
22
+ background: str
23
+ background_panel: str
24
+
25
+ text: str
26
+ text_muted: str
27
+
28
+ success: str
29
+ warning: str
30
+ error: str
31
+ info: str
32
+
33
+ def as_dict(self) -> dict[str, str]:
34
+ """Return color tokens as a plain dictionary.
35
+
36
+ Returns only color tokens (primary, secondary, accent, background, etc.),
37
+ excluding metadata fields (name, mode). This is intentional for use cases
38
+ like Textual TCSS mapping where only color values are needed.
39
+
40
+ Returns:
41
+ Dictionary mapping color token names to hex color strings.
42
+ """
43
+ return {
44
+ "primary": self.primary,
45
+ "secondary": self.secondary,
46
+ "accent": self.accent,
47
+ "background": self.background,
48
+ "background_panel": self.background_panel,
49
+ "text": self.text,
50
+ "text_muted": self.text_muted,
51
+ "success": self.success,
52
+ "warning": self.warning,
53
+ "error": self.error,
54
+ "info": self.info,
55
+ }