-
Notifications
You must be signed in to change notification settings - Fork 632
Expand file tree
/
Copy pathsystem_prompt.py
More file actions
501 lines (418 loc) · 18.2 KB
/
Copy pathsystem_prompt.py
File metadata and controls
501 lines (418 loc) · 18.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
from __future__ import annotations
from collections.abc import Sequence
from concurrent.futures import ThreadPoolExecutor
from datetime import date
import html
import os
from pathlib import Path
from string import Template
import subprocess
from typing import TYPE_CHECKING
from vibe.core.config import VibeConfigSchema
from vibe.core.config.harness_files import (
HarnessFilesManager,
get_harness_files_manager,
)
from vibe.core.paths import VIBE_HOME
from vibe.core.prompts import UtilityPrompt
from vibe.core.utils import (
WindowsShellKind,
get_platform_display_name,
is_windows,
resolve_windows_shell,
)
from vibe.utils.paths import is_dangerous_directory
if TYPE_CHECKING:
from vibe.core.agents import AgentManager
from vibe.core.config import ProjectContextConfig
from vibe.core.skills.manager import SkillManager
from vibe.core.tools.manager import ToolManager
_git_status_cache: dict[Path, str] = {}
_MAX_FILE_OVERVIEW_ENTRIES = 200
def _normalize_overview_entries(entries: Sequence[str]) -> list[str]:
clean_entries = []
for entry in entries:
clean = entry.strip()
if not clean:
continue
clean_entries.append(clean)
return sorted(dict.fromkeys(clean_entries))
class ProjectContextProvider:
def __init__(
self, config: ProjectContextConfig, root_path: str | Path = "."
) -> None:
self.root_path = Path(root_path).resolve()
self.config = config
def get_file_overview(self) -> str:
entries = self._list_project_files()
if not entries:
return "No project file overview available."
limit = _MAX_FILE_OVERVIEW_ENTRIES
visible = entries[:limit]
lines = ["Project file overview (snapshot at conversation start):"]
lines.extend(f"- {entry}" for entry in visible)
if len(entries) > limit:
lines.append(f"... {len(entries) - limit} more files omitted")
return "\n".join(lines)
def _list_project_files(self) -> list[str]:
if from_git := self._list_git_files():
return from_git
return self._list_directory_files()
def _list_git_files(self) -> list[str]:
try:
result = self._run_git(["ls-files"], min(self.config.timeout_seconds, 10.0))
except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
return []
return _normalize_overview_entries(result.stdout.splitlines())
def _list_directory_files(self) -> list[str]:
max_entries = _MAX_FILE_OVERVIEW_ENTRIES + 1
entries: list[str] = []
ignored_dirs = {
".git",
".hg",
".svn",
".mypy_cache",
".pytest_cache",
".ruff_cache",
".tox",
".venv",
"__pycache__",
"node_modules",
}
try:
for current_root, dirs, files in os.walk(self.root_path):
dirs[:] = [
d for d in dirs if d not in ignored_dirs and not d.startswith(".")
]
dirs.sort()
for file_name in sorted(files):
if file_name.startswith("."):
continue
path = Path(current_root, file_name)
entries.append(path.relative_to(self.root_path).as_posix())
if len(entries) >= max_entries:
return entries
except OSError:
return []
return entries
def get_git_status(self) -> str:
if self.root_path in _git_status_cache:
return _git_status_cache[self.root_path]
result = self._fetch_git_status()
_git_status_cache[self.root_path] = result
return result
def _run_git(
self, args: list[str], timeout: float
) -> subprocess.CompletedProcess[str]:
return subprocess.run(
["git", "--no-optional-locks", *args],
capture_output=True,
check=True,
cwd=self.root_path,
stdin=subprocess.DEVNULL if is_windows() else None,
text=True,
encoding="utf-8",
errors="replace",
timeout=timeout,
)
@staticmethod
def _format_git_status(status_output: str) -> str:
if not status_output:
return "(clean)"
status_lines = status_output.splitlines()
MAX_GIT_STATUS_SIZE = 50
if len(status_lines) > MAX_GIT_STATUS_SIZE:
return f"({len(status_lines)} changes - use 'git status' for details)"
return f"({len(status_lines)} changes)"
@staticmethod
def _parse_git_log(log_output: str) -> list[str]:
recent_commits: list[str] = []
for line in log_output.split("\n"):
if not (line := line.strip()):
continue
if " " in line:
commit_hash, commit_msg = line.split(" ", 1)
if (
"(" in commit_msg
and ")" in commit_msg
and (paren_index := commit_msg.rfind("(")) > 0
):
commit_msg = commit_msg[:paren_index].strip()
recent_commits.append(f"{commit_hash} {commit_msg}")
else:
recent_commits.append(line)
return recent_commits
def _fetch_git_status(self) -> str:
try:
timeout = min(self.config.timeout_seconds, 10.0)
num_commits = self.config.default_commit_count
with ThreadPoolExecutor(max_workers=4) as pool:
branch_future = pool.submit(
self._run_git, ["branch", "--show-current"], timeout
)
remote_future = pool.submit(self._run_git, ["branch", "-r"], timeout)
status_future = pool.submit(
self._run_git, ["status", "--porcelain"], timeout
)
log_future = pool.submit(
self._run_git,
["log", "--oneline", f"-{num_commits}", "--decorate"],
timeout,
)
current_branch = branch_future.result().stdout.strip()
main_branch = "main"
try:
branches_output = remote_future.result().stdout
if "origin/master" in branches_output:
main_branch = "master"
except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
pass
status = self._format_git_status(status_future.result().stdout.strip())
recent_commits = self._parse_git_log(log_future.result().stdout.strip())
git_info_parts = [
f"Current branch: {current_branch}",
f"Main branch (you will usually use this for PRs): {main_branch}",
f"Status: {status}",
]
if recent_commits:
git_info_parts.append("Recent commits:")
git_info_parts.extend(recent_commits)
return "\n".join(git_info_parts)
except subprocess.TimeoutExpired:
return "Git operations timed out (large repository)"
except subprocess.CalledProcessError:
return "Not a git repository or git not available"
except Exception as e:
return f"Error getting git status: {e}"
def get_full_context(self) -> str:
git_status = self.get_git_status()
template = UtilityPrompt.PROJECT_CONTEXT.read()
file_overview = self.get_file_overview()
return Template(template).safe_substitute(
abs_path=str(self.root_path),
git_status=git_status,
file_overview=file_overview,
)
def _get_os_system_prompt(
*, use_git_bash_treatment: bool = False, use_powershell_treatment: bool = False
) -> str:
platform_name = get_platform_display_name()
if not is_windows():
shell = os.environ.get("SHELL", "sh")
return f"The operating system is {platform_name} with shell `{shell}`"
if use_git_bash_treatment:
return (
f"The operating system is {platform_name} with shell `Git Bash`"
"\n" + _get_windows_bash_system_prompt()
)
if use_powershell_treatment:
return (
f"The operating system is {platform_name} with shell `PowerShell`"
"\n" + _get_windows_powershell_system_prompt()
)
shell = resolve_windows_shell()
if shell.kind is WindowsShellKind.BASH and shell.executable is not None:
shell_display = f"bash ({shell.executable})"
else:
shell_display = shell.executable or "cmd.exe"
prompt = f"The operating system is {platform_name} with shell `{shell_display}`"
prompt += "\n" + _get_windows_system_prompt(shell.kind)
return prompt
def _format_current_date() -> str:
today = date.today()
return f"{today.isoformat()} ({today.strftime('%A')})"
def _get_windows_bash_system_prompt() -> str:
return (
"### COMMAND COMPATIBILITY RULES (MUST FOLLOW):\n"
"- Commands run through bash (Git Bash), so Unix commands like `ls`, "
"`grep`, `cat`, `find` work - this is NOT cmd.exe or PowerShell\n"
"- Discard output with `2>/dev/null` - NEVER `2>nul` or `2>$null`\n"
"- `&&` and `||` are valid for command chaining\n"
"- Prefer forward slashes in paths; bash resolves Windows drives as "
"`/c/Users/...`\n"
"- Check command availability with: `command -v <command>`\n"
"### ALWAYS verify commands work on the detected platform before suggesting them"
)
def _get_windows_cmd_system_prompt() -> str:
return (
"### COMMAND COMPATIBILITY RULES (MUST FOLLOW):\n"
"- The shell is cmd.exe, NOT bash or PowerShell\n"
"- DO NOT use Unix commands like `ls`, `grep`, `cat` - they won't work; "
"use `dir`, `findstr`, `type`\n"
"- Use backslashes (\\\\) for paths\n"
"- Discard output with `2>nul` - NEVER `2>/dev/null` or `2>$null`\n"
"- `&&` and `||` are valid for command chaining in cmd.exe\n"
"- Check command availability with: `where command`\n"
"- Script shebang: Not applicable on Windows\n"
"### ALWAYS verify commands work on the detected platform before suggesting them"
)
def _get_windows_powershell_system_prompt() -> str:
return (
"### COMMAND COMPATIBILITY RULES (MUST FOLLOW):\n"
"- The shell is PowerShell, NOT bash or cmd.exe\n"
"- Use PowerShell syntax for variables, quoting, pipes, redirects, and conditionals\n"
"- Use backslashes (\\\\) for Windows paths unless a command explicitly accepts another form\n"
"- Discard output with `*> $null` or `2>$null` as appropriate - NEVER `2>/dev/null` or `2>nul`\n"
"- Check command availability with: `Get-Command <command>`\n"
"- Prefer `Get-ChildItem`, `Get-Content`, and `Select-String` over Unix-only shell commands when a dedicated Vibe tool is not available\n"
"### ALWAYS verify commands work on the detected platform before suggesting them"
)
def _get_windows_system_prompt(shell_kind: WindowsShellKind) -> str:
if shell_kind is WindowsShellKind.BASH:
return _get_windows_bash_system_prompt()
return _get_windows_cmd_system_prompt()
def _add_commit_signature() -> str:
return (
"When you want to commit changes, you will always use the 'git commit' bash command.\n"
"It will always be suffixed with a line telling it was generated by Mistral Vibe with the appropriate co-authoring information.\n"
"The format you will always uses is the following heredoc.\n\n"
"```bash\n"
"git commit -m <Commit message here>\n\n"
"Generated by Mistral Vibe.\n"
"Co-Authored-By: Mistral Vibe <vibe@mistral.ai>\n"
"```"
)
def _get_available_skills_section(skill_manager: SkillManager) -> str:
skills = skill_manager.available_skills
if not skills:
return ""
lines = [
"# Available Skills",
"",
"You have access to the following skills. When a task matches a skill's description,",
"use the `skill` tool if available to load the full skill instructions, if it is not available, read the files manually if they exist.",
"",
"When a user message is exactly `/skill-name` (optionally followed by extra",
"instructions), the user has explicitly invoked that skill. Its instructions are",
"loaded for you automatically: you will see a `skill` tool call and result",
"immediately after that message. Treat the loaded content as the active",
"instructions and act on it — you do not need to call the `skill` tool yourself.",
"",
"<available_skills>",
]
for name, info in sorted(skills.items()):
lines.append(" <skill>")
lines.append(f" <name>{html.escape(str(name))}</name>")
lines.append(
f" <description>{html.escape(str(info.description))}</description>"
)
if info.skill_path is not None:
lines.append(f" <path>{html.escape(str(info.skill_path))}</path>")
lines.append(" </skill>")
lines.append("</available_skills>")
return "\n".join(lines)
def _get_available_subagents_section(agent_manager: AgentManager) -> str:
agents = agent_manager.get_subagents()
if not agents:
return ""
lines = ["# Available Subagents", ""]
lines.append("The following subagents can be spawned via the Task tool:")
for agent in agents:
lines.append(f"- **{agent.name}**: {agent.description}")
return "\n".join(lines)
def _get_scratchpad_section(scratchpad_dir: Path | None) -> str | None:
if not scratchpad_dir:
return None
return (
"# Scratchpad Directory\n\n"
f"You have a scratchpad directory at: `{scratchpad_dir}`\n\n"
"Use this for temporary files: intermediate results, draft scripts, "
"working files, outputs that don't belong in the project.\n"
"Files here are automatically allowed — no permission prompts.\n"
"Session-scoped. Shared with subagents."
)
def _interpolate_prompt(prompt: str) -> str:
return Template(prompt).safe_substitute(current_date=_format_current_date())
def _get_headless_section() -> str:
return (
"# Headless Mode\n\n"
"You are running in headless mode — no human is available to respond.\n"
"Do not ask questions, request confirmation, or wait for user input.\n"
"If the task is ambiguous, make the best judgment call and proceed.\n"
"Complete the entire task in a single pass. Produce a final, complete result.\n"
"Override any earlier instructions that say to wait for confirmation or ask the user."
)
def _get_tool_aware_os_system_prompt(tool_manager: ToolManager | None) -> str:
if tool_manager is None:
return _get_os_system_prompt()
available_tools = tool_manager.available_tools
use_git_bash_treatment = "git_bash" in available_tools
return _get_os_system_prompt(
use_git_bash_treatment=use_git_bash_treatment,
use_powershell_treatment=(
"powershell" in available_tools and not use_git_bash_treatment
),
)
def get_universal_system_prompt(
config: VibeConfigSchema,
skill_manager: SkillManager,
agent_manager: AgentManager,
*,
scratchpad_dir: Path | None = None,
headless: bool = False,
cwd: Path | None = None,
harness_files: HarnessFilesManager | None = None,
tool_manager: ToolManager | None = None,
) -> str:
cwd = (cwd or Path.cwd()).resolve()
harness_files = harness_files or get_harness_files_manager()
sections = [_interpolate_prompt(config.system_prompt)]
if headless:
sections.append(_get_headless_section())
if config.include_commit_signature:
sections.append(_add_commit_signature())
if config.include_model_info:
sections.append(f"Your model name is: `{config.active_model}`")
if config.include_prompt_detail:
sections.append(_get_tool_aware_os_system_prompt(tool_manager))
skills_section = _get_available_skills_section(skill_manager)
if skills_section:
sections.append(skills_section)
subagents_section = _get_available_subagents_section(agent_manager)
if subagents_section:
sections.append(subagents_section)
sections.extend(filter(None, [_get_scratchpad_section(scratchpad_dir)]))
if config.include_project_context:
is_dangerous, reason = is_dangerous_directory(cwd)
if is_dangerous:
template = UtilityPrompt.DANGEROUS_DIRECTORY.read()
context = Template(template).safe_substitute(
reason=reason.lower(), abs_path=cwd.resolve()
)
else:
context = ProjectContextProvider(
config=config.project_context, root_path=cwd
).get_full_context()
sections.append(context)
cwd_resolved = cwd.resolve()
extra_roots = [
root
for root in harness_files.project_roots
if root.resolve() != cwd_resolved
]
if extra_roots:
dirs_lines = "\n".join(f" - {d}" for d in extra_roots)
sections.append(
"Additional working directories (treated with the same "
"file-access permissions as the primary working directory):\n"
+ dirs_lines
)
user_doc = harness_files.load_user_doc()
project_docs = harness_files.load_project_docs()
doc_sections: list[str] = []
if user_doc.strip():
doc_sections.append(
f"## User instructions\n\nContents of {VIBE_HOME.path}/AGENTS.md (user-level instructions):\n\n{user_doc.strip()}"
)
if project_docs:
doc_sections.append("## Project instructions (checked into the codebase)")
for doc_dir, doc_content in project_docs:
doc_sections.append(
f"Contents of {doc_dir}/AGENTS.md:\n\n{doc_content.strip()}"
)
if doc_sections:
template = UtilityPrompt.AGENTS_DOC.read()
sections.append(
Template(template).safe_substitute(sections="\n\n".join(doc_sections))
)
return "\n\n".join(sections)