zrb 1.13.1__py3-none-any.whl → 1.21.33__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 (117) hide show
  1. zrb/__init__.py +2 -6
  2. zrb/attr/type.py +10 -7
  3. zrb/builtin/__init__.py +2 -0
  4. zrb/builtin/git.py +12 -1
  5. zrb/builtin/group.py +31 -15
  6. zrb/builtin/http.py +7 -8
  7. zrb/builtin/llm/attachment.py +40 -0
  8. zrb/builtin/llm/chat_completion.py +287 -0
  9. zrb/builtin/llm/chat_session.py +130 -144
  10. zrb/builtin/llm/chat_session_cmd.py +288 -0
  11. zrb/builtin/llm/chat_trigger.py +78 -0
  12. zrb/builtin/llm/history.py +4 -4
  13. zrb/builtin/llm/llm_ask.py +218 -110
  14. zrb/builtin/llm/tool/api.py +74 -62
  15. zrb/builtin/llm/tool/cli.py +56 -21
  16. zrb/builtin/llm/tool/code.py +57 -47
  17. zrb/builtin/llm/tool/file.py +292 -255
  18. zrb/builtin/llm/tool/note.py +84 -0
  19. zrb/builtin/llm/tool/rag.py +25 -18
  20. zrb/builtin/llm/tool/search/__init__.py +1 -0
  21. zrb/builtin/llm/tool/search/brave.py +66 -0
  22. zrb/builtin/llm/tool/search/searxng.py +61 -0
  23. zrb/builtin/llm/tool/search/serpapi.py +61 -0
  24. zrb/builtin/llm/tool/sub_agent.py +53 -26
  25. zrb/builtin/llm/tool/web.py +94 -157
  26. zrb/builtin/project/add/fastapp/fastapp_template/my_app_name/_zrb/entity/add_entity_util.py +7 -7
  27. zrb/builtin/project/add/fastapp/fastapp_template/my_app_name/_zrb/module/add_module_util.py +5 -5
  28. zrb/builtin/project/add/fastapp/fastapp_util.py +1 -1
  29. zrb/builtin/searxng/config/settings.yml +5671 -0
  30. zrb/builtin/searxng/start.py +21 -0
  31. zrb/builtin/setup/latex/ubuntu.py +1 -0
  32. zrb/builtin/setup/ubuntu.py +1 -1
  33. zrb/builtin/shell/autocomplete/bash.py +4 -3
  34. zrb/builtin/shell/autocomplete/zsh.py +4 -3
  35. zrb/config/config.py +297 -79
  36. zrb/config/default_prompt/file_extractor_system_prompt.md +109 -9
  37. zrb/config/default_prompt/interactive_system_prompt.md +25 -28
  38. zrb/config/default_prompt/persona.md +1 -1
  39. zrb/config/default_prompt/repo_extractor_system_prompt.md +31 -31
  40. zrb/config/default_prompt/repo_summarizer_system_prompt.md +27 -8
  41. zrb/config/default_prompt/summarization_prompt.md +57 -16
  42. zrb/config/default_prompt/system_prompt.md +29 -25
  43. zrb/config/llm_config.py +129 -24
  44. zrb/config/llm_context/config.py +127 -90
  45. zrb/config/llm_context/config_parser.py +1 -7
  46. zrb/config/llm_context/workflow.py +81 -0
  47. zrb/config/llm_rate_limitter.py +100 -47
  48. zrb/context/any_shared_context.py +7 -1
  49. zrb/context/context.py +8 -2
  50. zrb/context/shared_context.py +6 -8
  51. zrb/group/any_group.py +12 -5
  52. zrb/group/group.py +67 -3
  53. zrb/input/any_input.py +5 -1
  54. zrb/input/base_input.py +18 -6
  55. zrb/input/option_input.py +13 -1
  56. zrb/input/text_input.py +7 -24
  57. zrb/runner/cli.py +21 -20
  58. zrb/runner/common_util.py +24 -19
  59. zrb/runner/web_route/task_input_api_route.py +5 -5
  60. zrb/runner/web_route/task_session_api_route.py +1 -4
  61. zrb/runner/web_util/user.py +7 -3
  62. zrb/session/any_session.py +12 -6
  63. zrb/session/session.py +39 -18
  64. zrb/task/any_task.py +24 -3
  65. zrb/task/base/context.py +17 -9
  66. zrb/task/base/execution.py +15 -8
  67. zrb/task/base/lifecycle.py +8 -4
  68. zrb/task/base/monitoring.py +12 -7
  69. zrb/task/base_task.py +69 -5
  70. zrb/task/base_trigger.py +12 -5
  71. zrb/task/llm/agent.py +130 -145
  72. zrb/task/llm/agent_runner.py +152 -0
  73. zrb/task/llm/config.py +45 -13
  74. zrb/task/llm/conversation_history.py +110 -29
  75. zrb/task/llm/conversation_history_model.py +4 -179
  76. zrb/task/llm/default_workflow/coding/workflow.md +41 -0
  77. zrb/task/llm/default_workflow/copywriting/workflow.md +68 -0
  78. zrb/task/llm/default_workflow/git/workflow.md +118 -0
  79. zrb/task/llm/default_workflow/golang/workflow.md +128 -0
  80. zrb/task/llm/default_workflow/html-css/workflow.md +135 -0
  81. zrb/task/llm/default_workflow/java/workflow.md +146 -0
  82. zrb/task/llm/default_workflow/javascript/workflow.md +158 -0
  83. zrb/task/llm/default_workflow/python/workflow.md +160 -0
  84. zrb/task/llm/default_workflow/researching/workflow.md +153 -0
  85. zrb/task/llm/default_workflow/rust/workflow.md +162 -0
  86. zrb/task/llm/default_workflow/shell/workflow.md +299 -0
  87. zrb/task/llm/file_replacement.py +206 -0
  88. zrb/task/llm/file_tool_model.py +57 -0
  89. zrb/task/llm/history_processor.py +206 -0
  90. zrb/task/llm/history_summarization.py +2 -192
  91. zrb/task/llm/print_node.py +192 -64
  92. zrb/task/llm/prompt.py +198 -153
  93. zrb/task/llm/subagent_conversation_history.py +41 -0
  94. zrb/task/llm/tool_confirmation_completer.py +41 -0
  95. zrb/task/llm/tool_wrapper.py +216 -55
  96. zrb/task/llm/workflow.py +76 -0
  97. zrb/task/llm_task.py +122 -70
  98. zrb/task/make_task.py +2 -3
  99. zrb/task/rsync_task.py +25 -10
  100. zrb/task/scheduler.py +4 -4
  101. zrb/util/attr.py +54 -39
  102. zrb/util/cli/markdown.py +12 -0
  103. zrb/util/cli/text.py +30 -0
  104. zrb/util/file.py +27 -11
  105. zrb/util/git.py +2 -2
  106. zrb/util/{llm/prompt.py → markdown.py} +2 -3
  107. zrb/util/string/conversion.py +1 -1
  108. zrb/util/truncate.py +23 -0
  109. zrb/util/yaml.py +204 -0
  110. zrb/xcom/xcom.py +10 -0
  111. {zrb-1.13.1.dist-info → zrb-1.21.33.dist-info}/METADATA +40 -20
  112. {zrb-1.13.1.dist-info → zrb-1.21.33.dist-info}/RECORD +114 -83
  113. {zrb-1.13.1.dist-info → zrb-1.21.33.dist-info}/WHEEL +1 -1
  114. zrb/task/llm/default_workflow/coding.md +0 -24
  115. zrb/task/llm/default_workflow/copywriting.md +0 -17
  116. zrb/task/llm/default_workflow/researching.md +0 -18
  117. {zrb-1.13.1.dist-info → zrb-1.21.33.dist-info}/entry_points.txt +0 -0
