langstage-cli 0.6.48__tar.gz → 0.6.50__tar.gz

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.
Files changed (79) hide show
  1. {langstage_cli-0.6.48/langstage_cli.egg-info → langstage_cli-0.6.50}/PKG-INFO +6 -2
  2. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/README.md +5 -1
  3. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/langstage_cli/cli.py +212 -25
  4. {langstage_cli-0.6.48 → langstage_cli-0.6.50/langstage_cli.egg-info}/PKG-INFO +6 -2
  5. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/langstage_cli.egg-info/SOURCES.txt +2 -0
  6. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/pyproject.toml +1 -1
  7. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_approval_menu_abort.py +9 -6
  8. langstage_cli-0.6.50/tests/test_custom_decision_195.py +275 -0
  9. langstage_cli-0.6.50/tests/test_menu_allowed_197.py +184 -0
  10. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/LICENSE +0 -0
  11. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/deepagent_code/__init__.py +0 -0
  12. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/langstage_cli/__init__.py +0 -0
  13. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/langstage_cli/agui_stream.py +0 -0
  14. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/langstage_cli/config.py +0 -0
  15. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/langstage_cli/exit_codes.py +0 -0
  16. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/langstage_cli/sessions.py +0 -0
  17. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/langstage_cli.egg-info/dependency_links.txt +0 -0
  18. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/langstage_cli.egg-info/entry_points.txt +0 -0
  19. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/langstage_cli.egg-info/requires.txt +0 -0
  20. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/langstage_cli.egg-info/top_level.txt +0 -0
  21. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/setup.cfg +0 -0
  22. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_advertised_wave4.py +0 -0
  23. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_agui_stream.py +0 -0
  24. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_async_mode.py +0 -0
  25. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_checkpointer.py +0 -0
  26. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_cli.py +0 -0
  27. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_cli_help.py +0 -0
  28. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_codeconfig.py +0 -0
  29. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_config.py +0 -0
  30. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_config_command.py +0 -0
  31. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_configurable.py +0 -0
  32. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_ctrl_c_sync_tool.py +0 -0
  33. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_deferred_pass.py +0 -0
  34. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_dumb_term.py +0 -0
  35. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_exit_codes.py +0 -0
  36. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_generic_interrupt.py +0 -0
  37. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_help_render.py +0 -0
  38. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_hidden_option_suggestions.py +0 -0
  39. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_history_persist.py +0 -0
  40. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_hitl_approval_preview.py +0 -0
  41. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_hitl_resume_warning.py +0 -0
  42. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_init.py +0 -0
  43. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_interrupt_non_tty.py +0 -0
  44. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_legacy_config_home.py +0 -0
  45. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_load_error.py +0 -0
  46. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_message_boundaries.py +0 -0
  47. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_no_color.py +0 -0
  48. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_no_interactive_approve.py +0 -0
  49. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_no_persist_resume.py +0 -0
  50. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_paused_session_message.py +0 -0
  51. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_persist_env.py +0 -0
  52. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_quiet_output.py +0 -0
  53. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_reasoning_render.py +0 -0
  54. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_rename_shim.py +0 -0
  55. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_render_markdown.py +0 -0
  56. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_routine_1024.py +0 -0
  57. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_session_lifecycle.py +0 -0
  58. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_sessions.py +0 -0
  59. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_show_config.py +0 -0
  60. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_show_config_malformed.py +0 -0
  61. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_spec_loading_core.py +0 -0
  62. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_spec_resolution.py +0 -0
  63. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_spinner_reply_survives.py +0 -0
  64. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_stdin_interactive.py +0 -0
  65. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_stdin_single_shot.py +0 -0
  66. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_stream_mode.py +0 -0
  67. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_streaming_marker.py +0 -0
  68. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_terminal_width.py +0 -0
  69. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_toml_relative_paths.py +0 -0
  70. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_tool_card_args.py +0 -0
  71. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_tool_output_escape.py +0 -0
  72. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_turn_error_verbose.py +0 -0
  73. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_turn_exit_and_render.py +0 -0
  74. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_unicode_console.py +0 -0
  75. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_usage_hint_186.py +0 -0
  76. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_verbose_command.py +0 -0
  77. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_verify_flag.py +0 -0
  78. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_workspace.py +0 -0
  79. {langstage_cli-0.6.48 → langstage_cli-0.6.50}/tests/test_wrong_type_graph.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: langstage-cli
3
- Version: 0.6.48
3
+ Version: 0.6.50
4
4
  Summary: The terminal stage for your LangGraph agent — Claude Code-style CLI for any CompiledGraph
5
5
  Author-email: Kedar Dabhadkar <kdabhadk@gmail.com>
6
6
  License-Expression: MIT
@@ -176,6 +176,10 @@ without you baking a checkpointer into your own graph:
176
176
  - A session left paused at an approval (exit `2`) is resolved before a new message: the
177
177
  CLI says so, asks you (or auto-approves under `--no-interactive`), then sends your
178
178
  message. Without a terminal it exits `2` again and says the message was not sent.
179
+ - **Provide custom decision (JSON)** at the approval menu takes one decision for every
180
+ pending action, such as `{"type": "approve"}` or `{"type": "reject", "message": "why"}`
181
+ (a pasted `{"decisions": [...]}` list also works). The prompt shows the shapes the
182
+ pending tool allows, and a decision it would refuse is caught before anything is sent.
179
183
 
180
184
  State lives in `~/.langstage/sessions/<workspace-hash>.sqlite` (honoring
181
185
  `LANGSTAGE_CONFIG_HOME`; override the whole location with `LANGSTAGE_CLI_SESSIONS_DIR`).
@@ -338,7 +342,7 @@ approval menu you answer by typing a number.
338
342
  |---|---|
339
343
  | `0` | success: the turn completed, `--verify` passed, `init` wrote its files |
340
344
  | `1` | failure: no agent configured, the agent failed to load, the turn errored or produced nothing, `--verify` failed, `--resume` found no session, `init` refused to overwrite |
341
- | `2` | paused on a human-in-the-loop interrupt: an approval is needed but stdin is not a terminal, or you left the approval prompt with **Exit** or Ctrl-C. `--no-interactive` auto-approves instead |
345
+ | `2` | paused on a human-in-the-loop interrupt: an approval is needed but stdin is not a terminal, or you left the approval prompt with **Exit** or Ctrl-C. `--no-interactive` auto-approves instead, unless the pending action doesn't allow approve, which also exits `2` |
342
346
  | `64` | usage error: an unknown option or bad value, `--demo` with `-a`, `--continue` with `--resume`, `MESSAGE` with `-f`, an empty `MESSAGE` |
