@tiens.nguyen/gu-cli 1.0.835 → 1.0.836

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7933,6 +7933,123 @@ def _ws_shell_command_risk(scan, denyset, wd="", allowset=None, roots=None):
7933
7933
  return (None, None, None)
7934
7934
 
7935
7935
 
7936
+ # ---- POWERSHELL LINES (task #374, GitHub #155) ---------------------------------------------------
7937
+ # The same policy as a bash line, read with gu_powershell: every simple command — inside $( ),
7938
+ # @( ), ( ) and { } too, since a ForEach-Object block runs — through the allow/deny lists,
7939
+ # elevation, deletes and writes outside the project (cmdlets' -Path/-Destination as well as
7940
+ # redirects), plus PowerShell's own ways to run text as code: Invoke-Expression, piping into an
7941
+ # interpreter (unless what is piped is a string the line itself wrote — PowerShell's heredoc),
7942
+ # [ScriptBlock]::Create and -EncodedCommand.
7943
+
7944
+ def _ps_mod():
7945
+ import gu_powershell as _gp
7946
+ return _gp
7947
+
7948
+
7949
+ def _ps_background_error(scan):
7950
+ """A line ending a command with `&` (a PowerShell job, gone when the shell exits), or None."""
7951
+ gp = _ps_mod()
7952
+ top, _ = gp.ps_all_commands(scan)
7953
+ if any(c["background"] for c in top):
7954
+ return ("Error: that command did NOT run. Do not end it with `&` — in PowerShell that "
7955
+ "starts a job that dies with the shell. run_command already leaves a server or app "
7956
+ "RUNNING when it starts listening or opens a window; for a long job pass "
7957
+ "background=True. Send the same command without the `&`.")
7958
+ return None
7959
+
7960
+
7961
+ def _ps_priv_reason(scan):
7962
+ """Elevation in any command of a PowerShell line (runas, -Verb RunAs, sudo, ACL/service/
7963
+ registry rewrites) — judged with the Windows rules whatever OS reads it."""
7964
+ gp = _ps_mod()
7965
+ top, inner = gp.ps_all_commands(scan)
7966
+ for c in top + inner:
7967
+ r = _ws_priv_reason(" ".join(c["argv"]), windows=True)
7968
+ if r:
7969
+ return r
7970
+ return None
7971
+
7972
+
7973
+ def _ps_native_paths(paths, wd):
7974
+ """PowerShell paths as the OS reads them: $env:X / $HOME / ~ filled in. A path that only
7975
+ exists at run time ($_, $x) becomes an impossible one, so it is never judged "inside"."""
7976
+ gp = _ps_mod()
7977
+ out = []
7978
+ for p in paths:
7979
+ q = gp.ps_expand_path(p, os.environ, os.path.expanduser("~"), wd or os.getcwd())
7980
+ out.append(q if q is not None else os.path.join(os.sep, "gu-unknown-at-run-time", p))
7981
+ return out
7982
+
7983
+
7984
+ def _ws_ps_command_risk(scan, denyset, wd="", allowset=None, roots=None):
7985
+ """_ws_shell_command_risk for a PowerShell line. Same contract: (refuse, hard, ask)."""
7986
+ gp = _ps_mod()
7987
+ top, inner = gp.ps_all_commands(scan)
7988
+ every = top + inner
7989
+ effects = [(c, gp.ps_effects(c)) for c in every]
7990
+
7991
+ def names(c, e):
7992
+ raw = re.split(r"[\\/]", c["argv"][0])[-1].lower() if c["argv"] else ""
7993
+ return {n for n in (raw, e["program"], c["argv"][0] if c["argv"] else "") if n}
7994
+
7995
+ if allowset:
7996
+ low = {a.lower() for a in allowset}
7997
+ for c, e in effects:
7998
+ if e["program"] and not (names(c, e) & (set(allowset) | low)):
7999
+ return (f"Error: '{c['argv'][0]}' is not in your run allowlist. Add it in web "
8000
+ "Settings → Agent, or clear the allowlist to allow all commands.", None, None)
8001
+ priv = _ps_priv_reason(scan)
8002
+ if priv:
8003
+ return (None, priv, priv)
8004
+ if denyset:
8005
+ low = {d.lower() for d in denyset}
8006
+ for c, e in effects:
8007
+ if e["program"] and names(c, e) & (set(denyset) | low):
8008
+ msg = f"'{c['argv'][0]}' is on your blocked-commands list"
8009
+ return (None, msg, msg)
8010
+ # Deletes and writes outside the project, following Set-Location the way PowerShell will.
8011
+ cur = wd
8012
+ for c, e in effects:
8013
+ is_top = any(c is t for t in top)
8014
+ if is_top and e["program"] in ("set-location", "push-location") and c["sep"] != "|":
8015
+ _, pos, _ = gp.ps_bound(c["argv"])
8016
+ if pos:
8017
+ p = _ps_native_paths(pos[:1], cur)[0]
8018
+ cur = os.path.normpath(os.path.join(cur or os.getcwd(), p))
8019
+ continue
8020
+ here = cur if is_top else wd
8021
+ why = None
8022
+ if e["deletes"]:
8023
+ why = _ws_delete_outside_reason(["rm"] + _ps_native_paths(e["deletes"], here), here, roots)
8024
+ if not why and e["writes"]:
8025
+ why = _ws_write_outside_reason([(">", t) for t in _ps_native_paths(e["writes"], here)],
8026
+ here, roots)
8027
+ if why:
8028
+ return (None, why, why)
8029
+ # Text run as code.
8030
+ for k, c in enumerate(top):
8031
+ e = gp.ps_effects(c)
8032
+ if c["sep"] == "|" and e["program"] in gp.PS_INTERPRETERS \
8033
+ and all(x.startswith("-") for x in c["argv"][1:]):
8034
+ # Upstream of this stage, back to the pipeline's start: only a literal string = the
8035
+ # code is in the line itself (a heredoc). Anything else feeds it unseen text.
8036
+ j = k
8037
+ while j > 0 and top[j]["sep"] == "|":
8038
+ j -= 1
8039
+ if not all(gp.ps_is_literal(x) for x in top[j:k]):
8040
+ msg = f"it pipes text into {c['argv'][0]}, which runs that text as code"
8041
+ return (None, msg, msg)
8042
+ for c, e in effects:
8043
+ if e["runs_text"]:
8044
+ return (None, None, f"it runs text as code ({e['runs_text']})")
8045
+ if e["dynamic"]:
8046
+ return (None, None, f"the program to run is only known at run time ({c['argv'][0][:40]})")
8047
+ for c, e in effects:
8048
+ if e["destructive"] or _WS_DESTRUCTIVE_RE.search(" ".join(c["argv"])):
8049
+ return (None, None, "a destructive command (deletes files / wipes disk / powers off)")
8050
+ return (None, None, None)
8051
+
8052
+
7936
8053
  def _with_attribution_text(command, scan, settings):
