langstage-cli 0.6.53__tar.gz → 0.6.55__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.53/langstage_cli.egg-info → langstage_cli-0.6.55}/PKG-INFO +9 -3
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/README.md +8 -2
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/langstage_cli/agui_stream.py +14 -1
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/langstage_cli/cli.py +125 -17
- {langstage_cli-0.6.53 → langstage_cli-0.6.55/langstage_cli.egg-info}/PKG-INFO +9 -3
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/langstage_cli.egg-info/SOURCES.txt +2 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/pyproject.toml +1 -1
- langstage_cli-0.6.55/tests/test_interrupt_answer_text_206.py +311 -0
- langstage_cli-0.6.55/tests/test_quiet_tool_result_204.py +344 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/LICENSE +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/deepagent_code/__init__.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/langstage_cli/__init__.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/langstage_cli/config.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/langstage_cli/exit_codes.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/langstage_cli/sessions.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/langstage_cli.egg-info/dependency_links.txt +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/langstage_cli.egg-info/entry_points.txt +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/langstage_cli.egg-info/requires.txt +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/langstage_cli.egg-info/top_level.txt +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/setup.cfg +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_advertised_wave4.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_agui_stream.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_approval_menu_abort.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_async_mode.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_checkpointer.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_cli.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_cli_help.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_codeconfig.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_config.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_config_command.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_configurable.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_ctrl_c_sync_tool.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_custom_decision_195.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_deferred_pass.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_dumb_term.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_exit_codes.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_generic_interrupt.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_help_render.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_hidden_option_suggestions.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_history_persist.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_hitl_approval_preview.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_hitl_resume_warning.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_init.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_interrupt_non_tty.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_legacy_config_home.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_load_error.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_menu_allowed_197.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_message_boundaries.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_no_color.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_no_interactive_approve.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_no_persist_resume.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_paused_session_message.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_persist_env.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_quiet_output.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_reasoning_render.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_rename_shim.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_render_markdown.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_routine_1024.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_session_lifecycle.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_sessions.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_show_config.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_show_config_malformed.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_spec_loading_core.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_spec_resolution.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_spinner_reply_survives.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_stdin_interactive.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_stdin_single_shot.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_stream_mode.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_streaming_marker.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_terminal_width.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_toml_relative_paths.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_tool_card_args.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_tool_output_escape.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_turn_error_verbose.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_turn_exit_and_render.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_unicode_console.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_usage_hint_186.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_verbose_command.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_verify_flag.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/tests/test_workspace.py +0 -0
- {langstage_cli-0.6.53 → langstage_cli-0.6.55}/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.55
|
|
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
|
|
@@ -180,6 +180,10 @@ without you baking a checkpointer into your own graph:
|
|
|
180
180
|
pending action, such as `{"type": "approve"}` or `{"type": "reject", "message": "why"}`
|
|
181
181
|
(a pasted `{"decisions": [...]}` list also works). The prompt shows the shapes the
|
|
182
182
|
pending tool allows, and a decision it would refuse is caught before anything is sent.
|
|
183
|
+
- **Provide a response**, the menu for a plain `interrupt("What is your ZIP code?")`,
|
|
184
|
+
sends your answer as the text you typed: `94110`, `true` and `null` reach the agent as
|
|
185
|
+
strings, like `input()`. To send structured data, type a complete JSON object or array
|
|
186
|
+
(`{"a": 1}`, `["Alice", "B"]`); it arrives as a dict or list.
|
|
183
187
|
|
|
184
188
|
State lives in `~/.langstage/sessions/<workspace-hash>.sqlite` (honoring
|
|
185
189
|
`LANGSTAGE_CONFIG_HOME`; override the whole location with `LANGSTAGE_CLI_SESSIONS_DIR`).
|
|
@@ -309,8 +313,10 @@ langstage-cli --verify -a my_agent.py:graph || { echo "agent broken" >&2; exit 1
|
|
|
309
313
|
A single-shot run (a `MESSAGE` argument or `-f/--file`) prints only the agent's
|
|
310
314
|
reply — no header, spinner, tool chatter, reasoning, timing, or color — as soon as its
|
|
311
315
|
output is **piped** (stdout isn't a TTY). Errors and diagnostics go to stderr, and so does
|
|
312
|
-
anything your agent module `print`s while it is being imported.
|
|
313
|
-
|
|
316
|
+
anything your agent module `print`s while it is being imported. When a turn ends on a
|
|
317
|
+
tool result with no assistant text after it (a `return_direct` tool), that result is the
|
|
318
|
+
reply. The process exits non-zero if the turn failed or left nothing to print, so a run
|
|
319
|
+
is safe to capture:
|
|
314
320
|
|
|
315
321
|
```bash
|
|
316
322
|
answer=$(langstage-cli --demo "say hi") || echo "run failed" >&2
|
|
@@ -142,6 +142,10 @@ without you baking a checkpointer into your own graph:
|
|
|
142
142
|
pending action, such as `{"type": "approve"}` or `{"type": "reject", "message": "why"}`
|
|
143
143
|
(a pasted `{"decisions": [...]}` list also works). The prompt shows the shapes the
|
|
144
144
|
pending tool allows, and a decision it would refuse is caught before anything is sent.
|
|
145
|
+
- **Provide a response**, the menu for a plain `interrupt("What is your ZIP code?")`,
|
|
146
|
+
sends your answer as the text you typed: `94110`, `true` and `null` reach the agent as
|
|
147
|
+
strings, like `input()`. To send structured data, type a complete JSON object or array
|
|
148
|
+
(`{"a": 1}`, `["Alice", "B"]`); it arrives as a dict or list.
|
|
145
149
|
|
|
146
150
|
State lives in `~/.langstage/sessions/<workspace-hash>.sqlite` (honoring
|
|
147
151
|
`LANGSTAGE_CONFIG_HOME`; override the whole location with `LANGSTAGE_CLI_SESSIONS_DIR`).
|
|
@@ -271,8 +275,10 @@ langstage-cli --verify -a my_agent.py:graph || { echo "agent broken" >&2; exit 1
|
|
|
271
275
|
A single-shot run (a `MESSAGE` argument or `-f/--file`) prints only the agent's
|
|
272
276
|
reply — no header, spinner, tool chatter, reasoning, timing, or color — as soon as its
|
|
273
277
|
output is **piped** (stdout isn't a TTY). Errors and diagnostics go to stderr, and so does
|
|
274
|
-
anything your agent module `print`s while it is being imported.
|
|
275
|
-
|
|
278
|
+
anything your agent module `print`s while it is being imported. When a turn ends on a
|
|
279
|
+
tool result with no assistant text after it (a `return_direct` tool), that result is the
|
|
280
|
+
reply. The process exits non-zero if the turn failed or left nothing to print, so a run
|
|
281
|
+
is safe to capture:
|
|
276
282
|
|
|
277
283
|
```bash
|
|
278
284
|
answer=$(langstage-cli --demo "say hi") || echo "run failed" >&2
|
|
@@ -15,6 +15,7 @@ bespoke event-parser path. ADR 0003 finished the migration: since langstage-core
|
|
|
15
15
|
0.6.1). The ``--agui`` flag it was named for is deprecated and inert (gh #88).
|
|
16
16
|
"""
|
|
17
17
|
|
|
18
|
+
import json
|
|
18
19
|
from typing import Any, AsyncIterator, Dict
|
|
19
20
|
|
|
20
21
|
_IMPORT_HINT = 'the AG-UI streaming path needs: pip install "langstage-core[agui]"'
|
|
@@ -64,5 +65,17 @@ async def agui_stream_updates(
|
|
|
64
65
|
"""
|
|
65
66
|
from langstage_core.agui import iter_chunk_frames
|
|
66
67
|
|
|
67
|
-
async for frame in iter_chunk_frames(agent, message, thread_id, resume=resume):
|
|
68
|
+
async for frame in iter_chunk_frames(agent, message, thread_id, resume=text_resume(resume)):
|
|
68
69
|
yield frame
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def text_resume(resume: Any) -> Any:
|
|
73
|
+
"""``resume`` in the form that reaches the graph unchanged over core's resume wire.
|
|
74
|
+
|
|
75
|
+
A ``str`` here is text the user typed. Core's wire (both ``RunAgentInput.resume[]``
|
|
76
|
+
and the legacy ``forwarded_props.command.resume``) JSON-decodes a string payload,
|
|
77
|
+
so ``"94110"`` arrived as the int ``94110``, ``"true"`` as ``True`` and ``"null"``
|
|
78
|
+
as ``None`` (gh #206). Encoding the text as a JSON string makes that decode return
|
|
79
|
+
the very same string. Anything else (a dict, a list, ``None``) passes through.
|
|
80
|
+
"""
|
|
81
|
+
return json.dumps(resume) if isinstance(resume, str) else resume
|
|
@@ -1819,19 +1819,17 @@ def handle_interrupt_input(
|
|
|
1819
1819
|
# A generic interrupt() asks for an arbitrary value, not tool approval, so
|
|
1820
1820
|
# "Approve/Reject" have no meaning and wrapping the answer in
|
|
1821
1821
|
# {"decisions": [...]} corrupts it (gh #99). Collect a raw value and resume
|
|
1822
|
-
# with it UNWRAPPED
|
|
1823
|
-
#
|
|
1824
|
-
#
|
|
1825
|
-
# types `Alice` and the agent must receive `"Alice"`, not an envelope.
|
|
1822
|
+
# with it UNWRAPPED: the canonical `value = interrupt("What is your name?")`
|
|
1823
|
+
# case, where the user types `Alice` and the agent must receive `"Alice"`,
|
|
1824
|
+
# not an envelope. What was typed is the answer, as text (gh #206).
|
|
1826
1825
|
options = ["Provide a response", "Exit"]
|
|
1827
1826
|
choice = select_option(options, "How would you like to respond?")
|
|
1828
1827
|
if choice != 0:
|
|
1829
1828
|
sys.exit(EXIT_PAUSED) # left while paused on the interrupt (ADR 0007)
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
return raw
|
|
1829
|
+
print(
|
|
1830
|
+
f"{DIM}Type your answer. It is sent as text; a JSON object or array is sent as data.{RESET}"
|
|
1831
|
+
)
|
|
1832
|
+
return _generic_answer(_approval_input())
|
|
1835
1833
|
|
|
1836
1834
|
# "Approve all" / "Reject all" are offered only when every pending action allows
|
|
1837
1835
|
# that verb. They used to be offered always, so on HumanInTheLoopMiddleware(
|
|
@@ -1859,6 +1857,30 @@ def handle_interrupt_input(
|
|
|
1859
1857
|
sys.exit(EXIT_PAUSED) # left while paused on the interrupt (ADR 0007)
|
|
1860
1858
|
|
|
1861
1859
|
|
|
1860
|
+
def _generic_answer(raw: str) -> Any:
|
|
1861
|
+
"""The value a typed answer to a generic ``interrupt()`` resumes the graph with.
|
|
1862
|
+
|
|
1863
|
+
The answer is the text that was typed, the way ``input()`` would return it. Every
|
|
1864
|
+
answer used to be tried as JSON first, so a ZIP code ``94110`` reached the graph
|
|
1865
|
+
as an int, ``true`` as a bool, ``1e3`` as a float, and ``null`` as ``None``, which
|
|
1866
|
+
LangGraph reads as "no answer" and asks the question again (gh #206).
|
|
1867
|
+
|
|
1868
|
+
One exception keeps a structured answer possible (gh #99): text that is a
|
|
1869
|
+
complete JSON object or array (``{"a": 1}``, ``["Alice", "B"]``) is sent as that
|
|
1870
|
+
dict or list. Nothing else is decoded, so ``[sic] yes`` and ``"quoted"`` stay
|
|
1871
|
+
exactly as typed, quotes and surrounding spaces included.
|
|
1872
|
+
"""
|
|
1873
|
+
text = raw.strip()
|
|
1874
|
+
if text[:1] in ("{", "["):
|
|
1875
|
+
try:
|
|
1876
|
+
value = json.loads(text)
|
|
1877
|
+
except json.JSONDecodeError:
|
|
1878
|
+
return raw
|
|
1879
|
+
if isinstance(value, (dict, list)):
|
|
1880
|
+
return value
|
|
1881
|
+
return raw
|
|
1882
|
+
|
|
1883
|
+
|
|
1862
1884
|
# Returned by _prompt_custom_decision when the user goes back to the menu. A sentinel,
|
|
1863
1885
|
# not None, because `null` is valid JSON a user could type as a decision.
|
|
1864
1886
|
_BACK_TO_MENU = object()
|
|
@@ -2529,7 +2551,7 @@ async def run_single_turn_agui(
|
|
|
2529
2551
|
f"{YELLOW}⏺ This session is paused at an approval from its previous turn; {note}{RESET}"
|
|
2530
2552
|
)
|
|
2531
2553
|
try:
|
|
2532
|
-
had_error, produced, saw_interrupt = await _stream_turn(
|
|
2554
|
+
had_error, produced, saw_interrupt, tool_results = await _stream_turn(
|
|
2533
2555
|
agent, message, thread_id, interactive, verbose
|
|
2534
2556
|
)
|
|
2535
2557
|
except SystemExit:
|
|
@@ -2538,12 +2560,21 @@ async def run_single_turn_agui(
|
|
|
2538
2560
|
if saw_interrupt: # the pass only answered the old approval
|
|
2539
2561
|
if produced:
|
|
2540
2562
|
print() # the previous turn's reply ends; the new message's begins
|
|
2541
|
-
more_error,
|
|
2563
|
+
more_error, more_produced, _, tool_results = await _stream_turn(
|
|
2542
2564
|
agent, message, thread_id, interactive, verbose
|
|
2543
2565
|
)
|
|
2544
2566
|
had_error = had_error or more_error
|
|
2567
|
+
# Quiet mode: the first pass's reply already reached stdout, so the run
|
|
2568
|
+
# as a whole printed something even if the new message's turn did not.
|
|
2569
|
+
produced = more_produced or (_QUIET and produced)
|
|
2545
2570
|
else:
|
|
2546
|
-
had_error, produced, _ = await _stream_turn(
|
|
2571
|
+
had_error, produced, _, tool_results = await _stream_turn(
|
|
2572
|
+
agent, message, thread_id, interactive, verbose
|
|
2573
|
+
)
|
|
2574
|
+
if _QUIET and not had_error and not produced:
|
|
2575
|
+
# Nothing reached stdout. A turn that ends on a tool result (a
|
|
2576
|
+
# `return_direct` tool) has its answer in that result: print it (gh #204).
|
|
2577
|
+
produced = await _print_final_tool_results(agent, thread_id, tool_results)
|
|
2547
2578
|
if not had_error and not produced:
|
|
2548
2579
|
had_error = not await _render_empty_turn(agent, thread_id)
|
|
2549
2580
|
return time.time() - start_time, had_error
|
|
@@ -2568,7 +2599,17 @@ async def _stream_turn(
|
|
|
2568
2599
|
) -> tuple[bool, bool, bool]:
|
|
2569
2600
|
"""One message through the adapter, answering interrupts until the run ends.
|
|
2570
2601
|
|
|
2571
|
-
Returns ``(had_error, produced, saw_interrupt)``.
|
|
2602
|
+
Returns ``(had_error, produced, saw_interrupt, tool_results)``.
|
|
2603
|
+
|
|
2604
|
+
``produced`` is whether the turn showed the user anything. In a terminal that is
|
|
2605
|
+
any text, reasoning, tool frame or interrupt (gh #120). In quiet mode only reply
|
|
2606
|
+
text reaches stdout, so only reply text counts: tool frames, reasoning and the
|
|
2607
|
+
approval banner are all dropped there, and counting them let a turn print nothing
|
|
2608
|
+
and exit 0 (gh #204).
|
|
2609
|
+
|
|
2610
|
+
``tool_results`` is the text of the tool results the turn ended on: those that
|
|
2611
|
+
arrived after the last reply text and the last tool call. A `return_direct` tool
|
|
2612
|
+
leaves its answer there, with no assistant text after it.
|
|
2572
2613
|
"""
|
|
2573
2614
|
from langstage_cli.agui_stream import agui_stream_updates
|
|
2574
2615
|
|
|
@@ -2576,8 +2617,9 @@ async def _stream_turn(
|
|
|
2576
2617
|
print_chunk._streaming_reasoning = False
|
|
2577
2618
|
_md_stream.reset()
|
|
2578
2619
|
had_error = False
|
|
2579
|
-
produced = False #
|
|
2620
|
+
produced = False # see the docstring: what counts depends on quiet mode
|
|
2580
2621
|
saw_interrupt = False
|
|
2622
|
+
tool_results: List[str] = [] # results since the last reply text / tool call
|
|
2581
2623
|
resume = None # first pass sends the message; later passes carry the decision
|
|
2582
2624
|
|
|
2583
2625
|
while True:
|
|
@@ -2600,10 +2642,17 @@ async def _stream_turn(
|
|
|
2600
2642
|
print_chunk(chunk, verbose=verbose)
|
|
2601
2643
|
if chunk.get("status") == "error":
|
|
2602
2644
|
had_error = True
|
|
2603
|
-
if
|
|
2645
|
+
if _QUIET:
|
|
2646
|
+
if chunk.get("chunk"):
|
|
2647
|
+
produced = True
|
|
2648
|
+
elif chunk.get("status") == "interrupt" or any(
|
|
2604
2649
|
chunk.get(k) for k in _CONTENT_KEYS
|
|
2605
2650
|
):
|
|
2606
2651
|
produced = True
|
|
2652
|
+
if chunk.get("chunk") or chunk.get("tool_calls"):
|
|
2653
|
+
tool_results = [] # the agent went on: those weren't the answer
|
|
2654
|
+
elif "tool_result" in chunk:
|
|
2655
|
+
tool_results.append(_tool_result_text(chunk.get("tool_result")))
|
|
2607
2656
|
if chunk.get("status") == "interrupt":
|
|
2608
2657
|
has_interrupt = saw_interrupt = True
|
|
2609
2658
|
interrupt_data = chunk.get("interrupt", {})
|
|
@@ -2656,13 +2705,72 @@ async def _stream_turn(
|
|
|
2656
2705
|
else:
|
|
2657
2706
|
break
|
|
2658
2707
|
|
|
2659
|
-
return had_error, produced, saw_interrupt
|
|
2708
|
+
return had_error, produced, saw_interrupt, tool_results
|
|
2660
2709
|
|
|
2661
2710
|
|
|
2662
|
-
# Chunk keys that carry turn output a user sees (text, reasoning, tool
|
|
2711
|
+
# Chunk keys that carry turn output a user sees in a terminal (text, reasoning, tool
|
|
2712
|
+
# frames). Quiet mode prints only the text, so there only "chunk" counts (gh #204).
|
|
2663
2713
|
_CONTENT_KEYS = ("chunk", "reasoning", "tool_calls", "tool_result", "extraction")
|
|
2664
2714
|
|
|
2665
2715
|
|
|
2716
|
+
def _tool_result_text(result: Any) -> str:
|
|
2717
|
+
"""A tool result as the text a script should capture."""
|
|
2718
|
+
if result is None:
|
|
2719
|
+
return ""
|
|
2720
|
+
if isinstance(result, str):
|
|
2721
|
+
return result
|
|
2722
|
+
if isinstance(result, (dict, list)):
|
|
2723
|
+
try:
|
|
2724
|
+
return json.dumps(result, default=str, ensure_ascii=False)
|
|
2725
|
+
except (TypeError, ValueError):
|
|
2726
|
+
return str(result)
|
|
2727
|
+
return str(result)
|
|
2728
|
+
|
|
2729
|
+
|
|
2730
|
+
async def _ends_on_assistant_message(agent: Any, thread_id: str) -> bool:
|
|
2731
|
+
"""Whether the thread's last message is the assistant's (so not a tool result).
|
|
2732
|
+
|
|
2733
|
+
Frames can't tell a `return_direct` turn from one where the model read the tool
|
|
2734
|
+
result and then wrote an empty message: both stream a tool call, its result and
|
|
2735
|
+
nothing else. The saved state can. ``False`` when there is no readable state.
|
|
2736
|
+
"""
|
|
2737
|
+
graph = getattr(agent, "graph", None)
|
|
2738
|
+
if not thread_id or graph is None or not hasattr(graph, "aget_state"):
|
|
2739
|
+
return False
|
|
2740
|
+
try:
|
|
2741
|
+
state = await graph.aget_state({"configurable": {"thread_id": thread_id}})
|
|
2742
|
+
except Exception: # noqa: BLE001 - no checkpointer / no state: go by the frames
|
|
2743
|
+
return False
|
|
2744
|
+
values = getattr(state, "values", None)
|
|
2745
|
+
messages = values.get("messages") if isinstance(values, dict) else None
|
|
2746
|
+
if not isinstance(messages, (list, tuple)) or not messages:
|
|
2747
|
+
return False
|
|
2748
|
+
last = messages[-1]
|
|
2749
|
+
if isinstance(last, dict):
|
|
2750
|
+
kind = last.get("type") or last.get("role")
|
|
2751
|
+
else:
|
|
2752
|
+
kind = getattr(last, "type", None)
|
|
2753
|
+
return kind in ("ai", "assistant", "AIMessageChunk")
|
|
2754
|
+
|
|
2755
|
+
|
|
2756
|
+
async def _print_final_tool_results(agent: Any, thread_id: str, results: List[str]) -> bool:
|
|
2757
|
+
"""Quiet mode: print the tool results a turn ended on as its reply (gh #204).
|
|
2758
|
+
|
|
2759
|
+
A `return_direct` tool's result *is* the agent's answer, and no assistant text
|
|
2760
|
+
follows it. Quiet mode dropped it as tool chatter, so ``answer=$(langstage-cli …)``
|
|
2761
|
+
captured an empty string with exit 0. Each result the turn ended on is printed
|
|
2762
|
+
as-is, one per line when several tools ran in the last step, the way two messages
|
|
2763
|
+
in one turn are separated. Returns ``False``, printing nothing, when there is no
|
|
2764
|
+
result text or the model had the last word and left it empty: that turn produced
|
|
2765
|
+
nothing, and the caller reports it.
|
|
2766
|
+
"""
|
|
2767
|
+
texts = [text for text in results if text]
|
|
2768
|
+
if not texts or await _ends_on_assistant_message(agent, thread_id):
|
|
2769
|
+
return False
|
|
2770
|
+
safe_write("\n".join(texts), flush=True)
|
|
2771
|
+
return True
|
|
2772
|
+
|
|
2773
|
+
|
|
2666
2774
|
async def _render_empty_turn(agent: Any, thread_id: str) -> bool:
|
|
2667
2775
|
"""A turn completed with no message: show the graph's final state, or fail clearly.
|
|
2668
2776
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: langstage-cli
|
|
3
|
-
Version: 0.6.
|
|
3
|
+
Version: 0.6.55
|
|
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
|
|
@@ -180,6 +180,10 @@ without you baking a checkpointer into your own graph:
|
|
|
180
180
|
pending action, such as `{"type": "approve"}` or `{"type": "reject", "message": "why"}`
|
|
181
181
|
(a pasted `{"decisions": [...]}` list also works). The prompt shows the shapes the
|
|
182
182
|
pending tool allows, and a decision it would refuse is caught before anything is sent.
|
|
183
|
+
- **Provide a response**, the menu for a plain `interrupt("What is your ZIP code?")`,
|
|
184
|
+
sends your answer as the text you typed: `94110`, `true` and `null` reach the agent as
|
|
185
|
+
strings, like `input()`. To send structured data, type a complete JSON object or array
|
|
186
|
+
(`{"a": 1}`, `["Alice", "B"]`); it arrives as a dict or list.
|
|
183
187
|
|
|
184
188
|
State lives in `~/.langstage/sessions/<workspace-hash>.sqlite` (honoring
|
|
185
189
|
`LANGSTAGE_CONFIG_HOME`; override the whole location with `LANGSTAGE_CLI_SESSIONS_DIR`).
|
|
@@ -309,8 +313,10 @@ langstage-cli --verify -a my_agent.py:graph || { echo "agent broken" >&2; exit 1
|
|
|
309
313
|
A single-shot run (a `MESSAGE` argument or `-f/--file`) prints only the agent's
|
|
310
314
|
reply — no header, spinner, tool chatter, reasoning, timing, or color — as soon as its
|
|
311
315
|
output is **piped** (stdout isn't a TTY). Errors and diagnostics go to stderr, and so does
|
|
312
|
-
anything your agent module `print`s while it is being imported.
|
|
313
|
-
|
|
316
|
+
anything your agent module `print`s while it is being imported. When a turn ends on a
|
|
317
|
+
tool result with no assistant text after it (a `return_direct` tool), that result is the
|
|
318
|
+
reply. The process exits non-zero if the turn failed or left nothing to print, so a run
|
|
319
|
+
is safe to capture:
|
|
314
320
|
|
|
315
321
|
```bash
|
|
316
322
|
answer=$(langstage-cli --demo "say hi") || echo "run failed" >&2
|
|
@@ -37,6 +37,7 @@ tests/test_history_persist.py
|
|
|
37
37
|
tests/test_hitl_approval_preview.py
|
|
38
38
|
tests/test_hitl_resume_warning.py
|
|
39
39
|
tests/test_init.py
|
|
40
|
+
tests/test_interrupt_answer_text_206.py
|
|
40
41
|
tests/test_interrupt_non_tty.py
|
|
41
42
|
tests/test_legacy_config_home.py
|
|
42
43
|
tests/test_load_error.py
|
|
@@ -48,6 +49,7 @@ tests/test_no_persist_resume.py
|
|
|
48
49
|
tests/test_paused_session_message.py
|
|
49
50
|
tests/test_persist_env.py
|
|
50
51
|
tests/test_quiet_output.py
|
|
52
|
+
tests/test_quiet_tool_result_204.py
|
|
51
53
|
tests/test_reasoning_render.py
|
|
52
54
|
tests/test_rename_shim.py
|
|
53
55
|
tests/test_render_markdown.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.55"
|
|
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"
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
"""A typed answer to a plain ``interrupt("…")`` reaches the graph as text (gh #206).
|
|
2
|
+
|
|
3
|
+
The answer was tried as JSON first, by the CLI and again by core's resume wire, so
|
|
4
|
+
what the graph received depended on what the user happened to type: ``94110`` arrived
|
|
5
|
+
as an int (and crashed an agent that called ``.strip()`` on it), ``true`` as a bool,
|
|
6
|
+
``1e3`` as a float, and ``null`` as ``None``, which LangGraph reads as "no answer" and
|
|
7
|
+
asks the same question again. ``02139`` stayed a string, so two answers to one
|
|
8
|
+
question had different types.
|
|
9
|
+
|
|
10
|
+
Now the answer is the text that was typed, as ``input()`` would return it. The one
|
|
11
|
+
exception keeps gh #99: a complete JSON object or array is sent as that dict or list.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import io
|
|
15
|
+
import os
|
|
16
|
+
import subprocess
|
|
17
|
+
import sys
|
|
18
|
+
import textwrap
|
|
19
|
+
import time
|
|
20
|
+
from contextlib import redirect_stdout
|
|
21
|
+
|
|
22
|
+
import pytest
|
|
23
|
+
from click.testing import CliRunner
|
|
24
|
+
|
|
25
|
+
pytest.importorskip("ag_ui_langgraph")
|
|
26
|
+
pytest.importorskip("fastapi")
|
|
27
|
+
|
|
28
|
+
from langstage_cli import cli # noqa: E402
|
|
29
|
+
from langstage_cli.agui_stream import build_session_agent, text_resume # noqa: E402
|
|
30
|
+
from langstage_cli.cli import _generic_answer, run_single_turn_agui # noqa: E402
|
|
31
|
+
|
|
32
|
+
# Echoes exactly what interrupt() returned, with its type.
|
|
33
|
+
_ECHO_AGENT = textwrap.dedent(
|
|
34
|
+
"""
|
|
35
|
+
from langgraph.graph import StateGraph, START, END
|
|
36
|
+
from langgraph.graph.message import MessagesState
|
|
37
|
+
from langgraph.checkpoint.memory import MemorySaver
|
|
38
|
+
from langgraph.types import interrupt
|
|
39
|
+
from langchain_core.messages import AIMessage
|
|
40
|
+
|
|
41
|
+
def respond(state):
|
|
42
|
+
ans = interrupt("What is your ZIP code?")
|
|
43
|
+
return {"messages": [AIMessage(content=f"answer={ans!r} type={type(ans).__name__}")]}
|
|
44
|
+
|
|
45
|
+
g = StateGraph(MessagesState)
|
|
46
|
+
g.add_node("r", respond)
|
|
47
|
+
g.add_edge(START, "r")
|
|
48
|
+
g.add_edge("r", END)
|
|
49
|
+
graph = g.compile(checkpointer=MemorySaver())
|
|
50
|
+
"""
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
# The issue's agent: it asked for text, so it treats the answer as text.
|
|
54
|
+
_ZIP_AGENT = _ECHO_AGENT.replace(
|
|
55
|
+
'f"answer={ans!r} type={type(ans).__name__}"',
|
|
56
|
+
'f"Shipping to ZIP {ans.strip()} (type={type(ans).__name__})"',
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
_TEXT = [
|
|
60
|
+
"94110",
|
|
61
|
+
"02139",
|
|
62
|
+
"true",
|
|
63
|
+
"false",
|
|
64
|
+
"null",
|
|
65
|
+
"1e3",
|
|
66
|
+
"-4.5",
|
|
67
|
+
"yes",
|
|
68
|
+
"Alice",
|
|
69
|
+
'"quoted"',
|
|
70
|
+
" padded ",
|
|
71
|
+
"",
|
|
72
|
+
" ",
|
|
73
|
+
"[sic] yes",
|
|
74
|
+
"[1, 2",
|
|
75
|
+
'{"a": 1} or so',
|
|
76
|
+
"{not json}",
|
|
77
|
+
]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@pytest.mark.parametrize("typed", _TEXT)
|
|
81
|
+
def test_an_answer_is_the_text_that_was_typed(typed):
|
|
82
|
+
assert _generic_answer(typed) == typed
|
|
83
|
+
assert type(_generic_answer(typed)) is str
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@pytest.mark.parametrize(
|
|
87
|
+
("typed", "value"),
|
|
88
|
+
[
|
|
89
|
+
('["Alice", "B"]', ["Alice", "B"]),
|
|
90
|
+
('{"a": 1}', {"a": 1}),
|
|
91
|
+
(' {"a": [1, null, true]} ', {"a": [1, None, True]}),
|
|
92
|
+
("[]", []),
|
|
93
|
+
("{}", {}),
|
|
94
|
+
],
|
|
95
|
+
)
|
|
96
|
+
def test_a_complete_json_object_or_array_is_sent_as_data(typed, value):
|
|
97
|
+
assert _generic_answer(typed) == value
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
@pytest.mark.parametrize("text", ["94110", "true", "null", "1e3", "", "Alice", '"q"', "é ✓"])
|
|
101
|
+
def test_text_survives_the_json_decode_cores_wire_applies(text):
|
|
102
|
+
import json
|
|
103
|
+
|
|
104
|
+
assert json.loads(text_resume(text)) == text
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def test_only_text_is_encoded_for_the_wire():
|
|
108
|
+
decisions = {"decisions": [{"type": "approve"}]}
|
|
109
|
+
assert text_resume(decisions) is decisions
|
|
110
|
+
assert text_resume(["Alice", "B"]) == ["Alice", "B"]
|
|
111
|
+
assert text_resume(None) is None
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _build(source: str):
|
|
115
|
+
ns: dict = {}
|
|
116
|
+
exec(source, ns)
|
|
117
|
+
return build_session_agent(ns["graph"])
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
async def _answer(monkeypatch, source: str, typed: str, thread: str) -> tuple[str, int, bool]:
|
|
121
|
+
"""Run one turn, answer its interrupt with ``typed``. Returns (output, menus, error)."""
|
|
122
|
+
agent = _build(source)
|
|
123
|
+
menus = []
|
|
124
|
+
|
|
125
|
+
def menu(options, prompt=""):
|
|
126
|
+
menus.append(prompt)
|
|
127
|
+
if len(menus) > 2: # the question came back: stop instead of looping forever
|
|
128
|
+
raise AssertionError("the same question was asked again")
|
|
129
|
+
return 0
|
|
130
|
+
|
|
131
|
+
monkeypatch.setattr(cli, "_is_a_tty", lambda *a, **k: True)
|
|
132
|
+
monkeypatch.setattr(cli, "select_option", menu)
|
|
133
|
+
monkeypatch.setattr("builtins.input", lambda *a, **k: typed)
|
|
134
|
+
buf = io.StringIO()
|
|
135
|
+
with redirect_stdout(buf):
|
|
136
|
+
_elapsed, had_error = await run_single_turn_agui(agent, "hi", thread, interactive=True)
|
|
137
|
+
return buf.getvalue(), len(menus), had_error
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@pytest.mark.parametrize("typed", _TEXT)
|
|
141
|
+
async def test_the_graph_receives_the_typed_text(monkeypatch, typed):
|
|
142
|
+
out, menus, had_error = await _answer(monkeypatch, _ECHO_AGENT, typed, f"t-{typed!r}")
|
|
143
|
+
assert had_error is False, out
|
|
144
|
+
assert f"answer={typed!r} type=str" in out, out
|
|
145
|
+
assert menus == 1, out # `null` used to bring the question back
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@pytest.mark.parametrize(
|
|
149
|
+
("typed", "shown"),
|
|
150
|
+
[
|
|
151
|
+
('["Alice", "B"]', "answer=['Alice', 'B'] type=list"),
|
|
152
|
+
('{"a": 1}', "answer={'a': 1} type=dict"),
|
|
153
|
+
],
|
|
154
|
+
)
|
|
155
|
+
async def test_the_graph_receives_a_structured_answer_as_data(monkeypatch, typed, shown):
|
|
156
|
+
out, menus, had_error = await _answer(monkeypatch, _ECHO_AGENT, typed, f"t-{typed!r}")
|
|
157
|
+
assert had_error is False, out
|
|
158
|
+
assert shown in out, out
|
|
159
|
+
assert menus == 1, out
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@pytest.mark.parametrize("zip_code", ["94110", "02139"])
|
|
163
|
+
async def test_the_issues_zip_agent_gets_a_string_either_way(monkeypatch, zip_code):
|
|
164
|
+
out, _menus, had_error = await _answer(monkeypatch, _ZIP_AGENT, zip_code, f"zip-{zip_code}")
|
|
165
|
+
assert had_error is False, out
|
|
166
|
+
assert f"Shipping to ZIP {zip_code} (type=str)" in out, out
|
|
167
|
+
assert "AttributeError" not in out, out
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
async def test_the_prompt_says_how_the_answer_is_sent(monkeypatch):
|
|
171
|
+
out, _menus, _err = await _answer(monkeypatch, _ECHO_AGENT, "94110", "t-hint")
|
|
172
|
+
assert "sent as text" in out, out
|
|
173
|
+
assert out.index("sent as text") < out.index("answer='94110'"), out
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@pytest.mark.parametrize("typed", ["94110", "null", "Alice"])
|
|
177
|
+
async def test_text_survives_the_legacy_resume_wire_too(monkeypatch, typed):
|
|
178
|
+
# Core falls back to forwarded_props.command.resume on an adapter without resume[];
|
|
179
|
+
# that reader JSON-decodes a string as well.
|
|
180
|
+
agui = pytest.importorskip("langstage_core.agui")
|
|
181
|
+
if not hasattr(agui, "_supports_agui_resume"):
|
|
182
|
+
pytest.skip("this core has no resume-wire switch to force")
|
|
183
|
+
monkeypatch.setattr(agui, "_supports_agui_resume", lambda agent: False)
|
|
184
|
+
out, menus, had_error = await _answer(monkeypatch, _ECHO_AGENT, typed, f"legacy-{typed}")
|
|
185
|
+
assert had_error is False, out
|
|
186
|
+
assert f"answer={typed!r} type=str" in out, out
|
|
187
|
+
assert menus == 1, out
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
async def test_no_interactive_still_resumes_with_an_empty_string():
|
|
191
|
+
agent = _build(_ECHO_AGENT)
|
|
192
|
+
buf = io.StringIO()
|
|
193
|
+
with redirect_stdout(buf):
|
|
194
|
+
_elapsed, had_error = await run_single_turn_agui(agent, "hi", "t-auto", interactive=False)
|
|
195
|
+
assert had_error is False, buf.getvalue()
|
|
196
|
+
assert "answer='' type=str" in buf.getvalue(), buf.getvalue()
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def test_the_numbered_menu_on_a_dumb_terminal_sends_text(tmp_path, monkeypatch):
|
|
200
|
+
# TERM=dumb answers the menu by typing a number, then the answer on the next line.
|
|
201
|
+
monkeypatch.chdir(tmp_path)
|
|
202
|
+
monkeypatch.setenv("LANGSTAGE_CLI_SESSIONS_DIR", str(tmp_path / "_sessions"))
|
|
203
|
+
monkeypatch.setenv("TERM", "dumb")
|
|
204
|
+
(tmp_path / "zip_agent.py").write_text(_ECHO_AGENT, encoding="utf-8")
|
|
205
|
+
monkeypatch.setattr(cli, "_is_a_tty", lambda stream: True)
|
|
206
|
+
typed = iter(["1", "94110"])
|
|
207
|
+
monkeypatch.setattr("builtins.input", lambda *a, **k: next(typed))
|
|
208
|
+
r = CliRunner().invoke(cli.main, ["-a", "zip_agent.py:graph", "ship my order"])
|
|
209
|
+
assert r.exit_code == 0, r.output
|
|
210
|
+
assert "answer='94110' type=str" in r.output, r.output
|
|
211
|
+
assert "sent as text" in r.output, r.output
|
|
212
|
+
assert "\x1b" not in r.output, repr(r.output)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def test_a_paused_session_answered_later_gets_text(tmp_path, monkeypatch):
|
|
216
|
+
# Left paused (exit 2), then answered on the next run: the same prompt, the same rule.
|
|
217
|
+
pytest.importorskip("langgraph.checkpoint.sqlite.aio")
|
|
218
|
+
monkeypatch.chdir(tmp_path)
|
|
219
|
+
monkeypatch.setenv("LANGSTAGE_CLI_SESSIONS_DIR", str(tmp_path / "_sessions"))
|
|
220
|
+
(tmp_path / "zip_agent.py").write_text(
|
|
221
|
+
_ECHO_AGENT.replace("checkpointer=MemorySaver()", ""), encoding="utf-8"
|
|
222
|
+
)
|
|
223
|
+
paused = CliRunner().invoke(cli.main, ["-a", "zip_agent.py:graph", "ship my order"])
|
|
224
|
+
assert paused.exit_code == 2, paused.output
|
|
225
|
+
|
|
226
|
+
monkeypatch.setattr(cli, "_is_a_tty", lambda stream: True)
|
|
227
|
+
monkeypatch.setattr(cli, "select_option", lambda *a, **k: 0)
|
|
228
|
+
answers = iter(["true", "null"]) # the old question, then the new message's question
|
|
229
|
+
monkeypatch.setattr("builtins.input", lambda *a, **k: next(answers))
|
|
230
|
+
r = CliRunner().invoke(cli.main, ["-a", "zip_agent.py:graph", "-c", "and another"])
|
|
231
|
+
assert r.exit_code == 0, r.output
|
|
232
|
+
assert "answer='true' type=str" in r.output, r.output
|
|
233
|
+
assert "answer='null' type=str" in r.output, r.output
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _type_on_pty(tmp_path, term, args, steps):
|
|
237
|
+
"""Run the CLI on a real pty; for each ``(wait_for, send)`` step, send once seen."""
|
|
238
|
+
import pty
|
|
239
|
+
import select
|
|
240
|
+
|
|
241
|
+
env = {k: v for k, v in os.environ.items() if k not in ("NO_COLOR", "TERM")}
|
|
242
|
+
env["LANGSTAGE_CLI_SESSIONS_DIR"] = str(tmp_path / "_sessions")
|
|
243
|
+
env["TERM"] = term
|
|
244
|
+
master, slave = pty.openpty()
|
|
245
|
+
proc = subprocess.Popen(
|
|
246
|
+
[sys.executable, "-c", "from langstage_cli.cli import main; main()", *args],
|
|
247
|
+
stdin=slave,
|
|
248
|
+
stdout=slave,
|
|
249
|
+
stderr=slave,
|
|
250
|
+
cwd=tmp_path,
|
|
251
|
+
env=env,
|
|
252
|
+
close_fds=True,
|
|
253
|
+
)
|
|
254
|
+
os.close(slave)
|
|
255
|
+
out = b""
|
|
256
|
+
steps = list(steps)
|
|
257
|
+
seen_upto = 0
|
|
258
|
+
deadline = time.monotonic() + 90
|
|
259
|
+
try:
|
|
260
|
+
while time.monotonic() < deadline:
|
|
261
|
+
ready, _, _ = select.select([master], [], [], 0.5)
|
|
262
|
+
if not ready:
|
|
263
|
+
if proc.poll() is not None:
|
|
264
|
+
break
|
|
265
|
+
continue
|
|
266
|
+
try:
|
|
267
|
+
data = os.read(master, 4096)
|
|
268
|
+
except OSError: # EIO: the child closed the terminal
|
|
269
|
+
break
|
|
270
|
+
if not data:
|
|
271
|
+
break
|
|
272
|
+
out += data
|
|
273
|
+
while steps and steps[0][0] in out[seen_upto:]:
|
|
274
|
+
wait_for, send = steps.pop(0)
|
|
275
|
+
seen_upto = out.index(wait_for, seen_upto) + len(wait_for)
|
|
276
|
+
os.write(master, send)
|
|
277
|
+
proc.wait(timeout=10)
|
|
278
|
+
finally:
|
|
279
|
+
if proc.poll() is None:
|
|
280
|
+
proc.kill()
|
|
281
|
+
os.close(master)
|
|
282
|
+
return proc.returncode, out.decode("utf-8", errors="replace")
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
@pytest.mark.skipif(sys.platform == "win32", reason="needs a POSIX pty")
|
|
286
|
+
@pytest.mark.parametrize("typed", ["94110", "null", "true"])
|
|
287
|
+
def test_text_typed_at_the_real_prompt_reaches_the_graph_as_text(tmp_path, typed):
|
|
288
|
+
(tmp_path / "zip_agent.py").write_text(_ECHO_AGENT, encoding="utf-8")
|
|
289
|
+
code, out = _type_on_pty(
|
|
290
|
+
tmp_path,
|
|
291
|
+
"dumb",
|
|
292
|
+
["-a", "zip_agent.py:graph", "ship my order"],
|
|
293
|
+
[(b"Choose 1-", b"1\n"), (b"sent as text", typed.encode() + b"\n")],
|
|
294
|
+
)
|
|
295
|
+
assert f"answer={typed!r} type=str" in out, repr(out)
|
|
296
|
+
assert out.count("What is your ZIP code?") == 1, repr(out) # asked once
|
|
297
|
+
assert code == 0, out
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
@pytest.mark.skipif(sys.platform == "win32", reason="needs a POSIX pty")
|
|
301
|
+
def test_arrow_key_menu_then_typed_text_on_a_real_terminal(tmp_path):
|
|
302
|
+
(tmp_path / "zip_agent.py").write_text(_ZIP_AGENT, encoding="utf-8")
|
|
303
|
+
code, out = _type_on_pty(
|
|
304
|
+
tmp_path,
|
|
305
|
+
"xterm-256color",
|
|
306
|
+
["-a", "zip_agent.py:graph", "ship my order"],
|
|
307
|
+
[(b"Provide a response", b"\r"), (b"sent as text", b"94110\n")],
|
|
308
|
+
)
|
|
309
|
+
assert "Shipping to ZIP 94110 (type=str)" in out, repr(out)
|
|
310
|
+
assert "AttributeError" not in out, repr(out)
|
|
311
|
+
assert code == 0, out
|