langstage-cli 0.6.47__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.
- {langstage_cli-0.6.47/langstage_cli.egg-info → langstage_cli-0.6.49}/PKG-INFO +8 -1
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/README.md +7 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/langstage_cli/cli.py +305 -18
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/langstage_cli/exit_codes.py +17 -1
- {langstage_cli-0.6.47 → langstage_cli-0.6.49/langstage_cli.egg-info}/PKG-INFO +8 -1
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/langstage_cli.egg-info/SOURCES.txt +4 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/pyproject.toml +1 -1
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_approval_menu_abort.py +9 -6
- langstage_cli-0.6.49/tests/test_ctrl_c_sync_tool.py +80 -0
- langstage_cli-0.6.49/tests/test_custom_decision_195.py +275 -0
- langstage_cli-0.6.49/tests/test_hidden_option_suggestions.py +27 -0
- langstage_cli-0.6.49/tests/test_paused_session_message.py +100 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/LICENSE +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/deepagent_code/__init__.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/langstage_cli/__init__.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/langstage_cli/agui_stream.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/langstage_cli/config.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/langstage_cli/sessions.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/langstage_cli.egg-info/dependency_links.txt +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/langstage_cli.egg-info/entry_points.txt +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/langstage_cli.egg-info/requires.txt +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/langstage_cli.egg-info/top_level.txt +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/setup.cfg +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_advertised_wave4.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_agui_stream.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_async_mode.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_checkpointer.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_cli.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_cli_help.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_codeconfig.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_config.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_config_command.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_configurable.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_deferred_pass.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_dumb_term.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_exit_codes.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_generic_interrupt.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_help_render.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_history_persist.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_hitl_approval_preview.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_hitl_resume_warning.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_init.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_interrupt_non_tty.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_legacy_config_home.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_load_error.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_message_boundaries.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_no_color.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_no_interactive_approve.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_no_persist_resume.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_persist_env.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_quiet_output.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_reasoning_render.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_rename_shim.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_render_markdown.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_routine_1024.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_session_lifecycle.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_sessions.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_show_config.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_show_config_malformed.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_spec_loading_core.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_spec_resolution.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_spinner_reply_survives.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_stdin_interactive.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_stdin_single_shot.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_stream_mode.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_streaming_marker.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_terminal_width.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_toml_relative_paths.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_tool_card_args.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_tool_output_escape.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_turn_error_verbose.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_turn_exit_and_render.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_unicode_console.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_usage_hint_186.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_verbose_command.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_verify_flag.py +0 -0
- {langstage_cli-0.6.47 → langstage_cli-0.6.49}/tests/test_workspace.py +0 -0
- {langstage_cli-0.6.47 → 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.
|
|
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
|
|
@@ -173,6 +173,13 @@ without you baking a checkpointer into your own graph:
|
|
|
173
173
|
ambiguous one is an error that lists the sessions it matches.
|
|
174
174
|
- A plain run with no flag starts a **new** session that is still persisted, so it can be
|
|
175
175
|
continued later.
|
|
176
|
+
- A session left paused at an approval (exit `2`) is resolved before a new message: the
|
|
177
|
+
CLI says so, asks you (or auto-approves under `--no-interactive`), then sends your
|
|
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.
|
|
176
183
|
|
|
177
184
|
State lives in `~/.langstage/sessions/<workspace-hash>.sqlite` (honoring
|
|
178
185
|
`LANGSTAGE_CONFIG_HOME`; override the whole location with `LANGSTAGE_CLI_SESSIONS_DIR`).
|
|
@@ -135,6 +135,13 @@ without you baking a checkpointer into your own graph:
|
|
|
135
135
|
ambiguous one is an error that lists the sessions it matches.
|
|
136
136
|
- A plain run with no flag starts a **new** session that is still persisted, so it can be
|
|
137
137
|
continued later.
|
|
138
|
+
- A session left paused at an approval (exit `2`) is resolved before a new message: the
|
|
139
|
+
CLI says so, asks you (or auto-approves under `--no-interactive`), then sends your
|
|
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.
|
|
138
145
|
|
|
139
146
|
State lives in `~/.langstage/sessions/<workspace-hash>.sqlite` (honoring
|
|
140
147
|
`LANGSTAGE_CONFIG_HOME`; override the whole location with `LANGSTAGE_CLI_SESSIONS_DIR`).
|
|
@@ -4,9 +4,11 @@ Styled after Claude Code / nanocode.
|
|
|
4
4
|
"""
|
|
5
5
|
|
|
6
6
|
import asyncio
|
|
7
|
+
import concurrent.futures
|
|
7
8
|
import copy
|
|
8
9
|
import json
|
|
9
10
|
import os
|
|
11
|
+
import queue
|
|
10
12
|
import re
|
|
11
13
|
import signal
|
|
12
14
|
import subprocess
|
|
@@ -1756,7 +1758,7 @@ def _select_option_typed(options: List[str], prompt: str) -> int:
|
|
|
1756
1758
|
def _prompt_line(prompt: str) -> str:
|
|
1757
1759
|
"""``input()`` at an approval prompt, where one Ctrl-C raises ``KeyboardInterrupt``.
|
|
1758
1760
|
|
|
1759
|
-
The approval prompts run inside the turn's ``asyncio.
|
|
1761
|
+
The approval prompts run inside the turn's ``asyncio.Runner``, whose SIGINT handler
|
|
1760
1762
|
(Python 3.11+) only schedules a task cancel on the first Ctrl-C. A blocking
|
|
1761
1763
|
``input()`` never yields to the loop, so that press was swallowed and only a
|
|
1762
1764
|
second one exited (gh #189). The default handler is put back for the duration of
|
|
@@ -1772,7 +1774,9 @@ def _prompt_line(prompt: str) -> str:
|
|
|
1772
1774
|
signal.signal(signal.SIGINT, previous)
|
|
1773
1775
|
|
|
1774
1776
|
|
|
1775
|
-
def handle_interrupt_input(
|
|
1777
|
+
def handle_interrupt_input(
|
|
1778
|
+
num_actions: int = 1, is_generic: bool = False, interrupt: Optional[Dict[str, Any]] = None
|
|
1779
|
+
) -> Any:
|
|
1776
1780
|
"""
|
|
1777
1781
|
Handle user input for an interrupt using arrow key navigation, returning the
|
|
1778
1782
|
value to resume the graph with (the resume payload).
|
|
@@ -1781,6 +1785,9 @@ def handle_interrupt_input(num_actions: int = 1, is_generic: bool = False) -> An
|
|
|
1781
1785
|
num_actions: Number of pending tool calls that need decisions
|
|
1782
1786
|
is_generic: True for a generic/scalar ``interrupt(value)`` (gh #99), False
|
|
1783
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).
|
|
1784
1791
|
|
|
1785
1792
|
Returns:
|
|
1786
1793
|
For a deepagents tool-review interrupt, a ``{"decisions": [...]}`` envelope
|
|
@@ -1843,10 +1850,10 @@ def handle_interrupt_input(num_actions: int = 1, is_generic: bool = False) -> An
|
|
|
1843
1850
|
# Reject decision for each pending action
|
|
1844
1851
|
return {"decisions": [{"type": "reject"} for _ in range(num_actions)]}
|
|
1845
1852
|
elif choice == 2:
|
|
1846
|
-
|
|
1847
|
-
if
|
|
1853
|
+
decisions = _prompt_custom_decision(num_actions, interrupt)
|
|
1854
|
+
if decisions is _BACK_TO_MENU:
|
|
1848
1855
|
continue # nothing sent; show the menu again
|
|
1849
|
-
return {"decisions":
|
|
1856
|
+
return {"decisions": decisions}
|
|
1850
1857
|
else:
|
|
1851
1858
|
sys.exit(EXIT_PAUSED) # left while paused on the interrupt (ADR 0007)
|
|
1852
1859
|
|
|
@@ -1869,23 +1876,147 @@ def _approval_input() -> str:
|
|
|
1869
1876
|
sys.exit(EXIT_PAUSED)
|
|
1870
1877
|
|
|
1871
1878
|
|
|
1872
|
-
def _prompt_custom_decision(
|
|
1873
|
-
|
|
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.
|
|
1874
1883
|
|
|
1875
1884
|
Invalid JSON shows the parse error and asks again. It used to send a reject for
|
|
1876
1885
|
every pending action, so a typo while editing a call rejected it and resumed the
|
|
1877
|
-
agent (gh #174).
|
|
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.
|
|
1878
1890
|
"""
|
|
1879
|
-
print("Enter your decision as JSON (
|
|
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}")
|
|
1880
1893
|
print(f"{DIM}Press Enter on an empty line to go back to the menu.{RESET}")
|
|
1881
1894
|
while True:
|
|
1882
1895
|
json_str = _approval_input().strip()
|
|
1883
1896
|
if not json_str:
|
|
1884
1897
|
return _BACK_TO_MENU
|
|
1885
1898
|
try:
|
|
1886
|
-
|
|
1899
|
+
value = json.loads(json_str)
|
|
1887
1900
|
except json.JSONDecodeError as e:
|
|
1888
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
|
|
1889
2020
|
|
|
1890
2021
|
|
|
1891
2022
|
def print_help():
|
|
@@ -2380,14 +2511,98 @@ async def run_single_turn_agui(
|
|
|
2380
2511
|
exception inside a node/tool arrives with its traceback on the error frame and
|
|
2381
2512
|
``print_chunk`` shows it (gh #153).
|
|
2382
2513
|
"""
|
|
2514
|
+
start_time = time.time()
|
|
2515
|
+
# A session left paused at an approval (exit 2) re-raises that interrupt when a new
|
|
2516
|
+
# message arrives, and the message is dropped. Resolve the pending approval the way
|
|
2517
|
+
# this run resolves any approval, then send the message (gh #191).
|
|
2518
|
+
if await _pending_interrupt(agent, thread_id):
|
|
2519
|
+
if interactive:
|
|
2520
|
+
note = "answer it first, then your message is sent."
|
|
2521
|
+
else:
|
|
2522
|
+
note = "auto-approving it first (--no-interactive), then your message is sent."
|
|
2523
|
+
_status(
|
|
2524
|
+
f"{YELLOW}⏺ This session is paused at an approval from its previous turn; {note}{RESET}"
|
|
2525
|
+
)
|
|
2526
|
+
try:
|
|
2527
|
+
had_error, produced, saw_interrupt = await _stream_turn(
|
|
2528
|
+
agent, message, thread_id, interactive, verbose
|
|
2529
|
+
)
|
|
2530
|
+
except SystemExit:
|
|
2531
|
+
_status(f"{DIM}⏺ Your message was not sent; the session is still paused.{RESET}")
|
|
2532
|
+
raise
|
|
2533
|
+
if saw_interrupt: # the pass only answered the old approval
|
|
2534
|
+
if produced:
|
|
2535
|
+
print() # the previous turn's reply ends; the new message's begins
|
|
2536
|
+
more_error, produced, _ = await _stream_turn(
|
|
2537
|
+
agent, message, thread_id, interactive, verbose
|
|
2538
|
+
)
|
|
2539
|
+
had_error = had_error or more_error
|
|
2540
|
+
else:
|
|
2541
|
+
had_error, produced, _ = await _stream_turn(agent, message, thread_id, interactive, verbose)
|
|
2542
|
+
if not had_error and not produced:
|
|
2543
|
+
had_error = not await _render_empty_turn(agent, thread_id)
|
|
2544
|
+
return time.time() - start_time, had_error
|
|
2545
|
+
|
|
2546
|
+
|
|
2547
|
+
async def _pending_interrupt(agent: Any, thread_id: str) -> bool:
|
|
2548
|
+
"""Whether the thread is paused on an ``interrupt()`` its last turn raised."""
|
|
2549
|
+
graph = getattr(agent, "graph", None)
|
|
2550
|
+
if not thread_id or graph is None or not hasattr(graph, "aget_state"):
|
|
2551
|
+
return False
|
|
2552
|
+
try:
|
|
2553
|
+
state = await graph.aget_state({"configurable": {"thread_id": thread_id}})
|
|
2554
|
+
except Exception: # noqa: BLE001 - no checkpointer / no state: nothing is pending
|
|
2555
|
+
return False
|
|
2556
|
+
if getattr(state, "interrupts", None):
|
|
2557
|
+
return True
|
|
2558
|
+
return any(getattr(task, "interrupts", None) for task in getattr(state, "tasks", ()) or ())
|
|
2559
|
+
|
|
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
|
+
|
|
2591
|
+
async def _stream_turn(
|
|
2592
|
+
agent: Any, message: str, thread_id: str, interactive: bool, verbose: bool
|
|
2593
|
+
) -> tuple[bool, bool, bool]:
|
|
2594
|
+
"""One message through the adapter, answering interrupts until the run ends.
|
|
2595
|
+
|
|
2596
|
+
Returns ``(had_error, produced, saw_interrupt)``.
|
|
2597
|
+
"""
|
|
2383
2598
|
from langstage_cli.agui_stream import agui_stream_updates
|
|
2384
2599
|
|
|
2385
2600
|
print_chunk._streaming_text = False # fresh marker state per turn (gh #34)
|
|
2386
2601
|
print_chunk._streaming_reasoning = False
|
|
2387
2602
|
_md_stream.reset()
|
|
2388
|
-
start_time = time.time()
|
|
2389
2603
|
had_error = False
|
|
2390
2604
|
produced = False # any text / reasoning / tool frame / interrupt this turn (gh #120)
|
|
2605
|
+
saw_interrupt = False
|
|
2391
2606
|
resume = None # first pass sends the message; later passes carry the decision
|
|
2392
2607
|
|
|
2393
2608
|
while True:
|
|
@@ -2400,6 +2615,8 @@ async def run_single_turn_agui(
|
|
|
2400
2615
|
spinner = None if _QUIET else Spinner("Thinking")
|
|
2401
2616
|
if spinner:
|
|
2402
2617
|
spinner.start()
|
|
2618
|
+
if resume is not None:
|
|
2619
|
+
await _discard_failed_resume(agent, thread_id)
|
|
2403
2620
|
try:
|
|
2404
2621
|
with _debug_tracebacks(verbose):
|
|
2405
2622
|
async for chunk in agui_stream_updates(agent, message, thread_id, resume=resume):
|
|
@@ -2415,7 +2632,7 @@ async def run_single_turn_agui(
|
|
|
2415
2632
|
):
|
|
2416
2633
|
produced = True
|
|
2417
2634
|
if chunk.get("status") == "interrupt":
|
|
2418
|
-
has_interrupt = True
|
|
2635
|
+
has_interrupt = saw_interrupt = True
|
|
2419
2636
|
interrupt_data = chunk.get("interrupt", {})
|
|
2420
2637
|
action_requests = interrupt_data.get("action_requests", [])
|
|
2421
2638
|
num_pending_actions = len(action_requests) if action_requests else 1
|
|
@@ -2426,7 +2643,9 @@ async def run_single_turn_agui(
|
|
|
2426
2643
|
_flush_markdown() # a stream that ends without `complete` keeps no held text
|
|
2427
2644
|
|
|
2428
2645
|
if has_interrupt and interactive:
|
|
2429
|
-
resume = handle_interrupt_input(
|
|
2646
|
+
resume = handle_interrupt_input(
|
|
2647
|
+
num_pending_actions, is_generic=is_generic_interrupt, interrupt=interrupt_data
|
|
2648
|
+
)
|
|
2430
2649
|
elif has_interrupt and is_generic_interrupt:
|
|
2431
2650
|
# --no-interactive on a generic interrupt() (gh #99): there is no action
|
|
2432
2651
|
# to "approve", and resuming with a {"decisions": [...]} envelope would
|
|
@@ -2451,9 +2670,7 @@ async def run_single_turn_agui(
|
|
|
2451
2670
|
else:
|
|
2452
2671
|
break
|
|
2453
2672
|
|
|
2454
|
-
|
|
2455
|
-
had_error = not await _render_empty_turn(agent, thread_id)
|
|
2456
|
-
return time.time() - start_time, had_error
|
|
2673
|
+
return had_error, produced, saw_interrupt
|
|
2457
2674
|
|
|
2458
2675
|
|
|
2459
2676
|
# Chunk keys that carry turn output a user sees (text, reasoning, tool frames).
|
|
@@ -2498,6 +2715,76 @@ async def _render_empty_turn(agent: Any, thread_id: str) -> bool:
|
|
|
2498
2715
|
return False
|
|
2499
2716
|
|
|
2500
2717
|
|
|
2718
|
+
class _DaemonThreadPool(concurrent.futures.ThreadPoolExecutor):
|
|
2719
|
+
"""The turn loop's default executor: daemon worker threads nothing waits for (gh #192).
|
|
2720
|
+
|
|
2721
|
+
LangGraph runs sync nodes and tools on the loop's default executor. A stock
|
|
2722
|
+
``ThreadPoolExecutor`` is joined twice when Ctrl-C ends a turn: ``asyncio.run``
|
|
2723
|
+
shuts the default executor down and waits, and the interpreter joins every pool
|
|
2724
|
+
thread at exit. A cancelled future can't stop a thread, so a hung ``def`` tool kept
|
|
2725
|
+
the process alive after ``Goodbye!``/``Aborted!``. These threads are daemons and
|
|
2726
|
+
``shutdown`` never joins them, so an abandoned call dies with the process. It
|
|
2727
|
+
subclasses ``ThreadPoolExecutor`` only because ``set_default_executor`` requires one;
|
|
2728
|
+
``submit`` and ``shutdown`` replace the base pool, whose threads are never started.
|
|
2729
|
+
"""
|
|
2730
|
+
|
|
2731
|
+
def __init__(self) -> None:
|
|
2732
|
+
super().__init__(thread_name_prefix="langstage-cli-turn")
|
|
2733
|
+
self._jobs: "queue.SimpleQueue[Any]" = queue.SimpleQueue()
|
|
2734
|
+
self._idle = threading.Semaphore(0)
|
|
2735
|
+
self._workers = 0
|
|
2736
|
+
self._lock = threading.Lock()
|
|
2737
|
+
self._shutdown = False
|
|
2738
|
+
|
|
2739
|
+
def submit(self, fn, /, *args, **kwargs): # type: ignore[override]
|
|
2740
|
+
with self._lock:
|
|
2741
|
+
if self._shutdown:
|
|
2742
|
+
raise RuntimeError("cannot schedule new futures after shutdown")
|
|
2743
|
+
future: concurrent.futures.Future = concurrent.futures.Future()
|
|
2744
|
+
self._jobs.put((future, fn, args, kwargs))
|
|
2745
|
+
if not self._idle.acquire(blocking=False):
|
|
2746
|
+
self._workers += 1
|
|
2747
|
+
threading.Thread(target=self._work, name="langstage-cli-turn", daemon=True).start()
|
|
2748
|
+
return future
|
|
2749
|
+
|
|
2750
|
+
def _work(self) -> None:
|
|
2751
|
+
while True:
|
|
2752
|
+
job = self._jobs.get()
|
|
2753
|
+
if job is None:
|
|
2754
|
+
return
|
|
2755
|
+
future, fn, args, kwargs = job
|
|
2756
|
+
if future.set_running_or_notify_cancel():
|
|
2757
|
+
try:
|
|
2758
|
+
result = fn(*args, **kwargs)
|
|
2759
|
+
except BaseException as exc: # noqa: BLE001 - delivered to the awaiting task
|
|
2760
|
+
future.set_exception(exc)
|
|
2761
|
+
else:
|
|
2762
|
+
future.set_result(result)
|
|
2763
|
+
del job, future, fn, args, kwargs
|
|
2764
|
+
self._idle.release()
|
|
2765
|
+
|
|
2766
|
+
def shutdown(self, wait: bool = True, *, cancel_futures: bool = False) -> None:
|
|
2767
|
+
# Never joins (see the class docstring). Idle workers exit on their sentinel; a
|
|
2768
|
+
# worker still inside a call finishes it, or dies with the process.
|
|
2769
|
+
with self._lock:
|
|
2770
|
+
if self._shutdown:
|
|
2771
|
+
return
|
|
2772
|
+
self._shutdown = True
|
|
2773
|
+
for _ in range(self._workers):
|
|
2774
|
+
self._jobs.put(None)
|
|
2775
|
+
|
|
2776
|
+
|
|
2777
|
+
def _run_turn(coro: Any) -> Any:
|
|
2778
|
+
"""``asyncio.run`` for one turn, on a loop whose sync work can be abandoned (gh #192).
|
|
2779
|
+
|
|
2780
|
+
Ctrl-C handling is ``asyncio.run``'s own (a cancel, then ``KeyboardInterrupt``); only
|
|
2781
|
+
the executor differs, so a sync tool that is still running no longer holds the exit.
|
|
2782
|
+
"""
|
|
2783
|
+
with asyncio.Runner() as runner:
|
|
2784
|
+
runner.get_loop().set_default_executor(_DaemonThreadPool())
|
|
2785
|
+
return runner.run(coro)
|
|
2786
|
+
|
|
2787
|
+
|
|
2501
2788
|
async def _run_turn_persistent(
|
|
2502
2789
|
graph: Any,
|
|
2503
2790
|
sqlite_path: Path,
|
|
@@ -2616,7 +2903,7 @@ def run_conversation_loop(
|
|
|
2616
2903
|
# first-message snippet.
|
|
2617
2904
|
on_turn(msg, thread_id)
|
|
2618
2905
|
if persist_sqlite_path is not None:
|
|
2619
|
-
return
|
|
2906
|
+
return _run_turn(
|
|
2620
2907
|
_run_turn_persistent(
|
|
2621
2908
|
graph,
|
|
2622
2909
|
persist_sqlite_path,
|
|
@@ -2628,7 +2915,7 @@ def run_conversation_loop(
|
|
|
2628
2915
|
session_config=session_config,
|
|
2629
2916
|
)
|
|
2630
2917
|
)
|
|
2631
|
-
return
|
|
2918
|
+
return _run_turn(run_single_turn_agui(agui_agent, msg, thread_id, interactive, verbose))
|
|
2632
2919
|
|
|
2633
2920
|
# Process initial message if provided
|
|
2634
2921
|
if initial_message is not None:
|
|
@@ -28,11 +28,27 @@ EXIT_USAGE = 64
|
|
|
28
28
|
|
|
29
29
|
class Command(click.Command):
|
|
30
30
|
"""A ``click.Command`` whose usage errors (unknown option, bad choice, a missing
|
|
31
|
-
``-f`` file, ...) exit 64 instead of click's 2.
|
|
31
|
+
``-f`` file, ...) exit 64 instead of click's 2.
|
|
32
|
+
|
|
33
|
+
It also keeps hidden options out of the "Did you mean" hint for an unknown option.
|
|
34
|
+
click matches against every option, so a typo was pointed at the deprecated no-op
|
|
35
|
+
flags hidden from ``--help`` (``--agnet`` -> ``--agui``, gh #193). Those flags still
|
|
36
|
+
parse; they just aren't suggested."""
|
|
32
37
|
|
|
33
38
|
def parse_args(self, ctx: click.Context, args: List[str]) -> List[str]:
|
|
34
39
|
try:
|
|
35
40
|
return super().parse_args(ctx, args)
|
|
41
|
+
except click.NoSuchOption as exc:
|
|
42
|
+
hidden = {
|
|
43
|
+
opt
|
|
44
|
+
for param in self.params
|
|
45
|
+
if getattr(param, "hidden", False)
|
|
46
|
+
for opt in (*param.opts, *param.secondary_opts)
|
|
47
|
+
}
|
|
48
|
+
if exc.possibilities:
|
|
49
|
+
exc.possibilities = [p for p in exc.possibilities if p not in hidden]
|
|
50
|
+
exc.exit_code = EXIT_USAGE
|
|
51
|
+
raise
|
|
36
52
|
except click.UsageError as exc:
|
|
37
53
|
exc.exit_code = EXIT_USAGE
|
|
38
54
|
raise
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: langstage-cli
|
|
3
|
-
Version: 0.6.
|
|
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
|
|
@@ -173,6 +173,13 @@ without you baking a checkpointer into your own graph:
|
|
|
173
173
|
ambiguous one is an error that lists the sessions it matches.
|
|
174
174
|
- A plain run with no flag starts a **new** session that is still persisted, so it can be
|
|
175
175
|
continued later.
|
|
176
|
+
- A session left paused at an approval (exit `2`) is resolved before a new message: the
|
|
177
|
+
CLI says so, asks you (or auto-approves under `--no-interactive`), then sends your
|
|
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.
|
|
176
183
|
|
|
177
184
|
State lives in `~/.langstage/sessions/<workspace-hash>.sqlite` (honoring
|
|
178
185
|
`LANGSTAGE_CONFIG_HOME`; override the whole location with `LANGSTAGE_CLI_SESSIONS_DIR`).
|
|
@@ -25,11 +25,14 @@ tests/test_codeconfig.py
|
|
|
25
25
|
tests/test_config.py
|
|
26
26
|
tests/test_config_command.py
|
|
27
27
|
tests/test_configurable.py
|
|
28
|
+
tests/test_ctrl_c_sync_tool.py
|
|
29
|
+
tests/test_custom_decision_195.py
|
|
28
30
|
tests/test_deferred_pass.py
|
|
29
31
|
tests/test_dumb_term.py
|
|
30
32
|
tests/test_exit_codes.py
|
|
31
33
|
tests/test_generic_interrupt.py
|
|
32
34
|
tests/test_help_render.py
|
|
35
|
+
tests/test_hidden_option_suggestions.py
|
|
33
36
|
tests/test_history_persist.py
|
|
34
37
|
tests/test_hitl_approval_preview.py
|
|
35
38
|
tests/test_hitl_resume_warning.py
|
|
@@ -41,6 +44,7 @@ tests/test_message_boundaries.py
|
|
|
41
44
|
tests/test_no_color.py
|
|
42
45
|
tests/test_no_interactive_approve.py
|
|
43
46
|
tests/test_no_persist_resume.py
|
|
47
|
+
tests/test_paused_session_message.py
|
|
44
48
|
tests/test_persist_env.py
|
|
45
49
|
tests/test_quiet_output.py
|
|
46
50
|
tests/test_reasoning_render.py
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "langstage-cli"
|
|
7
|
-
version = "0.6.
|
|
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
|
|
185
|
-
# The "go back" signal is an empty line
|
|
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
|
-
|
|
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": [
|
|
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,80 @@
|
|
|
1
|
+
"""Ctrl-C ends a turn while a sync tool is still running (gh #192).
|
|
2
|
+
|
|
3
|
+
LangGraph runs ``def`` nodes and tools on the event loop's default executor. A stock
|
|
4
|
+
thread pool is joined when ``asyncio.run`` closes and again at interpreter exit, so after
|
|
5
|
+
Ctrl-C the process waited for the tool, which could be forever. The turn loop's executor
|
|
6
|
+
now uses daemon threads that nothing joins.
|
|
7
|
+
|
|
8
|
+
Ctrl-C is a real SIGINT to the process on POSIX, sent from inside the tool.
|
|
9
|
+
``_thread.interrupt_main`` doesn't wake an idle epoll loop, so it can't stand in for a
|
|
10
|
+
keypress there. Windows has no in-process SIGINT, so it uses ``interrupt_main``, which
|
|
11
|
+
the proactor loop does pick up.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
import subprocess
|
|
16
|
+
import sys
|
|
17
|
+
import textwrap
|
|
18
|
+
import time
|
|
19
|
+
|
|
20
|
+
import pytest
|
|
21
|
+
|
|
22
|
+
pytest.importorskip("ag_ui_langgraph")
|
|
23
|
+
|
|
24
|
+
_SLOW = textwrap.dedent(
|
|
25
|
+
'''
|
|
26
|
+
import _thread, os, signal, threading, time
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from langchain_core.messages import AIMessage
|
|
29
|
+
from langchain_core.tools import tool
|
|
30
|
+
from langgraph.graph import StateGraph, START, END
|
|
31
|
+
from langgraph.graph.message import MessagesState
|
|
32
|
+
from langgraph.prebuilt import ToolNode
|
|
33
|
+
|
|
34
|
+
@tool
|
|
35
|
+
def run_job(seconds: int) -> str:
|
|
36
|
+
"""Run a slow job."""
|
|
37
|
+
Path("started").write_text(repr(time.time()))
|
|
38
|
+
if os.name == "posix":
|
|
39
|
+
press = lambda: os.kill(os.getpid(), signal.SIGINT)
|
|
40
|
+
else:
|
|
41
|
+
press = lambda: _thread.interrupt_main(signal.SIGINT)
|
|
42
|
+
threading.Timer(0.5, press).start()
|
|
43
|
+
time.sleep(seconds)
|
|
44
|
+
return "finished"
|
|
45
|
+
|
|
46
|
+
def plan(state):
|
|
47
|
+
call = {"name": "run_job", "args": {"seconds": 60}, "id": "c1"}
|
|
48
|
+
return {"messages": [AIMessage(content="", tool_calls=[call])]}
|
|
49
|
+
|
|
50
|
+
g = StateGraph(MessagesState)
|
|
51
|
+
g.add_node("plan", plan)
|
|
52
|
+
g.add_node("tools", ToolNode([run_job]))
|
|
53
|
+
g.add_edge(START, "plan")
|
|
54
|
+
g.add_edge("plan", "tools")
|
|
55
|
+
g.add_edge("tools", END)
|
|
56
|
+
graph = g.compile()
|
|
57
|
+
'''
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@pytest.mark.parametrize("persist", [True, False], ids=["persist", "no-persist"])
|
|
62
|
+
def test_ctrl_c_during_a_sync_tool_exits_without_waiting_for_it(tmp_path, persist):
|
|
63
|
+
(tmp_path / "slow_192.py").write_text(_SLOW, encoding="utf-8")
|
|
64
|
+
args = [sys.executable, "-m", "langstage_cli.cli", "-a", "slow_192.py:graph", "go"]
|
|
65
|
+
if not persist:
|
|
66
|
+
args.insert(-1, "--no-persist")
|
|
67
|
+
env = {
|
|
68
|
+
**os.environ,
|
|
69
|
+
"LANGSTAGE_CLI_SESSIONS_DIR": str(tmp_path / "sessions"),
|
|
70
|
+
"LANGSTAGE_CONFIG_HOME": str(tmp_path / "home"),
|
|
71
|
+
}
|
|
72
|
+
p = subprocess.run(
|
|
73
|
+
args, cwd=tmp_path, env=env, input="", capture_output=True, text=True, timeout=120
|
|
74
|
+
)
|
|
75
|
+
ended = time.time()
|
|
76
|
+
started = float((tmp_path / "started").read_text())
|
|
77
|
+
assert p.returncode == 1, (p.stdout, p.stderr)
|
|
78
|
+
assert "Aborted!" in p.stderr
|
|
79
|
+
# The tool sleeps 60s and the press comes 0.5s in; before the fix the exit waited ~60s.
|
|
80
|
+
assert ended - started < 20, (ended - started, p.stderr)
|