7937
8054
  """_with_attribution for a SHELL line: the co-author trailer is inserted into the text right
7938
8055
  after each top-level `git … commit` word. → (command, note). A gh pr create body written as a
@@ -7940,7 +8057,7 @@ def _with_attribution_text(command, scan, settings):
7940
8057
  import shlex as _shlex
7941
8058
  name = str(settings.get("name") or "").strip()
7942
8059
  email = str(settings.get("email") or "").strip()
7943
- cmds = _shell_commands(scan["tokens"])
8060
+ cmds = scan["commands"] if "commands" in scan else _shell_commands(scan["tokens"])
7944
8061
  notes = []
7945
8062
  if settings.get("commit") and name and email and email.lower() not in command.lower():
7946
8063
  at = []
@@ -7990,30 +8107,79 @@ def _git_bash_path(env=None, which=None, isfile=None):
7990
8107
  return ""
7991
8108
 
7992
8109
 
8110
+ _RUN_SHELL_KIND = None
8111
+
8112
+
8113
+ def _pwsh_path(env=None, which=None, isfile=None):
8114
+ """PowerShell for run_command, or "". PURE given its lookups (tested off Windows).
8115
+
8116
+ GU_PWSH_PATH first; then PowerShell 7 (`pwsh`), which has && and || of its own; then Windows
8117
+ PowerShell 5.1, which every Windows 10/11 has — gu supplies && and || there itself."""
8118
+ import ntpath
8119
+ import shutil as _sh
8120
+ env = os.environ if env is None else env
8121
+ which = which or _sh.which
8122
+ isfile = isfile or os.path.isfile
8123
+ if env.get("GU_PWSH_PATH") and isfile(env["GU_PWSH_PATH"]):
8124
+ return env["GU_PWSH_PATH"]
8125
+ for name in ("pwsh", "powershell"):
8126
+ p = which(name) or ""
8127
+ if p and "\\windowsapps\\" not in p.lower(): # never a Store alias stub
8128
+ return p
8129
+ root = env.get("SystemRoot") or env.get("SYSTEMROOT") or env.get("WINDIR") or ""
8130
+ if root:
8131
+ p = ntpath.join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
8132
+ if isfile(p):
8133
+ return p
8134
+ return ""
8135
+
8136
+
8137
+ def _run_shell_kind():
8138
+ """"bash" | "powershell" | "" — how run_command runs a line (see _run_shell_bin)."""
8139
+ _run_shell_bin()
8140
+ return _RUN_SHELL_KIND or ""
8141
+
8142
+
7993
8143
  def _run_shell_bin():
7994
- """The shell for run_command's shell lines: bash (else sh), Git Bash on Windows — or "" for
7995
- the argv-only path (Windows without Git for Windows, or GU_RUN_NO_SHELL=1, the way back if a
7996
- shell line ever misbehaves for a user)."""
7997
- global _RUN_SHELL_BIN
8144
+ """The shell for run_command (task #359; PowerShell #374): bash (else sh) on macOS/Linux;
8145
+ on Windows PowerShell, the way Claude Code does it there — Git Bash instead with
8146
+ GU_WINDOWS_SHELL=bash. "" = the argv-only path (GU_RUN_NO_SHELL=1, the way back if a shell
8147
+ line ever misbehaves for a user, or no shell found). GU_RUN_SHELL=powershell|bash picks one
8148
+ on any OS (how the PowerShell path is tested on a Mac)."""
8149
+ global _RUN_SHELL_BIN, _RUN_SHELL_KIND
7998
8150
  if os.environ.get("GU_RUN_NO_SHELL") == "1":
7999
8151
  return ""
8000
8152
  if _RUN_SHELL_BIN is None:
8001
- if os.name == "nt":
8002
- _RUN_SHELL_BIN = _git_bash_path()
8003
- _log("run_command shell: " + ("Git Bash" if _RUN_SHELL_BIN else
8004
- "none (Git for Windows not found) — commands run without a shell"))
8153
+ import shutil as _sh
8154
+ want = (os.environ.get("GU_RUN_SHELL") or "").strip().lower()
8155
+ if not want:
8156
+ want = ("bash" if (os.environ.get("GU_WINDOWS_SHELL") or "").strip().lower() == "bash"
8157
+ else "powershell") if os.name == "nt" else "bash"
8158
+ if want == "powershell":
8159
+ _RUN_SHELL_BIN, _RUN_SHELL_KIND = _pwsh_path(), "powershell"
8160
+ if not _RUN_SHELL_BIN and os.name == "nt":
8161
+ _RUN_SHELL_BIN, _RUN_SHELL_KIND = _git_bash_path(), "bash"
8162
+ elif os.name == "nt":
8163
+ _RUN_SHELL_BIN, _RUN_SHELL_KIND = _git_bash_path(), "bash"
8164
+ if not _RUN_SHELL_BIN:
8165
+ _RUN_SHELL_BIN, _RUN_SHELL_KIND = _pwsh_path(), "powershell"
8005
8166
  else:
8006
- import shutil as _sh
8007
- _RUN_SHELL_BIN = next((p for p in (_sh.which("bash"), "/bin/bash", "/bin/sh")
8008
- if p and os.path.exists(p)), "")
8167
+ _RUN_SHELL_BIN, _RUN_SHELL_KIND = next(
8168
+ (p for p in (_sh.which("bash"), "/bin/bash", "/bin/sh") if p and os.path.exists(p)), ""), "bash"
8169
+ if not _RUN_SHELL_BIN:
8170
+ _RUN_SHELL_KIND = ""
8171
+ _log("run_command shell: " + ({"powershell": "PowerShell", "bash": "bash"}.get(_RUN_SHELL_KIND, "none")
8172
+ + (f" ({_RUN_SHELL_BIN})" if _RUN_SHELL_BIN else " — commands run without a shell")))
8009
8173
  return _RUN_SHELL_BIN
8010
8174
 
8011
8175
 
8012
- def _run_command_prompt_line(shell, windows=None):
8176
+ def _run_command_prompt_line(shell, windows=None, kind=None):
8013
8177
  """The system prompt's run_command rule. With a shell it carries the git and GitHub recipes,
8014
8178
  the way Claude Code's Bash tool description does: told how to batch, the model does (#359).
8015
- On Windows the shell is Git Bash, and the line says what differs there."""
8179
+ On Windows the shell is PowerShell (#374) — or Git Bash, and the line says what differs there."""
8016
8180
  windows = (os.name == "nt") if windows is None else windows
8181
+ if shell and kind == "powershell":
8182
+ return _PS_PROMPT_LINE + _BG_LINE
8017
8183
  if not shell:
8018
8184
  return (
8019
8185
  " run_command CHAINS: put dependent commands in ONE call with && — e.g. "
@@ -8052,6 +8218,37 @@ def _run_command_prompt_line(shell, windows=None):
8052
8218
  "RUNNING — stop_server closes it. " + _BG_LINE)
8053
8219
 
8054
8220
 
8221
+ # The run_command rule when the shell is PowerShell (#374) — Claude Code's PowerShell tool, in gu's
8222
+ # words: the same recipes as the bash line, written the PowerShell way.
8223
+ _PS_PROMPT_LINE = (
8224
+ " run_command IS POWERSHELL (Windows), and it KEEPS its folder and $env: variables from one "
8225
+ "call to the next in this turn (`cd sub`, then `npm test` runs in sub; an explicit workdir "
8226
+ "wins). Write PowerShell, not bash: pipes `|`, `;`, `&&`, `||`, redirects (`> out.txt`, "
8227
+ "`2>&1`), `$env:NAME = 'x'` (not export), cmdlets (Get-ChildItem, Select-String, "
8228
+ "Get-Content -Tail 40, Remove-Item -Recurse), `$LASTEXITCODE`. Put a whole sequence in ONE call "
8229
+ "(e.g. `cd app && npm test 2>&1 | Select-Object -Last 40`); a multi-line command goes in a "
8230
+ "triple-quoted string. A program path with spaces needs the call operator: "
8231
+ "`& 'C:\\Program Files\\x\\x.exe' args`. Python is `py -3` or `python`, not python3.\n"
8232
+ " MULTI-LINE TEXT is a here-string: `@'` ends its line, the text follows, and `'@` STARTS "
8233
+ "the closing line; nothing inside needs escaping.\n"
8234
+ " GIT in one call each: look (`git status -sb; git diff --stat; git log --oneline -5`), "
8235
+ "commit (`git add a.py b.py; if ($?) { git commit -m \"msg\" }` or with a here-string: "
8236
+ "`@'` newline message newline `'@ | git commit -F -`).\n"
8237
+ " GITHUB: use `gh`. A multi-line body goes as a here-string on stdin — `@'` … `'@ | gh issue "
8238
+ "comment 12 --body-file -` (same for gh issue create / gh pr create) — never write a body file "
8239
+ "first, and do not run `gh auth status` first.\n"
8240
+ " CHECKS: a Python/Node script goes as a here-string piped in — `@'` … `'@ | py -3 -` (node: "
8241
+ "`| node --input-type=module -`). To check one function, load its module and call it with real "
8242
+ "input instead of running the app. Order: syntax check → the ONE test → the suite once. Test "
8243
+ "output arrives with a TEST SUMMARY of each failure first, so never pipe it into "
8244
+ "Select-Object/Select-String (a pipe hides the exit code).\n"
8245
+ " Read and search FILES with read_file_lines / grep_repo, not Get-Content/Select-String. "
8246
+ "Elevation (Start-Process -Verb RunAs, runas, sudo) is blocked; Invoke-Expression, piping "
8247
+ "into an interpreter, and writing or deleting outside the project ask the user first; never "
8248
+ "end a line with `&` (a background job). An interactive prompt (Read-Host) fails. A server "
8249
+ "or GUI app is left RUNNING — stop_server closes it. ")
8250
+
8251
+
8055
8252
  # THE BROWSER (task #363, GitHub #144): a real Chrome the agent drives through the gu extension.
8056
8253
  # Offered only where commands may run (the terminal's own folders, never the web app's scratch one)
8057
8254
  # and node can start the bridge. GU_BROWSER=0 turns it off.
@@ -8098,7 +8295,8 @@ _HEREDOC_HINT = ("\n\nSHELL QUOTING broke this line. For text with quotes or lin
8098
8295
  _PIPE_FAIL_RE = re.compile(
8099
8296
  r"^.*(?:No module named \S+|ModuleNotFoundError: .*|: command not found|: not found$"
8100
8297
  r"|^Traceback \(most recent call last\):|^fatal: .*|^error: .*|^npm ERR! .*"
8101
- r"|^E: Unable to locate package .*|: No such file or directory$)",
8298
+ r"|^E: Unable to locate package .*|: No such file or directory$"
8299
+ r"|is not recognized as (?:the |a )?name of a cmdlet.*)",
8102
8300
  re.M)
8103
8301
 
8104
8302
 
@@ -8110,12 +8308,12 @@ def _pipe_hidden_failure(scan, out: str) -> str:
8110
8308
  return m.group(0).strip()[:200] if m else ""
8111
8309
 
8112
8310
 
8113
- def _pipe_hidden_failure_note(line: str) -> str:
8311
+ def _pipe_hidden_failure_note(line: str, ps: bool = False) -> str:
8114
8312
  return ("\n\nWARNING — A FAILURE WAS HIDDEN BY A PIPE: the output shows "
8115
8313
  f"'{line}', but a pipeline reports only its LAST command's exit code, so this "
8116
8314
  "line counted as success and every part after `&&` RAN ANYWAY. Check what those "
8117
- "parts did before relying on them. To chain on a check, run it without a pipe, or "
8118
- "start the line with `set -o pipefail;`.")
8315
+ "parts did before relying on them. To chain on a check, run it without a pipe"
8316
+ + ("." if ps else ", or start the line with `set -o pipefail;`."))
8119
8317
 
8120
8318
 
8121
8319
  # THE PROJECT'S OWN TEST COMMANDS (#360 review). The model guessed `python3 -m pytest` in a repo
@@ -8218,7 +8416,18 @@ _SHELL_QUOTE_ERR_RE = re.compile(
8218
8416
  r"unexpected EOF while looking for matching|syntax error near unexpected token|"
8219
8417
  r"syntax error: unexpected end of file|unterminated quoted string")
8220
8418
 
8419
+ # PowerShell's words for a line it could not parse (#374), and the form that has nothing to quote.
8420
+ _PS_QUOTE_ERR_RE = re.compile(
8421
+ r"string is missing the terminator|Missing closing|Unexpected token|missing the closing|"
8422
+ r"ParserError|Missing (?:argument|expression)")
8423
+ _PS_HEREDOC_HINT = ("\n\nQUOTING broke this line. For text with quotes or line breaks (a commit "
8424
+ "message, an issue body) use a here-string inside a triple-quoted string: "
8425
+ "run_command(\"\"\"@'\n<message>\n'@ | git commit -F -\"\"\") — `'@` must start "
8426
+ "its line, and nothing in the message needs escaping.")
8427
+
8221
8428
  _RUN_DOC_ARGV = ("No other shell syntax (no pipes/redirects/;). sudo/su are blocked.")
8429
+ _RUN_DOC_PS = ("It runs in PowerShell, so pipes, ;, &&, ||, redirects, cmdlets and here-strings "
8430
+ "work too (e.g. 'npm test 2>&1 | Select-Object -Last 40'). Elevation is blocked.")
8222
8431
  _RUN_DOC_SHELL = ("It runs in bash, so pipes, redirects, ;, ||, $( ), globs and heredocs work too "
8223
8432
  "(e.g. 'npm test 2>&1 | tail -40'). sudo/su are blocked.")
8224
8433
 
@@ -9458,7 +9667,8 @@ def _shells_finished_note(shells: list, now=None) -> str:
9458
9667
  s["announced"] = True
9459
9668
  note = (f"[background shell {s.get('id')} finished: {_shell_status_text(st)} after "
9460
9669
  f"{_fmt_runtime(st['runtime'])} — '{_clip(str(s.get('command')), 120)}'. "
9461
- f"shell_output('{s.get('id')}') has its output.]")
9670
+ f"shell_output('{s.get('id')}') has its output. If it failed, find out why and fix it; "
9671
+ f"if it was a step of this task, carry on with the next one.]")
9462
9672
  try:
9463
9673
  with open(s.get("log") or "", encoding="utf-8", errors="replace") as fh:
9464
9674
  dg = _test_digest(fh.read(), str(s.get("workdir") or ""))
@@ -9532,7 +9742,7 @@ def _run_state_cwd() -> str:
9532
9742
  if not p:
9533
9743
  return ""
9534
9744
  try:
9535
- with open(p + ".cwd", encoding="utf-8") as fh:
9745
+ with open(p + ".cwd", encoding="utf-8-sig") as fh: # PowerShell 5.1 writes a BOM
9536
9746
  return fh.read().strip()
9537
9747
  except OSError:
9538
9748
  return ""
@@ -9572,7 +9782,9 @@ def _ws_scrubbed_env() -> dict:
9572
9782
  keep += ("SYSTEMROOT", "SystemDrive", "WINDIR", "COMSPEC", "PATHEXT", "USERPROFILE",
9573
9783
  "HOMEDRIVE", "HOMEPATH", "USERNAME", "APPDATA", "LOCALAPPDATA", "TEMP", "TMP",
9574
9784
  "ProgramFiles", "ProgramFiles(x86)", "ProgramW6432", "ProgramData",
9575
- "CommonProgramFiles", "NUMBER_OF_PROCESSORS", "PROCESSOR_ARCHITECTURE")
9785
+ "CommonProgramFiles", "NUMBER_OF_PROCESSORS", "PROCESSOR_ARCHITECTURE",
9786
+ # PowerShell finds its own modules (Microsoft.PowerShell.*) through it (#374).
9787
+ "PSModulePath")
9576
9788
  env = {k: os.environ[k] for k in keep if k in os.environ}