@@ -1,16 +1,37 @@
1
- """
2
- This module provides functions for managing interactive chat sessions with an LLM.
3
-
4
- It handles reading user input, triggering the LLM task, and managing the
5
- conversation flow via XCom.
6
- """
7
-
8
1
  import asyncio
9
2
  import sys
10
-
3
+ from typing import TYPE_CHECKING, Any
4
+
5
+ from zrb.builtin.llm.chat_session_cmd import (
6
+ ATTACHMENT_CMD,
7
+ HELP_CMD,
8
+ MULTILINE_END_CMD,
9
+ MULTILINE_START_CMD,
10
+ QUIT_CMD,
11
+ RUN_CLI_CMD,
12
+ SAVE_CMD,
13
+ WORKFLOW_CMD,
14
+ YOLO_CMD,
15
+ get_new_attachments,
16
+ get_new_workflows,
17
+ get_new_yolo_mode,
18
+ is_command_match,
19
+ print_commands,
20
+ print_current_attachments,
21
+ print_current_workflows,
22
+ print_current_yolo_mode,
23
+ run_cli_command,
24
+ save_final_result,
25
+ )
26
+ from zrb.builtin.llm.chat_trigger import llm_chat_trigger
11
27
  from zrb.config.llm_config import llm_config
12
28
  from zrb.context.any_context import AnyContext
