zrb 1.21.29__py3-none-any.whl → 2.0.0a4__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.

Potentially problematic release.


This version of zrb might be problematic. Click here for more details.

Files changed (192) hide show
  1. zrb/__init__.py +118 -129
  2. zrb/builtin/__init__.py +54 -2
  3. zrb/builtin/llm/chat.py +147 -0
  4. zrb/callback/callback.py +8 -1
  5. zrb/cmd/cmd_result.py +2 -1
  6. zrb/config/config.py +491 -280
  7. zrb/config/helper.py +84 -0
  8. zrb/config/web_auth_config.py +50 -35
  9. zrb/context/any_shared_context.py +13 -2
  10. zrb/context/context.py +31 -3
  11. zrb/context/print_fn.py +13 -0
  12. zrb/context/shared_context.py +14 -1
  13. zrb/input/option_input.py +30 -2
  14. zrb/llm/agent/__init__.py +9 -0
  15. zrb/llm/agent/agent.py +215 -0
  16. zrb/llm/agent/summarizer.py +20 -0
  17. zrb/llm/app/__init__.py +10 -0
  18. zrb/llm/app/completion.py +281 -0
  19. zrb/llm/app/confirmation/allow_tool.py +66 -0
  20. zrb/llm/app/confirmation/handler.py +178 -0
  21. zrb/llm/app/confirmation/replace_confirmation.py +77 -0
  22. zrb/llm/app/keybinding.py +34 -0
  23. zrb/llm/app/layout.py +117 -0
  24. zrb/llm/app/lexer.py +155 -0
  25. zrb/llm/app/redirection.py +28 -0
  26. zrb/llm/app/style.py +16 -0
  27. zrb/llm/app/ui.py +733 -0
  28. zrb/llm/config/__init__.py +4 -0
  29. zrb/llm/config/config.py +122 -0
  30. zrb/llm/config/limiter.py +247 -0
  31. zrb/llm/history_manager/__init__.py +4 -0
  32. zrb/llm/history_manager/any_history_manager.py +23 -0
  33. zrb/llm/history_manager/file_history_manager.py +91 -0
  34. zrb/llm/history_processor/summarizer.py +108 -0
  35. zrb/llm/note/__init__.py +3 -0
  36. zrb/llm/note/manager.py +122 -0
  37. zrb/llm/prompt/__init__.py +29 -0
  38. zrb/llm/prompt/claude_compatibility.py +92 -0
  39. zrb/llm/prompt/compose.py +55 -0
  40. zrb/llm/prompt/default.py +51 -0
  41. zrb/llm/prompt/markdown/mandate.md +23 -0
  42. zrb/llm/prompt/markdown/persona.md +3 -0
  43. zrb/llm/prompt/markdown/summarizer.md +21 -0
  44. zrb/llm/prompt/note.py +41 -0
  45. zrb/llm/prompt/system_context.py +46 -0
  46. zrb/llm/prompt/zrb.py +41 -0
  47. zrb/llm/skill/__init__.py +3 -0
  48. zrb/llm/skill/manager.py +86 -0
  49. zrb/llm/task/__init__.py +4 -0
  50. zrb/llm/task/llm_chat_task.py +316 -0
  51. zrb/llm/task/llm_task.py +245 -0
  52. zrb/llm/tool/__init__.py +39 -0
  53. zrb/llm/tool/bash.py +75 -0
  54. zrb/llm/tool/code.py +266 -0
  55. zrb/llm/tool/file.py +419 -0
  56. zrb/llm/tool/note.py +70 -0
  57. zrb/{builtin/llm → llm}/tool/rag.py +8 -5
  58. zrb/llm/tool/search/brave.py +53 -0
  59. zrb/llm/tool/search/searxng.py +47 -0
  60. zrb/llm/tool/search/serpapi.py +47 -0
  61. zrb/llm/tool/skill.py +19 -0
  62. zrb/llm/tool/sub_agent.py +70 -0
  63. zrb/llm/tool/web.py +97 -0
  64. zrb/llm/tool/zrb_task.py +66 -0
  65. zrb/llm/util/attachment.py +101 -0
  66. zrb/llm/util/prompt.py +104 -0
  67. zrb/llm/util/stream_response.py +178 -0
  68. zrb/session/any_session.py +0 -3
  69. zrb/session/session.py +1 -1
  70. zrb/task/base/context.py +25 -13
  71. zrb/task/base/execution.py +52 -47
  72. zrb/task/base/lifecycle.py +7 -4
  73. zrb/task/base_task.py +48 -49
  74. zrb/task/base_trigger.py +4 -1
  75. zrb/task/cmd_task.py +6 -0
  76. zrb/task/http_check.py +11 -5
  77. zrb/task/make_task.py +3 -0
  78. zrb/task/rsync_task.py +5 -0
  79. zrb/task/scaffolder.py +7 -4
  80. zrb/task/scheduler.py +3 -0
  81. zrb/task/tcp_check.py +6 -4
  82. zrb/util/ascii_art/art/bee.txt +17 -0
  83. zrb/util/ascii_art/art/cat.txt +9 -0
  84. zrb/util/ascii_art/art/ghost.txt +16 -0
  85. zrb/util/ascii_art/art/panda.txt +17 -0
  86. zrb/util/ascii_art/art/rose.txt +14 -0
  87. zrb/util/ascii_art/art/unicorn.txt +15 -0
  88. zrb/util/ascii_art/banner.py +92 -0
  89. zrb/util/cli/markdown.py +22 -2
  90. zrb/util/cmd/command.py +33 -10
  91. zrb/util/file.py +51 -32
  92. zrb/util/match.py +78 -0
  93. zrb/util/run.py +3 -3
  94. {zrb-1.21.29.dist-info → zrb-2.0.0a4.dist-info}/METADATA +9 -15
  95. {zrb-1.21.29.dist-info → zrb-2.0.0a4.dist-info}/RECORD +100 -128
  96. zrb/attr/__init__.py +0 -0
  97. zrb/builtin/llm/attachment.py +0 -40
  98. zrb/builtin/llm/chat_completion.py +0 -274
  99. zrb/builtin/llm/chat_session.py +0 -270
  100. zrb/builtin/llm/chat_session_cmd.py +0 -288
  101. zrb/builtin/llm/chat_trigger.py +0 -79
  102. zrb/builtin/llm/history.py +0 -71
  103. zrb/builtin/llm/input.py +0 -27
  104. zrb/builtin/llm/llm_ask.py +0 -269
  105. zrb/builtin/llm/previous-session.js +0 -21
  106. zrb/builtin/llm/tool/__init__.py +0 -0
  107. zrb/builtin/llm/tool/api.py +0 -75
  108. zrb/builtin/llm/tool/cli.py +0 -52
  109. zrb/builtin/llm/tool/code.py +0 -236
  110. zrb/builtin/llm/tool/file.py +0 -560
  111. zrb/builtin/llm/tool/note.py +0 -84
  112. zrb/builtin/llm/tool/sub_agent.py +0 -150
  113. zrb/builtin/llm/tool/web.py +0 -171
  114. zrb/builtin/project/__init__.py +0 -0
  115. zrb/builtin/project/add/fastapp/fastapp_template/my_app_name/__init__.py +0 -0
  116. zrb/builtin/project/add/fastapp/fastapp_template/my_app_name/_zrb/module/template/app_template/module/my_module/service/__init__.py +0 -0
  117. zrb/builtin/project/add/fastapp/fastapp_template/my_app_name/common/__init__.py +0 -0
  118. zrb/builtin/project/add/fastapp/fastapp_template/my_app_name/module/__init__.py +0 -0
  119. zrb/builtin/project/add/fastapp/fastapp_template/my_app_name/module/auth/service/__init__.py +0 -0
  120. zrb/builtin/project/add/fastapp/fastapp_template/my_app_name/module/auth/service/permission/__init__.py +0 -0
  121. zrb/builtin/project/add/fastapp/fastapp_template/my_app_name/module/auth/service/role/__init__.py +0 -0
  122. zrb/builtin/project/add/fastapp/fastapp_template/my_app_name/module/auth/service/user/__init__.py +0 -0
  123. zrb/builtin/project/add/fastapp/fastapp_template/my_app_name/schema/__init__.py +0 -0
  124. zrb/builtin/project/create/__init__.py +0 -0
  125. zrb/builtin/shell/__init__.py +0 -0
  126. zrb/builtin/shell/autocomplete/__init__.py +0 -0
  127. zrb/callback/__init__.py +0 -0
  128. zrb/cmd/__init__.py +0 -0
  129. zrb/config/default_prompt/interactive_system_prompt.md +0 -29
  130. zrb/config/default_prompt/persona.md +0 -1
  131. zrb/config/default_prompt/summarization_prompt.md +0 -57
  132. zrb/config/default_prompt/system_prompt.md +0 -38
  133. zrb/config/llm_config.py +0 -339
  134. zrb/config/llm_context/config.py +0 -166
  135. zrb/config/llm_context/config_parser.py +0 -40
  136. zrb/config/llm_context/workflow.py +0 -81
  137. zrb/config/llm_rate_limitter.py +0 -190
  138. zrb/content_transformer/__init__.py +0 -0
  139. zrb/context/__init__.py +0 -0
  140. zrb/dot_dict/__init__.py +0 -0
  141. zrb/env/__init__.py +0 -0
  142. zrb/group/__init__.py +0 -0
  143. zrb/input/__init__.py +0 -0
  144. zrb/runner/__init__.py +0 -0
  145. zrb/runner/web_route/__init__.py +0 -0
  146. zrb/runner/web_route/home_page/__init__.py +0 -0
  147. zrb/session/__init__.py +0 -0
  148. zrb/session_state_log/__init__.py +0 -0
  149. zrb/session_state_logger/__init__.py +0 -0
  150. zrb/task/__init__.py +0 -0
  151. zrb/task/base/__init__.py +0 -0
  152. zrb/task/llm/__init__.py +0 -0
  153. zrb/task/llm/agent.py +0 -204
  154. zrb/task/llm/agent_runner.py +0 -152
  155. zrb/task/llm/config.py +0 -122
  156. zrb/task/llm/conversation_history.py +0 -209
  157. zrb/task/llm/conversation_history_model.py +0 -67
  158. zrb/task/llm/default_workflow/coding/workflow.md +0 -41
  159. zrb/task/llm/default_workflow/copywriting/workflow.md +0 -68
  160. zrb/task/llm/default_workflow/git/workflow.md +0 -118
  161. zrb/task/llm/default_workflow/golang/workflow.md +0 -128
  162. zrb/task/llm/default_workflow/html-css/workflow.md +0 -135
  163. zrb/task/llm/default_workflow/java/workflow.md +0 -146
  164. zrb/task/llm/default_workflow/javascript/workflow.md +0 -158
  165. zrb/task/llm/default_workflow/python/workflow.md +0 -160
  166. zrb/task/llm/default_workflow/researching/workflow.md +0 -153
  167. zrb/task/llm/default_workflow/rust/workflow.md +0 -162
  168. zrb/task/llm/default_workflow/shell/workflow.md +0 -299
  169. zrb/task/llm/error.py +0 -95
  170. zrb/task/llm/file_replacement.py +0 -206
  171. zrb/task/llm/file_tool_model.py +0 -57
  172. zrb/task/llm/history_processor.py +0 -206
  173. zrb/task/llm/history_summarization.py +0 -25
  174. zrb/task/llm/print_node.py +0 -221
  175. zrb/task/llm/prompt.py +0 -321
  176. zrb/task/llm/subagent_conversation_history.py +0 -41
  177. zrb/task/llm/tool_wrapper.py +0 -361
  178. zrb/task/llm/typing.py +0 -3
  179. zrb/task/llm/workflow.py +0 -76
  180. zrb/task/llm_task.py +0 -379
  181. zrb/task_status/__init__.py +0 -0
  182. zrb/util/__init__.py +0 -0
  183. zrb/util/cli/__init__.py +0 -0
  184. zrb/util/cmd/__init__.py +0 -0
  185. zrb/util/codemod/__init__.py +0 -0
  186. zrb/util/string/__init__.py +0 -0
  187. zrb/xcom/__init__.py +0 -0
  188. /zrb/{config/default_prompt/file_extractor_system_prompt.md → llm/prompt/markdown/file_extractor.md} +0 -0
  189. /zrb/{config/default_prompt/repo_extractor_system_prompt.md → llm/prompt/markdown/repo_extractor.md} +0 -0
  190. /zrb/{config/default_prompt/repo_summarizer_system_prompt.md → llm/prompt/markdown/repo_summarizer.md} +0 -0
  191. {zrb-1.21.29.dist-info → zrb-2.0.0a4.dist-info}/WHEEL +0 -0
  192. {zrb-1.21.29.dist-info → zrb-2.0.0a4.dist-info}/entry_points.txt +0 -0
