langstage-cli 0.6.54__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.
Files changed (81) hide show
  1. {langstage_cli-0.6.54/langstage_cli.egg-info → langstage_cli-0.6.55}/PKG-INFO +5 -1
  2. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/README.md +4 -0
  3. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/langstage_cli/agui_stream.py +14 -1
  4. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/langstage_cli/cli.py +31 -9
  5. {langstage_cli-0.6.54 → langstage_cli-0.6.55/langstage_cli.egg-info}/PKG-INFO +5 -1
  6. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/langstage_cli.egg-info/SOURCES.txt +1 -0
  7. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/pyproject.toml +1 -1
  8. langstage_cli-0.6.55/tests/test_interrupt_answer_text_206.py +311 -0
  9. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/LICENSE +0 -0
  10. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/deepagent_code/__init__.py +0 -0
  11. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/langstage_cli/__init__.py +0 -0
  12. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/langstage_cli/config.py +0 -0
  13. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/langstage_cli/exit_codes.py +0 -0
  14. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/langstage_cli/sessions.py +0 -0
  15. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/langstage_cli.egg-info/dependency_links.txt +0 -0
  16. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/langstage_cli.egg-info/entry_points.txt +0 -0
  17. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/langstage_cli.egg-info/requires.txt +0 -0
  18. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/langstage_cli.egg-info/top_level.txt +0 -0
  19. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/setup.cfg +0 -0
  20. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_advertised_wave4.py +0 -0
  21. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_agui_stream.py +0 -0
  22. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_approval_menu_abort.py +0 -0
  23. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_async_mode.py +0 -0
  24. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_checkpointer.py +0 -0
  25. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_cli.py +0 -0
  26. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_cli_help.py +0 -0
  27. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_codeconfig.py +0 -0
  28. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_config.py +0 -0
  29. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_config_command.py +0 -0
  30. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_configurable.py +0 -0
  31. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_ctrl_c_sync_tool.py +0 -0
  32. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_custom_decision_195.py +0 -0
  33. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_deferred_pass.py +0 -0
  34. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_dumb_term.py +0 -0
  35. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_exit_codes.py +0 -0
  36. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_generic_interrupt.py +0 -0
  37. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_help_render.py +0 -0
  38. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_hidden_option_suggestions.py +0 -0
  39. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_history_persist.py +0 -0
  40. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_hitl_approval_preview.py +0 -0
  41. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_hitl_resume_warning.py +0 -0
  42. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_init.py +0 -0
  43. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_interrupt_non_tty.py +0 -0
  44. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_legacy_config_home.py +0 -0
  45. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_load_error.py +0 -0
  46. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_menu_allowed_197.py +0 -0
  47. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_message_boundaries.py +0 -0
  48. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_no_color.py +0 -0
  49. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_no_interactive_approve.py +0 -0
  50. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_no_persist_resume.py +0 -0
  51. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_paused_session_message.py +0 -0
  52. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_persist_env.py +0 -0
  53. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_quiet_output.py +0 -0
  54. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_quiet_tool_result_204.py +0 -0
  55. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_reasoning_render.py +0 -0
  56. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_rename_shim.py +0 -0
  57. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_render_markdown.py +0 -0
  58. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_routine_1024.py +0 -0
  59. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_session_lifecycle.py +0 -0
  60. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_sessions.py +0 -0
  61. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_show_config.py +0 -0
  62. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_show_config_malformed.py +0 -0
  63. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_spec_loading_core.py +0 -0
  64. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_spec_resolution.py +0 -0
  65. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_spinner_reply_survives.py +0 -0
  66. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_stdin_interactive.py +0 -0
  67. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_stdin_single_shot.py +0 -0
  68. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_stream_mode.py +0 -0
  69. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_streaming_marker.py +0 -0
  70. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_terminal_width.py +0 -0
  71. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_toml_relative_paths.py +0 -0
  72. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_tool_card_args.py +0 -0
  73. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_tool_output_escape.py +0 -0
  74. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_turn_error_verbose.py +0 -0
  75. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_turn_exit_and_render.py +0 -0
  76. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_unicode_console.py +0 -0
  77. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_usage_hint_186.py +0 -0
  78. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_verbose_command.py +0 -0
  79. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_verify_flag.py +0 -0
  80. {langstage_cli-0.6.54 → langstage_cli-0.6.55}/tests/test_workspace.py +0 -0
  81. {langstage_cli-0.6.54 → 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.54
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`).
@@ -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`).
@@ -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. JSON is attempted first so a structured value (number,
1823
- # list, dict) survives; a non-JSON entry is used verbatim as a string — the
1824
- # canonical `value = interrupt("What is your name?")` case, where the user
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
- raw = _approval_input()
1831
- try:
1832
- return json.loads(raw)
1833
- except json.JSONDecodeError:
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()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: langstage-cli
3
- Version: 0.6.54
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`).
@@ -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
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "langstage-cli"
7
- version = "0.6.54"
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
File without changes
File without changes