Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(agent-core): run commands through PowerShell on Windows (#2490)
Call Whitee8b9224b8a4b
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.ymlindex ac68ca140..483358cc3 100644--- a/.github/workflows/lint.yml+++ b/.github/workflows/lint.yml@@ -822,6 +822,11 @@ jobs:- name: Verify the job hostrun: python -m pytest -q -ra tests/agent_core/tools/test_jobs_windows.py+ # The command tool on Windows, under PowerShell 7 and under Windows+ # PowerShell 5.1, which every Windows has.+ - name: Verify the powershell tool+ run: python -m pytest -q -ra tests/agent_core/tools/test_powershell.py+# Its job object is the one the watch worker uses; no other job runs# this file on Windows.- name: Verify the watch worker's job objectdiff --git a/core/agent_core/harness/context.py b/core/agent_core/harness/context.pyindex 54725667e..8a53a8639 100644--- a/core/agent_core/harness/context.py+++ b/core/agent_core/harness/context.py@@ -76,7 +76,9 @@ CLEAR_SOFT_RATIO = 0.8CLEAR_MIN_TOKENS = 20_000CLEAR_KEEP_RESULTS = 5CLEAR_PROTECTED_TURNS = 2-CLEARABLE_TOOLS = frozenset({"read", "bash"})+#: The command tool: ``bash``, and ``powershell`` on Windows (C-7 tools.md).+COMMAND_TOOLS = frozenset({"bash", "powershell"})+CLEARABLE_TOOLS = frozenset({"read"}) | COMMAND_TOOLS#: How long a route's provider prompt cache stays warm after its last use, in seconds, by cache family (section 3):#: the documented lifetime of the cache mode Vibey requests for the conversation, where clearable results live.#: ``anthropic``: the message breakpoints' ``cache_control`` is ephemeral with no ``ttl``, 5 minutes, refreshed on use.diff --git a/core/agent_core/tools/bash.py b/core/agent_core/tools/bash.pyindex 1dd636667..85e98b93e 100644--- a/core/agent_core/tools/bash.py+++ b/core/agent_core/tools/bash.py@@ -48,6 +48,7 @@ from core.agent_core.tools.jobs import ()from core.agent_core.tools.paths import os_reasonfrom core.agent_core.tools.output import FINISH_BYTES, JobOutput+from core.agent_core.tools.shell import Shell, default_shelllogger = logging.getLogger(__name__)@@ -70,14 +71,27 @@ BASH_SCHEMA: Mapping[str, Any] = {}-def bash_description(foreground_window_s: float = DEFAULT_FOREGROUND_WINDOW_S) -> str:- return (- "Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to "+def bash_description(foreground_window_s: float = DEFAULT_FOREGROUND_WINDOW_S, shell: Optional[Shell] = None) -> str:+ """Pi's description; for PowerShell, its first sentence names PowerShell (C-7 tools.md section 5)."""+ shell = shell or default_shell()+ opening = (+ "Execute a PowerShell command in the current working directory. Returns its output and errors."+ if shell.powershell+ else "Execute a bash command in the current working directory. Returns stdout and stderr."+ )+ description = (+ f"{opening} Output is truncated to "f"last {MAX_LINES} lines or {MAX_BYTES // 1024}KB (whichever is hit first). If truncated, the output log is saved ""to a file; very large logs keep their beginning and end. Optionally provide a timeout in seconds. "f"Commands still running after {format_number(foreground_window_s)} seconds, or started with watch=true, ""continue in the background as an Avibe Watch; you get a follow-up message when they finish.")+ if shell.windows_powershell:+ description += (+ " This is Windows PowerShell 5.1: it has no && or ||, so separate commands with ; and test $? or "+ "$LASTEXITCODE."+ )+ return descriptiondef _append_status(text: str, status: str) -> str:@@ -210,10 +224,22 @@ class BashTool:concurrent = True- def __init__(self, jobs: JobHost, *, foreground_window_s: float = DEFAULT_FOREGROUND_WINDOW_S) -> None:+ def __init__(+ self,+ jobs: JobHost,+ *,+ foreground_window_s: float = DEFAULT_FOREGROUND_WINDOW_S,+ shell: Optional[Shell] = None,+ ) -> None:+ """``shell`` is what ``jobs`` runs commands in (``LocalJobHost.shell``); it names the tool."""+ shell = shell or default_shell()self._jobs = jobsself._window_s = foreground_window_s- self._spec = ToolSpec(name="bash", description=bash_description(foreground_window_s), input_schema=BASH_SCHEMA)+ self._spec = ToolSpec(+ name="powershell" if shell.powershell else "bash",+ description=bash_description(foreground_window_s, shell),+ input_schema=BASH_SCHEMA,+ )@propertydef spec(self) -> ToolSpec:@@ -229,9 +255,11 @@ class BashTool:except ToolInputError as exc:return error_result(str(exc))if not os.path.isdir(ctx.cwd):- return error_result(f"Working directory does not exist: {ctx.cwd}\nCannot execute bash commands.")+ return error_result(f"Working directory does not exist: {ctx.cwd}\nCannot execute {self._spec.name} commands.")if not os.access(ctx.cwd, os.X_OK):- return error_result(f"Working directory is not accessible: {ctx.cwd}\nCannot execute bash commands.")+ return error_result(+ f"Working directory is not accessible: {ctx.cwd}\nCannot execute {self._spec.name} commands."+ )if ctx.cancel.cancelled:return error_result("Command aborted")if ctx.call is None:diff --git a/core/agent_core/tools/coding.py b/core/agent_core/tools/coding.pyindex fd8dc28c9..49ada42ee 100644--- a/core/agent_core/tools/coding.py+++ b/core/agent_core/tools/coding.py@@ -1,4 +1,5 @@-"""The coding tool set: Pi's ``read``, ``write``, ``edit``, and ``bash`` with the Avibe additions (C-7)."""+"""The coding tool set: Pi's ``read``, ``write``, ``edit``, and ``bash`` (``powershell`` on Windows) with the Avibe+additions (C-7)."""from __future__ import annotations@@ -8,6 +9,7 @@ from core.agent_core.tools.base import JobHost, Toolfrom core.agent_core.tools.bash import DEFAULT_FOREGROUND_WINDOW_S, BashToolfrom core.agent_core.tools.edit import EditToolfrom core.agent_core.tools.read import ImageSink, ReadTool+from core.agent_core.tools.shell import Shellfrom core.agent_core.tools.write import WriteTool@@ -16,15 +18,17 @@ def create_coding_tools(*,image_sink: Optional[ImageSink] = None,foreground_window_s: float = DEFAULT_FOREGROUND_WINDOW_S,+ shell: Optional[Shell] = None,) -> tuple[Tool, ...]:"""One tool set for every model; each tool's ``spec`` is what the model sees.``jobs`` is the loop's ``Agent.jobs`` wrapper, so an abort can kill a- foreground command; ``image_sink`` stores images ``read`` attaches.+ foreground command; ``image_sink`` stores images ``read`` attaches;+ ``shell`` is what the host runs commands in, which names the command tool."""return (ReadTool(image_sink=image_sink),WriteTool(),EditTool(),- BashTool(jobs, foreground_window_s=foreground_window_s),+ BashTool(jobs, foreground_window_s=foreground_window_s, shell=shell),)diff --git a/core/agent_core/tools/edit.py b/core/agent_core/tools/edit.pyindex b98c1ef6e..380c58ce5 100644--- a/core/agent_core/tools/edit.py+++ b/core/agent_core/tools/edit.py@@ -16,6 +16,7 @@ import jsonimport osfrom typing import Any, Mapping+from core.agent_core.tools.shell import SHELL_ADVICEfrom core.agent_core.tools.args import ToolInputError, error_result, str_arg, text_resultfrom core.agent_core.tools.base import ToolContext, ToolResult, ToolSpecfrom core.agent_core.tools.edit_diff import (@@ -253,17 +254,17 @@ class EditTool:# The whole file and several copies would sit in the process every Session shares.return error_result(f"File {path} is {format_size(exc.size)}, over the {format_size(MAX_EDIT_BYTES)} edit limit. "- "Use bash (for example sed or a short script) to change files this large."+ f"Use {SHELL_ADVICE} to change files this large.")except _TooManyLines as exc:return error_result(f"File {path} has {exc.lines} lines, over the {MAX_EDIT_LINES} line edit limit. "- "Use bash (for example sed or a short script) to change files this large."+ f"Use {SHELL_ADVICE} to change files this large.")except ResultTooLarge:return error_result(f"File {path} would be over the {format_size(MAX_EDIT_BYTES)} edit limit after this edit. "- "Use bash (for example sed or a short script) to change files this large."+ f"Use {SHELL_ADVICE} to change files this large.")except NotReplaceable:return error_result(@@ -272,7 +273,7 @@ class EditTool:except EditError as exc:return error_result(str(exc))except FileChanged:- # Another writer (bash, an editor) changed it after it was read: the edit would overwrite that.+ # Another writer (a command, an editor) changed it after it was read: the edit would overwrite that.return error_result(f"Could not edit file: {path}. It changed while the edit was being applied; read it again.")diff --git a/core/agent_core/tools/edit_diff.py b/core/agent_core/tools/edit_diff.pyindex 997446024..40c4f0426 100644--- a/core/agent_core/tools/edit_diff.py+++ b/core/agent_core/tools/edit_diff.py@@ -24,6 +24,7 @@ import unicodedatafrom dataclasses import dataclassfrom typing import Callable, Optional+from core.agent_core.tools.shell import SHELL_ADVICEfrom core.agent_core.tools.text import shownBOM = "\ufeff"@@ -189,18 +190,18 @@ def _too_many(path: str, total: int, replacements: int) -> EditError:if total == 1:return EditError(f"Found {replacements} occurrences of the text in {path}, over the {MAX_REPLACEMENTS} replaceAll limit. "- "Use bash (for example sed or a short script) to replace this many."+ f"Use {SHELL_ADVICE} to replace this many.")return EditError(f"The edits make {replacements} replacements in {path}, over the {MAX_REPLACEMENTS} replacement limit. "- "Use bash (for example sed or a short script) to replace this many."+ f"Use {SHELL_ADVICE} to replace this many.")def _too_much_work(path: str, total: int, chars: int) -> EditError:return EditError(f"{total} edits over {path} ({chars} characters) are over the edit work limit. Split them into several "- "edit calls, or use bash (for example sed or a short script)."+ f"edit calls, or use {SHELL_ADVICE}.")diff --git a/core/agent_core/tools/job_wrapper.py b/core/agent_core/tools/job_wrapper.pyindex ce5345468..6090178f5 100644--- a/core/agent_core/tools/job_wrapper.py+++ b/core/agent_core/tools/job_wrapper.py@@ -1,9 +1,10 @@"""The process that runs one job's command (``LocalJobHost``'s ``pipe`` backend).-Run as ``python -I -S -B job_wrapper.py avibe-job <job_dir> <shell> <command>-<decision_timeout_s> <head_cap> <tail_cap> <deadline_epoch_s or ->`` in a new-session, so its pid is the job's process group. Standard library only: ``-S``-skips site-packages.+Run as ``python -I -S -B job_wrapper.py avibe-job <job_dir> <decision_timeout_s>+<head_cap> <tail_cap> <deadline_epoch_s or -> <argv...>`` in a new session, so+its pid is the job's process group, where ``argv`` runs the command (``shell.py``:+``<shell> -c <command>``, or PowerShell reading ``command.ps1``). Standard+library only: ``-S`` skips site-packages.On Windows the tree is held by a job object instead of a process group: thewrapper creates ``Local\\avibe-job-<job_id>`` with ``KILL_ON_JOB_CLOSE`` and@@ -16,8 +17,8 @@ makes its replacement fail.2. Wait for ``decision``, at most ``decision_timeout_s``; on timeout, decide``abandon`` itself through the same exclusive ``link(2)`` the host uses (onWindows a rename, which never replaces there).-3. Only on ``go``: run ``<shell> -c <command>`` with stdin closed and stdout and- stderr into one pipe.+3. Only on ``go``: run ``argv`` with stdin closed and stdout and stderr into one+ pipe.4. Keep the output bounded on disk: the first ``head_cap`` bytes are appendedto ``output.log`` as they arrive; after that, the last ``tail_cap`` bytes arekept in ``tail.log`` (a ``[output from byte <offset>]\\n`` header, readable by@@ -295,11 +296,11 @@ def _stay_while_the_job_runs() -> None:def main(argv: list[str]) -> int:- if len(argv) != 9 or argv[1] != "avibe-job":+ if len(argv) < 8 or argv[1] != "avibe-job":return 64- job_dir, shell, command = argv[2], argv[3], argv[4]- decision_timeout_s, head_cap, tail_cap = float(argv[5]), int(argv[6]), int(argv[7])- deadline = None if argv[8] == "-" else float(argv[8])+ job_dir, command = argv[2], argv[7:]+ decision_timeout_s, head_cap, tail_cap = float(argv[3]), int(argv[4]), int(argv[5])+ deadline = None if argv[6] == "-" else float(argv[6])proc: Optional[subprocess.Popen] = Nonedef stop_on_signal(signum: int, frame: object) -> None:@@ -320,9 +321,7 @@ def main(argv: list[str]) -> int:# The deadline passed during the launch: the command must not start at all._stop_group(job_dir, "timeout", None)log = _BoundedLog(job_dir, head_cap, tail_cap)- proc = subprocess.Popen(- [shell, "-c", command], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT- )+ proc = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)_run(job_dir, proc, log, deadline)if _WINDOWS:_stay_while_the_job_runs()diff --git a/core/agent_core/tools/jobs.py b/core/agent_core/tools/jobs.pyindex 77396de58..5f97e78ef 100644--- a/core/agent_core/tools/jobs.py+++ b/core/agent_core/tools/jobs.py@@ -63,6 +63,7 @@ import psutilfrom core.agent_core.tools import windows_files, windows_jobfrom core.agent_core.tools.base import CallInstance, JobStatusfrom core.agent_core.tools.paths import os_reason, run_to_end+from core.agent_core.tools.shell import Shell, default_shellfrom core.process_isolation import (DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS,KILL_SIGNAL,@@ -125,15 +126,6 @@ class JobHandOverUnavailable(RuntimeError):"""This host has no Watch to hand a job to."""-def default_shell() -> Optional[str]:- """Pi's choice: ``/bin/bash``, then ``bash`` on PATH, then ``sh``. None on Windows, which has no such shell."""- if _WINDOWS:- return None- if os.path.exists("/bin/bash"):- return "/bin/bash"- return shutil.which("bash") or "sh"--def _job_object_name(job_id: str) -> str:"""The Windows job object of a job's tree; the wrapper creates it under the same name."""return f"avibe-job-{job_id}"@@ -215,7 +207,7 @@ class LocalJobHost:jobs_dir: str,*,on_hand_over: Optional[HandOver] = None,- shell: Optional[str] = None,+ shell: Optional[Shell] = None,) -> None:# Canonical, so every host names a job's directory (and its wrapper's argv) the same way, whatever# alias it was given (``~/.vibe_remote`` -> ``~/.avibe``, ``/tmp`` -> ``/private/tmp``).@@ -226,6 +218,11 @@ class LocalJobHost:# as a zombie (which would keep its process group alive), and an unreaped pid cannot be recycled.self._children: dict[str, subprocess.Popen] = {}+ @property+ def shell(self) -> Shell:+ """The shell every command of this host runs in."""+ return self._shell+# --- paths and metadata ---------------------------------------------def job_dir(self, job_id: str) -> str:@@ -328,8 +325,6 @@ class LocalJobHost:Raises ``JobStartError`` when the command did not start."""- if self._shell is None:- raise JobStartError("No shell is available to run the command.")if not sys.executable:raise JobStartError("No Python interpreter is available to run the command.")# The host's own steps are small and synchronous, so the only await is the wait for the pid: a cancel@@ -391,6 +386,10 @@ class LocalJobHost:marker = new_process_identity_marker()child_env = dict(env)child_env[PROCESS_IDENTITY_ENV] = marker+ if self._shell.powershell:+ # Python writes a pipe in the ANSI code page otherwise; the bootstrap makes everything else UTF-8. Only+ # its standard streams: UTF-8 mode would also change the encoding of every file it opens.+ child_env.setdefault("PYTHONIOENCODING", "utf-8")argv = [sys.executable,"-I",@@ -399,12 +398,11 @@ class LocalJobHost:_WRAPPER,"avibe-job",job_dir,- self._shell,- command,repr(DECISION_TIMEOUT_S),str(OUTPUT_HEAD_BYTES),str(OUTPUT_TAIL_BYTES),repr(deadline.timestamp()) if deadline is not None else "-",+ *self._shell.prepare(command, job_dir),]open(self.output_path(job_id), "ab").close()diagnostics = os.open(diff --git a/core/agent_core/tools/read.py b/core/agent_core/tools/read.pyindex b73a7814c..bba5c21f7 100644--- a/core/agent_core/tools/read.py+++ b/core/agent_core/tools/read.py@@ -15,7 +15,6 @@ import asyncioimport codecsimport inspectimport os-import shleximport structfrom dataclasses import dataclassfrom typing import Any, Awaitable, BinaryIO, Callable, Mapping, Optional, Union@@ -37,6 +36,7 @@ from core.agent_core.tools.paths import (resolve_read_path,target_kind,)+from core.agent_core.tools.shell import read_line_advicefrom core.agent_core.tools.text import decode_file, shownfrom core.agent_core.tools.truncate import format_size, truncate_head, utf8_len@@ -226,7 +226,7 @@ def _read_text(if truncation.first_line_exceeds_limit:text = (f"[Line {start_display} is {format_size(first_line_bytes)}, exceeds {format_size(MAX_BYTES)} limit. "- f"Use bash: sed -n '{start_display}p' {shlex.quote(absolute)} | head -c {MAX_BYTES}]"+ f"{read_line_advice(absolute, start_display, MAX_BYTES)}]")details["truncation"] = truncation.to_details()elif truncation.truncated:diff --git a/core/agent_core/tools/shell.py b/core/agent_core/tools/shell.pynew file mode 100644index 000000000..df4902729--- /dev/null+++ b/core/agent_core/tools/shell.py@@ -0,0 +1,171 @@+"""The shell a command job runs in (C-7 tools.md section 5): bash on POSIX, PowerShell on Windows.++The command tool is named after the language its commands are written in, ``bash`` or+``powershell``, so the model writes what the shell runs.+"""++from __future__ import annotations++import ntpath+import os+import shlex+import shutil+from dataclasses import dataclass++WINDOWS = os.name == "nt"+#: The command tool's name, which tells the model the language of its commands.+SHELL_TOOL = "powershell" if WINDOWS else "bash"+#: What other tools' results suggest for work they will not do (C-7 tools.md section 5).+SHELL_ADVICE = "powershell (for example a short script)" if WINDOWS else "bash (for example sed or a short script)"+#: Where a PowerShell job's command waits for the bootstrap, in the job directory.+COMMAND_FILE = "command.ps1"++# Runs ``command.ps1`` (C-7 tools.md section 5). ConstrainedLanguage mode blocks the .NET calls it makes, so there it+# says so and runs nothing. It is passed with ``-Command``, where Windows PowerShell+# writes errors as text (with ``-EncodedCommand`` it writes them as CLIXML), so it holds no double quote,+# which the command line would have to escape. The command runs whole, as one script block, so PowerShell's own+# semantics hold. Only the statement that runs last (the last of the clean block, which PowerShell 7.3 and+# later run after the others, else of the end, process, or begin block) is wrapped, by its place in the text and on the lines it already has, so the lines PowerShell reports+# are the command's own: its status is taken right after it, and the value ``$LASTEXITCODE`` holds is noted+# where every path into it passes: after the statement before it in its block, else as its block begins (a+# ``clean`` block runs even after a ``return``), else after parameter binding. The note leaves ``$?`` as it found+# it, ending in a silently ignored error when it was false, since the last statement may test it. ``--%`` makes the rest of its line+# arguments, so nothing is added on such a line. A native program stores a new value even when the code is the+# same, so the exit code is one the last statement set, never a code an earlier one left there, and the+# command sees ``$LASTEXITCODE`` exactly as PowerShell sets it. It does not exist until something sets it, so+# the wrapping reads it through ``Get-Variable``, which strict mode allows. The edits go in from the end of the+# text, since blocks may be written in any order. The loop around the script block is where a ``break`` or+# ``continue`` outside any loop ends it.+_BOOTSTRAP = """\+if ($ExecutionContext.SessionState.LanguageMode -ne 'FullLanguage') {+ Write-Error -ErrorAction Continue -Message ('The powershell tool cannot run here: this PowerShell is in ' + \+$ExecutionContext.SessionState.LanguageMode + ' mode (an AppLocker or WDAC policy), which blocks the .NET calls the \+tool needs to read and run the command. Nothing was run.')+ exit 1+}+$ProgressPreference = 'SilentlyContinue'+if ($PSStyle) { $PSStyle.OutputRendering = 'PlainText' }+$__avibe_utf8 = New-Object System.Text.UTF8Encoding $false+[Console]::OutputEncoding = $__avibe_utf8+$OutputEncoding = $__avibe_utf8+$__avibe_errors = $null+$__avibe_script = [System.IO.File]::ReadAllText('{path}', $__avibe_utf8)+$__avibe_ast = [System.Management.Automation.Language.Parser]::ParseInput(\+$__avibe_script, [ref]$null, [ref]$__avibe_errors)+if ($__avibe_errors) {+ foreach ($__avibe_error in $__avibe_errors) {+ [Console]::Error.WriteLine(('At line:{0} char:{1}' -f $__avibe_error.Extent.StartLineNumber, \+$__avibe_error.Extent.StartColumnNumber) + [Environment]::NewLine + $__avibe_error.Message)+ }+ exit 1+}+$__avibe_status = $true+$__avibe_set = $false+$__avibe_code = $null+$__avibe_before = $null+$__avibe_run = @(foreach ($__avibe_block in $__avibe_ast.DynamicParamBlock, $__avibe_ast.BeginBlock, \+$__avibe_ast.ProcessBlock, $__avibe_ast.EndBlock, $__avibe_ast.CleanBlock) { if ($__avibe_block) { $__avibe_block.Statements } })+$__avibe_edits = @()+$__avibe_note = '$__avibe_q = $?; $__avibe_var = Get-Variable LASTEXITCODE -Scope Global -ErrorAction Ignore; \+if ($__avibe_var) { $__avibe_before = $__avibe_var.Value }; \+if (-not $__avibe_q) { Write-Error -Message avibe -ErrorAction Ignore }'+if ($__avibe_run.Count) {+ $__avibe_last = $__avibe_run[-1]+ $__avibe_after = '; '+ if ($__avibe_last.Extent.Text.Contains('--%')) { $__avibe_after = [Environment]::NewLine }+ $__avibe_edits += , @($__avibe_last.Extent.EndOffset, ($__avibe_after + '$__avibe_status = $?; \+$__avibe_var = Get-Variable LASTEXITCODE -Scope Global -ErrorAction Ignore; if ($__avibe_var) { \+$__avibe_code = $__avibe_var.Value; \+$__avibe_set = $__avibe_code -is [int] -and -not [object]::ReferenceEquals($__avibe_code, $__avibe_before) }'))+ $__avibe_home = $__avibe_last.Parent+ if ($__avibe_home.Statements.Count -gt 1) {+ $__avibe_prev = $__avibe_home.Statements[$__avibe_home.Statements.Count - 2]+ if ($__avibe_prev.Extent.Text.Contains('--%')) {+ $__avibe_edits += , @($__avibe_last.Extent.StartOffset, ($__avibe_note + '; '))+ } else {+ $__avibe_edits += , @($__avibe_prev.Extent.EndOffset, ('; ' + $__avibe_note))+ }+ } elseif (-not $__avibe_home.Unnamed) {+ $__avibe_edits += , @(($__avibe_home.Extent.StartOffset + $__avibe_home.Extent.Text.IndexOf('{') + 1), \+($__avibe_note + '; '))+ } elseif ($__avibe_ast.ParamBlock) {+ $__avibe_edits += , @($__avibe_ast.ParamBlock.Extent.EndOffset, (' ' + $__avibe_note + ';'))+ }+}+foreach ($__avibe_edit in $__avibe_edits | Sort-Object { $_[0] } -Descending) {+ $__avibe_script = $__avibe_script.Insert($__avibe_edit[0], $__avibe_edit[1])+}+try {+ foreach ($__avibe_once in 1) { . ([ScriptBlock]::Create($__avibe_script)) | Out-Default }+} catch {+ [Console]::Error.Write(($_ | Out-String))+ exit 1+}+if ($__avibe_status) { exit 0 }+if ($__avibe_set -and $__avibe_code) { exit $__avibe_code }+exit 1+"""+++@dataclass(frozen=True)+class Shell:+ """A program that runs a job's command: ``<path> -c <command>`` for a POSIX shell (and Python, in tests),+ or PowerShell through the bootstrap, which reads the command from ``command.ps1``."""++ path: str+ powershell: bool = False++ @property+ def windows_powershell(self) -> bool:+ """Windows PowerShell 5.1, which every Windows 10 and 11 has; else PowerShell 7 (``pwsh``)."""+ return self.powershell and ntpath.basename(self.path).lower() == "powershell.exe"++ def describe(self) -> str:+ """The environment block's ``shell`` field (tools.md section 8)."""+ if not self.powershell:+ return self.path+ return f"{'Windows PowerShell 5.1' if self.windows_powershell else 'PowerShell 7'} ({self.path})"++ def prepare(self, command: str, job_dir: str) -> list[str]:+ """The argv that runs ``command`` in ``job_dir``'s job; for PowerShell, ``command.ps1`` is written first.++ A Windows command line holds 32,767 characters; the file holds any command the job record does.+ """+ if not self.powershell:+ return [self.path, "-c", command]+ path = os.path.join(job_dir, COMMAND_FILE)+ with open(path, "w", encoding="utf-8", newline="") as handle:+ handle.write(command)+ bootstrap = _BOOTSTRAP.replace("{path}", path.replace("'", "''"))+ return [self.path, "-NoLogo", "-NoProfile", "-NonInteractive", "-Command", bootstrap]+++def default_shell() -> Shell:+ """Pi's choice on POSIX: ``/bin/bash``, then ``bash`` on PATH, then ``sh``. On Windows, PowerShell 7 when+ ``pwsh`` is on PATH, else Windows PowerShell 5.1."""+ if WINDOWS:+ pwsh = shutil.which("pwsh")+ if pwsh:+ return Shell(pwsh, powershell=True)+ system_root = os.environ.get("SystemRoot") or r"C:\Windows"+ return Shell(+ os.path.join(system_root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), powershell=True+ )+ if os.path.exists("/bin/bash"):+ return Shell("/bin/bash")+ return Shell(shutil.which("bash") or "sh")+++def read_line_advice(path: str, line: int, max_bytes: int) -> str:+ """How to read one line too long for ``read``, as a command that is safe to run whatever the path holds."""+ if WINDOWS:+ quoted = "'" + path.replace("'", "''") + "'"+ # What sed and head -c print: the line as UTF-8, at most max_bytes of it, cut at a character boundary,+ # streaming the lines before it. Get-Content also ends a line at a bare \r (C-7 tools.md section 2).+ return (+ f"Use powershell: Get-Content -LiteralPath {quoted} -TotalCount {line} -Encoding UTF8 | Select-Object -Last 1 | "+ f"ForEach-Object {{ $b = [Text.Encoding]::UTF8.GetBytes($_); $n = [Math]::Min($b.Length, {max_bytes}); "+ "while ($n -lt $b.Length -and ($b[$n] -band 0xC0) -eq 0x80) { $n-- }; "+ "[Console]::Out.Write([Text.Encoding]::UTF8.GetString($b, 0, $n)) }"+ )+ return f"Use bash: sed -n '{line}p' {shlex.quote(path)} | head -c {max_bytes}"diff --git a/docs/plans/agent-core-contracts/tools.md b/docs/plans/agent-core-contracts/tools.mdindex 397676cf3..94c0bd6ac 100644--- a/docs/plans/agent-core-contracts/tools.md+++ b/docs/plans/agent-core-contracts/tools.md@@ -5,6 +5,9 @@ The coding tools in `core/agent_core/tools/`. Names, parameters, logic, and modeare Pi's unless marked as an Avibe addition. tau 0.4.7 (MIT, Copyright (c) 2026 Alejandro AO) is the Pythonreference. One tool set serves every model.+On Windows the command tool is `powershell` instead of `bash` (§5); what this contract and the others (C-3, C-9, C-10)+say of `bash` holds for it.+`Tool.concurrent` (Avibe) says whether a tool's calls may run at the same time as the neighbouring concurrent calls ofthe same response (C-3 [`loop-control.md`](loop-control.md) §2). When it is absent or `False`, every call of the toolis exclusive. `read` and `bash` are concurrent; `write` and `edit` are exclusive. Pi instead runs a response's calls at@@ -42,7 +45,16 @@ Raw text, no line numbers, head kept. Model-facing suffixes:- `[Showing lines {start}-{end} of {total} (50KB limit). Use offset={next} to continue.]`- `[{remaining} more lines in file. Use offset={next} to continue.]` (an explicit `limit` stopped before the end)- `[Line {n} is {size}, exceeds 50KB limit. Use bash: sed -n '{n}p' {quoted_path} | head -c 51200]`, where- `{quoted_path}` is the path shell-quoted (Avibe change to Pi's text, so the suggested command is always safe to run)+ `{quoted_path}` is the path shell-quoted (Avibe change to Pi's text, so the suggested command is always safe to run).+ On Windows: `[Line {n} is {size}, exceeds 50KB limit. Use powershell: {command}]`, where `{command}` prints what+ `sed` and `head -c` would: line `{n}` read as UTF-8, at most its first 51200 bytes, cut at a character boundary,+ with no newline added, streaming the lines before it. The path is in single quotes with each `'` doubled:+ `Get-Content -LiteralPath {quoted_path} -TotalCount {n} -Encoding UTF8 | Select-Object -Last 1 | ForEach-Object {+ $b = [Text.Encoding]::UTF8.GetBytes($_); $n = [Math]::Min($b.Length, 51200); while ($n -lt $b.Length -and ($b[$n]+ -band 0xC0) -eq 0x80) { $n-- }; [Console]::Out.Write([Text.Encoding]::UTF8.GetString($b, 0, $n)) }`.+ Known limit: `Get-Content` ends a line at a bare `\r` as well, where `read` ends one only at `\n`, so in a file+ with bare carriage returns the command can count lines differently and show part of the line. PowerShell 7+ ignores `-Delimiter "`n"` for that, and a byte-scanning reader would not be a one-line command.- Error: `Offset {offset} is beyond end of file ({total} lines total)`Images are attached as `ImageBlock`s (C-1); for a model without image input the result says so and omits the image.@@ -220,6 +232,50 @@ continue in the background as an Avibe Watch; you get a follow-up message when t- The Watch follow-up states the command, exit code, elapsed time, the tail under the same rules, and the output logunder the same label.+### On Windows: `powershell` (Avibe)++The tool is named `powershell`, so the model writes PowerShell, with the same parameters, behavior, and results. Its+description is the one above with `Execute a PowerShell command in the current working directory. Returns its output+and errors.` as the first sentence; under Windows PowerShell 5.1 it adds `This is Windows PowerShell 5.1: it has no &&+or ||, so separate commands with ; and test $? or $LASTEXITCODE.` The advice in other tools' results that names `bash`+names `powershell` there, and "for example sed or a short script" becomes "for example a short script".++- Shell: PowerShell 7 (`pwsh`) when it is on the `PATH` the commands run with, else Windows PowerShell 5.1, which+ every Windows 10 and 11 has.+- The command is written to `command.ps1` in the job directory, so no length limit applies (a command line holds+ 32,767 characters), and a fixed bootstrap runs it through `-NoProfile -NonInteractive -Command`+ (`-EncodedCommand` makes Windows PowerShell write errors as CLIXML). It turns off progress records and color, and+ makes the output UTF-8: PowerShell's own, and the console code page that native programs inherit;+ `PYTHONIOENCODING=utf-8` is set unless the environment sets it, so Python's standard streams are UTF-8 while+ the files it opens keep the system's encoding.+- A command that does not parse fails with exit code 1 and the parser's messages before anything runs. Otherwise+ it runs whole, as one script block, so PowerShell's own semantics hold (`return`, classes, named blocks, traps,+ `using`). Only the statement that runs last is wrapped, to record how it ended; a `return`, `break`, or+ `continue` at the top level ends the command.+- The exit code follows PowerShell's `$?` for the last statement of the last block that runs (`clean`, which+ PowerShell 7.3 and later run after the others, and not at all in a script with no other block; else `end`, else+ `process`, else `begin`, else `dynamicparam`): the command's own `exit N`; else 0 when that statement succeeded, or the command ended+ before it; else the `$LASTEXITCODE` that statement set, when it is not 0, so a failed native program reports its+ code; else 1. A code an earlier statement left in `$LASTEXITCODE` is not the last statement's, and a function+ that writes an error and returns has succeeded, as `$?` says.+- The command sees `$LASTEXITCODE` and `$?` exactly as PowerShell sets them, so a last statement may test the one+ before it (`cmd /c exit 7; if (-not $?) { exit $LASTEXITCODE }`), and its named blocks may be written in any order.+ A compound last statement (an `if`, a loop, a `try`) is one statement: when a native program in it fails and a+ cmdlet after it fails too, the code is the native program's, which that statement set.+- Errors are reported at the command's own lines: the wrapping adds no line before the last statement, and one after+ it only when it uses `--%`, whose arguments run to the end of its line. Only an error in a last statement that+ shares its line with the statement before it or with its block's opening brace, or that follows a `--%` statement,+ is reported at a later column. Parameter binding, a `param` default included, runs before the last statement. The wrapping reads nothing that+ `Set-StrictMode` forbids, so a command may turn strict mode on.+- Known limit: which statement set `$LASTEXITCODE` is tracked for ordinary scripts. In unusual code it can credit+ the last statement with an earlier native code, for example after a named block's keyword followed by a comment+ that holds a brace (`end <# { #> { … }`).+- Known limit: PowerShell in ConstrainedLanguage mode (an AppLocker or WDAC policy) is not supported. The bootstrap+ needs .NET calls that mode blocks, so the tool says so and runs nothing.+- Known limit, as with `powershell -Command`: an `exit` ends the process before PowerShell formats objects that are+ still waiting to be laid out as a table, so `Get-ChildItem | Select-Object Name; exit 2` can print nothing.+ Strings and the output of native programs are written as they come.+## 6. Output normalizerEvery model-facing command output (`bash` results, job logs, Watch follow-ups) passes through one normalizer: decode@@ -280,13 +336,15 @@ the projected context no longer shows, because the inputs that carried the earli<environment>cwd: /absolute/pathos: macOS 26.0 (arm64)-shell: /bin/zsh+shell: /bin/bashdate: 2026-10-02timezone: Asia/Shanghaiwatches: wch_8f2k "nightly sync" command running; wch_3c1d job running</environment>```+`shell` is the shell the commands run in: the job host's on POSIX (`/bin/bash`, else `bash` on `PATH`, else `sh`), and+on Windows `PowerShell 7 ({path})` or `Windows PowerShell 5.1 ({path})`.`watches` names the Session's enabled Watches by id, name, and kind, never a command: at most 20, then `and N more`.A field's identity is its raw value; only the block displays it, through the one display helper (`display`, C-9`context.md` §7): one line of plain text, escaped injectively (a backslash doubled, control characters and `<`, `>`diff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.pyindex 3ef1c8ca3..175d545e8 100644--- a/modules/agents/vibey/agent.py+++ b/modules/agents/vibey/agent.py@@ -1093,7 +1093,10 @@ class VibeyAgent(BaseAgent):runtime = self._runtimes.get(session_id)cwd = ((runtime.run.cwd if runtime.run is not None else "") or runtime.cwd) if runtime is not None else ""return current_environment(- cwd, self._watch_lines(session_id), include_time=getattr(self.config, "include_time_info", True)+ cwd,+ self._watch_lines(session_id),+ shell=self._tools().shell,+ include_time=getattr(self.config, "include_time_info", True),)def _watch_lines(self, session_id: str) -> list[str]:diff --git a/modules/agents/vibey/context.py b/modules/agents/vibey/context.pyindex 52892c15b..c0783dc35 100644--- a/modules/agents/vibey/context.py+++ b/modules/agents/vibey/context.py@@ -24,7 +24,7 @@ from typing import Any, Callable, Mapping, Optional, Sequencefrom sqlalchemy.engine import Engine-from core.agent_core.harness.context import StateRequest, display+from core.agent_core.harness.context import COMMAND_TOOLS, StateRequest, displayfrom core.agent_core.tools.base import Tool, ToolContext, ToolResult, ToolSpecfrom core.managed_skills import is_skill_namefrom modules.agents.vibey.prompt import EnvironmentValue, render_environment@@ -148,5 +148,6 @@ class _SkillLoadMarking:def mark_skill_loads(tools: Sequence[Tool]) -> tuple[Tool, ...]:- """The tools with ``bash`` recording the skills it loads, which a checkpoint lists by name (section 7)."""- return tuple(_SkillLoadMarking(tool) if tool.spec.name == "bash" else tool for tool in tools)+ """The tools with the command tool (``bash``, ``powershell`` on Windows) recording the skills it loads, which a+ checkpoint lists by name (section 7)."""+ return tuple(_SkillLoadMarking(tool) if tool.spec.name in COMMAND_TOOLS else tool for tool in tools)diff --git a/modules/agents/vibey/prompt.py b/modules/agents/vibey/prompt.pyindex a59dfbfab..2adfbd4ce 100644--- a/modules/agents/vibey/prompt.py+++ b/modules/agents/vibey/prompt.py@@ -43,6 +43,8 @@ AGENT_PREAMBLE = "You are an agent running inside Avibe, a local-first Agent OSTOOL_SNIPPETS: dict[str, str] = {"read": "Read file contents","bash": "Execute bash commands (ls, grep, find, etc.)",+ # Avibe: the command tool on Windows (C-7 tools.md section 5).+ "powershell": "Execute PowerShell commands (Get-ChildItem, Select-String, etc.)","edit": "Make precise file edits with exact text replacement, including multiple disjoint edits in one call","write": "Create or overwrite files",}@@ -59,7 +61,7 @@ TOOL_GUIDELINES: dict[str, tuple[str, ...]] = {),"write": ("Use write only for new files or complete rewrites.",),}-TOOL_ORDER = ("read", "bash", "edit", "write")+TOOL_ORDER = ("read", "bash", "powershell", "edit", "write")FINAL_REPLY_RULE = "Only your final reply is reliably shown to the user; put anything the user must see in it"#: Avibe's: the loop runs a response's neighbouring read and bash calls at the same time (C-3 loop-control.md section 2).CONCURRENT_CALLS_RULE = (@@ -92,6 +94,8 @@ def coding_prompt(tool_names: Iterable[str], *, builtin_agent: bool, rg: bool) -rules: list[str] = []if "bash" in names:rules.append(f"Use bash for file operations like ls, {'rg' if rg else 'grep'}, find")+ if "powershell" in names:+ rules.append(f"Use powershell for file operations like Get-ChildItem, {'rg' if rg else 'Select-String'}")for name in names:rules.extend(TOOL_GUIDELINES.get(name, ()))if names:@@ -147,7 +151,7 @@ EnvironmentValue = Union[str, tuple[str, ...]]def current_environment(- cwd: str, watches: Sequence[str], *, include_time: bool = True, now: Optional[datetime] = None+ cwd: str, watches: Sequence[str], *, shell: str, include_time: bool = True, now: Optional[datetime] = None) -> dict[str, EnvironmentValue]:"""The environment fields, raw; the clock ones follow ``include_time_info``, as every input prefix does.@@ -157,7 +161,8 @@ def current_environment(fields: dict[str, EnvironmentValue] = {"cwd": str(Path(cwd).resolve()) if cwd else "","os": operating_system(),- "shell": os.environ.get("SHELL") or "/bin/sh",+ # The shell the commands run in (``Shell.describe``), not the user's login shell.+ "shell": shell,}if include_time:fields.update(date=(now or datetime.now()).date().isoformat(), timezone=local_timezone())diff --git a/modules/agents/vibey/tools.py b/modules/agents/vibey/tools.pyindex a77e77003..f9231ffde 100644--- a/modules/agents/vibey/tools.py+++ b/modules/agents/vibey/tools.py@@ -16,11 +16,12 @@ keeps the command in the foreground.from __future__ import annotationsimport asyncio-from dataclasses import dataclass+from dataclasses import dataclass, fieldfrom typing import Any, Awaitable, Callable, Mapping, Optional, Sequencefrom core.agent_core.agent.recovery import RecoveryRendererfrom core.agent_core.tools.base import CallInstance, JobHost, Tool+from core.agent_core.tools.shell import default_shellImageSink = Callable[[bytes, str, str], Awaitable[str]]#: Whether a job's tool call has a durable ``tool_result`` (the adapter's half of J5).@@ -35,6 +36,8 @@ class ToolSuite:#: The job a call instance started, if any.find_job: Callable[[CallInstance], Optional[str]]prune: Optional[Callable[[CallSettled], list[str]]] = None+ #: The shell commands run in, as the environment block names it (C-7 tools.md section 8).+ shell: str = field(default_factory=lambda: default_shell().describe())#: The hand-over route for a job (``hand_over_job``'s keywords), from its owning Turn.@@ -71,7 +74,7 @@ def local_tool_suite(jobs_dir: Optional[str] = None, *, route: Optional[HandOverhost = LocalJobHost(str(jobs_dir or agent_jobs_dir()), on_hand_over=hand_over)def create_tools(jobs: JobHost, image_sink: Optional[ImageSink]) -> Sequence[Tool]:- return create_coding_tools(jobs, image_sink=image_sink)+ return create_coding_tools(jobs, image_sink=image_sink, shell=host.shell)async def render(call: Any, job_id: str, status: Any, watch_id: Optional[str]) -> Any:return await recovered_result(host, job_id, status, watch_id)@@ -82,5 +85,10 @@ def local_tool_suite(jobs_dir: Optional[str] = None, *, route: Optional[HandOverreturn host.prune(lambda meta: call_settled(meta) and watches.job_watch_settled(str(meta.get("job_id"))))return ToolSuite(- jobs=host, create_tools=create_tools, render_recovered=render, find_job=host.find_job, prune=prune+ jobs=host,+ create_tools=create_tools,+ render_recovered=render,+ find_job=host.find_job,+ prune=prune,+ shell=host.shell.describe(),)diff --git a/tests/agent_core/tools/test_bash.py b/tests/agent_core/tools/test_bash.pyindex 090ca3908..78709af25 100644--- a/tests/agent_core/tools/test_bash.py+++ b/tests/agent_core/tools/test_bash.py@@ -19,6 +19,7 @@ import core.agent_core.tools.bash as bash_modulefrom core.agent_core.tools.bash import BashTool, settle_bash_callimport core.agent_core.tools.jobs as jobs_modulefrom core.agent_core.tools.jobs import LocalJobHost+from core.agent_core.tools.shell import Shellfrom tests import hang_guardfrom tests.agent_core.tools.conftest import instance, result_text@@ -192,7 +193,7 @@ async def test_a_command_that_cannot_start_has_a_defined_result(tmp_path, make_celif failure == "jobs_dir_not_writable":jobs_dir.mkdir(mode=0o555)else:- shell = str(tmp_path / "no-such-shell")+ shell = Shell(str(tmp_path / "no-such-shell"))locked = {"cwd_not_accessible": cwd, "jobs_dir_not_writable": jobs_dir}.get(failure)try:host = LocalJobHost(str(jobs_dir), shell=shell)diff --git a/tests/agent_core/tools/test_jobs.py b/tests/agent_core/tools/test_jobs.pyindex 50aa9578d..a7916ca02 100644--- a/tests/agent_core/tools/test_jobs.py+++ b/tests/agent_core/tools/test_jobs.py@@ -21,6 +21,7 @@ import pytestimport core.agent_core.tools.jobs as jobs_modulefrom core.agent_core.tools.jobs import JobStartError, LocalJobHost+from core.agent_core.tools.shell import Shellfrom tests.agent_core.tools.conftest import instance# Starts real job wrappers: none may outlive its test (tests/process_reaper.py).@@ -317,7 +318,7 @@ async def test_a_deadline_that_passed_during_the_launch_never_starts_the_commandreturn identitymonkeypatch.setattr(LocalJobHost, "_await_pid", slow_host)- host = LocalJobHost(str(tmp_path / "jobs"), shell=str(tmp_path / "no-such-shell"))+ host = LocalJobHost(str(tmp_path / "jobs"), shell=Shell(str(tmp_path / "no-such-shell")))job_id = await _start(host, tmp_path, "true", timeout_s=0.1)assert _wait_until(lambda: _wrapper_gone(host.job_dir(job_id)))@@ -407,7 +408,7 @@ async def test_a_command_outliving_a_killed_wrapper_is_still_running_and_held_tomonkeypatch.setattr(jobs_module, "_WRAPPER_DECIDES_S", 0.2)# Python as the shell: its environment, and so the marker, is readable on macOS too.- host = LocalJobHost(str(tmp_path / "jobs"), shell=sys.executable)+ host = LocalJobHost(str(tmp_path / "jobs"), shell=Shell(sys.executable))script = f"import os, time; open({str(tmp_path / 'sh.pid')!r}, 'w').write(str(os.getpid())); time.sleep(30)"job_id = await _start(host, tmp_path, script, timeout_s=60)shell_pid = _pid_written(tmp_path / "sh.pid")@@ -522,7 +523,7 @@ async def test_a_cancelled_kill_still_finishes_the_group(tmp_path):"""Once the first signal is sent, the SIGKILL fallback runs even if the caller is cancelled meanwhile."""import sys- host = LocalJobHost(str(tmp_path / "jobs"), shell=sys.executable)+ host = LocalJobHost(str(tmp_path / "jobs"), shell=Shell(sys.executable))script = ("import os, signal, time; signal.signal(signal.SIGTERM, signal.SIG_IGN); "f"open({str(tmp_path / 'sh.pid')!r}, 'w').write(str(os.getpid())); time.sleep(60)"@@ -640,7 +641,7 @@ def test_the_wrapper_stops_its_group_even_when_its_diagnostics_fail(tmp_path, momonkeypatch.setattr(wrapper, "_BoundedLog", full_disk)monkeypatch.setattr(wrapper.traceback, "print_exc", full_disk)monkeypatch.setattr(wrapper, "_stop_group", stop_group)- argv = ["job_wrapper.py", "avibe-job", str(tmp_path), "/bin/sh", "true", "30", "10", "10", "-"]+ argv = ["job_wrapper.py", "avibe-job", str(tmp_path), "30", "10", "10", "-", "/bin/sh", "-c", "true"]with pytest.raises(Stopped):wrapper.main(argv)diff --git a/tests/agent_core/tools/test_jobs_windows.py b/tests/agent_core/tools/test_jobs_windows.pyindex 8fce49d13..d6932c62d 100644--- a/tests/agent_core/tools/test_jobs_windows.py+++ b/tests/agent_core/tools/test_jobs_windows.py@@ -30,6 +30,7 @@ from core.agent_core.cancel import CancelTokenfrom core.agent_core.tools.base import ToolContextfrom core.agent_core.tools.bash import BashTool, settle_bash_callfrom core.agent_core.tools.jobs import JobStartError, LocalJobHost+from core.agent_core.tools.shell import Shellfrom tests.agent_core.tools.conftest import instance, result_textpytestmark = pytest.mark.skipif(os.name != "nt", reason="the Windows job host")@@ -73,7 +74,7 @@ def make_ctx(tmp_path):def _host(tmp_path, **kwargs):- return LocalJobHost(str(tmp_path / "jobs"), shell=sys.executable, **kwargs)+ return LocalJobHost(str(tmp_path / "jobs"), shell=Shell(sys.executable), **kwargs)async def _start(host, tmp_path, script, *, tool_call_id="toolu_1", response_seq=1, timeout_s=None):@@ -315,8 +316,9 @@ async def test_a_job_outlives_the_host_process_that_started_it(tmp_path):"import asyncio, os, sys\n""from core.agent_core.tools.base import CallInstance\n""from core.agent_core.tools.jobs import LocalJobHost\n"+ "from core.agent_core.tools.shell import Shell\n""async def main():\n"- f" host = LocalJobHost(r'{tmp_path / 'jobs'}', shell=sys.executable)\n"+ f" host = LocalJobHost(r'{tmp_path / 'jobs'}', shell=Shell(sys.executable))\n"f" job_id = await host.start({_tree(tmp_path)!r}, cwd=r'{tmp_path}', env=dict(os.environ),"" timeout_s=None, call=CallInstance('ses_test', 'msg_1', 1, 'toolu_1'))\n"" print(job_id, flush=True)\n"@@ -463,7 +465,7 @@ async def test_a_program_holding_tail_log_when_the_command_exits_leaves_its_exitasync def test_jobs_run_with_their_files_on_a_volume_without_hard_links(tmp_path):"""FAT has no hard links: a decision and a stop reason are each created once by a rename instead."""jobs_dir = Path(os.environ["AVIBE_TEST_FAT_DIR"]) / f"jobs-{secrets.token_hex(4)}"- host = LocalJobHost(str(jobs_dir), shell=sys.executable)+ host = LocalJobHost(str(jobs_dir), shell=Shell(sys.executable))try:done = await _start(host, tmp_path, "import sys; sys.stdout.buffer.write(b'ran\\n')")assert await host.wait(done, deadline_s=15) == jobs_module.JobStatus("exited", 0)diff --git a/tests/agent_core/tools/test_powershell.py b/tests/agent_core/tools/test_powershell.pynew file mode 100644index 000000000..7c1aabbc8--- /dev/null+++ b/tests/agent_core/tools/test_powershell.py@@ -0,0 +1,447 @@+"""The command tool on Windows: ``powershell``, over the job host (C-7 tools.md section 5).++Runs under both PowerShell 7 (``pwsh``, when installed) and Windows PowerShell 5.1, which every Windows+has. The tool's name and description are checked everywhere; running commands needs Windows.+"""++from __future__ import annotations++import asyncio+import json+import os+import shutil+import subprocess+import sys+import time++import psutil+import pytest++from core.agent_core.cancel import CancelToken+from core.agent_core.tools.base import ToolContext+from core.agent_core.tools.bash import BashTool+from core.agent_core.tools.jobs import LocalJobHost+from core.agent_core.tools.shell import Shell, read_line_advice+from tests.agent_core.tools.conftest import instance, result_text++WINDOWS = os.name == "nt"+ON_WINDOWS = pytest.mark.skipif(not WINDOWS, reason="PowerShell runs on Windows")+++def _shells():+ if not WINDOWS:+ return []+ root = os.environ.get("SystemRoot", r"C:\Windows")+ found = [pytest.param(os.path.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), id="5.1")]+ if shutil.which("pwsh"):+ found.append(pytest.param(shutil.which("pwsh"), id="7"))+ return found++[email protected](params=_shells())+def shell(request):+ return Shell(request.param, powershell=True)+++async def host(tmp_path, shell):+ """A job host over PowerShell; every job it started is ended with the test."""+ host = LocalJobHost(str(tmp_path / "jobs"), shell=shell)+ yield host+ for job_id in host._job_ids():+ await host.kill(job_id)+++def run(tmp_path, host):+ """Run a command through the powershell tool; return ``(is_error, text)``."""+ tool = BashTool(host, shell=host.shell)++ async def run_command(command, *, env=None, **arguments):+ ctx = ToolContext(+ session_id="ses_test",+ tool_call_id="toolu_1",+ call=instance(),+ cwd=str(tmp_path),+ env=dict(os.environ) if env is None else env,+ cancel=CancelToken(),+ on_progress=None,+ )+ result = await tool.execute({"command": command, **arguments}, ctx)+ return result.is_error, result_text(result)++ return run_command+++ ("path", "name", "legacy"),+ [+ (r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe", "powershell", True),+ (r"C:\Program Files\PowerShell\7\pwsh.exe", "powershell", False),+ ("/bin/bash", "bash", False),+ ],+)+def test_the_tool_is_named_after_its_shell(path, name, legacy):+ shell = Shell(path, powershell=name == "powershell")+ spec = BashTool(object(), shell=shell).spec++ assert spec.name == name+ assert spec.description.startswith(+ "Execute a PowerShell command in the current working directory. Returns its output and errors."+ if name == "powershell"+ else "Execute a bash command in the current working directory. Returns stdout and stderr."+ )+ assert ("This is Windows PowerShell 5.1: it has no && or ||" in spec.description) is legacy+++@ON_WINDOWS+ ("command", "is_error", "ending"),+ [+ ("Write-Output ok", False, "ok"),+ ("cmd /c exit 3", True, "Command exited with code 3"),+ ("Get-Item C:\\does-not-exist", True, "Command exited with code 1"),+ ("cmd /c exit 3; Write-Output ok", False, "ok"),+ ("Write-Output ok\ncmd /c exit 4", True, "Command exited with code 4"),+ ("exit 5", True, "Command exited with code 5"),+ ("throw 'boom'", True, "Command exited with code 1"),+ ("Write-Output ok\nif (", True, "Command exited with code 1"),+ ("cmd /c exit 23; Get-Item C:\\does-not-exist", True, "Command exited with code 1"),+ ("cmd /c exit 3; cmd /c exit 3", True, "Command exited with code 3"),+ ],+ ids=[+ "ok",+ "native-fails",+ "cmdlet-fails",+ "fails-then-ok",+ "ok-then-fails",+ "exit",+ "throw",+ "parse-error",+ "native-then-cmdlet-fails",+ "the-same-code-twice",+ ],+)+async def test_the_exit_code_follows_bash(run, command, is_error, ending):+ error, text = await run(command)++ assert (error, text.rstrip().splitlines()[-1]) == (is_error, ending)+++@ON_WINDOWS+async def test_a_command_that_does_not_parse_runs_nothing_and_says_why(run, tmp_path):+ error, text = await run(f"Set-Content -Path '{tmp_path / 'ran'}' -Value x\nif (")++ assert error and "Missing condition in if statement" in text+ assert not (tmp_path / "ran").exists()+++@ON_WINDOWS[email protected]("flow", ["return", "break", "continue"])+async def test_a_top_level_return_ends_the_whole_script(run, tmp_path, flow):+ """The command is one script: a ``return`` at its top level ends it, and nothing after it runs."""+ marker = tmp_path / "after"+ error, text = await run(+ f"if ($true) {{ Write-Output before; {flow} }}\n"+ f"New-Item -ItemType File -Path '{marker}' | Out-Null\n"+ "Write-Output after"+ )++ assert (error, text.split()) == (False, ["before"])+ assert not marker.exists()+++@ON_WINDOWS+async def test_text_comes_before_an_exit_that_follows_it(run):+ """Strings and native programs' output are written as they come; only objects still waiting to be laid out+ as a table can be lost to an ``exit`` (C-7 tools.md section 5, as with ``powershell -Command``)."""+ error, text = await run("Write-Output before; cmd /c echo native; exit 2")++ assert error and text.split()[:2] == ["before", "native"]+ assert text.rstrip().endswith("Command exited with code 2")+++@ON_WINDOWS+ ("command", "output"),+ [+ ("class Item { [string] $Name = 'item' }\nenum Color { Red }\n[Item]::new().Name; [Color]::Red", "item Red"),+ ("param($Name = 'default')\nWrite-Output $Name", "default"),+ ("using namespace System.Text\n[StringBuilder]::new().Append('built').ToString()", "built"),+ ("begin { Write-Output first }\nprocess { Write-Output each }\nend { Write-Output last }", "first each last"),+ ("process { Write-Output only }", "only"),+ ],+ ids=["types", "param", "using", "named-blocks", "process-only"],+)+async def test_a_command_keeps_powershell_script_semantics(run, command, output):+ """Types are visible across its statements, and a param block, using, or named blocks work as in a script."""+ error, text = await run(command)++ assert (error, " ".join(text.split())) == (False, output)+++@ON_WINDOWS+ ("command", "code"),+ [+ ("begin { Write-Output first }\nend { Write-Output last; cmd /c exit 4 }", 4),+ ("process { cmd /c exit 7 }", 7),+ ("begin { cmd /c exit 6 }", 6),+ # A function that writes an error and returns has succeeded, as $? says (C-7 tools.md section 5).+ ("function Get-Twice { cmd /c exit 23; Get-Item C:\\does-not-exist }\nGet-Twice", 0),+ # A compound statement is one statement, and it set $LASTEXITCODE.+ ("if ($true) { cmd /c exit 23; Get-Item C:\\does-not-exist }", 23),+ # Blocks may be written in any order; they run begin, process, end.+ ("end { cmd /c exit 4 }\nbegin { Write-Output begin }", 4),+ # The code an earlier block left is not the last statement's, whatever path led to it.+ ("begin { cmd /c exit 23 }\nend { Get-Item C:\\does-not-exist }", 1),+ # ...or parameter binding: a param default runs before the only statement.+ ("param($Ignored = $(cmd /c exit 23))\nGet-Item C:\\does-not-exist", 1),+ # --% makes the rest of its line arguments: nothing may be added there.+ ("cmd.exe --% /c exit 7", 7),+ ("cmd.exe --% /c exit 23\nGet-Item C:\\does-not-exist", 1),+ # The last statement sees $? as the one before left it.+ ("cmd /c exit 7; if (-not $?) { exit $LASTEXITCODE }", 7),+ ("cmd /c exit 0; if ($?) { cmd /c exit 5 }", 5),+ ],+ ids=[+ "end",+ "process-only",+ "begin-only",+ "a-function-returns",+ "a-compound-statement",+ "blocks-out-of-order",+ "a-code-from-an-earlier-block",+ "a-code-from-a-param-default",+ "stop-parsing-last",+ "stop-parsing-before-the-last",+ "the-last-tests-the-one-before",+ "the-last-tests-a-success",+ ],+)+async def test_the_exit_code_follows_the_statement_that_runs_last(run, command, code):+ error, text = await run(command)++ assert error == bool(code)+ if code:+ assert text.rstrip().endswith(f"Command exited with code {code}")+++@ON_WINDOWS+async def test_a_clean_block_runs_last(run, shell, tmp_path):+ """PowerShell 7.3 and later run ``clean`` after the other blocks, so its last statement is the one that counts;+ in a script with no other block, PowerShell runs none of it, and nothing fails."""+ if shell.windows_powershell:+ pytest.skip("Windows PowerShell 5.1 has no clean block")+ marker = tmp_path / "clean-ran"++ after_process = await run("process { Write-Output ok }\nclean { cmd /c exit 5 }")+ alone = await run(f"clean {{ New-Item -ItemType File -Path '{marker}' | Out-Null; cmd /c exit 7 }}")++ assert after_process[0] and after_process[1].rstrip().endswith("Command exited with code 5")+ assert alone[0] is False+ assert not marker.exists()+++@ON_WINDOWS+def test_constrained_language_mode_is_refused_with_a_reason(shell, tmp_path):+ """AppLocker and WDAC put PowerShell in ConstrainedLanguage mode, which blocks the bootstrap's .NET calls. A+ session can enter that mode itself, which stands in for the policy here."""+ marker = tmp_path / "ran"+ argv = shell.prepare(f"New-Item -ItemType File -Path '{marker}' | Out-Null", str(tmp_path))+ argv[-1] = "$ExecutionContext.SessionState.LanguageMode = 'ConstrainedLanguage'\n" + argv[-1]++ completed = subprocess.run(+ argv, capture_output=True, text=True, creationflags=subprocess.CREATE_NO_WINDOW, timeout=60+ )++ assert completed.returncode == 1+ assert "ConstrainedLanguage mode" in completed.stderr and "Nothing was run" in completed.stderr, completed.stderr+ assert not marker.exists()+++@ON_WINDOWS+async def test_a_clean_block_after_an_early_return_reports_its_own_failure(run, shell):+ """``clean`` runs even after ``return``; the native code ``begin`` left is not its last statement's."""+ if shell.windows_powershell:+ pytest.skip("Windows PowerShell 5.1 has no clean block")+ error, text = await run("begin { cmd /c exit 23; return }\nclean { Get-Item C:\\does-not-exist }")++ assert error and text.rstrip().endswith("Command exited with code 1"), text+++@ON_WINDOWS+async def test_a_dynamicparam_block_counts_when_it_runs(run, tmp_path):+ """It runs first, during parameter binding; if it is the only block, its last statement is the one that counts."""+ marker = tmp_path / "dynamicparam-ran"+ error, text = await run(+ f"dynamicparam {{ New-Item -ItemType File -Path '{marker}' | Out-Null; cmd /c exit 7 }}"+ )++ if marker.exists():+ assert error and text.rstrip().endswith("Command exited with code 7"), text+ else:+ assert not error, text+++@ON_WINDOWS+ ("command", "is_error", "ending"),+ [+ ("Set-StrictMode -Version Latest\nWrite-Output ok", False, "ok"),+ ("Set-StrictMode -Version Latest\nWrite-Output ok; cmd /c exit 3", True, "Command exited with code 3"),+ ],+ ids=["ok", "native-fails"],+)+async def test_a_command_may_turn_strict_mode_on(run, command, is_error, ending):+ """``$LASTEXITCODE`` does not exist until something sets it, and strict mode refuses to read it then."""+ error, text = await run(command)++ assert (error, text.rstrip().splitlines()[-1]) == (is_error, ending)+++@ON_WINDOWS+async def test_the_command_sees_lastexitcode_as_powershell_sets_it(run):+ """Watching which statement set ``$LASTEXITCODE`` leaves its value, and its type, as they are."""+ error, text = await run("cmd /c exit 7\n$LASTEXITCODE.GetType().Name; $LASTEXITCODE")++ assert (error, text.split()) == (False, ["Int32", "7"])+++@ON_WINDOWS+async def test_an_error_is_reported_at_the_command_s_own_line_and_column(run):+ """The wrapping adds no line, so the model is pointed at the line it wrote (in the view that shows it)."""+ error, text = await run("$ErrorView = 'NormalView'\nWrite-Output first\n throw 'boom'")++ assert error+ assert "At line:3 char:3" in text, text+++@ON_WINDOWS+async def test_output_is_utf8_from_powershell_and_from_native_programs(run):+ error, text = await run(+ "Write-Output '中文 ps'\n"+ "cmd /c echo 中文 cmd\n"+ f"& '{sys.executable}' -c \"import sys; print('中文 py', sys.flags.utf8_mode)\""+ )++ # Only Python's standard streams are made UTF-8: the files it opens keep the system's encoding.+ utf8_mode = 1 if os.environ.get("PYTHONUTF8") == "1" else 0+ assert not error, text+ assert text.splitlines() == ["中文 ps", "中文 cmd", f"中文 py {utf8_mode}"]+++# Runs in a console of its own (CREATE_NO_WINDOW), sets it to code page 936 as Chinese Windows starts one,+# then runs the shell in it, as a job's wrapper would, and hands back the bytes the shell wrote.+_UNDER_CODE_PAGE_936 = """+import ctypes, json, subprocess, sys+ctypes.windll.kernel32.SetConsoleOutputCP(936)+ctypes.windll.kernel32.SetConsoleCP(936)+completed = subprocess.run(json.loads(sys.argv[1]), stdin=subprocess.DEVNULL, capture_output=True)+sys.stdout.write(json.dumps([completed.returncode, completed.stdout.hex(), completed.stderr.hex()]))+"""+++@ON_WINDOWS+def test_output_is_utf8_on_a_console_with_a_chinese_code_page(tmp_path, shell):+ """Chinese Windows starts a console at code page 936; the bootstrap makes the output UTF-8 anyway."""+ job_dir = tmp_path / "job"+ job_dir.mkdir()+ argv = shell.prepare("Write-Output '中文 ps'\ncmd /c echo 中文 cmd", str(job_dir))+ completed = subprocess.run(+ [sys.executable, "-c", _UNDER_CODE_PAGE_936, json.dumps(argv)],+ capture_output=True,+ creationflags=subprocess.CREATE_NO_WINDOW,+ timeout=60,+ )+ code, stdout, stderr = json.loads(completed.stdout)++ assert code == 0, bytes.fromhex(stderr)+ assert bytes.fromhex(stdout).decode("utf-8").splitlines() == ["中文 ps", "中文 cmd"]+++@ON_WINDOWS+async def test_a_command_longer_than_a_command_line_runs(run):+ """A command line holds 32,767 characters; the command reaches PowerShell through a file."""+ error, text = await run("Write-Output ('" + "x" * 40_000 + "').Length")++ assert (error, text.strip()) == (False, "40000")+++@ON_WINDOWS+async def test_a_process_started_with_start_process_stays_in_the_job_until_it_is_killed(tmp_path, host):+ job_id = await host.start(+ f"(Start-Process -FilePath '{sys.executable}' -ArgumentList '-c \"import time; time.sleep(60)\"' -PassThru).Id",+ cwd=str(tmp_path),+ env=dict(os.environ),+ timeout_s=None,+ call=instance(),+ )+ status = await host.wait(job_id, deadline_s=60)+ pid = int(host.output(job_id)[0].decode().strip())++ assert (status.state, status.exit_code) == ("exited", 0)+ assert psutil.pid_exists(pid)+ await host.kill(job_id)+ deadline = time.monotonic() + 10+ while psutil.pid_exists(pid) and time.monotonic() < deadline:+ await asyncio.sleep(0.05)+ assert not psutil.pid_exists(pid)+++@ON_WINDOWS+ ("content", "line", "expected"),+ [+ (b"short\n" + b"x" * 61_440 + b"\nafter\n", 2, "x" * 51_200),+ (b"x" * 61_440, 1, "x" * 51_200),+ # UTF-8 without a BOM, which Windows PowerShell would read as ANSI; 51,200 bytes end on a character.+ (b"ab" + "\u4e2d".encode() * 30_000 + b"\n", 1, "ab" + "\u4e2d" * 17_066),+ # ...and inside one, which is left out whole.+ (b"a" + "\u4e2d".encode() * 30_000, 1, "a" + "\u4e2d" * 17_066),+ ],+ ids=["a later line", "the only line", "cjk", "cjk-cut-inside-a-character"],+)+async def test_the_advice_read_gives_for_a_long_line_runs_as_given(tmp_path, run, content, line, expected):+ """``read`` points at a command for a line too long to show. Run through the tool, it prints what ``sed`` and+ ``head -c`` would: that line as UTF-8, at most 51,200 bytes of it, whatever the path holds; line 1 too, which+ ``Get-Content`` alone gives as a string rather than a list of lines."""+ target = tmp_path / "it's big.txt"+ target.write_bytes(content)+ advice = read_line_advice(str(target), line, 51_200).removeprefix("Use powershell: ")++ error, text = await run(advice)++ assert not error, text[-300:]+ assert text.encode() == expected.encode()+++@ON_WINDOWS+async def test_the_agent_loop_runs_a_powershell_call_and_answers_with_its_output(tmp_path, host):+ """End to end without a model: a scripted provider calls the tool, and its output reaches the next request."""+ from core.agent_core.agent.loop import Agent+ from core.agent_core.ai.provider import Done+ from core.agent_core.messages import ToolCallBlock, ToolResultMessage+ from core.agent_core.tools.coding import create_coding_tools+ from tests.agent_core.fakes import FakeModelRouter, InMemoryTranscriptStore, ScriptedProvider, assistant, input_row++ call = ToolCallBlock("call_1", "powershell", {"command": "Write-Output ('中文 ' + $PSVersionTable.PSEdition)"})+ provider = ScriptedProvider([[Done(assistant(calls=[call]))], [Done(assistant("done"))]])+ agent = Agent(+ session_id="ses_windows",+ models=FakeModelRouter(provider),+ tools=(),+ hooks=(),+ store=InMemoryTranscriptStore(),+ jobs=host,+ cwd=str(tmp_path),+ env=dict(os.environ),+ )+ agent.set_tools(create_coding_tools(agent.jobs, shell=host.shell))++ [event async for event in agent.run(input_row("input", "run it"), turn_id="turn")]++ assert [spec.name for spec in provider.requests[0].tools] == ["read", "write", "edit", "powershell"]+ [result] = [message for message in provider.requests[1].messages if isinstance(message, ToolResultMessage)]+ edition = "Desktop" if host.shell.windows_powershell else "Core"+ assert (result.is_error, result.content[0].text.strip()) == (False, f"中文 {edition}")diff --git a/tests/agent_core/tools/test_read.py b/tests/agent_core/tools/test_read.pyindex 99cad01c7..6f1188815 100644--- a/tests/agent_core/tools/test_read.py+++ b/tests/agent_core/tools/test_read.py@@ -84,7 +84,7 @@ async def test_an_over_long_first_line_is_measured_as_it_would_be_shown(tmp_path@pytest.mark.parametrize("spelling", ["big file.txt", "~/big file.txt", "file://{home}/big%20file.txt", "@big file.txt"])-async def test_an_over_long_first_line_points_at_bash_with_the_file_read_opened(tmp_path, make_ctx, spelling):+async def test_an_over_long_first_line_points_at_the_shell_with_the_file_read_opened(tmp_path, make_ctx, spelling):"""The suggested command names the resolved file, so it runs whatever spelling the model used."""home = os.path.expanduser("~")os.makedirs(home, exist_ok=True)@@ -95,9 +95,15 @@ async def test_an_over_long_first_line_points_at_bash_with_the_file_read_opened(result = await ReadTool().execute({"path": spelling.format(home=home), "offset": 2}, make_ctx(cwd=home))text = result_text(result)- assert text == (- f"[Line 2 is 60.0KB, exceeds 50.0KB limit. Use bash: sed -n '2p' {shlex.quote(target)} | head -c 51200]"+ advice = (+ f"Use powershell: Get-Content -LiteralPath '{target}' -TotalCount 2 -Encoding UTF8 | Select-Object -Last 1 | "+ "ForEach-Object { $b = [Text.Encoding]::UTF8.GetBytes($_); $n = [Math]::Min($b.Length, 51200); "+ "while ($n -lt $b.Length -and ($b[$n] -band 0xC0) -eq 0x80) { $n-- }; "+ "[Console]::Out.Write([Text.Encoding]::UTF8.GetString($b, 0, $n)) }"+ if os.name == "nt"+ else f"Use bash: sed -n '2p' {shlex.quote(target)} | head -c 51200")+ assert text == f"[Line 2 is 60.0KB, exceeds 50.0KB limit. {advice}]"class _CancelledAfter(CancelToken):diff --git a/tests/agent_core/tools/test_write_edit.py b/tests/agent_core/tools/test_write_edit.pyindex 0e9c4b729..3fdec4db6 100644--- a/tests/agent_core/tools/test_write_edit.py+++ b/tests/agent_core/tools/test_write_edit.py@@ -34,6 +34,8 @@ from tests.agent_core.tools.conftest import result_textWINDOWS = os.name == "nt"# The OS's own words, which Windows chooses differently.NO_SUCH_FILE = "the system cannot find the file specified" if WINDOWS else "no such file or directory"+# The command tool, as other tools' advice names it (C-7 tools.md section 5).+SHELL = "powershell (for example a short script)" if WINDOWS else "bash (for example sed or a short script)"async def test_write_creates_parent_directories_and_keeps_bytes(tmp_path, make_ctx):@@ -1026,7 +1028,7 @@ async def test_edit_refuses_files_with_more_lines_than_it_plans(tmp_path, make_cassert (big.is_error, result_text(big)) == (True,"File big.txt has 101 lines, over the 100 line edit limit. "- "Use bash (for example sed or a short script) to change files this large.",+ f"Use {SHELL} to change files this large.",)@@ -1036,7 +1038,7 @@ async def test_edit_refuses_files_with_more_lines_than_it_plans(tmp_path, make_c([{"oldText": "a", "newText": "b", "replaceAll": True}],"Found 11 occurrences of the text in f.txt, over the 10 replaceAll limit. "- "Use bash (for example sed or a short script) to replace this many.",+ f"Use {SHELL} to replace this many.",),(# The budget is for the whole call: 11 + 10 replacements by two edits, each under it alone.@@ -1045,13 +1047,13 @@ async def test_edit_refuses_files_with_more_lines_than_it_plans(tmp_path, make_c{"oldText": "c", "newText": "d", "replaceAll": True},],"The edits make 21 replacements in f.txt, over the 19 replacement limit. "- "Use bash (for example sed or a short script) to replace this many.",+ f"Use {SHELL} to replace this many.",),(# Ten replacements of 200 characters: over a 1,000-byte limit before anything is built.[{"oldText": "c", "newText": "y" * 200, "replaceAll": True}],"File f.txt would be over the 1000B edit limit after this edit. "- "Use bash (for example sed or a short script) to change files this large.",+ f"Use {SHELL} to change files this large.",),],ids=["single", "batch-total", "inserted-text"],@@ -1080,7 +1082,7 @@ async def test_edit_work_has_a_budget_over_all_edits(tmp_path, make_ctx, monkeypassert (two.is_error, result_text(two)) == (True,"2 edits over f.txt (790 characters) are over the edit work limit. Split them into several edit calls, "- "or use bash (for example sed or a short script).",+ f"or use {SHELL}.",)@@ -1124,7 +1126,7 @@ async def test_a_planned_result_over_the_limit_is_refused_and_its_diff_skipped(tassert too_big.is_errorassert result_text(too_big) == ("File small.txt would be over the 1000B edit limit after this edit. "- "Use bash (for example sed or a short script) to change files this large."+ f"Use {SHELL} to change files this large.")assert (tmp_path / "small.txt").read_text(encoding="utf-8") == "x" * 600 + "\n"@@ -1138,7 +1140,7 @@ async def test_files_over_the_edit_limit_are_refused_and_large_diffs_skipped(tmpassert refused.is_errorassert result_text(refused) == ("File big.log is 500B, over the 400B edit limit. "- "Use bash (for example sed or a short script) to change files this large."+ f"Use {SHELL} to change files this large.")assert (tmp_path / "big.log").read_text(encoding="utf-8") == "line\n" * 100diff --git a/tests/test_vibey_agent.py b/tests/test_vibey_agent.pyindex f6bd5b4ad..dbb9f77aa 100644--- a/tests/test_vibey_agent.py+++ b/tests/test_vibey_agent.py@@ -473,6 +473,8 @@ async def test_a_turn_commits_its_context_once_and_shows_the_reply_once(assert [entry.kind for entry in rows] == ["input", "response", "tool_result", "response"]environment, typed = rows[0].message.contentassert environment.text.startswith("<environment>\ncwd: ") and typed == TextBlock(text="看一下目录")+ # The shell is the one the commands run in, the job host's, not the user's login shell.+ assert f"\nshell: {harness.suite.shell}\n" in environment.text# The clock fields follow include_time_info (off here), as every input prefix does.assert "date:" not in environment.text and "timezone:" not in environment.text# The steer identity existed when the Turn owner bound the native start.@@ -1642,6 +1644,16 @@ async def test_a_relative_tool_path_is_shown_under_the_runs_cwd(engine, session,assert shown(other_drive) == other_drive+def test_on_windows_the_command_tool_is_powershell_with_its_own_rule() -> None:+ from modules.agents.vibey.prompt import coding_prompt++ text = coding_prompt(["read", "powershell", "edit", "write"], builtin_agent=True, rg=True)++ assert "- powershell: Execute PowerShell commands (Get-ChildItem, Select-String, etc.)" in text+ assert "Use powershell for file operations like Get-ChildItem, rg" in text+ assert "bash" not in text++async def test_the_system_prompt_lists_every_tool_the_run_offers(engine, session, tmp_path, published) -> None:harness = _Harness(engine, tmp_path, "avibe", [[Done(assistant("ok"))]],diff --git a/tests/test_vibey_agent_context.py b/tests/test_vibey_agent_context.pyindex 31fe42ccb..46cfbf894 100644--- a/tests/test_vibey_agent_context.py+++ b/tests/test_vibey_agent_context.py@@ -10,6 +10,8 @@ parts are checked against real rows and the real read-only query guard.from __future__ import annotations+import dataclasses+import jsonimport refrom pathlib import Path@@ -418,7 +420,7 @@ async def test_a_3000_byte_cwd_is_kept_whole_on_every_input_and_in_the_state(eng# The cwd is never cut, only escaped: the model builds absolute paths from it, so a cut one would be false.cwd = "/工作区/" + "/".join(["目录" * 40] * 12) + "/a<b"- fields = current_environment(cwd, [])+ fields = current_environment(cwd, [], shell="/bin/bash")assert fields["cwd"] == cwd and len(cwd.encode()) > 2_900shown = cwd.replace("<", "\\u003c")assert f"\ncwd: {shown}\n" in render_environment(fields) # every input@@ -427,14 +429,16 @@ async def test_a_3000_byte_cwd_is_kept_whole_on_every_input_and_in_the_state(engassert f"\ncwd: {shown}\n" in environment and "…" not in environment-async def test_two_values_that_look_alike_once_cut_are_still_two_environments(engine, session, tmp_path, monkeypatch):+async def test_two_values_that_look_alike_once_cut_are_still_two_environments(engine, session, tmp_path):# Identity is the raw value, and only the block the model reads is cut (display): a cut display never proves a# field unchanged, so two shells alike in their head and tail still tell the model the shell changed. A value# displayed whole is proved unchanged by its display, so the cwd is not sent again.scripts = [[Done(assistant("one"))], [Done(assistant("two"))]]harness = _Harness(engine, tmp_path, "avibe", scripts)for middle in ("one", "two"):- monkeypatch.setenv("SHELL", f"/opt/{'head' * 40}{middle}{'tail' * 40}")+ # The shell is the job host's; a restart can change it (PowerShell 7 installed meanwhile, say).+ harness.suite = dataclasses.replace(harness.suite, shell=f"/opt/{'head' * 40}{middle}{'tail' * 40}")+ harness.new_agent()await _turn(harness, f"with {middle}")first, second = [row.message.content[0].text for row in await harness.context_rows() if row.kind == "input"]shell = [line for line in first.split("\n") if line.startswith("shell: ")]diff --git a/ui/src/lib/agentActivity.test.ts b/ui/src/lib/agentActivity.test.tsindex 93dc73c14..6f6c0176c 100644--- a/ui/src/lib/agentActivity.test.ts+++ b/ui/src/lib/agentActivity.test.ts@@ -54,6 +54,9 @@ describe('toolSummary', () => {describe('toolIconKind', () => {it('maps tool-name families to a stable icon key', () => {expect(toolIconKind('Bash')).toBe('terminal');+ // Vibey's command tool on Windows, and Claude Code's PowerShell tool.+ expect(toolIconKind('powershell')).toBe('terminal');+ expect(toolIconKind('PowerShell')).toBe('terminal');expect(toolIconKind('Read')).toBe('file');expect(toolIconKind('Edit')).toBe('edit');expect(toolIconKind('Write')).toBe('edit');@@ -97,6 +100,7 @@ describe('parseToolCall (tier gating: extract name + JSON args, or null)', () =>describe('toolRecipe (tier 1: known-tool recipes, backend-agnostic)', () => {it('bash/shell family → command (Claude/Codex/OpenCode)', () => {expect(toolRecipe('Bash', { command: 'pwd' })).toEqual({ kind: 'command', command: 'pwd' });+ expect(toolRecipe('powershell', { command: 'Get-Location' })).toEqual({ kind: 'command', command: 'Get-Location' });expect(toolRecipe('bash', { command: 'ls', status: 'completed', exit_code: 0 })).toEqual({kind: 'command',command: 'ls',diff --git a/ui/src/lib/agentActivity.ts b/ui/src/lib/agentActivity.tsindex 044cbf21e..99d85a12c 100644--- a/ui/src/lib/agentActivity.ts+++ b/ui/src/lib/agentActivity.ts@@ -259,7 +259,7 @@ export const toolIconKind = (toolName: string): ToolIconKind => {// ``ls`` inside "SomethingElse", ``run`` inside "current".const name = (toolName || '').trim().toLowerCase();const startsWithAny = (prefixes: string[]) => prefixes.some((p) => name.startsWith(p));- if (startsWithAny(['bash', 'shell', 'terminal', 'exec', 'command', 'run', 'sh'])) return 'terminal';+ if (startsWithAny(['bash', 'powershell', 'pwsh', 'shell', 'terminal', 'exec', 'command', 'run', 'sh'])) return 'terminal';if (startsWithAny(['write', 'edit', 'patch', 'create', 'update', 'apply', 'notebook', 'todo', 'file'])) return 'edit';if (startsWithAny(['read', 'cat', 'grep', 'glob', 'ls', 'open', 'view', 'list', 'find'])) return 'file';if (startsWithAny(['web', 'fetch', 'http', 'browse', 'url'])) return 'web';@@ -387,7 +387,7 @@ export const toolRecipe = (name: string, args: Record<string, unknown>): ToolRecconst path = asStr(args.file_path) ?? asStr(args.filePath) ?? asStr(args.path) ?? asStr(args.file);const command = asStr(args.command) ?? asStr(args.cmd);- if (starts(['bash', 'shell', 'exec', 'run', 'sh', 'zsh', 'terminal', 'command'])) {+ if (starts(['bash', 'powershell', 'pwsh', 'shell', 'exec', 'run', 'sh', 'zsh', 'terminal', 'command'])) {return command != null ? { kind: 'command', command: summarizeShellCommand(command) } : null;}if (starts(['write', 'edit', 'create', 'update', 'apply', 'patch', 'notebook', 'multiedit', 'file_change', 'filechange'])) {