@yasaswy.nagavolu/agents 0.24.0 → 0.25.0

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.
@@ -540,6 +540,11 @@
540
540
  "path": "proxy/git_shell_parse.py",
541
541
  "kind": "hook",
542
542
  "note": "Shared shell-command parsing helpers imported by execution_worker_review_gate.py (without it that hook dies with ModuleNotFoundError on every Bash call) — not wired to an event itself. Also claimed by self-infra; safe to double-claim."
543
+ },
544
+ {
545
+ "path": "proxy/shell_parse.py",
546
+ "kind": "hook",
547
+ "note": "Generic parsing layer git_shell_parse.py imports from (task #73) — without it git_shell_parse.py dies with ModuleNotFoundError on every Bash call. Not wired to an event itself. Also claimed by self-infra; safe to double-claim."
543
548
  }
544
549
  ],
545
550
  "deps": [
@@ -782,6 +787,11 @@
782
787
  "kind": "infra",
783
788
  "note": "Registered PreToolUse Bash hook in settings.json, unscoped like publish_guard.py — blocks credential mutation/exposure for main session and every subagent."
784
789
  },
790
+ {
791
+ "path": "proxy/shell_parse.py",
792
+ "kind": "hook",
793
+ "note": "Shared, project-agnostic shell-command parsing helpers (task #73), imported by credential_mutation_guard.py for heredoc-body stripping — not wired to an event itself. Also claimed by agent-orchestration and self-infra; safe to double-claim."
794
+ },
785
795
  {
786
796
  "path": "proxy/headless_spawn_guard.py",
787
797
  "kind": "infra",
@@ -932,6 +942,11 @@
932
942
  "kind": "hook",
933
943
  "note": "Shared, project-agnostic shell-command parsing helpers (quote/heredoc/substitution-aware segment split, cd tracking, MSYS path normalization) — not wired to an event itself. Used by shared_worktree_revert_guard.py."
934
944
  },
945
+ {
946
+ "path": "proxy/shell_parse.py",
947
+ "kind": "hook",
948
+ "note": "Generic parsing layer git_shell_parse.py imports from (task #73), and imported directly by credential_mutation_guard.py for heredoc-body stripping — not wired to an event itself."
949
+ },
935
950
  {
936
951
  "path": "proxy/shared_worktree_revert_guard.py",
937
952
  "kind": "hook",
@@ -1305,6 +1320,11 @@
1305
1320
  "path": "proxy/git_shell_parse.py",
1306
1321
  "kind": "hook",
1307
1322
  "note": "Shared, project-agnostic shell-command parsing helpers (quote/heredoc/substitution-aware segment split) used by resolve_policy_guard.py to split Bash/PowerShell commands before scanning them — not wired to an event itself. Also claimed by agent-orchestration and self-infra; safe to double-claim."
1323
+ },
1324
+ {
1325
+ "path": "proxy/shell_parse.py",
1326
+ "kind": "hook",
1327
+ "note": "Generic parsing layer git_shell_parse.py imports from (task #73) — not wired to an event itself. Also claimed by self-infra; safe to double-claim."
1308
1328
  }
1309
1329
  ],
1310
1330
  "deps": [],
@@ -218,6 +218,15 @@ import json
218
218
  import re
219
219
  import shlex
220
220
 
221
+ from shell_parse import (
222
+ binary_name,
223
+ is_shell_like_binary,
224
+ strip_command_timeout_prefix,
225
+ strip_heredoc_bodies,
226
+ strip_quotes,
227
+ unwind_shell_wrapper,
228
+ )
229
+
221
230
  _SHELL_OPERATORS = {"&&", "||", "|", "&", ";", "(", ")", "<", "<<", ">", ">>"}
222
231
 
223
232
  HTTP_TOOL = re.compile(r"\b(curl|wget|glab|Invoke-RestMethod|Invoke-WebRequest|iwr|irm)\b", re.I)
@@ -377,10 +386,14 @@ def _split_glued_punctuation(cmd: str) -> str:
377
386
 
378
387
  def _preprocess(cmd: str) -> str:
379
388
  """Shared normalization pipeline for both `_segments` and
380
- `_env_segments`: real-newline-to-`;` normalization, then glued-
381
- punctuation splitting, then the existing backslash-to-forward-slash
382
- pass — in that order, all quote-aware."""
383
- return _split_glued_punctuation(_normalize_newlines(cmd).replace("\\", "/"))
389
+ `_env_segments`: heredoc-body stripping (shared
390
+ `shell_parse.strip_heredoc_bodies` — an inert heredoc body is DATA,
391
+ e.g. prose in a `cat <<'EOF' >> docs/notes.md` write that merely
392
+ mentions a guarded filename, and must never be scanned as if it were
393
+ command text), then real-newline-to-`;` normalization, then
394
+ glued-punctuation splitting, then the existing backslash-to-forward-
395
+ slash pass — in that order, all quote-aware."""
396
+ return _split_glued_punctuation(_normalize_newlines(strip_heredoc_bodies(cmd)).replace("\\", "/"))
384
397
 
385
398
 
386
399
  def _segments(cmd: str) -> list[str] | None:
@@ -490,11 +503,78 @@ _EGRESS_TOOL = re.compile(
490
503
  _REDIRECT_OPERATORS = {"<", "<<", ">", ">>"}
491
504
 
492
505
 
493
- def _env_segments(cmd: str) -> list[tuple[str, bool]] | None:
506
+ _CODE_INTERPRETER_NAMES = {"python", "python3", "python2", "perl", "ruby", "node", "nodejs", "php"}
507
+
508
+
509
+ def _is_code_reader(name: str) -> bool:
510
+ """True for a binary whose stdin/argument is executed as code, not
511
+ read as data — a shell (`is_shell_like_binary`) or a common scripting
512
+ interpreter. Used both for wrapper-argument unwinding (`bash -c ...`)
513
+ and for the "piped into a shell" shape (`echo ... | bash`), where the
514
+ PRECEDING segment's own output becomes code the reader executes."""
515
+ return is_shell_like_binary(name) or name in _CODE_INTERPRETER_NAMES
516
+
517
+
518
+ def _wrapper_expanded_tokens(tokens: list[str]) -> list[str]:
519
+ """Returns extra candidate words hidden inside a code-taking wrapper's
520
+ payload argument, so the file-operand check (`_env_file_touch`) can
521
+ still find a guarded filename that only appears once that payload is
522
+ treated as the real (executed) shell text it is — `bash -c 'cat
523
+ .env'`, `eval "cat .env"`, `python3 -c "open('.env').read()"`, `cmd /c
524
+ type .env` are all covered by `shell_parse.unwind_shell_wrapper`;
525
+ `su -c`, `ssh <host> <cmd>`, and `watch <cmd>` are not wrappers that
526
+ module recognizes (they don't re-parse as shell syntax), so they get
527
+ their own narrow handling here. Every extra word is ADDED to the
528
+ caller's token list, never REMOVES a token — this only widens what
529
+ counts as a possible file-operand, it never narrows the existing
530
+ per-token check, so it cannot reintroduce a prose false positive on
531
+ its own (prose tokens still never enter this function's wrapper-name
532
+ branches)."""
533
+ extra: list[str] = []
534
+ kind, payload = unwind_shell_wrapper(tokens)
535
+ if kind in ("string", "text") and payload:
536
+ extra.extend(str(payload).split())
537
+ elif kind == "tokens" and payload:
538
+ extra.extend(payload)
539
+
540
+ probe = strip_command_timeout_prefix(tokens)
541
+ if not probe:
542
+ return extra
543
+ name = binary_name(probe[0])
544
+ rest = probe[1:]
545
+
546
+ if name == "su":
547
+ for i, t in enumerate(rest):
548
+ if strip_quotes(t) == "-c" and i + 1 < len(rest):
549
+ extra.extend(strip_quotes(rest[i + 1]).split())
550
+ break
551
+
552
+ elif name == "ssh":
553
+ positionals = [t for t in rest if not strip_quotes(t).startswith("-")]
554
+ if len(positionals) >= 2:
555
+ host_idx = rest.index(positionals[0])
556
+ for t in rest[host_idx + 1 :]:
557
+ extra.extend(strip_quotes(t).split())
558
+
559
+ elif name == "watch":
560
+ i = 0
561
+ while i < len(rest) and strip_quotes(rest[i]).startswith("-"):
562
+ i += 1
563
+ for t in rest[i:]:
564
+ extra.extend(strip_quotes(t).split())
565
+
566
+ return extra
567
+
568
+
569
+ def _env_segments(cmd: str) -> list[tuple[str, bool, list[str]]] | None:
494
570
  """Like _segments(), but additionally tags each segment with whether it
495
571
  sits inside a real `$(...)` command substitution that is ALSO actually
496
572
  captured (in_subst=True) — the capture-vs-emission distinction the .env
497
- checks need. A bare `(cmd)` grouping subshell (no leading `$`) still
573
+ checks need — and with the segment's own raw shlex token list (task
574
+ #73: the file-operand check must run against real tokens, never a
575
+ whitespace re-split of the joined text, which would destroy the fact
576
+ that a quoted multi-word argument was one token, not several). A bare
577
+ `(cmd)` grouping subshell (no leading `$`) still
498
578
  writes straight to real stdout, so it is NOT treated as captured; nor
499
579
  is a `$(...)` whose surrounding text isn't a capture context (see
500
580
  _is_capture_pending). in_subst is True only when EVERY enclosing paren
@@ -521,15 +601,40 @@ def _env_segments(cmd: str) -> list[tuple[str, bool]] | None:
521
601
  except ValueError:
522
602
  return None
523
603
 
524
- segments: list[tuple[str, bool]] = []
604
+ segments: list[tuple[str, bool, list[str]]] = []
525
605
  current: list[str] = []
526
606
  subst_stack: list[bool] = [] # one entry per open paren; True = genuinely-captured "$(" substitution
527
607
  prev_tok = ""
528
608
 
609
+ pending_piped_to_code = False
610
+
529
611
  def flush() -> None:
612
+ nonlocal pending_piped_to_code
530
613
  if current:
531
614
  captured = bool(subst_stack) and all(subst_stack)
532
- segments.append((" ".join(current), captured))
615
+ # `tokens` preserves each shlex token's own boundary —
616
+ # `_env_file_touch`'s file-operand check must never re-derive
617
+ # tokens by whitespace-splitting the joined `" ".join(current)`
618
+ # text, because that destroys the fact that a quoted multi-word
619
+ # argument (a grep pattern, an echo message, a `--note` value)
620
+ # was ONE token, not several — re-splitting it can turn an
621
+ # innocuous word inside that phrase (`... in .env, ...`) into
622
+ # what looks like its own bare file-operand token.
623
+ #
624
+ # Two shapes of hidden operand still need MORE than the raw
625
+ # token list, though: `bash -c 'cat .env'` etc. hide it inside
626
+ # one wrapper-argument token that IS real, executed shell
627
+ # syntax, not prose — added via `_wrapper_expanded_tokens`.
628
+ # `echo "cat .env" | bash` hides it in a segment whose own
629
+ # stdout becomes the NEXT segment's executed code — added when
630
+ # `pending_piped_to_code` is set by the `|` handling below,
631
+ # right before this flush.
632
+ expanded = list(current) + _wrapper_expanded_tokens(current)
633
+ if pending_piped_to_code:
634
+ for t in current:
635
+ expanded.extend(strip_quotes(t).split())
636
+ segments.append((" ".join(current), captured, expanded))
637
+ pending_piped_to_code = False
533
638
 
534
639
  def poison_top() -> None:
535
640
  if subst_stack:
@@ -562,6 +667,8 @@ def _env_segments(cmd: str) -> list[tuple[str, bool]] | None:
562
667
  nxt = tokens[idx + 1] if idx + 1 < n_tokens else ""
563
668
  if _EGRESS_TOOL.match(nxt):
564
669
  poison_top()
670
+ if _is_code_reader(binary_name(strip_quotes(nxt))):
671
+ pending_piped_to_code = True
565
672
  flush()
566
673
  current.clear()
567
674
  elif tok in _SHELL_OPERATORS:
@@ -695,9 +802,29 @@ _ENV_EXPOSURE_MSG = (
695
802
  )
696
803
 
697
804
 
698
- def _env_file_touch(seg: str, in_subst: bool, parsed: bool) -> str | None:
699
- tokens = seg.split()
700
- if not any(_is_env_credential_path(tok) for tok in tokens):
805
+ def _env_file_touch(seg: str, in_subst: bool, parsed: bool, tokens: list[str] | None) -> str | None:
806
+ # Task #73: `tokens` is the segment's OWN raw shlex token list (one
807
+ # entry per real shell argument, quotes already consumed by shlex) when
808
+ # available — never `seg.split()`, which re-splits the joined text on
809
+ # whitespace and can turn one word INSIDE a quoted multi-word argument
810
+ # (a grep pattern, an echo message, a `--note` value) into what looks
811
+ # like its own bare `.env` file-operand token. `tokens` is None only on
812
+ # the unparsed/fail-closed path (`parsed=False`), where the `seg.split()`
813
+ # fallback is fine because that path denies unconditionally anyway.
814
+ check_tokens = list(tokens) if tokens is not None else seg.split()
815
+ # A DOUBLE-QUOTED `$(...)` (`echo "$(cat .env)"`) is one shlex token —
816
+ # quoting hides the substitution from the `(`/`)` operator handling in
817
+ # `_env_segments`, so the whole `$(cat .env)` text survives as a single
818
+ # token instead of being walked into its own paren level. That token IS
819
+ # real shell syntax (a substitution, still executed), unlike a plain
820
+ # prose token — so it additionally gets word-split and re-checked, but
821
+ # ONLY when it actually contains `$(`/backtick syntax; an ordinary
822
+ # multi-word prose token (a grep pattern, an echo message, a `--note`
823
+ # value) never does, so it is never word-split and stays exempt.
824
+ for tok in list(check_tokens):
825
+ if "$(" in tok or "`" in tok:
826
+ check_tokens.extend(tok.split())
827
+ if not any(_is_env_credential_path(tok) for tok in check_tokens):
701
828
  return None
702
829
 
703
830
  if not parsed:
@@ -758,8 +885,17 @@ def _safe_main() -> None:
758
885
  if not cmd.strip():
759
886
  return
760
887
 
761
- # .env credential-literal write check — whole-command scan (see comment above).
762
- if ENV_REDIRECT_TARGET.search(cmd) and CRED_LITERAL.search(cmd):
888
+ # .env credential-literal write check — whole-command scan (see comment
889
+ # above). ENV_REDIRECT_TARGET runs on the heredoc-body-stripped text: a
890
+ # heredoc write whose PROSE merely mentions a redirect-looking ".env"
891
+ # string must never trip this on its own. CRED_LITERAL runs on the
892
+ # RAW, unstripped `cmd`: the redirect target match already proves a
893
+ # real `.env`-shaped write exists in the
894
+ # command, so the literal-shape check must not depend on
895
+ # `strip_heredoc_bodies` also being correct for this exact command —
896
+ # any literal actually present in `cmd` is real regardless of what
897
+ # heredoc handling did or didn't do to a copy of the text.
898
+ if ENV_REDIRECT_TARGET.search(strip_heredoc_bodies(cmd)) and CRED_LITERAL.search(cmd):
763
899
  _deny(
764
900
  "Blocked by code-is-law (credential-mutation-guard). This command writes a "
765
901
  "live-looking credential literal into a .env-shaped file. Credentials must "
@@ -785,10 +921,10 @@ def _safe_main() -> None:
785
921
  # segment, never granted the substitution exemption.
786
922
  env_segments = _env_segments(cmd)
787
923
  env_parsed = env_segments is not None
788
- env_seg_texts = env_segments if env_parsed else [(cmd, False)]
924
+ env_seg_texts = env_segments if env_parsed else [(cmd, False, None)]
789
925
 
790
- for seg, in_subst in env_seg_texts:
791
- reason = _env_file_touch(seg, in_subst, env_parsed)
926
+ for seg, in_subst, seg_tokens in env_seg_texts:
927
+ reason = _env_file_touch(seg, in_subst, env_parsed, seg_tokens)
792
928
  if reason:
793
929
  _deny(reason)
794
930
  return