13
- from zrb.util.cli.style import stylize_bold_yellow, stylize_faint
29
+ from zrb.util.cli.markdown import render_markdown
30
+
31
+ if TYPE_CHECKING:
32
+ from asyncio import StreamReader
33
+
34
+ from prompt_toolkit import PromptSession
14
35
 
15
36
 
16
37
  async def read_user_prompt(ctx: AnyContext) -> str:
@@ -18,114 +39,97 @@ async def read_user_prompt(ctx: AnyContext) -> str:
18
39
  Reads user input from the CLI for an interactive chat session.
19
40
  Orchestrates the session by calling helper functions.
20
41
  """
21
- _show_info(ctx)
22
- final_result = await _handle_initial_message(ctx)
23
- if ctx.is_web_mode:
24
- return final_result
25
- is_tty = ctx.is_tty
26
- reader = await _setup_input_reader(is_tty)
42
+ print_commands(ctx)
43
+ is_tty: bool = ctx.is_tty
44
+ reader: PromptSession[Any] | StreamReader = await _setup_input_reader(is_tty)
27
45
  multiline_mode = False
28
- current_modes = ctx.input.modes
29
- user_inputs = []
30
- while True:
46
+ is_first_time = True
47
+ current_workflows: str = ctx.input.workflows
48
+ current_yolo_mode: bool | str = ctx.input.yolo
49
+ current_attachments: str = ctx.input.attach
50
+ user_inputs: list[str] = []
51
+ final_result: str = ""
52
+ should_end = False
53
+ while not should_end:
31
54
  await asyncio.sleep(0.01)
32
- # Get user input based on mode
33
- if not multiline_mode:
34
- ctx.print("💬 >>", plain=True)
35
- user_input = await _read_next_line(is_tty, reader, ctx)
36
- if not multiline_mode:
37
- ctx.print("", plain=True)
38
- # Handle user input
39
- if user_input.strip().lower() in ("/bye", "/quit", "/q", "/exit"):
40
- user_prompt = "\n".join(user_inputs)
41
- user_inputs = []
42
- result = await _trigger_ask_and_wait_for_result(
43
- ctx, user_prompt, current_modes
44
- )
45
- if result is not None:
46
- final_result = result
47
- break
48
- elif user_input.strip().lower() in ("/multi",):
49
- multiline_mode = True
50
- elif user_input.strip().lower() in ("/end",):
51
- ctx.print("", plain=True)
52
- multiline_mode = False
53
- user_prompt = "\n".join(user_inputs)
54
- user_inputs = []
55
- result = await _trigger_ask_and_wait_for_result(
56
- ctx, user_prompt, current_modes
57
- )
58
- if result is not None:
59
- final_result = result
60
- elif user_input.strip().lower().startswith("/mode"):
61
- mode_parts = user_input.split(" ", maxsplit=2)
62
- if len(mode_parts) > 1:
63
- current_modes = mode_parts[1]
64
- ctx.print(f"Current mode: {current_modes}", plain=True)
65
- ctx.print("", plain=True)
66
- continue
67
- elif user_input.strip().lower() in ("/help", "/info"):
68
- _show_info(ctx)
69
- continue
55
+ previous_session_name: str | None = (
56
+ ctx.input.previous_session if is_first_time else ""
57
+ )
58
+ start_new: bool = ctx.input.start_new if is_first_time else False
59
+ if is_first_time and ctx.input.message.strip() != "":
60
+ user_input = ctx.input.message
70
61
  else:
71
- user_inputs.append(user_input)
72
- if multiline_mode:
62
+ # Get user input based on mode
63
+ if not multiline_mode:
64
+ ctx.print("💬 >>", plain=True)
65
+ user_input = await llm_chat_trigger.wait(reader, ctx)
66
+ if not multiline_mode:
67
+ ctx.print("", plain=True)
68
+ # At this point, is_first_time has to be False
69
+ if is_first_time:
70
+ is_first_time = False
71
+ # Handle user input (including slash commands)
72
+ if multiline_mode:
73
+ if is_command_match(user_input, MULTILINE_END_CMD):
74
+ ctx.print("", plain=True)
75
+ multiline_mode = False
76
+ else:
77
+ user_inputs.append(user_input)
78
+ continue
79
+ else:
80
+ if is_command_match(user_input, QUIT_CMD):
81
+ should_end = True
82
+ elif is_command_match(user_input, MULTILINE_START_CMD):
83
+ multiline_mode = True
84
+ ctx.print("", plain=True)
85
+ continue
86
+ elif is_command_match(user_input, WORKFLOW_CMD):
87
+ current_workflows = get_new_workflows(current_workflows, user_input)
88
+ print_current_workflows(ctx, current_workflows)
89
+ continue
90
+ elif is_command_match(user_input, SAVE_CMD):
91
+ save_final_result(ctx, user_input, final_result)
92
+ continue
93
+ elif is_command_match(user_input, ATTACHMENT_CMD):
94
+ current_attachments = get_new_attachments(
95
+ current_attachments, user_input
96
+ )
97
+ print_current_attachments(ctx, current_attachments)
73
98
  continue
74
- user_prompt = "\n".join(user_inputs)
75
- user_inputs = []
76
- result = await _trigger_ask_and_wait_for_result(
77
- ctx, user_prompt, current_modes
78
- )
79
- if result is not None:
80
- final_result = result
99
+ elif is_command_match(user_input, YOLO_CMD):
100
+ current_yolo_mode = get_new_yolo_mode(current_yolo_mode, user_input)
101
+ print_current_yolo_mode(ctx, current_yolo_mode)
102
+ continue
103
+ elif is_command_match(user_input, RUN_CLI_CMD):
104
+ run_cli_command(ctx, user_input)
105
+ continue
106
+ elif is_command_match(user_input, HELP_CMD):
107
+ print_commands(ctx)
108
+ continue
109
+ else:
110
+ user_inputs.append(user_input)
111
+ # Trigger LLM
112
+ user_prompt = "\n".join(user_inputs)
113
+ user_inputs = []
114
+ result = await _trigger_ask_and_wait_for_result(
115
+ ctx=ctx,
116
+ user_prompt=user_prompt,
117
+ attach=current_attachments,
118
+ workflows=current_workflows,
119
+ yolo_mode=current_yolo_mode,
120
+ previous_session_name=previous_session_name,
121
+ start_new=start_new,
122
+ )
123
+ current_attachments = ""
124
+ final_result = final_result if result is None else result
125
+ if ctx.is_web_mode or not is_tty:
126
+ return final_result
81
127
  return final_result
82
128
 
83
129
 
84
- def _show_info(ctx: AnyContext):
85
- """
86
- Displays the available chat session commands to the user.
87
- Args:
88
- ctx: The context object for the task.
89
- """
90
- ctx.print(
91
- "\n".join(
92
- [
93
- _format_info_line("/bye", "Quit from chat session"),
94
- _format_info_line("/multi", "Start multiline input"),
95
- _format_info_line("/end", "End multiline input"),
96
- _format_info_line("/modes", "Show current modes"),
97
- _format_info_line("/modes <mode1,mode2,..>", "Set current modes"),
98
- _format_info_line("/help", "Show this message"),
99
- ]
100
- ),
101
- plain=True,
102
- )
103
-
104
-
105
- def _format_info_line(command: str, description: str) -> str:
106
- styled_command = stylize_bold_yellow(command.ljust(25))
107
- styled_description = stylize_faint(description)
108
- return f" {styled_command} {styled_description}"
109
-
110
-
111
- async def _handle_initial_message(ctx: AnyContext) -> str:
112
- """Processes the initial message from the command line."""
113
- if not ctx.input.message or ctx.input.message.strip() == "":
114
- return ""
115
- ctx.print("💬 >>", plain=True)
116
- ctx.print(ctx.input.message, plain=True)
117
- ctx.print("", plain=True)
118
- result = await _trigger_ask_and_wait_for_result(
119
- ctx,
120
- user_prompt=ctx.input.message,
121
- modes=ctx.input.modes,
122
- previous_session_name=ctx.input.previous_session,
123
- start_new=ctx.input.start_new,
124
- )
125
- return result if result is not None else ""
126
-
127
-
128
- async def _setup_input_reader(is_interactive: bool):
130
+ async def _setup_input_reader(
131
+ is_interactive: bool,
132
+ ) -> "PromptSession[Any] | StreamReader":
129
133
  """Sets up and returns the appropriate asynchronous input reader."""
130
134
  if is_interactive:
131
135
  from prompt_toolkit import PromptSession
@@ -139,24 +143,12 @@ async def _setup_input_reader(is_interactive: bool):
139
143
  return reader
140
144
 
141
145
 
142
- async def _read_next_line(is_interactive: bool, reader, ctx: AnyContext) -> str:
143
- """Reads one line of input using the provided reader."""
144
- if is_interactive:
145
- return await reader.prompt_async()
146
-
147
- line_bytes = await reader.readline()
148
- if not line_bytes:
149
- return "/bye" # Signal to exit
150
-
151
- user_input = line_bytes.decode().strip()
152
- ctx.print(user_input, plain=True)
153
- return user_input
154
-
155
-
156
146
  async def _trigger_ask_and_wait_for_result(
157
147
  ctx: AnyContext,
158
148
  user_prompt: str,
159
- modes: str,
149
+ attach: str,
150
+ workflows: str,
151
+ yolo_mode: bool | str,
160
152
  previous_session_name: str | None = None,
161
153
  start_new: bool = False,
162
154
  ) -> str | None:
@@ -174,29 +166,17 @@ async def _trigger_ask_and_wait_for_result(
174
166
  """