zrb/task/llm/config.py DELETED
@@ -1,122 +0,0 @@
1
- from typing import TYPE_CHECKING, Callable
2
-
3
- if TYPE_CHECKING:
4
- from pydantic_ai.models import Model
5
- from pydantic_ai.settings import ModelSettings
6
-
7
- from zrb.attr.type import BoolAttr, StrAttr, StrListAttr
8
- from zrb.config.llm_config import LLMConfig, llm_config
9
- from zrb.context.any_context import AnyContext
10
- from zrb.util.attr import get_attr, get_bool_attr, get_str_list_attr
11
-
12
-
13
- def get_yolo_mode(
14
- ctx: AnyContext,
15
- yolo_mode_attr: (
16
- Callable[[AnyContext], list[str] | bool | None] | StrListAttr | BoolAttr | None
17
- ) = None,
18
- render_yolo_mode: bool = True,
19
- ) -> bool | list[str]:
20
- if yolo_mode_attr is None:
21
- return llm_config.default_yolo_mode
22
- try:
23
- return get_bool_attr(
24
- ctx,
25
- yolo_mode_attr,
26
- False,
27
- auto_render=render_yolo_mode,
28
- )
29
- except Exception:
30
- return get_str_list_attr(
31
- ctx,
32
- yolo_mode_attr,
33
- auto_render=render_yolo_mode,
34
- )
35
-
36
-
37
- def get_model_settings(
38
- ctx: AnyContext,
39
- model_settings_attr: (
40
- "ModelSettings | Callable[[AnyContext], ModelSettings] | None"
41
- ) = None,
42
- ) -> "ModelSettings | None":
43
- """Gets the model settings, resolving callables if necessary."""
44
- model_settings = get_attr(ctx, model_settings_attr, None, auto_render=False)
45
- if model_settings is None:
46
- return llm_config.default_model_settings
47
- return model_settings
48
-
49
-
50
- def get_model_base_url(
51
- ctx: AnyContext,
52
- model_base_url_attr: StrAttr | None = None,
53
- render_model_base_url: bool = True,
54
- ) -> str | None:
55
- """Gets the model base URL, rendering if configured."""
56
- base_url = get_attr(
57
- ctx, model_base_url_attr, None, auto_render=render_model_base_url
58
- )
59
- if base_url is None and llm_config.default_model_base_url is not None:
60
- return llm_config.default_model_base_url
61
- if isinstance(base_url, str) or base_url is None:
62
- return base_url
63
- raise ValueError(f"Invalid model base URL: {base_url}")
64
-
65
-
66
- def get_model_api_key(
67
- ctx: AnyContext,
68
- model_api_key_attr: StrAttr | None = None,
69
- render_model_api_key: bool = True,
70
- ) -> str | None:
71
- """Gets the model API key, rendering if configured."""
72
- api_key = get_attr(ctx, model_api_key_attr, None, auto_render=render_model_api_key)
73
- if api_key is None and llm_config.default_model_api_key is not None:
74
- return llm_config.default_model_api_key
75
- if isinstance(api_key, str) or api_key is None:
76
- return api_key
77
- raise ValueError(f"Invalid model API key: {api_key}")
78
-
79
-
80
- def get_model(
81
- ctx: AnyContext,
82
- model_attr: "Callable[[AnyContext], Model | str | None] | Model | str | None",
83
- render_model: bool,
84
- model_base_url_attr: "Callable[[AnyContext], Model | str | None] | Model | str | None",
85
- render_model_base_url: bool = True,
86
- model_api_key_attr: "Callable[[AnyContext], Model | str | None] | Model | str | None" = None,
87
- render_model_api_key: bool = True,
88
- is_small_model: bool = False,
89
- ) -> "str | Model":
90
- """Gets the model instance or name, handling defaults and configuration."""
91
- from pydantic_ai.models import Model
92
-
93
- model = get_attr(ctx, model_attr, None, auto_render=render_model)
94
- if model is None:
95
- if is_small_model:
96
- return llm_config.default_small_model
97
- return llm_config.default_model
98
- if isinstance(model, str):
99
- model_base_url = get_model_base_url(
100
- ctx, model_base_url_attr, render_model_base_url
101
- )
102
- model_api_key = get_model_api_key(ctx, model_api_key_attr, render_model_api_key)
103
- new_llm_config = LLMConfig(
104
- default_model_name=model,
105
- default_model_base_url=model_base_url,
106
- default_model_api_key=model_api_key,
107
- )
108
- if model_base_url is None and model_api_key is None:
109
- default_model_provider = _get_default_model_provider(is_small_model)
110
- if default_model_provider is not None:
111
- new_llm_config.set_default_model_provider(default_model_provider)
112
- return new_llm_config.default_model
113
- # If it's already a Model instance, return it directly
114
- if isinstance(model, Model):
115
- return model
116
- raise ValueError(f"Invalid model type resolved: {type(model)}, value: {model}")
117
-
118
-
119
- def _get_default_model_provider(is_small_model: bool = False):
120
- if is_small_model:
121
- return llm_config.default_small_model_provider
122
- return llm_config.default_model_provider
@@ -1,209 +0,0 @@
1
- import json
2
- import os
3
- from collections.abc import Callable
4
- from typing import Any
5
-
6
- from zrb.attr.type import StrAttr
7
- from zrb.config.llm_context.config import llm_context_config
8
- from zrb.context.any_context import AnyContext
9
- from zrb.task.llm.conversation_history_model import ConversationHistory
10
- from zrb.task.llm.typing import ListOfDict
11
- from zrb.util.attr import get_str_attr
12
- from zrb.util.file import read_file, write_file
13
- from zrb.util.markdown import make_markdown_section
14
- from zrb.util.run import run_async
15
- from zrb.xcom.xcom import Xcom
16
-
17
-
18
- def _get_global_subagent_messages_xcom(ctx: AnyContext) -> Xcom:
19
- if "_global_subagents" not in ctx.xcom:
20
- ctx.xcom["_global_subagents"] = Xcom([{}])
21
- if not isinstance(ctx.xcom["_global_subagents"], Xcom):
22
- raise ValueError("ctx.xcom._global_subagents must be an Xcom")
23
- return ctx.xcom["_global_subagents"]
24
-
25
-
26
- def inject_subagent_history_into_ctx(
27
- ctx: AnyContext, conversation_history: ConversationHistory
28
- ):
29
- subagent_messages_xcom = _get_global_subagent_messages_xcom(ctx)
30
- existing_subagent_history = subagent_messages_xcom.get({})
31
- subagent_messages_xcom.set(
32
- {**existing_subagent_history, **conversation_history.subagent_history}
33
- )
34
-
35
-
36
- def set_ctx_subagent_history(ctx: AnyContext, subagent_name: str, messages: ListOfDict):
37
- subagent_messages_xcom = _get_global_subagent_messages_xcom(ctx)
38
- subagent_history = subagent_messages_xcom.get({})
39
- subagent_history[subagent_name] = messages
40
- subagent_messages_xcom.set(subagent_history)
41
-
42
-
43
- def get_subagent_histories_from_ctx(ctx: AnyContext) -> dict[str, ListOfDict]:
44
- subagent_messsages_xcom = _get_global_subagent_messages_xcom(ctx)
45
- return subagent_messsages_xcom.get({})
46
-
47
-
48
- def inject_conversation_history_notes(conversation_history: ConversationHistory):
49
- conversation_history.long_term_note = _fetch_long_term_note(
50
- conversation_history.project_path
51
- )
52
- conversation_history.contextual_note = _fetch_contextual_note(
53
- conversation_history.project_path
54
- )
55
-
56
-
57
- def _fetch_long_term_note(project_path: str) -> str:
58
- contexts = llm_context_config.get_notes(cwd=project_path)
59
- return contexts.get("/", "")
60
-
61
-
62
- def _fetch_contextual_note(project_path: str) -> str:
63
- contexts = llm_context_config.get_notes(cwd=project_path)
64
- return "\n".join(
65
- [
66
- make_markdown_section(header, content)
67
- for header, content in contexts.items()
68
- if header != "/"
69
- ]
70
- )
71
-
72
-
73
- def get_history_file(
74
- ctx: AnyContext,
75
- conversation_history_file_attr: StrAttr | None,
76
- render_history_file: bool,
77
- ) -> str:
78
- """Gets the path to the conversation history file, rendering if configured."""
79
- return get_str_attr(
80
- ctx,
81
- conversation_history_file_attr,
82
- "",
83
- auto_render=render_history_file,
84
- )
85
-
86
-
87
- async def _read_from_source(
88
- ctx: AnyContext,
89
- reader: (
90
- Callable[[AnyContext], ConversationHistory | dict[str, Any] | list | None]
91
- | None
92
- ),
93
- file_path: str | None,
94
- ) -> "ConversationHistory | None":
95
- # Priority 1: Reader function
96
- if reader:
97
- try:
98
- raw_data = await run_async(reader(ctx))
99
- if raw_data:
100
- instance = ConversationHistory.parse_and_validate(
101
- ctx, raw_data, "reader"
102
- )
103
- if instance:
104
- return instance
105
- except Exception as e:
106
- ctx.log_warning(
107
- f"Error executing conversation history reader: {e}. Ignoring."
108
- )
109
- # Priority 2: History file
110
- if file_path and os.path.isfile(file_path):
111
- try:
112
- content = read_file(file_path)
113
- raw_data = json.loads(content)
114
- instance = ConversationHistory.parse_and_validate(
115
- ctx, raw_data, f"file '{file_path}'"
116
- )
117
- if instance:
118
- return instance
119
- except json.JSONDecodeError:
120
- ctx.log_warning(
121
- f"Could not decode JSON from history file '{file_path}'. "
122
- "Ignoring file content."
123
- )
124
- except Exception as e:
125
- ctx.log_warning(
126
- f"Error reading history file '{file_path}': {e}. "
127
- "Ignoring file content."
128
- )
129
- # Fallback: Return default value
130
- return None
131
-
132
-
133
- async def read_conversation_history(
134
- ctx: AnyContext,
135
- conversation_history_reader: (
136
- Callable[[AnyContext], ConversationHistory | dict | list | None] | None
137
- ),
138
- conversation_history_file_attr: StrAttr | None,
139
- render_history_file: bool,
140
- conversation_history_attr: (
141
- ConversationHistory
142
- | Callable[[AnyContext], ConversationHistory | dict | list]
143
- | dict
144
- | list
145
- ),
146
- ) -> ConversationHistory:
147
- """Reads conversation history from reader, file, or attribute, with validation."""
148
- history_file = get_history_file(
149
- ctx, conversation_history_file_attr, render_history_file
150
- )
151
- # Use the class method defined above
152
- history_data = await _read_from_source(
153
- ctx=ctx,
154
- reader=conversation_history_reader,
155
- file_path=history_file,
156
- )
157
- if history_data:
158
- return history_data
159
- # Priority 3: Callable or direct conversation_history attribute
160
- raw_data_attr: Any = None
161
- if callable(conversation_history_attr):
162
- try:
163
- raw_data_attr = await run_async(conversation_history_attr(ctx))
164
- except Exception as e:
165
- ctx.log_warning(
166
- f"Error executing callable conversation_history attribute: {e}. "
167
- "Ignoring."
168
- )
169
- if raw_data_attr is None:
170
- raw_data_attr = conversation_history_attr
171
- if raw_data_attr:
172
- # Use the class method defined above
173
- history_data = ConversationHistory.parse_and_validate(
174
- ctx, raw_data_attr, "attribute"
175
- )
176
- if history_data:
177
- return history_data
178
- # Fallback: Return default value
179
- return ConversationHistory()
180
-
181
-
182
- async def write_conversation_history(
183
- ctx: AnyContext,
184
- history_data: ConversationHistory,
185
- conversation_history_writer: (
186
- Callable[[AnyContext, ConversationHistory], None] | None
187
- ),
188
- conversation_history_file_attr: StrAttr | None,
189
- render_history_file: bool,
190
- ):
191
- """Writes conversation history using the writer or to a file."""
192
- if conversation_history_writer is not None:
193
- await run_async(conversation_history_writer(ctx, history_data))
194
- history_file = get_history_file(
195
- ctx, conversation_history_file_attr, render_history_file
196
- )
197
- if history_file != "":
198
- write_file(history_file, json.dumps(history_data.to_dict(), indent=2))
199
-
200
-
201
- def count_part_in_history_list(history_list: ListOfDict) -> int:
202
- """Calculates the total number of 'parts' in a history list."""
203
- history_part_len = 0
204
- for history in history_list:
205
- if "parts" in history:
206
- history_part_len += len(history["parts"])
207
- else:
208
- history_part_len += 1
209
- return history_part_len
@@ -1,67 +0,0 @@
1
- import json
2
- import os
3
- from typing import Any
4
-
5
- from zrb.context.any_context import AnyContext
6
- from zrb.task.llm.typing import ListOfDict
7
-
8
-
9
- class ConversationHistory:
10
-
11
- def __init__(
12
- self,
13
- history: ListOfDict | None = None,
14
- contextual_note: str | None = None,
15
- long_term_note: str | None = None,
16
- project_path: str | None = None,
17
- subagent_history: dict[str, ListOfDict] | None = None,
18
- ):
19
- self.history = history if history is not None else []
20
- self.contextual_note = contextual_note if contextual_note is not None else ""
21
- self.long_term_note = long_term_note if long_term_note is not None else ""
22
- self.project_path = project_path if project_path is not None else os.getcwd()
23
- self.subagent_history = subagent_history if subagent_history is not None else {}
24
-
25
- def to_dict(self) -> dict[str, Any]:
26
- return {
27
- "history": self.history,
28
- "contextual_note": self.contextual_note,
29
- "long_term_note": self.long_term_note,
30
- "subagent_history": self.subagent_history,
31
- }
32
-
33
- def model_dump_json(self, indent: int = 2) -> str:
34
- return json.dumps(self.to_dict(), indent=indent)
35
-
36
- @classmethod
37
- def parse_and_validate(
38
- cls, ctx: AnyContext, data: Any, source: str
39
- ) -> "ConversationHistory":
40
- try:
41
- if isinstance(data, cls):
42
- return data # Already a valid instance
43
- if isinstance(data, dict):
44
- return cls(
45
- history=data.get("history", data.get("messages", [])),
46
- contextual_note=data.get("contextual_note", ""),
47
- long_term_note=data.get("long_term_note", ""),
48
- subagent_history=data.get("subagent_history", {}),
49
- )
50
- elif isinstance(data, list):
51
- # Handle very old format (just a list) - wrap it
52
- ctx.log_warning(
53
- f"History from {source} contains legacy list format. "
54
- "Wrapping it into the new structure. "
55
- "Consider updating the source format."
56
- )
57
- return cls(history=data)
58
- else:
59
- ctx.log_warning(
60
- f"History data from {source} has unexpected format "
61
- f"(type: {type(data)}). Ignoring."
62
- )
63
- except Exception as e: # Catch validation errors too
64
- ctx.log_warning(
65
- f"Error validating/parsing history data from {source}: {e}. Ignoring."
66
- )
67
- return cls()
@@ -1,41 +0,0 @@
1
- ---
2
- description: "A comprehensive workflow for software engineering tasks, including writing, modifying, and debugging code, as well as creating new applications. ALWAYS activate this workflow whenever you need to deal with software engineering tasks."
3
- ---
4
-
5
- This workflow provides a structured approach to software engineering tasks. Adhere to these guidelines to deliver high-quality, idiomatic code that respects the project's existing patterns and conventions.
6
-
7
- # Workflow Loading Strategy
8
-
9
- This is a general-purpose coding workflow. For tasks involving specific languages or tools, you **MUST** load the relevant specialized workflows.
10
-
11
- - **If the task involves Python:** Load the `python` workflow.
12
- - **If the task involves Git:** Load the `git` workflow.
13
- - **If the task involves shell scripting:** Load the `shell` workflow.
14
- - **If the task involves Go:** Load the `golang` workflow.
15
- - **If the task involves Java:** Load the `java` workflow.
16
- - **If the task involves Javascript/Typescript:** Load the `javascript` workflow.
17
- - **If the task involves HTML/CSS:** Load the `html-css` workflow.
18
- - **If the task involves Rust:** Load the `rust` workflow.
19
-
20
- Always consider if a more specific workflow is available and appropriate for the task at hand.
21
-
22
- # Core Mandates
23
-
24
- - **Conventions:** Rigorously adhere to existing project conventions when reading or modifying code. Analyze surrounding code, tests, and configuration first.
25
- - **Libraries/Frameworks:** NEVER assume a library/framework is available or appropriate. Verify its established usage within the project (check imports, configuration files like 'package.json', 'Cargo.toml', 'requirements.txt', 'build.gradle', etc., or observe neighboring files) before employing it.
26
- - **Style & Structure:** Mimic the style (formatting, naming), structure, framework choices, typing, and architectural patterns of existing code in the project.
27
- - **Idiomatic Changes:** When editing, understand the local context (imports, functions/classes) to ensure your changes integrate naturally and idiomatically.
28
- - **Comments:** Add code comments sparingly. Focus on *why* something is done, especially for complex logic, rather than *what* is done. Only add high-value comments if necessary for clarity or if requested by the user. Do not edit comments that are separate from the code you are changing. *NEVER* talk to the user or describe your changes through comments.
29
- - **Proactiveness:** Fulfill the user's request thoroughly. When adding features or fixing bugs, this includes adding tests to ensure quality. Consider all created files, especially tests, to be permanent artifacts unless the user says otherwise.
30
- - **Confirm Ambiguity/Expansion:** Do not take significant actions beyond the clear scope of the request without confirming with the user. If asked *how* to do something, explain first, don't just do it.
31
- - **Explaining Changes:** After completing a code modification or file operation *do not* provide summaries unless asked.
32
- - **Do Not revert changes:** Do not revert changes to the codebase unless asked to do so by the user. Only revert changes made by you if they have resulted in an error or if the user has explicitly asked you to revert the changes.
33
-
34
- # Software Engineering Tasks
35
- When requested to perform tasks like fixing bugs, adding features, refactoring, or explaining code, follow this sequence:
36
- 1. **Understand & Strategize:** Think about the user's request and the relevant codebase context. When the task involves **complex refactoring, codebase exploration or system-wide analysis**, your **first and primary tool** must be 'codebase_investigator'. Use it to build a comprehensive understanding of the code, its structure, and dependencies. For **simple, targeted searches** (like finding a specific function name, file path, or variable declaration), you should use 'search_file_content' or 'glob' directly.
37
- 2. **Plan:** Build a coherent and grounded (based on the understanding in step 1) plan for how you intend to resolve the user's task. Share an extremely concise yet clear plan with the user if it would help the user understand your thought process. As part of the plan, you should use an iterative development process that includes writing unit tests to verify your changes. Use output logs or debug statements as part of this process to arrive at a solution.
38
- 3. **Implement:** Use the available tools (e.g., 'replace_in_file', 'write_to_file' 'run_shell_command' ...) to act on the plan, strictly adhering to the project's established conventions (detailed under 'Core Mandates').
39
- 4. **Verify (Tests):** If applicable and feasible, verify the changes using the project's testing procedures. Identify the correct test commands and frameworks by examining 'README' files, build/package configuration (e.g., 'package.json'), or existing test execution patterns. NEVER assume standard test commands.
40
- 5. **Verify (Standards):** VERY IMPORTANT: After making code changes, execute the project-specific build, linting and type-checking commands (e.g., 'tsc', 'npm run lint', 'ruff check .') that you have identified for this project (or obtained from the user). This ensures code quality and adherence to standards. If unsure about these commands, you can ask the user if they'd like you to run them and if so how to.
41
- 6. **Finalize:** After all verification passes, consider the task complete. Do not remove or revert any changes or created files (like tests). Await the user's next instruction.
@@ -1,68 +0,0 @@
1
- ---
2
- description: "A workflow for creating, refining, and organizing textual content."
3
- ---
4
- Follow this workflow to produce content that is not just correct, but compelling, clear, and perfectly suited to its purpose.
5
-
6
- # Core Mandates
7
-
8
- - **Audience-First:** Always understand who you're writing for and what they need to know
9
- - **Purpose-Driven:** Every piece of content must serve a clear objective
10
- - **Quality Standards:** Deliver polished, professional content that meets the highest standards
11
- - **Iterative Refinement:** Content improves through multiple rounds of review and editing
12
-
13
- # Tool Usage Guideline
14
- - Use `read_from_file` to analyze existing content and style guides
15
- - Use `write_to_file` for creating new content drafts
16
- - Use `replace_in_file` for targeted edits and refinements
17
-
18
- # Step 1: Understand Intent and Audience
19
-
20
- 1. **Define the Goal:** What is this text supposed to achieve? (e.g., persuade, inform, entertain, sell). If the user is vague, ask for clarification.
21
- 2. **Identify the Audience:** Who are you writing for? (e.g., experts, beginners, customers). This dictates your tone, vocabulary, and level of detail.
22
- 3. **Determine the Tone:** Choose a voice that serves the goal and resonates with the audience (e.g., formal, witty, technical, urgent).
23
- 4. **Analyze Existing Content:** Review any provided examples, style guides, or reference materials to understand established patterns.
24
-
25
- # Step 2: Plan and Outline
26
-
27
- 1. **Create Logical Structure:** Develop an outline that flows naturally from introduction to conclusion
28
- 2. **Key Sections:** Identify main talking points and supporting arguments
29
- 3. **Call-to-Action:** Define what you want the reader to do or think after reading
30
- 4. **Get Approval:** Present the outline to the user for confirmation before proceeding
31
-
32
- # Step 3: Draft with Purpose
33
-
34
- 1. **Hook the Reader:** Start with a strong opening that grabs attention
35
- 2. **Use Active Voice:** Make your writing direct and energetic
36
- 3. **Show, Don't Just Tell:** Use examples, stories, and data to illustrate your points
37
- 4. **Maintain Consistency:** Stick to the established tone and style throughout
38
-
39
- # Step 4: Refine and Polish
40
-
41
- 1. **Read Aloud:** Catch awkward phrasing and grammatical errors
42
- 2. **Cut Mercilessly:** Remove anything that doesn't serve the goal
43
- 3. **Enhance Readability:** Use short paragraphs, headings, bullet points, and bold text
44
- 4. **Verify Accuracy:** Ensure all facts, figures, and claims are correct
45
-
46
- # Step 5: Task-Specific Execution
47
-
48
- ## Summarization
49
- - Distill the essence while preserving key information
50
- - Be objective and ruthless in cutting fluff
51
- - Maintain the original meaning and context
52
-
53
- ## Proofreading
54
- - Correct grammar, spelling, and punctuation
55
- - Improve sentence flow and clarity
56
- - Preserve the original meaning and voice
57
-
58
- ## Refining/Editing
59
- - Sharpen the author's message
60
- - Strengthen arguments and improve clarity
61
- - Ensure consistent tone while respecting the original voice
62
-
63
- # Step 6: Finalize and Deliver
64
-
65
- - Present the final content to the user
66
- - Be prepared to make additional refinements based on feedback
67
- - Ensure the content meets all stated objectives
68
- - Confirm the content is ready for its intended use
@@ -1,118 +0,0 @@
1
- ---
2
- description: "A workflow for managing version control with git."
3
- ---
4
- Follow this workflow for safe, consistent, and effective version control operations.
5
-
6
- # Core Mandates
7
-
8
- - **Safety First:** Never force operations that could lose data
9
- - **Atomic Commits:** One logical change per commit
10
- - **Descriptive Messages:** Explain the "why" in imperative mood
11
- - **Clean History:** Maintain a readable and useful commit history
12
-
13
- # Tool Usage Guideline
14
- - Use `run_shell_command` for all git operations
15
- - Use `read_from_file` to examine git configuration files
16
- - Use `search_files` to find specific commit messages or patterns
17
-
18
- # Step 1: Pre-Operation Safety Check
19
-
20
- 1. **Check Status:** Always run `git status` before operations
21
- 2. **Verify Working Directory:** Ensure the working directory is clean before destructive operations
22
- 3. **Review Changes:** Use `git diff` and `git diff --staged` to understand what will be committed
23
- 4. **Backup Important Changes:** Consider stashing or creating a backup branch for risky operations
24
-
25
- # Step 2: Standard Development Workflow
26
-
27
- 1. **Create Feature Branch:** `git checkout -b <branch-name>`
28
- 2. **Make Changes:** Implement features or fixes
29
- 3. **Stage Changes:** Use `git add -p` for precision staging
30
- 4. **Commit with Description:** Write clear, descriptive commit messages
31
- 5. **Review and Amend:** Use `git log -1` to review, amend if needed
32
- 6. **Push to Remote:** `git push origin <branch-name>`
33
-
34
- # Step 3: Commit Message Standards
35
-
36
- ```
37
- feat: Add user authentication endpoint
38
-
39
- Implement the /login endpoint using JWT for token-based auth.
40
- This resolves issue #123 by providing a mechanism for users to
41
- log in and receive an access token.
42
- ```
43
-
44
- - **Type Prefix:** feat, fix, docs, style, refactor, test, chore
45
- - **Imperative Mood:** "Add feature" not "Added feature"
46
- - **50/72 Rule:** 50 character subject, 72 character body lines
47
-
48
- # Step 4: Branch Management
49
-
50
- ## Safe Branch Operations
51
- - **Create:** `git checkout -b <name>` or `git switch -c <name>`
52
- - **Switch:** `git switch <name>`
53
- - **Update:** `git rebase main` (use with care)
54
- - **Merge:** `git merge --no-ff <branch>` for explicit merge commits
55
-
56
- ## Remote Branch Operations
57
- - **Fetch Updates:** `git fetch origin`
58
- - **Push:** `git push origin <branch>`
59
- - **Delete Remote:** `git push origin --delete <branch>`
60
-
61
- # Step 5: Advanced Operations (Use with Caution)
62
-
63
- ## Rebasing
64
- - **Update Branch:** `git rebase main`
65
- - **Interactive:** `git rebase -i <commit>` for history editing
66
- - **Safety:** Never rebase shared/public branches
67
-
68
- ## Stashing
69
- - **Save Changes:** `git stash push -m "message"`
70
- - **List Stashes:** `git stash list`
71
- - **Apply:** `git stash pop` or `git stash apply`
72
-
73
- ## Cherry-picking
74
- - **Apply Specific Commit:** `git cherry-pick <commit-hash>`
75
- - **Use Case:** Only when absolutely necessary to avoid duplicate commits
76
-
77
- # Step 6: Verification and Cleanup
78
-
79
- 1. **Verify Operations:** Check `git status` and `git log` after operations
80
- 2. **Run Tests:** Ensure all tests pass after changes
81
- 3. **Clean Up:** Remove temporary branches and stashes when no longer needed
82
- 4. **Document:** Update documentation if workflow changes affect team processes
83
-
84
- # Risk Assessment Guidelines
85
-
86
- ## Low Risk (Proceed Directly)
87
- - `git status`, `git log`, `git diff`
88
- - Creating new branches
89
- - Stashing changes
90
-
91
- ## Moderate Risk (Explain and Confirm)
92
- - `git rebase` operations
93
- - `git push --force-with-lease`
94
- - Deleting branches
95
-
96
- ## High Risk (Refuse and Explain)
97
- - `git push --force` (use --force-with-lease instead)
98
- - Operations that could lose commit history
99
- - Modifying shared/public branches
100
-
101
- # Common Commands Reference
102
-
103
- ## Status & History
104
- - `git status`: Check working directory status
105
- - `git diff`: See uncommitted changes to tracked files
106
- - `git diff --staged`: See staged changes
107
- - `git log --oneline --graph -10`: View recent commit history
108
- - `git blame <file>`: See who changed what in a file
109
-
110
- ## Branch Operations
111
- - `git branch -a`: List all branches (local and remote)
112
- - `git branch -d <branch>`: Delete a local branch
113
- - `git remote prune origin`: Clean up remote tracking branches
114
-
115
- ## Configuration
116
- - `git config --list`: View current configuration
117
- - `git config user.name "Your Name"`: Set user name
118
- - `git config user.email "your.email@example.com"`: Set user email