343
347
 
344
348
  ## Creating Your Own Agent
@@ -138,6 +138,10 @@ without you baking a checkpointer into your own graph:
138
138
  - A session left paused at an approval (exit `2`) is resolved before a new message: the
139
139
  CLI says so, asks you (or auto-approves under `--no-interactive`), then sends your
140
140
  message. Without a terminal it exits `2` again and says the message was not sent.
141
+ - **Provide custom decision (JSON)** at the approval menu takes one decision for every
142
+ pending action, such as `{"type": "approve"}` or `{"type": "reject", "message": "why"}`
143
+ (a pasted `{"decisions": [...]}` list also works). The prompt shows the shapes the
144
+ pending tool allows, and a decision it would refuse is caught before anything is sent.
141
145
 
142
146
  State lives in `~/.langstage/sessions/<workspace-hash>.sqlite` (honoring
143
147
  `LANGSTAGE_CONFIG_HOME`; override the whole location with `LANGSTAGE_CLI_SESSIONS_DIR`).
@@ -300,7 +304,7 @@ approval menu you answer by typing a number.
300
304
  |---|---|
301
305
  | `0` | success: the turn completed, `--verify` passed, `init` wrote its files |
302
306
  | `1` | failure: no agent configured, the agent failed to load, the turn errored or produced nothing, `--verify` failed, `--resume` found no session, `init` refused to overwrite |
303
- | `2` | paused on a human-in-the-loop interrupt: an approval is needed but stdin is not a terminal, or you left the approval prompt with **Exit** or Ctrl-C. `--no-interactive` auto-approves instead |
307
+ | `2` | paused on a human-in-the-loop interrupt: an approval is needed but stdin is not a terminal, or you left the approval prompt with **Exit** or Ctrl-C. `--no-interactive` auto-approves instead, unless the pending action doesn't allow approve, which also exits `2` |
304
308
  | `64` | usage error: an unknown option or bad value, `--demo` with `-a`, `--continue` with `--resume`, `MESSAGE` with `-f`, an empty `MESSAGE` |
305
309
 
306
310
  ## Creating Your Own Agent
@@ -1774,7 +1774,9 @@ def _prompt_line(prompt: str) -> str:
1774
1774
  signal.signal(signal.SIGINT, previous)
1775
1775
 
1776
1776
 
1777
- def handle_interrupt_input(num_actions: int = 1, is_generic: bool = False) -> Any:
1777
+ def handle_interrupt_input(
1778
+ num_actions: int = 1, is_generic: bool = False, interrupt: Optional[Dict[str, Any]] = None
1779
+ ) -> Any:
1778
1780
  """
1779
1781
  Handle user input for an interrupt using arrow key navigation, returning the
1780
1782
  value to resume the graph with (the resume payload).
@@ -1783,6 +1785,9 @@ def handle_interrupt_input(num_actions: int = 1, is_generic: bool = False) -> An
1783
1785
  num_actions: Number of pending tool calls that need decisions
1784
1786
  is_generic: True for a generic/scalar ``interrupt(value)`` (gh #99), False
1785
1787
  for a deepagents tool-REVIEW interrupt.
1788
+ interrupt: The interrupt frame's payload (``action_requests``,
1789
+ ``review_configs``, ``allowed_decisions``), used to check a custom decision
1790
+ before it is sent (gh #195).
1786
1791
 
1787
1792
  Returns:
1788
1793
  For a deepagents tool-review interrupt, a ``{"decisions": [...]}`` envelope
@@ -1828,27 +1833,28 @@ def handle_interrupt_input(num_actions: int = 1, is_generic: bool = False) -> An
1828
1833
  except json.JSONDecodeError:
1829
1834
  return raw
1830
1835
 
1831
- options = [
1832
- "Approve all actions",
1833
- "Reject all actions",
1834
- "Provide custom decision (JSON)",
1835
- "Exit",
1836
- ]
1836
+ # "Approve all" / "Reject all" are offered only when every pending action allows
1837
+ # that verb. They used to be offered always, so on HumanInTheLoopMiddleware(
1838
+ # allowed_decisions=["approve", "edit"]) "Reject all" sent a decision the
1839
+ # middleware refuses and the turn errored (gh #197).
1840
+ entries = []
1841
+ if _all_actions_allow("approve", num_actions, interrupt):
1842
+ entries.append(("Approve all actions", "approve"))
1843
+ if _all_actions_allow("reject", num_actions, interrupt):
1844
+ entries.append(("Reject all actions", "reject"))
1845
+ entries += [("Provide custom decision (JSON)", "custom"), ("Exit", "exit")]
1846
+ options = [label for label, _ in entries]
1837
1847
 
1838
1848
  while True:
1839
- choice = select_option(options, "How would you like to proceed?")
1840
-
1841
- if choice == 0:
1842
- # Approve decision for each pending action
1843
- return {"decisions": [{"type": "approve"} for _ in range(num_actions)]}
1844
- elif choice == 1:
1845
- # Reject decision for each pending action
1846
- return {"decisions": [{"type": "reject"} for _ in range(num_actions)]}
1847
- elif choice == 2:
1848
- decision = _prompt_custom_decision()
1849
- if decision is _BACK_TO_MENU:
1849
+ action = entries[select_option(options, "How would you like to proceed?")][1]
1850
+
1851
+ if action in ("approve", "reject"):
1852
+ return {"decisions": [{"type": action} for _ in range(num_actions)]}
1853
+ elif action == "custom":
1854
+ decisions = _prompt_custom_decision(num_actions, interrupt)
1855
+ if decisions is _BACK_TO_MENU:
1850
1856
  continue # nothing sent; show the menu again
1851
- return {"decisions": [decision for _ in range(num_actions)]}
1857
+ return {"decisions": decisions}
1852
1858
  else:
1853
1859
  sys.exit(EXIT_PAUSED) # left while paused on the interrupt (ADR 0007)
1854
1860
 
@@ -1871,23 +1877,157 @@ def _approval_input() -> str:
1871
1877
  sys.exit(EXIT_PAUSED)
1872
1878
 
1873
1879
 
1874
- def _prompt_custom_decision() -> Any:
1875
- """Read the "Provide custom decision (JSON)" answer.
1880
+ def _prompt_custom_decision(
1881
+ num_actions: int = 1, interrupt: Optional[Dict[str, Any]] = None
1882
+ ) -> Any:
1883
+ """Read the "Provide custom decision (JSON)" answer as a list of decisions.
1876
1884
 
1877
1885
  Invalid JSON shows the parse error and asks again. It used to send a reject for
1878
1886
  every pending action, so a typo while editing a call rejected it and resumed the
1879
- agent (gh #174). An empty line returns ``_BACK_TO_MENU`` and nothing is sent.
1887
+ agent (gh #174). A decision the interrupt would refuse is caught the same way:
1888
+ once LangGraph has a resume value for an interrupt, a failed resume keeps it and
1889
+ every later answer replays it, so it must be checked before it is sent (gh #195).
1890
+ An empty line returns ``_BACK_TO_MENU`` and nothing is sent.
1880
1891
  """
