langstage-cli 0.6.48__tar.gz → 0.6.49__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 (78) hide show
  1. {langstage_cli-0.6.48/langstage_cli.egg-info → langstage_cli-0.6.49}/PKG-INFO +5 -1
  2. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/README.md +4 -0
  3. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/langstage_cli/cli.py +173 -10
  4. {langstage_cli-0.6.48 → langstage_cli-0.6.49/langstage_cli.egg-info}/PKG-INFO +5 -1
  5. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/langstage_cli.egg-info/SOURCES.txt +1 -0
  6. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/pyproject.toml +1 -1
  7. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_approval_menu_abort.py +9 -6
  8. langstage_cli-0.6.49/tests/test_custom_decision_195.py +275 -0
  9. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/LICENSE +0 -0
  10. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/deepagent_code/__init__.py +0 -0
  11. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/langstage_cli/__init__.py +0 -0
  12. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/langstage_cli/agui_stream.py +0 -0
  13. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/langstage_cli/config.py +0 -0
  14. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/langstage_cli/exit_codes.py +0 -0
  15. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/langstage_cli/sessions.py +0 -0
  16. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/langstage_cli.egg-info/dependency_links.txt +0 -0
  17. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/langstage_cli.egg-info/entry_points.txt +0 -0
  18. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/langstage_cli.egg-info/requires.txt +0 -0
  19. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/langstage_cli.egg-info/top_level.txt +0 -0
  20. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/setup.cfg +0 -0
  21. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_advertised_wave4.py +0 -0
  22. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_agui_stream.py +0 -0
  23. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_async_mode.py +0 -0
  24. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_checkpointer.py +0 -0
  25. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_cli.py +0 -0
  26. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_cli_help.py +0 -0
  27. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_codeconfig.py +0 -0
  28. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_config.py +0 -0
  29. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_config_command.py +0 -0
  30. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_configurable.py +0 -0
  31. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_ctrl_c_sync_tool.py +0 -0
  32. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_deferred_pass.py +0 -0
  33. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_dumb_term.py +0 -0
  34. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_exit_codes.py +0 -0
  35. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_generic_interrupt.py +0 -0
  36. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_help_render.py +0 -0
  37. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_hidden_option_suggestions.py +0 -0
  38. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_history_persist.py +0 -0
  39. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_hitl_approval_preview.py +0 -0
  40. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_hitl_resume_warning.py +0 -0
  41. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_init.py +0 -0
  42. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_interrupt_non_tty.py +0 -0
  43. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_legacy_config_home.py +0 -0
  44. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_load_error.py +0 -0
  45. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_message_boundaries.py +0 -0
  46. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_no_color.py +0 -0
  47. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_no_interactive_approve.py +0 -0
  48. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_no_persist_resume.py +0 -0
  49. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_paused_session_message.py +0 -0
  50. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_persist_env.py +0 -0
  51. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_quiet_output.py +0 -0
  52. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_reasoning_render.py +0 -0
  53. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_rename_shim.py +0 -0
  54. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_render_markdown.py +0 -0
  55. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_routine_1024.py +0 -0
  56. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_session_lifecycle.py +0 -0
  57. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_sessions.py +0 -0
  58. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_show_config.py +0 -0
  59. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_show_config_malformed.py +0 -0
  60. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_spec_loading_core.py +0 -0
  61. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_spec_resolution.py +0 -0
  62. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_spinner_reply_survives.py +0 -0
  63. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_stdin_interactive.py +0 -0
  64. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_stdin_single_shot.py +0 -0
  65. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_stream_mode.py +0 -0
  66. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_streaming_marker.py +0 -0
  67. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_terminal_width.py +0 -0
  68. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_toml_relative_paths.py +0 -0
  69. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_tool_card_args.py +0 -0
  70. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_tool_output_escape.py +0 -0
  71. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_turn_error_verbose.py +0 -0
  72. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_turn_exit_and_render.py +0 -0
  73. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_unicode_console.py +0 -0
  74. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_usage_hint_186.py +0 -0
  75. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_verbose_command.py +0 -0
  76. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_verify_flag.py +0 -0
  77. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/tests/test_workspace.py +0 -0
  78. {langstage_cli-0.6.48 → langstage_cli-0.6.49}/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.49
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`).
@@ -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`).
@@ -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
@@ -1845,10 +1850,10 @@ def handle_interrupt_input(num_actions: int = 1, is_generic: bool = False) -> An
1845
1850
  # Reject decision for each pending action