9577
9789
  # CI=1 makes watch-mode test runners (CRA's `npm test`, jest --watch) run ONCE and
9578
9790
  # exit instead of sitting in interactive watch mode until the timeout kills them.
@@ -10948,7 +11160,7 @@ def run_agent_chat(cfg):
10948
11160
  "and reads do not pile up here and are not re-sent on every later step. Then read only "
10949
11161
  "the exact ranges you will edit. Use grep_repo/read_file_lines directly when you already "
10950
11162
  "know the file or the exact string.\n"
10951
- + _run_command_prompt_line(bool(_run_shell_bin()))
11163
+ + _run_command_prompt_line(bool(_run_shell_bin()), kind=_run_shell_kind())
10952
11164
  + (_BROWSER_LINE if _browser_on() else "") +
10953
11165
  " DEPLOY: prefer deploy_web(local_dir, host, user, remote_path, domain) over "
10954
11166
  "hand-written scp/ssh/rsync (it rsyncs over your SSH key and finishes nginx when it "
@@ -14993,20 +15205,25 @@ def run_agent_chat(cfg):
14993
15205
  # A REAL SHELL WHEN THE LINE NEEDS ONE (task #359). Scanned BEFORE shlex.split,
14994
15206
  # which raises on a heredoc body with an apostrophe in it ("don't").