1881
- print("Enter your decision as JSON (will be applied to all actions):")
1892
+ print("Enter your decision as JSON (one decision is applied to all actions):")
1893
+ print(f"{DIM} {_decision_shapes(_allowed_verbs(interrupt, 0), interrupt)}{RESET}")
1882
1894
  print(f"{DIM}Press Enter on an empty line to go back to the menu.{RESET}")
1883
1895
  while True:
1884
1896
  json_str = _approval_input().strip()
1885
1897
  if not json_str:
1886
1898
  return _BACK_TO_MENU
1887
1899
  try:
1888
- return json.loads(json_str)
1900
+ value = json.loads(json_str)
1889
1901
  except json.JSONDecodeError as e:
1890
1902
  print(f"{RED}⏺ Invalid JSON: {e}. Nothing was sent; try again.{RESET}")
1903
+ continue
1904
+ decisions, problem = _check_custom_decision(value, num_actions, interrupt)
1905
+ if problem is None:
1906
+ return decisions
1907
+ print(f"{RED}⏺ {problem} Nothing was sent; try again.{RESET}")
1908
+
1909
+
1910
+ _FALLBACK_VERBS = ("approve", "edit", "reject", "respond")
1911
+
1912
+
1913
+ def _allowed_verbs(interrupt: Optional[Dict[str, Any]], index: int) -> List[str]:
1914
+ """The decision verbs the interrupt allows for its ``index``-th action.
1915
+
1916
+ LangChain's HumanInTheLoopMiddleware lists them per tool in ``review_configs``;
1917
+ core also puts the union on the frame as ``allowed_decisions``.
1918
+ """
1919
+ interrupt = interrupt if isinstance(interrupt, dict) else {}
1920
+ requests = interrupt.get("action_requests")
1921
+ configs = interrupt.get("review_configs")
1922
+ if isinstance(requests, list) and isinstance(configs, list) and index < len(requests):
1923
+ key = _tool_key(requests[index])
1924
+ name = requests[index].get(key) if key else None
1925
+ for rc in configs:
1926
+ if isinstance(rc, dict) and rc.get("action_name") == name:
1927
+ verbs = rc.get("allowed_decisions")
1928
+ if isinstance(verbs, list) and verbs:
1929
+ return [str(v) for v in verbs]
1930
+ verbs = interrupt.get("allowed_decisions")
1931
+ if isinstance(verbs, list) and verbs:
1932
+ return [str(v) for v in verbs]
1933
+ return list(_FALLBACK_VERBS)
1934
+
1935
+
1936
+ def _all_actions_allow(verb: str, num_actions: int, interrupt: Optional[Dict[str, Any]]) -> bool:
1937
+ """Whether every pending action allows ``verb`` (gh #197)."""
1938
+ from langstage_core import normalize_decision
1939
+
1940
+ return all(
1941
+ normalize_decision(verb, _allowed_verbs(interrupt, i)) == verb
1942
+ for i in range(max(num_actions, 1))
1943
+ )
1944
+
1945
+
1946
+ def _decision_shapes(allowed: List[str], interrupt: Optional[Dict[str, Any]] = None) -> str:
1947
+ """One line showing the JSON shape of each allowed decision.
1948
+
1949
+ The fields are LangChain HumanInTheLoopMiddleware's, so other interrupts get the
1950
+ bare ``{"type": ...}`` of each verb.
1951
+ """
1952
+ shapes = (
1953
+ {}
1954
+ if not _is_middleware_interrupt(interrupt)
1955
+ else {
1956
+ "approve": '{"type": "approve"}',
1957
+ "reject": '{"type": "reject", "message": "why"}',
1958
+ "respond": '{"type": "respond", "message": "reply"}',
1959
+ "edit": '{"type": "edit", "edited_action": {"name": "tool", "args": {...}}}',
1960
+ }
1961
+ )
1962
+ order = [v for v in _FALLBACK_VERBS if v in allowed] + [
1963
+ v for v in allowed if v not in _FALLBACK_VERBS
1964
+ ]
1965
+ return " | ".join(shapes.get(v, f'{{"type": "{v}"}}') for v in order)
1966
+
1967
+
1968
+ def _is_middleware_interrupt(interrupt: Optional[Dict[str, Any]]) -> bool:
1969
+ """Whether the interrupt is LangChain HumanInTheLoopMiddleware's (it has review_configs)."""
1970
+ configs = interrupt.get("review_configs") if isinstance(interrupt, dict) else None
1971
+ return isinstance(configs, list) and bool(configs)
1972
+
1973
+
1974
+ def _check_custom_decision(
1975
+ value: Any, num_actions: int, interrupt: Optional[Dict[str, Any]]
1976
+ ) -> Tuple[List[Any], Optional[str]]:
1977
+ """Check a typed custom decision against the pending interrupt (gh #195).
1978
+
1979
+ Returns ``(decisions, None)`` with one decision per pending action, or
1980
+ ``([], problem)`` naming what is wrong. One decision object applies to every
1981
+ action. A pasted ``{"decisions": [...]}`` envelope (or a bare list) is unwrapped
1982
+ and must hold one decision, or one per action.
1983
+ """
1984
+ from langstage_core import normalize_decision
1985
+
1986
+ if isinstance(value, dict) and "decisions" in value and "type" not in value:
1987
+ value = value["decisions"]
1988
+ if isinstance(value, list):
1989
+ if len(value) == 1:
1990
+ value = value * num_actions
1991
+ elif len(value) != num_actions:
1992
+ return [], (
1993
+ f"Got {len(value)} decisions for {num_actions} pending action(s); "
1994
+ "give one decision, or one per action."
1995
+ )
1996
+ items = value
1997
+ else:
1998
+ items = [value] * num_actions
1999
+
2000
+ # The edited_action / message fields are LangChain HumanInTheLoopMiddleware's
2001
+ # shape (its interrupts carry review_configs); other interrupts read their own.
2002
+ middleware = _is_middleware_interrupt(interrupt)
2003
+ for i, decision in enumerate(items):
2004
+ allowed = _allowed_verbs(interrupt, i)
2005
+ if not isinstance(decision, dict) or not isinstance(decision.get("type"), str):
2006
+ return [], (
2007
+ 'A decision is a JSON object with a "type", e.g. {"type": "approve"}; '
2008
+ f"allowed: {', '.join(allowed)}."
2009
+ )
2010
+ verb = normalize_decision(decision["type"], allowed)
2011
+ if verb is None:
2012
+ return [], (
2013
+ f"Decision type '{decision['type']}' is not allowed here; "
2014
+ f"allowed: {', '.join(allowed)}."
2015
+ )
2016
+ if not middleware:
2017
+ continue
2018
+ if verb == "edit":
2019
+ edited = decision.get("edited_action")
2020
+ if not (
2021
+ isinstance(edited, dict)
2022
+ and isinstance(edited.get("name"), str)
2023
+ and isinstance(edited.get("args"), dict)
2024
+ ):
2025
+ return [], 'An edit needs "edited_action": {"name": "<tool>", "args": {...}}.'
2026
+ elif verb == "respond" and not isinstance(decision.get("message"), str):
2027
+ return [], 'A respond decision needs a "message" string.'
2028
+ elif verb == "reject" and not isinstance(decision.get("message", ""), str):
2029
+ return [], 'The "message" of a reject decision must be a string.'
2030
+ return list(items), None
1891
2031
 