1846
1851
  return {"decisions": [{"type": "reject"} for _ in range(num_actions)]}
1847
1852
  elif choice == 2:
1848
- decision = _prompt_custom_decision()
1849
- if decision is _BACK_TO_MENU:
1853
+ decisions = _prompt_custom_decision(num_actions, interrupt)
1854
+ if decisions is _BACK_TO_MENU:
1850
1855
  continue # nothing sent; show the menu again
1851
- return {"decisions": [decision for _ in range(num_actions)]}
1856
+ return {"decisions": decisions}
1852
1857
  else:
1853
1858
  sys.exit(EXIT_PAUSED) # left while paused on the interrupt (ADR 0007)
1854
1859
 
@@ -1871,23 +1876,147 @@ def _approval_input() -> str:
1871
1876
  sys.exit(EXIT_PAUSED)
1872
1877
 
1873
1878
 
1874
- def _prompt_custom_decision() -> Any:
1875
- """Read the "Provide custom decision (JSON)" answer.
1879
+ def _prompt_custom_decision(
1880
+ num_actions: int = 1, interrupt: Optional[Dict[str, Any]] = None
1881
+ ) -> Any:
1882
+ """Read the "Provide custom decision (JSON)" answer as a list of decisions.
1876
1883
 
1877
1884
  Invalid JSON shows the parse error and asks again. It used to send a reject for
1878
1885
  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.