14995
15207
  _shell_bin = _run_shell_bin()
14996
- _scan = _shell_scan(command) if _shell_bin else None
15208
+ # PowerShell on Windows (#374): every line goes through it — a cmdlet is no program.
15209
+ _ps = bool(_shell_bin) and _run_shell_kind() == "powershell"
15210
+ _scan = (_ps_mod().ps_scan(command) if _ps else _shell_scan(command)) if _shell_bin else None
14997
15211
  if _scan and _scan["error"]:
14998
15212
  msg = (f"Error: that command did NOT run — {_scan['error']}. Nothing was "
14999
15213
  "executed; fix the quoting and send it again."
15000
- + (_HEREDOC_HINT if "quote" in str(_scan["error"]) else ""))
15214
+ + ((_PS_HEREDOC_HINT if _ps else _HEREDOC_HINT)
15215
+ if re.search(r"quote|here-string", str(_scan["error"])) else ""))
15001
15216
  _last_obs["text"] = msg
15002
15217
  return msg
15003
15218
  # Once this turn has shell state (a cd, an activated venv), every line goes through
15004
15219
  # the shell so it starts from that state — not only lines with shell syntax.
15005
- _words = [c["argv"][0] for c in _shell_commands(_scan["tokens"]) if c["argv"]] if _scan else []
15220
+ _words = [c["argv"][0] for c in _shell_commands(_scan["tokens"]) if c["argv"]] \
15221
+ if (_scan and not _ps) else []
15006
15222
  _builtin = sorted({w for w in _words if w in _SHELL_STATE_BUILTINS})