175
167
  if user_prompt.strip() == "":
176
168
  return None
177
- await _trigger_ask(ctx, user_prompt, modes, previous_session_name, start_new)
169
+ await _trigger_ask(
170
+ ctx, user_prompt, attach, workflows, yolo_mode, previous_session_name, start_new
171
+ )
178
172
  result = await _wait_ask_result(ctx)
179
- md_result = _render_markdown(result) if result is not None else ""
173
+ md_result = render_markdown(result) if result is not None else ""
180
174
  ctx.print("\n🤖 >>", plain=True)
181
175
  ctx.print(md_result, plain=True)
182
176
  ctx.print("", plain=True)
183
177
  return result
184
178
 
185
179
 
186
- def _render_markdown(markdown_text: str) -> str:
187
- """
188
- Renders Markdown to a string, ensuring link URLs are visible.
189
- """
190
- from rich.console import Console
191
- from rich.markdown import Markdown
192
-
193
- console = Console()
194
- markdown = Markdown(markdown_text, hyperlinks=False)
195
- with console.capture() as capture:
196
- console.print(markdown)
197
- return capture.get()
198
-
199
-
200
180
  def get_llm_ask_input_mapping(callback_ctx: AnyContext):
201
181
  """
202
182
  Generates the input mapping for the LLM ask task from the callback context.
@@ -219,14 +199,18 @@ def get_llm_ask_input_mapping(callback_ctx: AnyContext):
219
199
  "start-new": data.get("start_new"),
220
200
  "previous-session": data.get("previous_session_name"),
221
201
  "message": data.get("message"),
222
- "modes": data.get("modes"),
202
+ "attach": data.get("attach"),
203
+ "workflows": data.get("workflows"),
204
+ "yolo": data.get("yolo"),
223
205
  }
224
206
 
225
207
 
226
208
  async def _trigger_ask(
227
209
  ctx: AnyContext,
228
210
  user_prompt: str,
229
- modes: str,
211
+ attach: str,
212
+ workflows: str,
213
+ yolo_mode: bool | str,
230
214
  previous_session_name: str | None = None,
231
215
  start_new: bool = False,
232
216
  ):
@@ -246,7 +230,9 @@ async def _trigger_ask(
246
230
  "previous_session_name": previous_session_name,
247
231
  "start_new": start_new,
248
232
  "message": user_prompt,
249
- "modes": modes,
233
+ "attach": attach,
234
+ "workflows": workflows,
235
+ "yolo": yolo_mode,
250
236
  }
251
237
  )
252
238
 
@@ -0,0 +1,288 @@
1
+ import os
2
+ import subprocess
3
+
4
+ from zrb.context.any_context import AnyContext
5
+ from zrb.task.llm.workflow import get_available_workflows
6
+ from zrb.util.cli.markdown import render_markdown
7
+ from zrb.util.cli.style import (
8
+ stylize_blue,
9
+ stylize_bold_yellow,
10
+ stylize_error,
11
+ stylize_faint,
12
+ )
13
+ from zrb.util.file import write_file
14
+ from zrb.util.markdown import make_markdown_section
15
+ from zrb.util.string.conversion import FALSE_STRS, TRUE_STRS, to_boolean
16
+
17
+ MULTILINE_START_CMD = ["/multi", "/multiline"]
18
+ MULTILINE_END_CMD = ["/end"]
19
+ QUIT_CMD = ["/bye", "/quit", "/q", "/exit"]
20
+ WORKFLOW_CMD = ["/workflow", "/workflows", "/skill", "/skills", "/w"]
21
+ SAVE_CMD = ["/save", "/s"]
22
+ ATTACHMENT_CMD = ["/attachment", "/attachments", "/attach"]
23
+ YOLO_CMD = ["/yolo"]
24
+ HELP_CMD = ["/help", "/info"]
25
+ ADD_SUB_CMD = ["add"]
26
+ SET_SUB_CMD = ["set"]
27
+ CLEAR_SUB_CMD = ["clear"]
28
+ RUN_CLI_CMD = ["/run", "/exec", "/execute", "/cmd", "/cli", "!"]
29
+
30
+ # Command display constants
31
+ MULTILINE_START_CMD_DESC = "Start multiline input"
32
+ MULTILINE_END_CMD_DESC = "End multiline input"
33
+ QUIT_CMD_DESC = "Quit from chat session"
34
+ WORKFLOW_CMD_DESC = "Show active workflows"
35
+ WORKFLOW_ADD_SUB_CMD_DESC = (
36
+ "Add active workflow "
37
+ f"(e.g., `{WORKFLOW_CMD[0]} {ADD_SUB_CMD[0]} coding,researching`)"
38
+ )
39
+ WORKFLOW_SET_SUB_CMD_DESC = (
40
+ "Set active workflows " f"(e.g., `{WORKFLOW_CMD[0]} {SET_SUB_CMD[0]} coding,`)"
41
+ )
42
+ WORKFLOW_CLEAR_SUB_CMD_DESC = "Deactivate all workflows"
43
+ SAVE_CMD_DESC = f"Save last response to a file (e.g., `{SAVE_CMD[0]} conclusion.md`)"
44
+ ATTACHMENT_CMD_DESC = "Show current attachment"
45
+ ATTACHMENT_ADD_SUB_CMD_DESC = (
46
+ "Attach a file " f"(e.g., `{ATTACHMENT_CMD[0]} {ADD_SUB_CMD[0]} ./logo.png`)"
47
+ )
48
+ ATTACHMENT_SET_SUB_CMD_DESC = (
49
+ "Set attachments "
50
+ f"(e.g., `{ATTACHMENT_CMD[0]} {SET_SUB_CMD[0]} ./logo.png,./diagram.png`)"
51
+ )
52
+ ATTACHMENT_CLEAR_SUB_CMD_DESC = "Clear attachment"
53
+ YOLO_CMD_DESC = "Show/manipulate current YOLO mode"
54
+ YOLO_SET_CMD_DESC = (
55
+ "Assign YOLO tools "
56
+ f"(e.g., `{YOLO_CMD[0]} {SET_SUB_CMD[0]} read_from_file,analyze_file`)"
57
+ )
58
+ YOLO_SET_TRUE_CMD_DESC = "Activate YOLO mode for all tools"
59
+ YOLO_SET_FALSE_CMD_DESC = "Deactivate YOLO mode for all tools"
60
+ RUN_CLI_CMD_DESC = "Run a non-interactive CLI command"
61
+ HELP_CMD_DESC = "Show info/help"
62
+
63
+
64
+ def print_current_yolo_mode(
65
+ ctx: AnyContext, current_yolo_mode_value: str | bool
66
+ ) -> None:
67
+ yolo_mode_str = (
68
+ current_yolo_mode_value if current_yolo_mode_value != "" else "*Not Set*"
69
+ )
70
+ ctx.print(render_markdown(f"🎲 Current YOLO mode: {yolo_mode_str}"), plain=True)
71
+ ctx.print("", plain=True)
72
+
73
+
74
+ def print_current_attachments(ctx: AnyContext, current_attachments_value: str) -> None:
75
+ attachments_str = (
76
+ current_attachments_value if current_attachments_value != "" else "*Not Set*"
77
+ )
78
+ ctx.print(render_markdown(f"📎 Current attachments: {attachments_str}"), plain=True)
79
+ ctx.print("", plain=True)
80
+
81
+
82
+ def print_current_workflows(ctx: AnyContext, current_workflows_value: str) -> None:
83
+ available_workflows = get_available_workflows()
84
+ available_workflows_str = (
85
+ ", ".join(sorted([workflow_name for workflow_name in available_workflows]))
86
+ if len(available_workflows) > 0
87
+ else "*No Available Workflow*"
88
+ )
89
+ current_workflows_str = (
90
+ current_workflows_value
91
+ if current_workflows_value != ""
92
+ else "*No Active Workflow*"
93
+ )
94
+ ctx.print(
95
+ render_markdown(
96
+ "\n".join(
97
+ [
98
+ f"- 🔄 Current workflows : {current_workflows_str}",
99
+ f"- 📚 Available workflows : {available_workflows_str}",
100
+ ]
101
+ )
102
+ ),
103
+ plain=True,
104
+ )
105
+ ctx.print("", plain=True)
106
+
107
+
108
+ def save_final_result(ctx: AnyContext, user_input: str, final_result: str) -> None:
109
+ save_path = get_command_param(user_input, SAVE_CMD)
110
+ save_path = os.path.expanduser(save_path)
111
+ if os.path.exists(save_path):
112
+ ctx.print(
113
+ stylize_error(f"Cannot save to existing file: {save_path}"),
114
+ plain=True,
115
+ )
116
+ return
117
+ write_file(save_path, final_result)
118
+ ctx.print(f"Response saved to {save_path}", plain=True)
119
+
120
+
121
+ def run_cli_command(ctx: AnyContext, user_input: str) -> None:
122
+ command = get_command_param(user_input, RUN_CLI_CMD)
123
+ result = subprocess.run(
124
+ command,
125
+ shell=True,
126
+ capture_output=True,
127
+ text=True,
128
+ )
129
+ ctx.print(
130
+ render_markdown(
131
+ make_markdown_section(
132
+ f"`{command}`",
133
+ "\n".join(
134
+ [
135
+ make_markdown_section("📤 Stdout", result.stdout, as_code=True),
136
+ make_markdown_section("🚫 Stderr", result.stderr, as_code=True),
137
+ make_markdown_section(
138
+ "🎯 Return code", f"Return Code: {result.returncode}"
139
+ ),
140
+ ]
141
+ ),
142
+ )
143
+ ),
144
+ plain=True,
145
+ )
146
+ ctx.print("", plain=True)
147
+
148
+
149
+ def get_new_yolo_mode(old_yolo_mode: str | bool, user_input: str) -> str | bool:
150
+ new_yolo_mode = get_command_param(user_input, YOLO_CMD)
151
+ if new_yolo_mode != "":
152
+ if new_yolo_mode in TRUE_STRS or new_yolo_mode in FALSE_STRS:
153
+ return to_boolean(new_yolo_mode)
154
+ return new_yolo_mode
155
+ if isinstance(old_yolo_mode, bool):
156
+ return old_yolo_mode
157
+ return _normalize_comma_separated_str(old_yolo_mode)
158
+
159
+
160
+ def get_new_attachments(old_attachment: str, user_input: str) -> str:
161
+ if not is_command_match(user_input, ATTACHMENT_CMD):
162
+ return _normalize_comma_separated_str(old_attachment)
163
+ if is_command_match(user_input, ATTACHMENT_CMD, SET_SUB_CMD):
164
+ return _normalize_comma_separated_str(
165
+ get_command_param(user_input, ATTACHMENT_CMD, SET_SUB_CMD)
166
+ )
167
+ if is_command_match(user_input, ATTACHMENT_CMD, CLEAR_SUB_CMD):
168
+ return ""
169
+ if is_command_match(user_input, ATTACHMENT_CMD, ADD_SUB_CMD):
170
+ new_attachment = get_command_param(user_input, ATTACHMENT_CMD, ADD_SUB_CMD)
171
+ return _normalize_comma_separated_str(
172
+ ",".join([old_attachment, new_attachment])
173
+ )
174
+ return old_attachment
175
+
176
+
177
+ def get_new_workflows(old_workflow: str, user_input: str) -> str:
178
+ if not is_command_match(user_input, WORKFLOW_CMD):
179
+ return _normalize_comma_separated_str(old_workflow)
180
+ if is_command_match(user_input, WORKFLOW_CMD, SET_SUB_CMD):
181
+ return _normalize_comma_separated_str(
182
+ get_command_param(user_input, WORKFLOW_CMD, SET_SUB_CMD)
183
+ )
184
+ if is_command_match(user_input, WORKFLOW_CMD, CLEAR_SUB_CMD):
185
+ return ""
186
+ if is_command_match(user_input, WORKFLOW_CMD, ADD_SUB_CMD):
187
+ new_workflow = get_command_param(user_input, WORKFLOW_CMD, ADD_SUB_CMD)
188
+ return _normalize_comma_separated_str(",".join([old_workflow, new_workflow]))
189
+ return _normalize_comma_separated_str(old_workflow)
190
+
191
+
192
+ def _normalize_comma_separated_str(comma_separated_str: str) -> str:
193
+ return ",".join(
194
+ [
195
+ workflow_name.strip()
196
+ for workflow_name in comma_separated_str.split(",")
197
+ if workflow_name.strip() != ""
198
+ ]
199
+ )
200
+
201
+
202
+ def get_command_param(user_input: str, *cmd_patterns: list[str]) -> str:
203
+ if not is_command_match(user_input, *cmd_patterns):
204
+ return ""
205
+ parts = [part for part in user_input.split(" ") if part.strip() != ""]
206
+ if len(parts) <= len(cmd_patterns):
207
+ return ""
208
+ params = parts[len(cmd_patterns) :]
209
+ return " ".join(params)
210
+
211
+
212
+ def is_command_match(user_input: str, *cmd_patterns: list[str]) -> bool:
213
+ parts = [part for part in user_input.split(" ") if part.strip() != ""]
214
+ if len(cmd_patterns) > len(parts):
215
+ return False
216
+ for index, cmd_pattern in enumerate(cmd_patterns):
217
+ part = parts[index]
218
+ if part.lower() not in cmd_pattern:
219
+ return False
220
+ return True
221
+
222
+
223
+ def print_commands(ctx: AnyContext):
224
+ """
225
+ Displays the available chat session commands to the user.
226
+ Args:
227
+ ctx: The context object for the task.
228
+ """
229
+ ctx.print(
230
+ "\n".join(
231
+ [
232
+ _show_command(QUIT_CMD[0], QUIT_CMD_DESC),
233
+ _show_command(MULTILINE_START_CMD[0], MULTILINE_START_CMD_DESC),
234
+ _show_command(MULTILINE_END_CMD[0], MULTILINE_END_CMD_DESC),
235
+ _show_command(ATTACHMENT_CMD[0], ATTACHMENT_CMD_DESC),
236
+ _show_subcommand(
237
+ ADD_SUB_CMD[0], "<file-path>", ATTACHMENT_ADD_SUB_CMD_DESC
238
+ ),
239
+ _show_subcommand(
240
+ SET_SUB_CMD[0],
241
+ "<file1-path,file2-path,...>",
242
+ ATTACHMENT_SET_SUB_CMD_DESC,
243
+ ),
244
+ _show_subcommand(CLEAR_SUB_CMD[0], "", ATTACHMENT_CLEAR_SUB_CMD_DESC),
245
+ _show_command(WORKFLOW_CMD[0], WORKFLOW_CMD_DESC),
246
+ _show_subcommand(
247
+ ADD_SUB_CMD[0], "<workflow>", WORKFLOW_ADD_SUB_CMD_DESC
248
+ ),
249
+ _show_subcommand(
250
+ SET_SUB_CMD[0],
251
+ "<workflow1,workflow2,..>",
252
+ WORKFLOW_SET_SUB_CMD_DESC,
253
+ ),
254
+ _show_subcommand(CLEAR_SUB_CMD[0], "", WORKFLOW_CLEAR_SUB_CMD_DESC),
255
+ _show_command(f"{SAVE_CMD[0]}", SAVE_CMD_DESC),
256
+ _show_command(YOLO_CMD[0], YOLO_CMD_DESC),
257
+ _show_subcommand(SET_SUB_CMD[0], "true", YOLO_SET_TRUE_CMD_DESC),
258
+ _show_subcommand(SET_SUB_CMD[0], "false", YOLO_SET_FALSE_CMD_DESC),
259
+ _show_subcommand(
260
+ SET_SUB_CMD[0], "<tool1,tool2,tool2>", YOLO_SET_CMD_DESC
261
+ ),
262
+ _show_command(RUN_CLI_CMD[0], ""),
263
+ _show_command_param("<cli-command>", RUN_CLI_CMD_DESC),
264
+ _show_command(HELP_CMD[0], HELP_CMD_DESC),
265
+ ]
266
+ ),
267
+ plain=True,
268
+ )
269
+ ctx.print("", plain=True)
270
+
271
+
272
+ def _show_command(command: str, description: str) -> str:
273
+ styled_command = stylize_bold_yellow(command.ljust(37))
274
+ styled_description = stylize_faint(description)
275
+ return f" {styled_command} {styled_description}"
276
+
277
+
278
+ def _show_subcommand(subcommand: str, param: str, description: str) -> str:
279
+ styled_subcommand = stylize_bold_yellow(f" {subcommand}")
280
+ styled_param = stylize_blue(param.ljust(32 - len(subcommand)))
281
+ styled_description = stylize_faint(description)
282
+ return f" {styled_subcommand} {styled_param} {styled_description}"
283
+
284
+
285
+ def _show_command_param(param: str, description: str) -> str:
286
+ styled_param = stylize_blue(f" {param}".ljust(37))
287
+ styled_description = stylize_faint(description)
288
+ return f" {styled_param} {styled_description}"