1886
+ agent (gh #174). A decision the interrupt would refuse is caught the same way:
1887
+ once LangGraph has a resume value for an interrupt, a failed resume keeps it and
1888
+ every later answer replays it, so it must be checked before it is sent (gh #195).
1889
+ An empty line returns ``_BACK_TO_MENU`` and nothing is sent.
1880
1890
  """
1881
- print("Enter your decision as JSON (will be applied to all actions):")
1891
+ print("Enter your decision as JSON (one decision is applied to all actions):")
1892
+ print(f"{DIM} {_decision_shapes(_allowed_verbs(interrupt, 0), interrupt)}{RESET}")
1882
1893
  print(f"{DIM}Press Enter on an empty line to go back to the menu.{RESET}")
1883
1894
  while True:
1884
1895
  json_str = _approval_input().strip()
1885
1896
  if not json_str:
1886
1897
  return _BACK_TO_MENU
1887
1898
  try:
1888
- return json.loads(json_str)
1899
+ value = json.loads(json_str)
1889
1900
  except json.JSONDecodeError as e:
1890
1901
  print(f"{RED}⏺ Invalid JSON: {e}. Nothing was sent; try again.{RESET}")
1902
+ continue
1903
+ decisions, problem = _check_custom_decision(value, num_actions, interrupt)
1904
+ if problem is None:
1905
+ return decisions
1906
+ print(f"{RED}⏺ {problem} Nothing was sent; try again.{RESET}")
1907
+
1908
+
1909
+ _FALLBACK_VERBS = ("approve", "edit", "reject", "respond")
1910
+
1911
+
1912
+ def _allowed_verbs(interrupt: Optional[Dict[str, Any]], index: int) -> List[str]:
1913
+ """The decision verbs the interrupt allows for its ``index``-th action.
1914
+
1915
+ LangChain's HumanInTheLoopMiddleware lists them per tool in ``review_configs``;
1916
+ core also puts the union on the frame as ``allowed_decisions``.
1917
+ """
1918
+ interrupt = interrupt if isinstance(interrupt, dict) else {}
1919
+ requests = interrupt.get("action_requests")
1920
+ configs = interrupt.get("review_configs")
1921
+ if isinstance(requests, list) and isinstance(configs, list) and index < len(requests):
1922
+ key = _tool_key(requests[index])
1923
+ name = requests[index].get(key) if key else None
1924
+ for rc in configs:
1925
+ if isinstance(rc, dict) and rc.get("action_name") == name:
1926
+ verbs = rc.get("allowed_decisions")
1927
+ if isinstance(verbs, list) and verbs:
1928
+ return [str(v) for v in verbs]
1929
+ verbs = interrupt.get("allowed_decisions")
1930
+ if isinstance(verbs, list) and verbs:
1931
+ return [str(v) for v in verbs]
1932
+ return list(_FALLBACK_VERBS)
1933
+
1934
+
1935
+ def _decision_shapes(allowed: List[str], interrupt: Optional[Dict[str, Any]] = None) -> str:
1936
+ """One line showing the JSON shape of each allowed decision.
1937
+
1938
+ The fields are LangChain HumanInTheLoopMiddleware's, so other interrupts get the
1939
+ bare ``{"type": ...}`` of each verb.
1940
+ """
1941
+ shapes = (
1942
+ {}
1943
+ if not _is_middleware_interrupt(interrupt)
1944
+ else {
1945
+ "approve": '{"type": "approve"}',
1946
+ "reject": '{"type": "reject", "message": "why"}',
1947
+ "respond": '{"type": "respond", "message": "reply"}',
1948
+ "edit": '{"type": "edit", "edited_action": {"name": "tool", "args": {...}}}',
1949
+ }
1950
+ )
1951
+ order = [v for v in _FALLBACK_VERBS if v in allowed] + [
1952
+ v for v in allowed if v not in _FALLBACK_VERBS
1953
+ ]
1954
+ return " | ".join(shapes.get(v, f'{{"type": "{v}"}}') for v in order)
1955
+
1956
+
1957
+ def _is_middleware_interrupt(interrupt: Optional[Dict[str, Any]]) -> bool:
1958
+ """Whether the interrupt is LangChain HumanInTheLoopMiddleware's (it has review_configs)."""
1959
+ configs = interrupt.get("review_configs") if isinstance(interrupt, dict) else None
1960
+ return isinstance(configs, list) and bool(configs)
1961
+
1962
+
1963
+ def _check_custom_decision(
1964
+ value: Any, num_actions: int, interrupt: Optional[Dict[str, Any]]
1965
+ ) -> Tuple[List[Any], Optional[str]]:
1966
+ """Check a typed custom decision against the pending interrupt (gh #195).
1967
+
1968
+ Returns ``(decisions, None)`` with one decision per pending action, or
1969
+ ``([], problem)`` naming what is wrong. One decision object applies to every
1970
+ action. A pasted ``{"decisions": [...]}`` envelope (or a bare list) is unwrapped
1971
+ and must hold one decision, or one per action.
1972
+ """
1973
+ from langstage_core import normalize_decision
1974
+
1975
+ if isinstance(value, dict) and "decisions" in value and "type" not in value:
1976
+ value = value["decisions"]
1977
+ if isinstance(value, list):
1978
+ if len(value) == 1:
1979
+ value = value * num_actions
1980
+ elif len(value) != num_actions:
1981
+ return [], (
1982
+ f"Got {len(value)} decisions for {num_actions} pending action(s); "
1983
+ "give one decision, or one per action."
1984
+ )
1985
+ items = value
1986
+ else:
1987
+ items = [value] * num_actions
1988
+
1989
+ # The edited_action / message fields are LangChain HumanInTheLoopMiddleware's
1990
+ # shape (its interrupts carry review_configs); other interrupts read their own.
1991
+ middleware = _is_middleware_interrupt(interrupt)
1992
+ for i, decision in enumerate(items):
1993
+ allowed = _allowed_verbs(interrupt, i)
1994
+ if not isinstance(decision, dict) or not isinstance(decision.get("type"), str):
1995
+ return [], (
1996
+ 'A decision is a JSON object with a "type", e.g. {"type": "approve"}; '
1997
+ f"allowed: {', '.join(allowed)}."
1998
+ )
1999
+ verb = normalize_decision(decision["type"], allowed)
2000
+ if verb is None:
2001
+ return [], (
2002
+ f"Decision type '{decision['type']}' is not allowed here; "
2003
+ f"allowed: {', '.join(allowed)}."
2004
+ )
2005
+ if not middleware:
2006
+ continue
2007
+ if verb == "edit":
2008
+ edited = decision.get("edited_action")
2009
+ if not (
2010
+ isinstance(edited, dict)
2011
+ and isinstance(edited.get("name"), str)
2012
+ and isinstance(edited.get("args"), dict)
2013
+ ):
2014
+ return [], 'An edit needs "edited_action": {"name": "<tool>", "args": {...}}.'
2015
+ elif verb == "respond" and not isinstance(decision.get("message"), str):
2016
+ return [], 'A respond decision needs a "message" string.'
2017
+ elif verb == "reject" and not isinstance(decision.get("message", ""), str):
2018
+ return [], 'The "message" of a reject decision must be a string.'
2019
+ return list(items), None
1891
2020
 
1892
2021
 
1893
2022
  def print_help():
@@ -2429,6 +2558,36 @@ async def _pending_interrupt(agent: Any, thread_id: str) -> bool:
2429
2558
  return any(getattr(task, "interrupts", None) for task in getattr(state, "tasks", ()) or ())
2430
2559
 
2431
2560
 
2561
+ async def _discard_failed_resume(agent: Any, thread_id: str) -> None:
2562
+ """Drop the answer a failed resume left on the thread, so the next one is used.
2563
+
2564
+ When resuming an interrupt raises (a decision the agent refused), LangGraph keeps
2565
+ that resume value on the checkpoint and replays it on every later resume, so the
2566
+ approval could never be answered again, even with ``-c`` (gh #195). The failed
2567
+ task still shows its interrupt and carries the error. A checkpoint with no new
2568
+ values drops the stale answer: the interrupted step runs again and takes the new
2569
+ one. If that isn't possible the stale answer stays, and the error says so again.
2570
+ """
2571
+ graph = getattr(agent, "graph", None)
2572
+ if not thread_id or graph is None or not hasattr(graph, "aupdate_state"):
2573
+ return
2574
+ config = {"configurable": {"thread_id": thread_id}}
2575
+ try:
2576
+ state = await graph.aget_state(config)
2577
+ except Exception: # noqa: BLE001 - no checkpointer / no state: nothing to clear
2578
+ return
2579
+ tasks = getattr(state, "tasks", ()) or ()
2580
+ if not any(getattr(t, "interrupts", None) and getattr(t, "error", None) for t in tasks):
2581
+ return
2582
+ try:
2583
+ await graph.aupdate_state(config, None)
2584
+ except Exception as e: # noqa: BLE001 - leave the thread as it is
2585
+ _status(
2586
+ f"{YELLOW}⏺ Couldn't clear the refused answer on this session ({e}); "
2587
+ f"start a new session if the approval keeps failing.{RESET}"
2588
+ )
2589
+
2590
+
2432
2591
  async def _stream_turn(
2433
2592
  agent: Any, message: str, thread_id: str, interactive: bool, verbose: bool
2434
2593
  ) -> tuple[bool, bool, bool]:
@@ -2456,6 +2615,8 @@ async def _stream_turn(
2456
2615
  spinner = None if _QUIET else Spinner("Thinking")
2457
2616
  if spinner:
2458
2617
  spinner.start()
2618
+ if resume is not None:
2619
+ await _discard_failed_resume(agent, thread_id)
2459
2620
  try:
2460
2621
  with _debug_tracebacks(verbose):
2461
2622
  async for chunk in agui_stream_updates(agent, message, thread_id, resume=resume):
@@ -2482,7 +2643,9 @@ async def _stream_turn(
2482
2643
  _flush_markdown() # a stream that ends without `complete` keeps no held text
2483
2644
 
2484
2645
  if has_interrupt and interactive:
2485
- resume = handle_interrupt_input(num_pending_actions, is_generic=is_generic_interrupt)
2646
+ resume = handle_interrupt_input(
2647
+ num_pending_actions, is_generic=is_generic_interrupt, interrupt=interrupt_data
2648
+ )
2486
2649
  elif has_interrupt and is_generic_interrupt:
2487
2650
  # --no-interactive on a generic interrupt() (gh #99): there is no action
2488
2651
  # to "approve", and resuming with a {"decisions": [...]} envelope would
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: langstage-cli
3
- Version: 0.6.48
3
+ Version: 0.6.49
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`).
@@ -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
@@ -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.49"
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
File without changes
File without changes