15007
- _use_shell = bool(_scan) and (_shell_needed(_scan) or bool(_builtin) or bool(
15223
+ _use_shell = bool(_scan) and (_ps or _shell_needed(_scan) or bool(_builtin) or bool(
15008
15224
  _RUN_STATE["path"] and os.path.exists(_RUN_STATE["path"])))
15009
- _bg_err = _shell_background_error(_scan) if _use_shell else None
15225
+ _bg_err = ((_ps_background_error(_scan) if _ps else _shell_background_error(_scan))
15226
+ if _use_shell else None)
15010
15227
  if _bg_err:
15011
15228
  _last_obs["text"] = _bg_err
15012
15229
  return _bg_err
@@ -15020,7 +15237,7 @@ def run_agent_chat(cfg):
15020
15237
  # the first failure stops the rest. `cd DIR` sets the folder for what follows.
15021
15238
  # A chain runs each part as a program; `export`/`source` in it would run nothing,
15022
15239
  # so with a shell such a line goes to bash whole. (`cd` the chain does itself.)
15023
- _chain = None if (_use_shell and [b for b in _builtin if b != "cd"]) \
15240
+ _chain = None if (_ps or (_use_shell and [b for b in _builtin if b != "cd"])) \
15024
15241
  else _and_chain_parts(command)
15025
15242
  if _chain:
15026
15243
  _chain_start = _t.time()
@@ -15084,7 +15301,13 @@ def run_agent_chat(cfg):
15084
15301
  # `/usr/bin/<x>` can't slip past a bare-name rule.
15085
15302
  _runner = argv[0]
15086
15303
  _rbase = os.path.basename(_runner)
15087
- if _use_shell:
15304
+ if _use_shell and _ps:
15305
+ _refuse, _hard_reason, _ask_reason = _ws_ps_command_risk(
15306
+ _scan, _WS_RUN_DENYLIST, wd, _WS_RUN_ALLOWLIST)
15307
+ if _refuse:
15308
+ _last_obs["text"] = _refuse
15309
+ return _refuse
15310
+ elif _use_shell:
15088
15311
  # Every simple command in the line, including those inside $( ), gets the
15089
15312
  # checks an argv command gets — allowlist, privilege, denylist, deletes —
15090
15313
  # plus the shell-only ones (redirect outside the project, `| sh`).
@@ -15122,7 +15345,8 @@ def run_agent_chat(cfg):
15122
15345
  # states it. "this needs root and sudo needs a password we cannot type" is a
15123
15346
  # different question from "sudo is passwordless here", and the user can only
15124
15347
  # answer the one they are shown.
15125
- _priv = _shell_priv_reason(_scan) if _use_shell else _ws_priv_reason(command)
15348
+ _priv = ((_ps_priv_reason(_scan) if _ps else _shell_priv_reason(_scan))
15349
+ if _use_shell else _ws_priv_reason(command))
15126
15350
  _facts = _ws_access_facts() if _priv else None
15127
15351
  if _priv and _facts and not _facts["can_elevate"]:
15128
15352
  # REFUSE BEFORE SPAWNING (requirement 5). With no tty, `sudo x` dies with
@@ -15186,7 +15410,24 @@ def run_agent_chat(cfg):
15186
15410
  exit_path = log_path[:-4] + ".exit"
15187
15411
  # gu as a co-author on the commits it makes (task #289) — after every check
15188
15412
  # above, which judged the command as the model wrote it.
15189
- if _use_shell:
15413
+ if _use_shell and _ps:
15414
+ # PowerShell (#374): the line, sequenced (&& / || for 5.1, the exit status
15415
+ # kept), in a file the wrapper dot-sources — no quoting crosses a command
15416
+ # line — and the wrapper keeps the exit code, folder and $env: changes.
15417
+ _gp = _ps_mod()
15418
+ _cmd_text, _attrib_note = _with_attribution_text(
15419
+ command, dict(_scan, commands=_gp.ps_commands(_scan["tokens"])),
15420
+ _attribution_settings(wd))
15421
+ _ps_cmd = log_path[:-4] + ".cmd.ps1"
15422
+ _ps_wrap = log_path[:-4] + ".ps1"
15423
+ with open(_ps_cmd, "w", encoding="utf-8") as _fh:
15424
+ # Windows PowerShell 5.1 (powershell.exe) needs the 2>&1 care; pwsh 7 does not.
15425
+ _fh.write(_gp.ps_sequence(_cmd_text, legacy=os.path.basename(
15426
+ _shell_bin).lower().startswith("powershell")))
15427
+ with open(_ps_wrap, "w", encoding="utf-8-sig") as _fh: # 5.1 reads a BOM-less file as ANSI
15428
+ _fh.write(_gp.ps_wrapper(_ps_cmd, exit_path, _run_state_path()))
15429
+ argv = _gp.ps_argv(_shell_bin, _ps_wrap)
15430
+ elif _use_shell:
15190
15431
  _cmd_text, _attrib_note = _with_attribution_text(
15191
15432
  command, _scan, _attribution_settings(wd))
15192
15433
  # The exit code is written to a file so it outlives this turn's process, and
@@ -15287,11 +15528,11 @@ def run_agent_chat(cfg):
15287
15528
  # triple-quoted string has no quoting to get wrong.
15288
15529
  _hidden = _pipe_hidden_failure(_scan, out) if (rc == 0 and _use_shell) else ""
15289
15530
  if _hidden:
15290
- result += _pipe_hidden_failure_note(_hidden)
15531
+ result += _pipe_hidden_failure_note(_hidden, ps=_ps)
15291
15532
  _emit({"type": "step", "text":
15292
15533
  f"Command failed behind a pipe → {_trim_words(_hidden)}"})
15293
- if rc != 0 and _use_shell and _SHELL_QUOTE_ERR_RE.search(out or ""):
15294
- result += _HEREDOC_HINT
15534
+ if rc != 0 and _use_shell and (_PS_QUOTE_ERR_RE if _ps else _SHELL_QUOTE_ERR_RE).search(out or ""):
15535
+ result += _PS_HEREDOC_HINT if _ps else _HEREDOC_HINT
15295
15536
  # Say where the shell now is, so a next `cd sub` is not done twice (#362).
15296
15537
  _now = _run_state_cwd() if _use_shell else ""
15297
15538
  if _now and os.path.realpath(_now) != os.path.realpath(wd):
@@ -15386,7 +15627,8 @@ def run_agent_chat(cfg):
15386
15627
  # bash here (Git Bash on Windows), argv when there is none (#359). Set before tool() reads
15387
15628
  # the docstring.
15388
15629
  if _run_shell_bin():
15389
- run_command.__doc__ = run_command.__doc__.replace(_RUN_DOC_ARGV, _RUN_DOC_SHELL)
15630
+ run_command.__doc__ = run_command.__doc__.replace(
15631
+ _RUN_DOC_ARGV, _RUN_DOC_PS if _run_shell_kind() == "powershell" else _RUN_DOC_SHELL)
15390
15632
  run_command = tool(run_command)
15391
15633
 
15392
15634
  @tool
package/gu-cli.mjs CHANGED
@@ -139,7 +139,7 @@ Usage:
139
139
  gu-cli workspace revert [runId] # undo an agent run's file edits from its backups
140
140
  gu-cli mongo migrate-from-docker # macOS: move a Docker MongoDB to native (Homebrew)
141
141
  gu-cli clear [--scratch|--keep-history] [--yes] # back to a fresh machine (asks first)
142
- gu-cli fix-path # macOS/Linux: put npm's global bin folder on PATH
142
+ gu-cli fix-path [--check] # put npm's global folder on PATH (Windows: check, then ask)
143
143
  # (what the install does, if npm skipped it)
144
144
  gu-cli fix-powershell [--check] # Windows: drop PowerShell's built-in \`gu\` alias
145
145
  # (it is Get-Unique and shadows this CLI)
@@ -1068,8 +1068,39 @@ if (args[0] === "token-usage" || args[0] === "tokens") {
1068
1068
  // prefix worked out from where this file is installed, so there is one implementation.
1069
1069
  if (args[0] === "fix-path") {
1070
1070
  if (process.platform === "win32") {
1071
- console.log(" Nothing to fix here — on Windows npm's folder is on PATH through the registry.");
1072
- console.log(" If `gu` is not found in PowerShell: gu-cli fix-powershell");
1071
+ // #375 (GitHub #156): Windows keeps PATH in the registry — check the SAVED one (what a new
1072
+ // terminal reads), say what to do the way the installer does, and add it only on a yes.
1073
+ const wp = await import("./win-path.mjs");
1074
+ const { fileURLToPath } = await import("node:url");
1075
+ const { dirname, join } = await import("node:path");
1076
+ const { readFileSync } = await import("node:fs");
1077
+ const here = dirname(fileURLToPath(import.meta.url));
1078
+ const dir = wp.windowsPrefixOf(here) || String(process.env.npm_config_prefix || "");
1079
+ if (!dir) {
1080
+ console.log(` gu is not installed globally with npm (${here}) — there is no PATH to fix.`);
1081
+ console.log(" Install it with: irm https://gu.getmarsic.cc/install.ps1 | iex");
1082
+ process.exit(0);
1083
+ }
1084
+ let version = "?";
1085
+ try { version = JSON.parse(readFileSync(join(here, "package.json"), "utf8")).version; } catch { /* shown as ? */ }
1086
+ const saved = wp.readSavedPaths();
1087
+ const status = wp.pathStatus({ dir, sessionPath: process.env.Path || process.env.PATH || "", ...saved });
1088
+ const psHost = Boolean(process.env.PSModulePath) && !process.env.PROMPT; // cmd.exe sets PROMPT
1089
+ let summary = wp.installSummary({ version, location: wp.guLocation(dir), dir, status, powershell: psHost });
1090
+ if (!status.saved && !args.includes("--check") && process.stdin.isTTY) {
1091
+ const { createInterface } = await import("node:readline/promises");
1092
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
1093
+ const answer = (await rl.question(` Add ${dir} to your user PATH now? [Y/n] `)).trim().toLowerCase();
1094
+ rl.close();
1095
+ if (answer === "" || answer === "y" || answer === "yes") {
1096
+ const r = wp.addToUserPath(dir);
1097
+ if (r.ok) {
1098
+ console.log(" Added. Open a new terminal and gu is there.");
1099
+ summary = wp.installSummary({ version, location: wp.guLocation(dir), dir, status: { saved: true, session: status.session }, powershell: psHost });
1100
+ } else console.log(` Could not change PATH: ${r.error || "PowerShell refused"}`);
1101
+ }
1102
+ }
1103
+ console.log(wp.formatSummary(summary, { color: Boolean(process.stdout.isTTY) }).replace(/^/gm, " "));
1073
1104
  process.exit(0);
1074
1105
  }
1075
1106
  const { fixPathPrefix } = await import("./install-path.mjs");