kash-shell 0.3.9__py3-none-any.whl → 0.3.11__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 (151) hide show
  1. kash/actions/__init__.py +4 -4
  2. kash/actions/core/format_markdown_template.py +2 -5
  3. kash/actions/core/markdownify.py +7 -6
  4. kash/actions/core/readability.py +7 -6
  5. kash/actions/core/render_as_html.py +37 -0
  6. kash/actions/core/show_webpage.py +6 -11
  7. kash/actions/core/strip_html.py +2 -6
  8. kash/actions/core/tabbed_webpage_config.py +31 -0
  9. kash/actions/core/{webpage_generate.py → tabbed_webpage_generate.py} +5 -4
  10. kash/commands/__init__.py +8 -20
  11. kash/commands/base/basic_file_commands.py +15 -0
  12. kash/commands/base/debug_commands.py +13 -0
  13. kash/commands/base/files_command.py +28 -10
  14. kash/commands/base/general_commands.py +21 -16
  15. kash/commands/base/logs_commands.py +4 -2
  16. kash/commands/base/model_commands.py +8 -8
  17. kash/commands/base/search_command.py +3 -2
  18. kash/commands/base/show_command.py +5 -3
  19. kash/commands/extras/parse_uv_lock.py +186 -0
  20. kash/commands/help/doc_commands.py +2 -31
  21. kash/commands/help/welcome.py +33 -0
  22. kash/commands/workspace/selection_commands.py +11 -6
  23. kash/commands/workspace/workspace_commands.py +19 -17
  24. kash/config/colors.py +3 -1
  25. kash/config/env_settings.py +14 -1
  26. kash/config/init.py +2 -2
  27. kash/config/logger.py +59 -56
  28. kash/config/logger_basic.py +3 -3
  29. kash/config/settings.py +116 -57
  30. kash/config/setup.py +28 -12
  31. kash/config/text_styles.py +3 -13
  32. kash/docs/load_api_docs.py +2 -1
  33. kash/docs/markdown/topics/a3_getting_started.md +3 -2
  34. kash/{concepts → embeddings}/text_similarity.py +2 -2
  35. kash/exec/__init__.py +20 -3
  36. kash/exec/action_decorators.py +24 -10
  37. kash/exec/action_exec.py +41 -23
  38. kash/exec/action_registry.py +13 -48
  39. kash/exec/command_registry.py +2 -1
  40. kash/exec/fetch_url_metadata.py +4 -6
  41. kash/exec/importing.py +56 -0
  42. kash/exec/llm_transforms.py +12 -10
  43. kash/exec/precondition_registry.py +2 -1
  44. kash/exec/preconditions.py +22 -1
  45. kash/exec/resolve_args.py +4 -0
  46. kash/exec/shell_callable_action.py +33 -19
  47. kash/file_storage/file_store.py +42 -27
  48. kash/file_storage/item_file_format.py +5 -2
  49. kash/file_storage/metadata_dirs.py +11 -2
  50. kash/help/assistant.py +1 -1
  51. kash/help/assistant_instructions.py +2 -1
  52. kash/help/function_param_info.py +1 -1
  53. kash/help/help_embeddings.py +2 -2
  54. kash/help/help_printing.py +7 -11
  55. kash/llm_utils/clean_headings.py +1 -1
  56. kash/llm_utils/llm_api_keys.py +4 -4
  57. kash/llm_utils/llm_features.py +68 -0
  58. kash/llm_utils/llm_messages.py +1 -2
  59. kash/llm_utils/llm_names.py +1 -1
  60. kash/llm_utils/llms.py +8 -3
  61. kash/local_server/__init__.py +5 -2
  62. kash/local_server/local_server.py +8 -5
  63. kash/local_server/local_server_commands.py +2 -2
  64. kash/local_server/local_server_routes.py +1 -7
  65. kash/local_server/local_url_formatters.py +1 -1
  66. kash/mcp/__init__.py +5 -2
  67. kash/mcp/mcp_cli.py +5 -5
  68. kash/mcp/mcp_server_commands.py +5 -5
  69. kash/mcp/mcp_server_routes.py +5 -5
  70. kash/mcp/mcp_server_sse.py +4 -2
  71. kash/media_base/media_cache.py +8 -8
  72. kash/media_base/media_services.py +1 -1
  73. kash/media_base/media_tools.py +6 -6
  74. kash/media_base/services/local_file_media.py +2 -2
  75. kash/media_base/{speech_transcription.py → transcription_deepgram.py} +25 -110
  76. kash/media_base/transcription_format.py +73 -0
  77. kash/media_base/transcription_whisper.py +38 -0
  78. kash/model/__init__.py +73 -5
  79. kash/model/actions_model.py +38 -4
  80. kash/model/concept_model.py +30 -0
  81. kash/model/items_model.py +115 -32
  82. kash/model/params_model.py +24 -0
  83. kash/shell/completions/completion_scoring.py +37 -5
  84. kash/shell/output/kerm_codes.py +1 -2
  85. kash/shell/output/shell_formatting.py +14 -4
  86. kash/shell/shell_main.py +2 -2
  87. kash/shell/utils/exception_printing.py +6 -0
  88. kash/shell/utils/native_utils.py +26 -20
  89. kash/shell/utils/shell_function_wrapper.py +15 -15
  90. kash/text_handling/custom_sliding_transforms.py +12 -4
  91. kash/text_handling/doc_normalization.py +6 -2
  92. kash/text_handling/markdown_render.py +118 -0
  93. kash/text_handling/markdown_utils.py +226 -0
  94. kash/utils/common/function_inspect.py +360 -110
  95. kash/utils/common/import_utils.py +12 -3
  96. kash/utils/common/type_utils.py +0 -29
  97. kash/utils/common/url.py +27 -3
  98. kash/utils/errors.py +6 -0
  99. kash/utils/file_utils/file_ext.py +4 -0
  100. kash/utils/file_utils/file_formats.py +2 -2
  101. kash/utils/file_utils/file_formats_model.py +20 -1
  102. kash/web_content/dir_store.py +1 -2
  103. kash/web_content/file_cache_utils.py +37 -10
  104. kash/web_content/file_processing.py +68 -0
  105. kash/web_content/local_file_cache.py +12 -9
  106. kash/web_content/web_extract.py +8 -3
  107. kash/web_content/web_fetch.py +12 -4
  108. kash/web_gen/__init__.py +0 -4
  109. kash/web_gen/simple_webpage.py +52 -0
  110. kash/web_gen/tabbed_webpage.py +24 -14
  111. kash/web_gen/template_render.py +37 -2
  112. kash/web_gen/templates/base_styles.css.jinja +169 -43
  113. kash/web_gen/templates/base_webpage.html.jinja +110 -45
  114. kash/web_gen/templates/content_styles.css.jinja +4 -2
  115. kash/web_gen/templates/item_view.html.jinja +49 -39
  116. kash/web_gen/templates/simple_webpage.html.jinja +24 -0
  117. kash/web_gen/templates/tabbed_webpage.html.jinja +42 -33
  118. kash/workspaces/__init__.py +15 -2
  119. kash/workspaces/selections.py +18 -3
  120. kash/workspaces/source_items.py +0 -1
  121. kash/workspaces/workspaces.py +5 -11
  122. kash/xonsh_custom/command_nl_utils.py +40 -19
  123. kash/xonsh_custom/custom_shell.py +43 -11
  124. kash/xonsh_custom/customize_prompt.py +39 -21
  125. kash/xonsh_custom/load_into_xonsh.py +22 -25
  126. kash/xonsh_custom/shell_load_commands.py +2 -2
  127. kash/xonsh_custom/xonsh_completers.py +2 -249
  128. kash/xonsh_custom/xonsh_keybindings.py +282 -0
  129. kash/xonsh_custom/xonsh_modern_tools.py +3 -3
  130. kash/xontrib/kash_extension.py +5 -6
  131. {kash_shell-0.3.9.dist-info → kash_shell-0.3.11.dist-info}/METADATA +10 -8
  132. {kash_shell-0.3.9.dist-info → kash_shell-0.3.11.dist-info}/RECORD +137 -136
  133. kash/actions/core/webpage_config.py +0 -21
  134. kash/concepts/concept_formats.py +0 -23
  135. kash/shell/clideps/api_keys.py +0 -100
  136. kash/shell/clideps/dotenv_setup.py +0 -115
  137. kash/shell/clideps/dotenv_utils.py +0 -98
  138. kash/shell/clideps/pkg_deps.py +0 -257
  139. kash/shell/clideps/platforms.py +0 -11
  140. kash/shell/clideps/terminal_features.py +0 -56
  141. kash/shell/utils/osc_utils.py +0 -95
  142. kash/shell/utils/terminal_images.py +0 -133
  143. kash/text_handling/markdown_util.py +0 -167
  144. kash/utils/common/atomic_var.py +0 -171
  145. kash/utils/common/string_replace.py +0 -93
  146. kash/utils/common/string_template.py +0 -101
  147. /kash/{concepts → embeddings}/cosine.py +0 -0
  148. /kash/{concepts → embeddings}/embeddings.py +0 -0
  149. {kash_shell-0.3.9.dist-info → kash_shell-0.3.11.dist-info}/WHEEL +0 -0
  150. {kash_shell-0.3.9.dist-info → kash_shell-0.3.11.dist-info}/entry_points.txt +0 -0
  151. {kash_shell-0.3.9.dist-info → kash_shell-0.3.11.dist-info}/licenses/LICENSE +0 -0