1892
2032
 
1893
2033
  def print_help():
@@ -2429,6 +2569,36 @@ async def _pending_interrupt(agent: Any, thread_id: str) -> bool:
2429
2569
  return any(getattr(task, "interrupts", None) for task in getattr(state, "tasks", ()) or ())
2430
2570
 
2431
2571
 
2572
+ async def _discard_failed_resume(agent: Any, thread_id: str) -> None:
2573
+ """Drop the answer a failed resume left on the thread, so the next one is used.
2574
+
2575
+ When resuming an interrupt raises (a decision the agent refused), LangGraph keeps
2576
+ that resume value on the checkpoint and replays it on every later resume, so the
2577
+ approval could never be answered again, even with ``-c`` (gh #195). The failed
2578
+ task still shows its interrupt and carries the error. A checkpoint with no new
2579
+ values drops the stale answer: the interrupted step runs again and takes the new
2580
+ one. If that isn't possible the stale answer stays, and the error says so again.
2581
+ """
2582
+ graph = getattr(agent, "graph", None)
2583
+ if not thread_id or graph is None or not hasattr(graph, "aupdate_state"):
2584
+ return
2585
+ config = {"configurable": {"thread_id": thread_id}}
2586
+ try:
2587
+ state = await graph.aget_state(config)
2588
+ except Exception: # noqa: BLE001 - no checkpointer / no state: nothing to clear
2589
+ return
2590
+ tasks = getattr(state, "tasks", ()) or ()
2591
+ if not any(getattr(t, "interrupts", None) and getattr(t, "error", None) for t in tasks):
2592
+ return
2593
+ try:
2594
+ await graph.aupdate_state(config, None)
2595
+ except Exception as e: # noqa: BLE001 - leave the thread as it is
2596
+ _status(
2597
+ f"{YELLOW}⏺ Couldn't clear the refused answer on this session ({e}); "
2598
+ f"start a new session if the approval keeps failing.{RESET}"
2599
+ )
2600
+
2601
+
2432
2602
  async def _stream_turn(
2433
2603
  agent: Any, message: str, thread_id: str, interactive: bool, verbose: bool
2434
2604
  ) -> tuple[bool, bool, bool]:
@@ -2456,6 +2626,8 @@ async def _stream_turn(
2456
2626
  spinner = None if _QUIET else Spinner("Thinking")
2457
2627
  if spinner:
2458
2628
  spinner.start()
2629
+ if resume is not None:
2630
+ await _discard_failed_resume(agent, thread_id)
2459
2631
  try:
2460
2632
  with _debug_tracebacks(verbose):
2461
2633
  async for chunk in agui_stream_updates(agent, message, thread_id, resume=resume):
@@ -2482,7 +2654,9 @@ async def _stream_turn(
2482
2654
  _flush_markdown() # a stream that ends without `complete` keeps no held text
2483
2655
 
2484
2656
  if has_interrupt and interactive:
2485
- resume = handle_interrupt_input(num_pending_actions, is_generic=is_generic_interrupt)
2657
+ resume = handle_interrupt_input(
2658
+ num_pending_actions, is_generic=is_generic_interrupt, interrupt=interrupt_data
2659
+ )
2486
2660
  elif has_interrupt and is_generic_interrupt:
2487
2661
  # --no-interactive on a generic interrupt() (gh #99): there is no action
2488
2662
  # to "approve", and resuming with a {"decisions": [...]} envelope would
@@ -2495,6 +2669,19 @@ async def _stream_turn(
2495
2669
  f"(--no-interactive){RESET}"
2496
2670
  )
2497
2671
  resume = ""
2672
+ elif has_interrupt and not _all_actions_allow(
2673
+ "approve", num_pending_actions, interrupt_data
2674
+ ):
2675
+ # --no-interactive can only approve. An action that doesn't allow approve
2676
+ # would refuse the decision and error the turn, so stop paused instead and
2677
+ # say why (gh #197).
2678
+ print(
2679
+ "Error: approval required, but the pending action does not allow "
2680
+ f"approve (allowed: {', '.join(_allowed_verbs(interrupt_data, 0))}).\n"
2681
+ "Answer it in an interactive session.",
2682
+ file=sys.stderr,
2683
+ )
2684
+ sys.exit(EXIT_PAUSED)
2498
2685
  elif has_interrupt:
2499
2686
  # --no-interactive: auto-approve and resume so the agent runs to
2500
2687
  # completion (same behavior as the default path, gh #32).
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: langstage-cli
3
- Version: 0.6.48
3
+ Version: 0.6.50
4
4
  Summary: The terminal stage for your LangGraph agent — Claude Code-style CLI for any CompiledGraph
5
5
  Author-email: Kedar Dabhadkar <kdabhadk@gmail.com>
6
6
  License-Expression: MIT
@@ -176,6 +176,10 @@ without you baking a checkpointer into your own graph:
176
176
  - A session left paused at an approval (exit `2`) is resolved before a new message: the
177
177
  CLI says so, asks you (or auto-approves under `--no-interactive`), then sends your
178
178
  message. Without a terminal it exits `2` again and says the message was not sent.
179
+ - **Provide custom decision (JSON)** at the approval menu takes one decision for every
180
+ pending action, such as `{"type": "approve"}` or `{"type": "reject", "message": "why"}`
181
+ (a pasted `{"decisions": [...]}` list also works). The prompt shows the shapes the
182
+ pending tool allows, and a decision it would refuse is caught before anything is sent.
179
183
 
180
184
  State lives in `~/.langstage/sessions/<workspace-hash>.sqlite` (honoring
181
185
  `LANGSTAGE_CONFIG_HOME`; override the whole location with `LANGSTAGE_CLI_SESSIONS_DIR`).
@@ -338,7 +342,7 @@ approval menu you answer by typing a number.
338
342
  |---|---|
339
343
  | `0` | success: the turn completed, `--verify` passed, `init` wrote its files |
340
344
  | `1` | failure: no agent configured, the agent failed to load, the turn errored or produced nothing, `--verify` failed, `--resume` found no session, `init` refused to overwrite |
341
- | `2` | paused on a human-in-the-loop interrupt: an approval is needed but stdin is not a terminal, or you left the approval prompt with **Exit** or Ctrl-C. `--no-interactive` auto-approves instead |
345
+ | `2` | paused on a human-in-the-loop interrupt: an approval is needed but stdin is not a terminal, or you left the approval prompt with **Exit** or Ctrl-C. `--no-interactive` auto-approves instead, unless the pending action doesn't allow approve, which also exits `2` |
342
346
  | `64` | usage error: an unknown option or bad value, `--demo` with `-a`, `--continue` with `--resume`, `MESSAGE` with `-f`, an empty `MESSAGE` |
343
347
 
344
348
  ## Creating Your Own Agent
@@ -26,6 +26,7 @@ tests/test_config.py
26
26
  tests/test_config_command.py
27
27
  tests/test_configurable.py
28
28
  tests/test_ctrl_c_sync_tool.py
29
+ tests/test_custom_decision_195.py
29
30
  tests/test_deferred_pass.py
30
31
  tests/test_dumb_term.py
31
32
  tests/test_exit_codes.py
@@ -39,6 +40,7 @@ tests/test_init.py
39
40
  tests/test_interrupt_non_tty.py
40
41
  tests/test_legacy_config_home.py
41
42
  tests/test_load_error.py
43
+ tests/test_menu_allowed_197.py
42
44
  tests/test_message_boundaries.py
43
45
  tests/test_no_color.py
44
46
  tests/test_no_interactive_approve.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "langstage-cli"
7
- version = "0.6.48"
7
+ version = "0.6.50"
8
8
  description = "The terminal stage for your LangGraph agent — Claude Code-style CLI for any CompiledGraph"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -181,13 +181,16 @@ def test_empty_line_then_approve_sends_only_the_approval(tty, monkeypatch):
181
181
  assert resume == {"decisions": [{"type": "approve"}]}
182
182
 
183
183
 
184
- def test_json_null_is_a_decision_not_back_to_menu(tty, monkeypatch):
185
- # The "go back" signal is an empty line, so valid JSON like `null` still resumes.
184
+ def test_json_null_is_refused_not_back_to_menu(tty, monkeypatch):
185
+ # The "go back" signal is an empty line. Valid JSON like `null` isn't a decision,
186
+ # so it is refused in place with nothing sent (gh #195).
186
187
  shown = _choices(monkeypatch, 2)
187
- _typed(monkeypatch, "null")
188
- with redirect_stdout(io.StringIO()):
188
+ _typed(monkeypatch, "null", '{"type": "approve"}')
189
+ buf = io.StringIO()
190
+ with redirect_stdout(buf):
189
191
  resume = cli.handle_interrupt_input(1)
190
- assert resume == {"decisions": [None]}
192
+ assert resume == {"decisions": [{"type": "approve"}]}
193
+ assert "Nothing was sent" in buf.getvalue()
191
194
  assert len(shown) == 1
192
195
 
193
196
 
@@ -207,4 +210,4 @@ async def test_invalid_json_typo_resumes_the_agent_with_the_corrected_decision(t
207
210
  out = buf.getvalue()
208
211
  assert had_error is False, out
209
212
  assert "Decision was" in out and "'edit'" in out, out
210
- assert "reject" not in out, out
213
+ assert "'type': 'reject'" not in out, out
@@ -0,0 +1,275 @@
1
+ """A custom approval decision is checked before it is sent, and a session wedged by a
2
+ refused one recovers (gh #195).
3
+
4
+ "Provide custom decision (JSON)" sent any valid JSON. When the agent's HITL middleware
5
+ refused it (a typo like ``{"type": "aprove"}``, or the whole ``{"decisions": [...]}``
6
+ envelope), LangGraph kept that resume value on the checkpoint and replayed it on every
7
+ later resume. "Approve all actions" failed with the same error, the menu came back
8
+ forever, and ``-c --no-interactive`` on the persisted session exited 1.
9
+
10
+ Now the decision is checked against the interrupt's allowed decisions (and LangChain's
11
+ decision shapes) and refused in place with nothing sent, a pasted envelope is unwrapped,
12
+ and a thread already holding a refused answer drops it before the next resume.
13
+ """
14
+
15
+ import io
16
+ import textwrap
17
+ from contextlib import redirect_stdout
18
+
19
+ import pytest
20
+ from click.testing import CliRunner
21
+
22
+ from langstage_cli import cli
23
+ from langstage_cli.cli import main
24
+
25
+ # LangChain's HumanInTheLoopMiddleware on a keyless model: the first turn calls
26
+ # send_email, and once the tool has answered the model says "done".
27
+ _HITL_AGENT = textwrap.dedent(
28
+ """
29
+ from langchain.agents import create_agent
30
+ from langchain.agents.middleware import HumanInTheLoopMiddleware
31
+ from langchain_core.language_models.chat_models import BaseChatModel
32
+ from langchain_core.messages import AIMessage
33
+ from langchain_core.outputs import ChatGeneration, ChatResult
34
+
35
+ class Model(BaseChatModel):
36
+ @property
37
+ def _llm_type(self):
38
+ return "fake-195"
39
+
40
+ def bind_tools(self, tools, **kw):
41
+ return self
42
+
43
+ def _generate(self, messages, stop=None, run_manager=None, **kw):
44
+ if messages[-1].type == "tool":
45
+ msg = AIMessage(content=f"done: {messages[-1].content}")
46
+ else:
47
+ msg = AIMessage(content="", tool_calls=[
48
+ {"name": "send_email", "args": {"to": "a@example.org"}, "id": "c1"}
49
+ ])
50
+ return ChatResult(generations=[ChatGeneration(message=msg)])
51
+
52
+ def send_email(to: str) -> str:
53
+ \"\"\"Send an email.\"\"\"
54
+ return f"sent to {to}"
55
+
56
+ graph = create_agent(
57
+ Model(),
58
+ tools=[send_email],
59
+ middleware=[HumanInTheLoopMiddleware(interrupt_on={
60
+ "send_email": {"allowed_decisions": ["approve", "reject"]},
61
+ })],
62
+ )
63
+ """
64
+ )
65
+
66
+ # The interrupt frame core emits for that agent.
67
+ _FRAME = {
68
+ "action_requests": [{"name": "send_email", "args": {"to": "a@example.org"}}],
69
+ "review_configs": [{"action_name": "send_email", "allowed_decisions": ["approve", "reject"]}],
70
+ "allowed_decisions": ["approve", "reject"],
71
+ }
72
+
73
+
74
+ def _typed(monkeypatch, *lines):
75
+ it = iter(lines)
76
+ monkeypatch.setattr("builtins.input", lambda *_a, **_k: next(it))
77
+
78
+
79
+ def _choices(monkeypatch, *choices):
80
+ it = iter(choices)
81
+ shown = []
82
+
83
+ def fake_select(options, prompt=""):
84
+ shown.append(prompt)
85
+ return next(it)
86
+
87
+ monkeypatch.setattr(cli, "select_option", fake_select)
88
+ return shown
89
+
90
+
91
+ @pytest.fixture
92
+ def tty(monkeypatch):
93
+ monkeypatch.setattr(cli, "_is_a_tty", lambda *a, **k: True)
94
+
95
+
96
+ # ---- Checking the decision ----------------------------------------------------------
97
+
98
+
99
+ @pytest.mark.parametrize(
100
+ "value, problem",
101
+ [
102
+ (
103
+ {"type": "aprove"},
104
+ "Decision type 'aprove' is not allowed here; allowed: approve, reject.",
105
+ ),
106
+ (
107
+ {"type": "edit", "edited_action": {"name": "send_email", "args": {}}},
108
+ "'edit' is not allowed",
109
+ ),
110
+ (None, 'A decision is a JSON object with a "type"'),
111
+ ({"decisions": [{"kind": "approve"}]}, 'A decision is a JSON object with a "type"'),
112
+ ([{"type": "approve"}] * 3, "Got 3 decisions for 2 pending action(s)"),
113
+ ({"type": "reject", "message": 5}, "must be a string"),
114
+ ],
115
+ )
116
+ def test_bad_decisions_are_refused(value, problem):
117
+ frame = {**_FRAME, "action_requests": _FRAME["action_requests"] * 2}
118
+ decisions, got = cli._check_custom_decision(value, 2, frame)
119
+ assert decisions == []
120
+ assert problem in got
121
+
122
+
123
+ def test_one_decision_applies_to_every_action():
124
+ decisions, problem = cli._check_custom_decision({"type": "reject", "message": "no"}, 2, _FRAME)
125
+ assert problem is None
126
+ assert decisions == [{"type": "reject", "message": "no"}] * 2
127
+
128
+
129
+ def test_a_pasted_envelope_is_unwrapped():
130
+ one = {"decisions": [{"type": "approve"}]}
131
+ assert cli._check_custom_decision(one, 2, _FRAME) == ([{"type": "approve"}] * 2, None)
132
+ each = {"decisions": [{"type": "approve"}, {"type": "reject"}]}
133
+ assert cli._check_custom_decision(each, 2, _FRAME) == (each["decisions"], None)
134
+
135
+
136
+ def test_legacy_alias_verbs_pass():
137
+ # core rewrites accept -> approve before the middleware sees it.
138
+ assert cli._check_custom_decision({"type": "accept"}, 1, _FRAME)[1] is None
139
+
140
+
141
+ def test_langchain_shapes_are_checked_only_for_its_interrupts():
142
+ frame = {
143
+ **_FRAME,
144
+ "review_configs": [{"action_name": "send_email", "allowed_decisions": ["edit", "respond"]}],
145
+ }
146
+ assert "edited_action" in cli._check_custom_decision({"type": "edit"}, 1, frame)[1]
147
+ assert '"message" string' in cli._check_custom_decision({"type": "respond"}, 1, frame)[1]
148
+ edit = {"type": "edit", "edited_action": {"name": "send_email", "args": {"to": "b"}}}
149
+ assert cli._check_custom_decision(edit, 1, frame) == ([edit], None)
150
+ # A plain interrupt() payload (no review_configs) reads its own edit shape.
151
+ legacy = {"type": "edit", "args": {"path": "/tmp/hosts"}}
152
+ assert (
153
+ cli._check_custom_decision(
154
+ legacy, 1, {"action_requests": [{"action": "x"}], "review_configs": []}
155
+ )[1]
156
+ is None
157
+ )
158
+
159
+
160
+ def test_allowed_verbs_are_per_tool():
161
+ frame = {
162
+ "action_requests": [{"name": "a", "args": {}}, {"name": "b", "args": {}}],
163
+ "review_configs": [
164
+ {"action_name": "a", "allowed_decisions": ["approve"]},
165
+ {"action_name": "b", "allowed_decisions": ["approve", "reject"]},
166
+ ],
167
+ "allowed_decisions": ["approve", "reject"],
168
+ }
169
+ decisions, problem = cli._check_custom_decision({"type": "reject"}, 2, frame)
170
+ assert "allowed: approve." in problem
171
+
172
+
173
+ def test_menu_reprompts_on_a_refused_decision_and_shows_the_shapes(tty, monkeypatch):
174
+ shown = _choices(monkeypatch, 2)
175
+ _typed(monkeypatch, '{"type":"aprove"}', '{"type":"approve"}')
176
+ buf = io.StringIO()
177
+ with redirect_stdout(buf):
178
+ resume = cli.handle_interrupt_input(1, interrupt=_FRAME)
179
+ out = buf.getvalue()
180
+ assert resume == {"decisions": [{"type": "approve"}]}
181
+ assert "'aprove' is not allowed here" in out and "Nothing was sent" in out
182
+ assert '{"type": "approve"} | {"type": "reject", "message": "why"}' in out
183
+ assert '"edit"' not in out # not offered for this tool
184
+ assert len(shown) == 1 # re-prompted in place
185
+
186
+
187
+ # ---- End to end ---------------------------------------------------------------------
188
+
189
+
190
+ async def test_a_typo_is_refused_then_the_corrected_decision_runs_the_tool(tty, monkeypatch):
191
+ pytest.importorskip("ag_ui_langgraph")
192
+ from langgraph.checkpoint.memory import MemorySaver
193
+
194
+ from langstage_cli.agui_stream import build_session_agent
195
+
196
+ ns: dict = {}
197
+ exec(_HITL_AGENT, ns)
198
+ agent = build_session_agent(ns["graph"].copy(update={"checkpointer": MemorySaver()}))
199
+ _choices(monkeypatch, 2)
200
+ _typed(monkeypatch, '{"type":"aprove"}', '{"decisions":[{"type":"approve"}]}')
201
+ buf = io.StringIO()
202
+ with redirect_stdout(buf):
203
+ _elapsed, had_error = await cli.run_single_turn_agui(agent, "email them", "t-195", True)
204
+ out = buf.getvalue()
205
+ assert had_error is False, out
206
+ assert "done: sent to a@example.org" in out, out
207
+
208
+
209
+ async def test_a_thread_holding_a_refused_answer_takes_the_next_one(monkeypatch):
210
+ # A thread wedged by an older CLI: the refused answer is already on the checkpoint.
211
+ pytest.importorskip("ag_ui_langgraph")
212
+ from langgraph.checkpoint.memory import MemorySaver
213
+ from langgraph.types import Command
214
+
215
+ from langstage_cli.agui_stream import build_session_agent
216
+
217
+ ns: dict = {}
218
+ exec(_HITL_AGENT, ns)
219
+ graph = ns["graph"].copy(update={"checkpointer": MemorySaver()})
220
+ cfg = {"configurable": {"thread_id": "t-wedged"}}
221
+ await graph.ainvoke({"messages": [("user", "email them")]}, cfg)
222
+ with pytest.raises(ValueError, match="aprove"):
223
+ await graph.ainvoke(Command(resume={"decisions": [{"type": "aprove"}]}), cfg)
224
+ with pytest.raises(ValueError, match="aprove"): # LangGraph replays the stale answer
225
+ await graph.ainvoke(Command(resume={"decisions": [{"type": "approve"}]}), cfg)
226
+
227
+ agent = build_session_agent(graph)
228
+ buf = io.StringIO()
229
+ with redirect_stdout(buf):
230
+ _elapsed, had_error = await cli.run_single_turn_agui(
231
+ agent, "and now?", "t-wedged", interactive=False
232
+ )
233
+ out = buf.getvalue()
234
+ assert had_error is False, out
235
+ assert "aprove" not in out, out
236
+ assert "done: sent to a@example.org" in out, out
237
+
238
+
239
+ def test_continue_recovers_a_persisted_session_wedged_by_a_refused_answer(tmp_path, monkeypatch):
240
+ pytest.importorskip("ag_ui_langgraph")
241
+ pytest.importorskip("langgraph.checkpoint.sqlite.aio")
242
+ ws = tmp_path / "ws"
243
+ ws.mkdir()
244
+ (ws / "hitl_195.py").write_text(_HITL_AGENT, encoding="utf-8")
245
+ (ws / "langstage.toml").write_text('[agent]\nspec = "hitl_195.py:graph"\n')
246
+ monkeypatch.setenv("LANGSTAGE_CONFIG_HOME", str(tmp_path / "empty_home"))
247
+ monkeypatch.chdir(ws)
248
+ runner = CliRunner()
249
+
250
+ # An older CLI sent the typo unchecked, then the user left at the menu.
251
+ answers = iter([{"decisions": [{"type": "aprove"}]}])
252
+
253
+ def old_menu(*_a, **_k):
254
+ try:
255
+ return next(answers)
256
+ except StopIteration:
257
+ raise SystemExit(2)
258
+
259
+ monkeypatch.setattr(cli, "_is_a_tty", lambda *a, **k: True)
260
+ monkeypatch.setattr(cli, "handle_interrupt_input", old_menu)
261
+ monkeypatch.setattr(cli, "_discard_failed_resume", _no_discard)
262
+ r = runner.invoke(main, ["email them"])
263
+ assert "aprove" in r.output, r.output
264
+ monkeypatch.undo()
265
+ monkeypatch.setenv("LANGSTAGE_CONFIG_HOME", str(tmp_path / "empty_home"))
266
+ monkeypatch.chdir(ws)
267
+
268
+ r = runner.invoke(main, ["-c", "--no-interactive", "x"])
269
+ assert r.exit_code == 0, r.output
270
+ assert "aprove" not in r.output, r.output
271
+ assert "done: sent to a@example.org" in r.output, r.output
272
+
273
+
274
+ async def _no_discard(*_a, **_k):
275
+ return None
@@ -0,0 +1,184 @@
1
+ """The approval menu offers only the decisions the pending interrupt allows (gh #197).
2
+
3
+ "Approve all actions" and "Reject all actions" were always offered, so on LangChain's
4
+ HumanInTheLoopMiddleware(allowed_decisions=["approve", "edit"]) "Reject all" sent a
5
+ decision the middleware refuses and the turn errored. ``--no-interactive`` likewise
6
+ sent an approve to an action that doesn't allow one. Each is now offered (or sent) only
7
+ when every pending action allows it.
8
+ """
9
+
10
+ import io
11
+ import textwrap
12
+ from contextlib import redirect_stdout
13
+
14
+ import pytest
15
+
16
+ from langstage_cli import cli
17
+
18
+
19
+ def _frame(*tools):
20
+ """An interrupt frame for (name, allowed_decisions) pairs, as core emits it."""
21
+ union = sorted({v for _, allowed in tools for v in allowed})
22
+ return {
23
+ "action_requests": [{"name": n, "args": {}} for n, _ in tools],
24
+ "review_configs": [{"action_name": n, "allowed_decisions": a} for n, a in tools],
25
+ "allowed_decisions": union,
26
+ }
27
+
28
+
29
+ @pytest.fixture
30
+ def tty(monkeypatch):
31
+ monkeypatch.setattr(cli, "_is_a_tty", lambda *a, **k: True)
32
+
33
+
34
+ def _pick(monkeypatch, label):
35
+ """Choose the menu entry ``label``, recording every menu shown."""
36
+ shown = []
37
+
38
+ def fake_select(options, prompt=""):
39
+ shown.append(list(options))
40
+ return options.index(label)
41
+
42
+ monkeypatch.setattr(cli, "select_option", fake_select)
43
+ return shown
44
+
45
+
46
+ @pytest.mark.parametrize(
47
+ "frame, expected",
48
+ [
49
+ (
50
+ _frame(("send_email", ["approve", "edit"])),
51
+ ["Approve all actions", "Provide custom decision (JSON)", "Exit"],
52
+ ),
53
+ (
54
+ _frame(("send_email", ["edit", "reject"])),
55
+ ["Reject all actions", "Provide custom decision (JSON)", "Exit"],
56
+ ),
57
+ (
58
+ _frame(("send_email", ["respond"])),
59
+ ["Provide custom decision (JSON)", "Exit"],
60
+ ),
61
+ # Per tool: one of two actions doesn't allow reject, so "Reject all" can't apply.
62
+ (
63
+ _frame(("a", ["approve", "reject"]), ("b", ["approve"])),
64
+ ["Approve all actions", "Provide custom decision (JSON)", "Exit"],
65
+ ),
66
+ # No allowed list at all (an older or plain interrupt): the full menu, as before.
67
+ (
68
+ None,
69
+ [
70
+ "Approve all actions",
71
+ "Reject all actions",
72
+ "Provide custom decision (JSON)",
73
+ "Exit",
74
+ ],
75
+ ),
76
+ ],
77
+ )
78
+ def test_menu_offers_only_allowed_bulk_decisions(frame, expected, tty, monkeypatch):
79
+ shown = _pick(monkeypatch, "Exit")
80
+ n = len(frame["action_requests"]) if frame else 1
81
+ with pytest.raises(SystemExit) as exc:
82
+ cli.handle_interrupt_input(n, interrupt=frame)
83
+ assert exc.value.code == 2
84
+ assert shown == [expected]
85
+
86
+
87
+ def test_each_entry_sends_its_own_decision(tty, monkeypatch):
88
+ frame = _frame(("a", ["edit", "reject"]), ("b", ["reject"]))
89
+ _pick(monkeypatch, "Reject all actions")
90
+ assert cli.handle_interrupt_input(2, interrupt=frame) == {
91
+ "decisions": [{"type": "reject"}, {"type": "reject"}]
92
+ }
93
+ _pick(monkeypatch, "Provide custom decision (JSON)")
94
+ monkeypatch.setattr("builtins.input", lambda *_a, **_k: '{"type": "reject"}')
95
+ with redirect_stdout(io.StringIO()):
96
+ assert cli.handle_interrupt_input(2, interrupt=frame) == {
97
+ "decisions": [{"type": "reject"}, {"type": "reject"}]
98
+ }
99
+
100
+
101
+ # ---- End to end on the issue's agent ------------------------------------------------
102
+
103
+ _AGENT = textwrap.dedent(
104
+ """
105
+ from langchain.agents import create_agent
106
+ from langchain.agents.middleware import HumanInTheLoopMiddleware
107
+ from langchain_core.language_models.chat_models import BaseChatModel
108
+ from langchain_core.messages import AIMessage
109
+ from langchain_core.outputs import ChatGeneration, ChatResult
110
+
111
+ class Model(BaseChatModel):
112
+ @property
113
+ def _llm_type(self):
114
+ return "fake-197"
115
+
116
+ def bind_tools(self, tools, **kw):
117
+ return self
118
+
119
+ def _generate(self, messages, stop=None, run_manager=None, **kw):
120
+ if messages[-1].type == "tool":
121
+ msg = AIMessage(content=f"done: {messages[-1].content}")
122
+ else:
123
+ msg = AIMessage(content="", tool_calls=[
124
+ {"name": "send_email", "args": {"to": "a@example.org"}, "id": "c1"}
125
+ ])
126
+ return ChatResult(generations=[ChatGeneration(message=msg)])
127
+
128
+ def send_email(to: str) -> str:
129
+ \"\"\"Send an email.\"\"\"
130
+ return f"sent to {to}"
131
+
132
+ graph = create_agent(
133
+ Model(),
134
+ tools=[send_email],
135
+ middleware=[HumanInTheLoopMiddleware(interrupt_on={
136
+ "send_email": {"allowed_decisions": ALLOWED},
137
+ })],
138
+ )
139
+ """
140
+ )
141
+
142
+
143
+ def _agent(allowed):
144
+ pytest.importorskip("ag_ui_langgraph")
145
+ from langgraph.checkpoint.memory import MemorySaver
146
+
147
+ from langstage_cli.agui_stream import build_session_agent
148
+
149
+ ns: dict = {"ALLOWED": allowed}
150
+ exec(_AGENT, ns)
151
+ return build_session_agent(ns["graph"].copy(update={"checkpointer": MemorySaver()}))
152
+
153
+
154
+ async def test_the_issue_agent_never_shows_reject_and_approve_runs_the_tool(tty, monkeypatch):
155
+ agent = _agent(["approve", "edit"])
156
+ shown = _pick(monkeypatch, "Approve all actions")
157
+ buf = io.StringIO()
158
+ with redirect_stdout(buf):
159
+ _elapsed, had_error = await cli.run_single_turn_agui(agent, "email them", "t-197", True)
160
+ out = buf.getvalue()
161
+ assert had_error is False, out
162
+ assert "done: sent to a@example.org" in out, out
163
+ assert all("Reject all actions" not in menu for menu in shown)
164
+
165
+
166
+ async def test_no_interactive_stops_paused_when_approve_is_not_allowed(monkeypatch, capsys):
167
+ agent = _agent(["edit", "reject"])
168
+ with pytest.raises(SystemExit) as exc:
169
+ await cli.run_single_turn_agui(agent, "email them", "t-197-ni", False)
170
+ assert exc.value.code == 2
171
+ err = capsys.readouterr().err
172
+ assert "does not allow approve (allowed: edit, reject)" in err
173
+ assert "ValueError" not in err
174
+ # Nothing was sent: the thread is still paused on the same approval.
175
+ assert await cli._pending_interrupt(agent, "t-197-ni")
176
+
177
+
178
+ async def test_no_interactive_still_auto_approves_when_allowed(monkeypatch):
179
+ agent = _agent(["approve", "edit"])
180
+ buf = io.StringIO()
181
+ with redirect_stdout(buf):
182
+ _elapsed, had_error = await cli.run_single_turn_agui(agent, "email them", "t-197-ok", False)
183
+ assert had_error is False
184
+ assert "done: sent to a@example.org" in buf.getvalue()
File without changes
File without changes