@@ -1,3 +1,4 @@
1
+ {% block item_styles %}
1
2
  <style>
2
3
  .item-view {
3
4
  font-family: var(--font-sans);
@@ -19,9 +20,9 @@
19
20
  .item-type {
20
21
  font-family: var(--font-sans);
21
22
  text-transform: uppercase;
23
+ letter-spacing: 0.02em;
22
24
  font-size: var(--font-size-smaller);
23
- font-weight: 800;
24
- letter-spacing: 0.05em;
25
+ font-weight: var(--font-weight-sans-bold);
25
26
  padding-right: 1rem;
26
27
  }
27
28
 
@@ -176,9 +177,11 @@ h1.item-title {
176
177
  gap: 0.25rem;
177
178
  }
178
179
  </style>
180
+ {% endblock item_styles %}
179
181
 
182
+ {% block item_view %}
180
183
  <div class="item-view">
181
-
184
+ {% block item_path %}
182
185
  <div class="item-path">
183
186
  <div class="path-group">
184
187
  <div class="path-icon">
@@ -202,48 +205,52 @@ h1.item-title {
202
205
  {% endif %}
203
206
  </div>
204
207
  </div>
205
-
206
- <div class="item-header">
207
- {% if not brief_header %}
208
- <div class="item-meta">
209
- {% if item.type %}
210
- <span class="item-type">{{ item.type.value }}</span>
211
- {% endif %}
212
- {% if item.format %}
213
- <span class="item-label">Format:</span> <span class="item-format">{{ item.format.value }}</span>
214
- {% endif %}
215
- {% if item.state %}
216
- <span class="item-label">State:</span> <span class="item-state">{{ item.state.value }}</span>
217
- {% endif %}
218
- </div>
219
-
220
- {% if item.title %}
221
- <h1 class="item-title">{{ item.title }}</h1>
208
+ {% endblock item_path %}
209
+
210
+ {% block item_header %}
211
+ <div class="item-header">
212
+ {% if not brief_header %}
213
+ <div class="item-meta">
214
+ {% if item.type %}
215
+ <span class="item-type">{{ item.type.value }}</span>
222
216
  {% endif %}
223
-
224
- {% if item.url %}
225
- <div class="item-url">
226
- <div class="url-container">
227
- <a href="{{ item.url }}" target="_blank" rel="noopener noreferrer">{{ item.url }}</a>
228
- <i data-feather="copy" class="action-icon" onclick="copyDataValue(this.parentElement)" title="Copy URL"></i>
229
- </div>
230
- </div>
217
+ {% if item.format %}
218
+ <span class="item-label">Format:</span> <span class="item-format">{{ item.format.value }}</span>
231
219
  {% endif %}
232
- {% endif %}
220
+ {% if item.state %}
221
+ <span class="item-label">State:</span> <span class="item-state">{{ item.state.value }}</span>
222
+ {% endif %}
223
+ </div>
233
224
 
234
- {% if file_info_html %}
235
- <div class="item-file-info">{{ file_info_html | safe }}</div>
225
+ {% if item.title %}
226
+ <h1 class="item-title">{{ item.title }}</h1>
236
227
  {% endif %}
237
228
 
238
- {% if not brief_header %}
239
- {% if item.description %}
240
- <div class="item-description">
241
- {{ item.description }}
229
+ {% if item.url %}
230
+ <div class="item-url">
231
+ <div class="url-container">
232
+ <a href="{{ item.url }}" target="_blank" rel="noopener noreferrer">{{ item.url }}</a>
233
+ <i data-feather="copy" class="action-icon" onclick="copyDataValue(this.parentElement)" title="Copy URL"></i>
242
234
  </div>
243
- {% endif %}
235
+ </div>
244
236
  {% endif %}
245
- </div>
237
+ {% endif %}
238
+
239
+ {% if file_info_html %}
240
+ <div class="item-file-info">{{ file_info_html | safe }}</div>
241
+ {% endif %}
242
+
243
+ {% if not brief_header %}
244
+ {% if item.description %}
245
+ <div class="item-description">
246
+ {{ item.description }}
247
+ </div>
248
+ {% endif %}
249
+ {% endif %}
250
+ </div>
251
+ {% endblock item_header %}
246
252
 
253
+ {% block item_content %}
247
254
  <div class="item-content">
248
255
  {% if body_text %}
249
256
  <div class="item-body">{{ body_text }}</div>
@@ -261,9 +268,11 @@ h1.item-title {
261
268
  {% endif %}
262
269
  {% endif %}
263
270
  </div>
264
-
271
+ {% endblock item_content %}
265
272
  </div>
273
+ {% endblock item_view %}
266
274
 
275
+ {% block item_scripts %}
267
276
  <script>
268
277
  function copyText(element, text) {
269
278
  navigator.clipboard.writeText(text).then(() => {
@@ -291,4 +300,5 @@ function copyDataValue(element) {
291
300
  document.addEventListener('DOMContentLoaded', () => {
292
301
  feather.replace();
293
302
  });
294
- </script>
303
+ </script>
304
+ {% endblock item_scripts %}
@@ -0,0 +1,24 @@
1
+ {% extends "base_webpage.html.jinja" %}
2
+
3
+ <!-- simple_webpage begin main_content block -->
4
+ {% block main_content %}
5
+ <div class="long-text container max-w-3xl mx-auto bg-white py-8 px-6 md:px-16 md:shadow-lg">
6
+ {% block page_title %}
7
+ {% if title and add_title_h1 %}
8
+ <h1 class="text-center text-4xl mt-6 mb-6">{{ title }}</h1>
9
+ {% endif %}
10
+ {% endblock page_title %}
11
+
12
+ <div>
13
+ {% block page_content %}
14
+ {% if thumbnail_url %}
15
+ <img class="thumbnail" src="{{ thumbnail_url }}" alt="{{ title }}" />
16
+ {% endif %}
17
+ <div class="content">
18
+ {{ content_html | safe }}
19
+ </div>
20
+ {% endblock page_content %}
21
+ </div>
22
+ </div>
23
+ {% endblock main_content %}
24
+ <!-- simple_webpage end main_content block -->
@@ -1,39 +1,47 @@
1
- <div class="long-text container max-w-3xl mx-auto bg-white py-8 px-16 shadow-lg">
2
- <h1 class="text-center text-4xl mt-6 mb-6">{{ title }}</h1>
3
- <div>
4
- <!-- Navigation Tabs -->
5
- {% if show_tabs %}
6
- <nav>
7
- {% for tab in tabs %}
8
- <button
9
- class="tab-button {% if loop.first %}tab-button-active{% else %}tab-button-inactive{% endif %}"
10
- onclick="showTab('{{ tab.id }}', this)"
11
- >
12
- {{ tab.label }}
13
- </button>
14
- {% endfor %}
15
- </nav>
16
- {% endif %}
17
- <div class="tab-content mt-8">
18
- <!-- Tab Content -->
19
- {% for tab in tabs %}
20
- <div
21
- id="{{ tab.id }}"
22
- class="tab-pane {% if not loop.first %}hidden{% endif %}"
23
- >
24
- {% if tab.thumbnail_url %}
25
- <img class="thumbnail" src="{{ tab.thumbnail_url }}" alt="{{ tab.label }}" />
26
- {% endif %}
27
- {% if show_tabs %} <h2 class="text-2xl">{{ tab.label }}</h2> {% endif %}
28
- <p>{{ tab.content_html | safe }}</p>
1
+ {% extends "simple_webpage.html.jinja" %}
2
+
3
+ <!-- tabbed_webpage begin page_content block -->
4
+ {% block page_content %}
5
+ {% block tab_navigation %}
6
+ <!-- tab_navigation block -->
7
+ {% if show_tabs %}
8
+ <nav>
9
+ {% for tab in tabs %}
10
+ <button
11
+ class="tab-button {% if loop.first %}tab-button-active{% else %}tab-button-inactive{% endif %}"
12
+ onclick="showTab('{{ tab.id }}', this)"
13
+ >
14
+ {{ tab.label }}
15
+ </button>
16
+ {% endfor %}
17
+ </nav>
18
+ {% endif %}
19
+ {% endblock tab_navigation %}
20
+
21
+ {% block tab_content_container %}
22
+ <!-- tab_content_container block -->
23
+ <div class="tab-content mt-8">
24
+ {% for tab in tabs %}
25
+ <div
26
+ id="{{ tab.id }}"
27
+ class="tab-pane {% if not loop.first %}hidden{% endif %}"
28
+ >
29
+ {% if tab.thumbnail_url %}
30
+ <img class="thumbnail" src="{{ tab.thumbnail_url }}" alt="{{ tab.label }}" />
31
+ {% endif %}
32
+ {% if show_tabs %} <h2 class="text-2xl">{{ tab.label }}</h2> {% endif %}
33
+ <div class="content">
34
+ {{ tab.content_html | safe }}
29
35
  </div>
30
- {% endfor %}
31
36
  </div>
37
+ {% endfor %}
32
38
  </div>
33
- <!-- TODO: Footer info (match with pdf export) -->
34
- </div>
39
+ {% endblock tab_content_container %}
40
+ {% endblock page_content %}
41
+ <!-- tabbed_webpage end page_content block -->
35
42
 
36
- <script>
43
+ <!-- tabbed_webpage begin scripts_extra block -->
44
+ {% block scripts_extra %}
37
45
  function showTab(tabId, element) {
38
46
  document.querySelectorAll(".tab-pane").forEach((tab) => {
39
47
  tab.classList.add("hidden");
@@ -46,4 +54,5 @@
46
54
  element.classList.add("tab-button-active");
47
55
  element.classList.remove("tab-button-inactive");
48
56
  }
49
- </script>
57
+ {% endblock scripts_extra %}
58
+ <!-- tabbed_webpage end scripts_extra block -->
@@ -1,5 +1,3 @@
1
- # flake8: noqa: F401
2
-
3
1
  from kash.workspaces.selections import Selection, SelectionHistory
4
2
  from kash.workspaces.workspaces import (
5
3
  Workspace,
@@ -9,5 +7,20 @@ from kash.workspaces.workspaces import (
9
7
  get_ws,
10
8
  global_ws_dir,
11
9
  resolve_ws,
10
+ switch_to_ws,
12
11
  ws_param_value,
13
12
  )
13
+
14
+ __all__ = [
15
+ "Selection",
16
+ "SelectionHistory",
17
+ "Workspace",
18
+ "current_ignore",
19
+ "current_ws",
20
+ "get_global_ws",
21
+ "get_ws",
22
+ "global_ws_dir",
23
+ "resolve_ws",
24
+ "ws_param_value",
25
+ "switch_to_ws",
26
+ ]
@@ -1,3 +1,5 @@
1
+ from __future__ import annotations
2
+
1
3
  from collections.abc import Callable, Sequence
2
4
  from functools import wraps
3
5
  from pathlib import Path
@@ -78,6 +80,12 @@ class Selection(BaseModel):
78
80
  if current_path == old_path:
79
81
  self.paths[idx] = new_path
80
82
 
83
+ def refresh(self, base_dir: Path) -> None:
84
+ """
85
+ Refresh the selection paths, dropping any that no longer exist.
86
+ """
87
+ self.paths[:] = [p for p in self.paths if (base_dir / p).exists()]
88
+
81
89
  def as_str(self, max_lines: int = SELECTION_DISPLAY_MAX) -> str:
82
90
  lines = [
83
91
  f"{fmt_count_items(len(self.paths), 'item')}:",
@@ -113,7 +121,7 @@ class SelectionHistory(BaseModel):
113
121
  }
114
122
 
115
123
  @classmethod
116
- def init(cls, save_path: Path, max_history: int = SELECTION_HISTORY_MAX) -> "SelectionHistory":
124
+ def init(cls, save_path: Path, max_history: int = SELECTION_HISTORY_MAX) -> SelectionHistory:
117
125
  """
118
126
  Initialize selection history, loading from save_path if it exists.
119
127
  """
@@ -144,9 +152,9 @@ class SelectionHistory(BaseModel):
144
152
  yaml_util.write_yaml_file(data, str(self._save_path))
145
153
 
146
154
  @persist_after(_save)
147
- def clear(self) -> None:
155
+ def clear_all(self) -> None:
148
156
  """
149
- Clear the history.
157
+ Clear the entire selection history.
150
158
  """
151
159
  self.history.clear()
152
160
  self.current_index = 0
@@ -306,6 +314,13 @@ class SelectionHistory(BaseModel):
306
314
  for selection in self.history:
307
315
  selection.replace_values(replacements)
308
316
 
317
+ @persist_after(_save)
318
+ def refresh_current(self, base_dir: Path) -> None:
319
+ """
320
+ Refresh the current selection to drop any paths that no longer exist.
321
+ """
322
+ self.current.refresh(base_dir)
323
+
309
324
  def previous_n(self, n: int, expected_size: int | None = None) -> list[Selection]:
310
325
  """
311
326
  Get the `n` previous selections (backwards and including the current position),
@@ -7,7 +7,6 @@ from kash.model.items_model import Item
7
7
  from kash.model.paths_model import StorePath
8
8
  from kash.model.preconditions_model import Precondition
9
9
  from kash.utils.common.format_utils import fmt_loc
10
- from kash.utils.common.type_utils import not_none
11
10
  from kash.utils.errors import NoMatch
12
11
  from kash.workspaces import current_ws
13
12
 
@@ -7,18 +7,14 @@ from typing import TYPE_CHECKING, TypeVar
7
7
 
8
8
  from prettyfmt import fmt_path
9
9
 
10
- from kash.config.logger import get_logger, reset_log_root
10
+ from kash.config.logger import get_logger, reset_rich_logging
11
11
  from kash.config.settings import (
12
12
  GLOBAL_WS_NAME,
13
- RECOMMENDED_API_KEYS,
14
- get_global_ws_dir,
15
- get_ws_root_dir,
16
13
  global_settings,
17
14
  resolve_and_create_dirs,
18
15
  )
19
16
  from kash.file_storage.metadata_dirs import MetadataDirs
20
17
  from kash.model.params_model import GLOBAL_PARAMS, RawParamValues
21
- from kash.shell.clideps.api_keys import print_api_key_setup
22
18
  from kash.utils.errors import FileNotFound, InvalidInput, InvalidState
23
19
  from kash.utils.file_utils.ignore_files import IgnoreFilter, is_ignored_default
24
20
  from kash.workspaces.workspace_registry import WorkspaceInfo, get_ws_registry
@@ -128,7 +124,7 @@ def resolve_ws(name: str | Path) -> WorkspaceInfo:
128
124
  resolved = name
129
125
  parent_dir = resolved.parent
130
126
  else:
131
- parent_dir = get_ws_root_dir()
127
+ parent_dir = global_settings().ws_root_dir
132
128
  resolved = parent_dir / name
133
129
  elif name_str.startswith(".") or name_str.startswith("/"):
134
130
  # Explicit paths respected otherwise use workspace root.
@@ -136,7 +132,7 @@ def resolve_ws(name: str | Path) -> WorkspaceInfo:
136
132
  parent_dir = resolved.parent
137
133
  name = resolved.name
138
134
  else:
139
- parent_dir = get_ws_root_dir()
135
+ parent_dir = global_settings().ws_root_dir
140
136
  resolved = parent_dir / Path(name_str)
141
137
 
142
138
  ws_name = check_strict_workspace_name(resolved.name)
@@ -161,7 +157,7 @@ def get_ws(name_or_path: str | Path, auto_init: bool = True) -> "FileStore":
161
157
 
162
158
  @cache
163
159
  def global_ws_dir() -> Path:
164
- kb_path = resolve_and_create_dirs(get_global_ws_dir(), is_dir=True)
160
+ kb_path = resolve_and_create_dirs(global_settings().global_ws_dir, is_dir=True)
165
161
  log.debug("Global workspace path: %s", kb_path)
166
162
  return kb_path
167
163
 
@@ -190,7 +186,7 @@ def switch_to_ws(base_dir: Path) -> "FileStore":
190
186
  ws_dirs = MetadataDirs(base_dir=info.base_dir, is_global_ws=info.is_global_ws)
191
187
 
192
188
  # Use the global log root for the global_ws, and the workspace log root otherwise.
193
- reset_log_root(None, info.name if not info.is_global_ws else None)
189
+ reset_rich_logging(None, info.name if not info.is_global_ws else None)
194
190
 
195
191
  if info.is_global_ws:
196
192
  # If not in a workspace, use the global cache locations.
@@ -237,8 +233,6 @@ def current_ws(silent: bool = False) -> "FileStore":
237
233
  ws = switch_to_ws(base_dir)
238
234
 
239
235
  if not silent:
240
- # Delayed, once-only logging of any setup warnings.
241
- print_api_key_setup(RECOMMENDED_API_KEYS, once=True)
242
236
  ws.log_workspace_info(once=True)
243
237
 
244
238
  return ws
@@ -3,20 +3,16 @@ import re
3
3
  from prettyfmt import fmt_words
4
4
 
5
5
  INNER_PUNCT_CHARS = r"-'’–—"
6
- OUTER_PUNCT_CHARS = r".,'\"“”‘’:!?()"
6
+ OUTER_PUNCT_CHARS = r".,'\"" "''':;!?()"
7
7
 
8
- WORD_PAT = (
9
- rf"[{OUTER_PUNCT_CHARS}]{{0,2}}[\w]+(?:[{INNER_PUNCT_CHARS}\w]+)*[{OUTER_PUNCT_CHARS}]{{0,2}}"
10
- )
11
- """
12
- Pattern to match a word in natural language text (i.e. words and natural
13
- language-only punctuation).
14
- """
8
+ ESCAPED_INNER_PUNCT_CHARS = re.escape(INNER_PUNCT_CHARS)
9
+ ESCAPED_OUTER_PUNCT_CHARS = re.escape(OUTER_PUNCT_CHARS)
15
10
 
16
- NL_PAT = rf"^{WORD_PAT}(?:\s+{WORD_PAT})*$"
17
- """
18
- Pattern to match natural language text in a command line.
19
- """
11
+ PUNCT_SEQ_RE = re.compile(rf"[{ESCAPED_INNER_PUNCT_CHARS}{ESCAPED_OUTER_PUNCT_CHARS}]+")
12
+
13
+ ONLY_WORDS_RE = re.compile(rf"^[\w\s{ESCAPED_INNER_PUNCT_CHARS}]*$")
14
+
15
+ PLAIN_WORD_RE = re.compile(r"^\w.*\w$")
20
16
 
21
17
 
22
18
  def as_nl_words(text: str) -> str:
@@ -30,18 +26,25 @@ def as_nl_words(text: str) -> str:
30
26
 
31
27
  def looks_like_nl(text: str) -> bool:
32
28
  """
33
- Check if a text looks like plain natural language text, i.e. word chars,
34
- possibly with ? or hyphens/apostrophes when inside words but not other
35
- code or punctuation.
29
+ Check if a text looks like plain natural language text. Just very simple
30
+ based on words and only basic punctuation.
36
31
  """
37
- return bool(re.match(NL_PAT, text.strip()))
32
+ is_only_word_chars = bool(ONLY_WORDS_RE.fullmatch(text))
33
+ without_punct = PUNCT_SEQ_RE.sub("", text)
34
+ is_only_words_punct = bool(ONLY_WORDS_RE.fullmatch(without_punct))
35
+ words = without_punct.strip().split()
36
+ one_longer_word = any(len(word) > 3 for word in words)
37
+
38
+ return one_longer_word and (
39
+ (is_only_words_punct and len(words) >= 3) or (is_only_word_chars and len(words) >= 2)
40
+ )
38
41
 
39
42
 
40
43
  ## Tests
41
44
 
42
45
 
43
46
  def test_as_nl_words():
44
- assert as_nl_words("x=3+9; foo('bar')") == "x=3+9; foo('bar"
47
+ assert as_nl_words("x=3+9; foo('bar')") == "x=3+9 foo('bar"
45
48
  assert as_nl_words("cd ..") == "cd .."
46
49
  assert as_nl_words("transcribe some-file_23.mp3") == "transcribe some-file_23.mp3"
47
50
  assert as_nl_words("hello world ") == "hello world"
@@ -57,14 +60,32 @@ def test_looks_like_nl():
57
60
  assert looks_like_nl("hello world")
58
61
  assert looks_like_nl(" hello world ")
59
62
  assert looks_like_nl("what's up")
60
- assert looks_like_nl("hello-world")
61
63
  assert looks_like_nl("is this a question?")
62
64
  assert looks_like_nl("'quoted text'")
63
65
  assert looks_like_nl("git push origin main")
66
+ assert looks_like_nl("this is natural language")
67
+ assert looks_like_nl(" what's up, doc? ")
68
+ assert looks_like_nl("multiple spaces here")
69
+ assert looks_like_nl("go to the store (buy milk)")
70
+ assert looks_like_nl("'quoted text' has three words")
71
+ assert looks_like_nl("git push origin main")
72
+ assert looks_like_nl("what's up")
64
73
 
74
+ assert not looks_like_nl("hello-world")
75
+ assert not looks_like_nl("cd ..")
76
+ assert not looks_like_nl("file_name.txt")
77
+ assert not looks_like_nl("ls -la")
78
+ assert not looks_like_nl("https://example.com")
79
+ assert not looks_like_nl("cmd | grep pattern")
80
+ assert not looks_like_nl("use a+b")
81
+ assert not looks_like_nl("x=3")
82
+ assert not looks_like_nl("a > b")
83
+ assert not looks_like_nl("file_name.txt")
84
+ assert not looks_like_nl("foo;")
85
+ assert not looks_like_nl("hello-world")
65
86
  assert not looks_like_nl("ls -la")
66
87
  assert not looks_like_nl("cd ..")
67
88
  assert not looks_like_nl("echo $HOME")
68
89
  assert not looks_like_nl("https://example.com")
69
- assert not looks_like_nl("file.txt")
90
+ assert not looks_like_nl(text="file.txt")
70
91
  assert not looks_like_nl("cmd | grep pattern")
@@ -1,15 +1,17 @@
1
1
  import os
2
- import sys
2
+ import signal
3
3
  import threading
4
4
  import time
5
5
  from collections.abc import Callable
6
6
  from os.path import expanduser
7
- from typing import cast
7
+ from subprocess import CalledProcessError
8
+ from types import TracebackType
9
+ from typing import TypeAlias, cast
8
10
 
9
11
  import xonsh.tools as xt
10
12
  from prompt_toolkit.formatted_text import FormattedText
11
13
  from pygments.token import Token
12
- from strif import abbrev_str
14
+ from strif import abbrev_str, quote_if_needed
13
15
  from typing_extensions import override
14
16
  from xonsh.built_ins import XSH
15
17
  from xonsh.environ import xonshrc_context
@@ -27,7 +29,7 @@ from kash.config import colors
27
29
  from kash.config.lazy_imports import import_start_time # usort:skip
28
30
  from kash.config.logger import get_console, get_log_settings, get_logger
29
31
  from kash.config.settings import APP_NAME, find_rcfiles
30
- from kash.config.text_styles import SPINNER, STYLE_ASSISTANCE
32
+ from kash.config.text_styles import SPINNER, STYLE_ASSISTANCE, STYLE_HINT
31
33
  from kash.help.assistant import AssistanceType
32
34
  from kash.shell.output.shell_output import cprint
33
35
  from kash.shell.ui.shell_syntax import is_assist_request_str
@@ -108,12 +110,33 @@ class CustomPTKPromptFormatter(PTKPromptFormatter):
108
110
  return super().__call__(template=cast(str, template), **kwargs)
109
111
 
110
112
 
113
+ def exit_code_str(e: CalledProcessError) -> str:
114
+ """
115
+ Prettier version of `CalledProcessError.__str__()`.
116
+ """
117
+ if isinstance(e.cmd, list):
118
+ cmd = "`" + " ".join(quote_if_needed(c) for c in e.cmd) + "`"
119
+ else:
120
+ cmd = str(e.cmd)
121
+ if e.returncode and e.returncode < 0:
122
+ try:
123
+ signal_name = signal.Signals(-e.returncode).name
124
+ return f"Command died with {signal_name} ({e.returncode}): {cmd}"
125
+ except ValueError:
126
+ return f"Command died with unknown signal {e.returncode}: {cmd}"
127
+ else:
128
+ return f"Command returned non-zero exit status {e.returncode}: {cmd}"
129
+
130
+
111
131
  # Base shell can be ReadlineShell or PromptToolkitShell.
112
132
  # Completer can be RankingCompleter or the standard Completer.
113
133
  # from xonsh.completer import Completer
114
134
  # from xonsh.shells.readline_shell import ReadlineShell
115
135
  from xonsh.shells.ptk_shell import PromptToolkitShell
116
136
 
137
+ ExcInfo: TypeAlias = tuple[type[BaseException], BaseException, TracebackType]
138
+ OptExcInfo: TypeAlias = ExcInfo | tuple[None, None, None]
139
+
117
140
 
118
141
  class CustomAssistantShell(PromptToolkitShell):
119
142
  """
@@ -122,7 +145,6 @@ class CustomAssistantShell(PromptToolkitShell):
122
145
  We're trying to reuse code where possible but need to change some of xonsh's
123
146
  behavior. Note event hooks in xonsh do let you customize handling but don't
124
147
  let you disable xonsh's processing, so it seems like this is necessary.
125
- so it seems like this is necessary.
126
148
  """
127
149
 
128
150
  def __init__(self, **kwargs):
@@ -186,16 +208,24 @@ class CustomAssistantShell(PromptToolkitShell):
186
208
  exc_info = (None, None, None)
187
209
  try:
188
210
  log.info("Running shell code: %r", src)
189
- exc_info = run_compiled_code(code, self.ctx, None, "single")
190
- if exc_info != (None, None, None):
191
- raise exc_info[1] # pyright: ignore
211
+ exc_info: OptExcInfo = run_compiled_code(code, self.ctx, None, "single") # pyright: ignore
212
+ log.debug("Completed shell code: %r", src)
213
+ _type, exc, _traceback = exc_info
214
+ if exc:
215
+ log.info("Shell exception info: %s", exc)
216
+ raise exc
192
217
  ts1 = time.time()
193
218
  if hist is not None and hist.last_cmd_rtn is None:
194
219
  hist.last_cmd_rtn = 0 # returncode for success
195
- log.info("Shell code completed successfully: %s", src)
220
+ except CalledProcessError as e:
221
+ # No point in logging stack trace here as it is only the shell stack,
222
+ # not the original code.
223
+ log.warning("%s", exit_code_str(e))
224
+ cprint("See `logs` for more details.", style=STYLE_HINT)
225
+ # print(e.args[0], file=sys.stderr)
196
226
  except xt.XonshError as e:
197
227
  log.info("Shell exception details: %s", e, exc_info=True)
198
- print(e.args[0], file=sys.stderr)
228
+ # print(e.args[0], file=sys.stderr)
199
229
  if hist is not None and hist.last_cmd_rtn is None: # pyright: ignore
200
230
  hist.last_cmd_rtn = 1 # return code for failure
201
231
  except (SystemExit, KeyboardInterrupt) as err:
@@ -323,7 +353,9 @@ def customize_xonsh_settings(is_interactive: bool):
323
353
  # Disable suggest for command not found errors (we handle this ourselves).
324
354
  "SUGGEST_COMMANDS": False,
325
355
  # TODO: Consider enabling and adapting auto-suggestions.
326
- "AUTO_SUGGEST": False,
356
+ "AUTO_SUGGEST": True,
357
+ # Show auto-suggestions in the completion menu.
358
+ "AUTO_SUGGEST_IN_COMPLETIONS": False,
327
359
  # Completions can be "none", "single", "multi", or "readline".
328
360
  # "single" lets us have rich completions with descriptions alongside.
329
361
  # https://xon.sh/envvars.html#completions-display