langstage-cli 0.6.47__tar.gz → 0.6.48__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 (77) hide show
  1. {langstage_cli-0.6.47/langstage_cli.egg-info → langstage_cli-0.6.48}/PKG-INFO +4 -1
  2. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/README.md +3 -0
  3. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/langstage_cli/cli.py +132 -8
  4. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/langstage_cli/exit_codes.py +17 -1
  5. {langstage_cli-0.6.47 → langstage_cli-0.6.48/langstage_cli.egg-info}/PKG-INFO +4 -1
  6. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/langstage_cli.egg-info/SOURCES.txt +3 -0
  7. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/pyproject.toml +1 -1
  8. langstage_cli-0.6.48/tests/test_ctrl_c_sync_tool.py +80 -0
  9. langstage_cli-0.6.48/tests/test_hidden_option_suggestions.py +27 -0
  10. langstage_cli-0.6.48/tests/test_paused_session_message.py +100 -0
  11. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/LICENSE +0 -0
  12. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/deepagent_code/__init__.py +0 -0
  13. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/langstage_cli/__init__.py +0 -0
  14. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/langstage_cli/agui_stream.py +0 -0
  15. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/langstage_cli/config.py +0 -0
  16. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/langstage_cli/sessions.py +0 -0
  17. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/langstage_cli.egg-info/dependency_links.txt +0 -0
  18. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/langstage_cli.egg-info/entry_points.txt +0 -0
  19. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/langstage_cli.egg-info/requires.txt +0 -0
  20. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/langstage_cli.egg-info/top_level.txt +0 -0
  21. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/setup.cfg +0 -0
  22. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_advertised_wave4.py +0 -0
  23. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_agui_stream.py +0 -0
  24. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_approval_menu_abort.py +0 -0
  25. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_async_mode.py +0 -0
  26. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_checkpointer.py +0 -0
  27. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_cli.py +0 -0
  28. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_cli_help.py +0 -0
  29. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_codeconfig.py +0 -0
  30. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_config.py +0 -0
  31. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_config_command.py +0 -0
  32. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_configurable.py +0 -0
  33. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_deferred_pass.py +0 -0
  34. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_dumb_term.py +0 -0
  35. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_exit_codes.py +0 -0
  36. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_generic_interrupt.py +0 -0
  37. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_help_render.py +0 -0
  38. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_history_persist.py +0 -0
  39. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_hitl_approval_preview.py +0 -0
  40. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_hitl_resume_warning.py +0 -0
  41. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_init.py +0 -0
  42. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_interrupt_non_tty.py +0 -0
  43. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_legacy_config_home.py +0 -0
  44. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_load_error.py +0 -0
  45. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_message_boundaries.py +0 -0
  46. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_no_color.py +0 -0
  47. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_no_interactive_approve.py +0 -0
  48. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_no_persist_resume.py +0 -0
  49. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_persist_env.py +0 -0
  50. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_quiet_output.py +0 -0
  51. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_reasoning_render.py +0 -0
  52. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_rename_shim.py +0 -0
  53. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_render_markdown.py +0 -0
  54. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_routine_1024.py +0 -0
  55. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_session_lifecycle.py +0 -0
  56. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_sessions.py +0 -0
  57. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_show_config.py +0 -0
  58. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_show_config_malformed.py +0 -0
  59. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_spec_loading_core.py +0 -0
  60. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_spec_resolution.py +0 -0
  61. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_spinner_reply_survives.py +0 -0
  62. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_stdin_interactive.py +0 -0
  63. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_stdin_single_shot.py +0 -0
  64. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_stream_mode.py +0 -0
  65. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_streaming_marker.py +0 -0
  66. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_terminal_width.py +0 -0
  67. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_toml_relative_paths.py +0 -0
  68. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_tool_card_args.py +0 -0
  69. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_tool_output_escape.py +0 -0
  70. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_turn_error_verbose.py +0 -0
  71. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_turn_exit_and_render.py +0 -0
  72. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_unicode_console.py +0 -0
  73. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_usage_hint_186.py +0 -0
  74. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_verbose_command.py +0 -0
  75. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_verify_flag.py +0 -0
  76. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/tests/test_workspace.py +0 -0
  77. {langstage_cli-0.6.47 → langstage_cli-0.6.48}/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.47
3
+ Version: 0.6.48
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,9 @@ 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.
176
179
 
177
180
  State lives in `~/.langstage/sessions/<workspace-hash>.sqlite` (honoring
178
181
  `LANGSTAGE_CONFIG_HOME`; override the whole location with `LANGSTAGE_CLI_SESSIONS_DIR`).
@@ -135,6 +135,9 @@ 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.
138
141
 
139
142
  State lives in `~/.langstage/sessions/<workspace-hash>.sqlite` (honoring
140
143
  `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.run``, whose SIGINT handler
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
@@ -2380,14 +2382,68 @@ async def run_single_turn_agui(
2380
2382
  exception inside a node/tool arrives with its traceback on the error frame and
2381
2383
  ``print_chunk`` shows it (gh #153).
2382
2384
  """
2385
+ start_time = time.time()
2386
+ # A session left paused at an approval (exit 2) re-raises that interrupt when a new
2387
+ # message arrives, and the message is dropped. Resolve the pending approval the way
2388
+ # this run resolves any approval, then send the message (gh #191).
2389
+ if await _pending_interrupt(agent, thread_id):
2390
+ if interactive:
2391
+ note = "answer it first, then your message is sent."
2392
+ else:
2393
+ note = "auto-approving it first (--no-interactive), then your message is sent."
2394
+ _status(
2395
+ f"{YELLOW}⏺ This session is paused at an approval from its previous turn; {note}{RESET}"
2396
+ )
2397
+ try:
2398
+ had_error, produced, saw_interrupt = await _stream_turn(
2399
+ agent, message, thread_id, interactive, verbose
2400
+ )
2401
+ except SystemExit:
2402
+ _status(f"{DIM}⏺ Your message was not sent; the session is still paused.{RESET}")
2403
+ raise
2404
+ if saw_interrupt: # the pass only answered the old approval
2405
+ if produced:
2406
+ print() # the previous turn's reply ends; the new message's begins
2407
+ more_error, produced, _ = await _stream_turn(
2408
+ agent, message, thread_id, interactive, verbose
2409
+ )
2410
+ had_error = had_error or more_error
2411
+ else:
2412
+ had_error, produced, _ = await _stream_turn(agent, message, thread_id, interactive, verbose)
2413
+ if not had_error and not produced:
2414
+ had_error = not await _render_empty_turn(agent, thread_id)
2415
+ return time.time() - start_time, had_error
2416
+
2417
+
2418
+ async def _pending_interrupt(agent: Any, thread_id: str) -> bool:
2419
+ """Whether the thread is paused on an ``interrupt()`` its last turn raised."""
2420
+ graph = getattr(agent, "graph", None)
2421
+ if not thread_id or graph is None or not hasattr(graph, "aget_state"):
2422
+ return False
2423
+ try:
2424
+ state = await graph.aget_state({"configurable": {"thread_id": thread_id}})
2425
+ except Exception: # noqa: BLE001 - no checkpointer / no state: nothing is pending
2426
+ return False
2427
+ if getattr(state, "interrupts", None):
2428
+ return True
2429
+ return any(getattr(task, "interrupts", None) for task in getattr(state, "tasks", ()) or ())
2430
+
2431
+
2432
+ async def _stream_turn(
2433
+ agent: Any, message: str, thread_id: str, interactive: bool, verbose: bool
2434
+ ) -> tuple[bool, bool, bool]:
2435
+ """One message through the adapter, answering interrupts until the run ends.
2436
+
2437
+ Returns ``(had_error, produced, saw_interrupt)``.
2438
+ """
2383
2439
  from langstage_cli.agui_stream import agui_stream_updates
2384
2440
 
2385
2441
  print_chunk._streaming_text = False # fresh marker state per turn (gh #34)
2386
2442
  print_chunk._streaming_reasoning = False
2387
2443
  _md_stream.reset()
2388
- start_time = time.time()
2389
2444
  had_error = False
2390
2445
  produced = False # any text / reasoning / tool frame / interrupt this turn (gh #120)
2446
+ saw_interrupt = False
2391
2447
  resume = None # first pass sends the message; later passes carry the decision
2392
2448
 
2393
2449
  while True:
@@ -2415,7 +2471,7 @@ async def run_single_turn_agui(
2415
2471
  ):
2416
2472
  produced = True
2417
2473
  if chunk.get("status") == "interrupt":
2418
- has_interrupt = True
2474
+ has_interrupt = saw_interrupt = True
2419
2475
  interrupt_data = chunk.get("interrupt", {})
2420
2476
  action_requests = interrupt_data.get("action_requests", [])
2421
2477
  num_pending_actions = len(action_requests) if action_requests else 1
@@ -2451,9 +2507,7 @@ async def run_single_turn_agui(
2451
2507
  else:
2452
2508
  break
2453
2509
 
2454
- if not had_error and not produced:
2455
- had_error = not await _render_empty_turn(agent, thread_id)
2456
- return time.time() - start_time, had_error
2510
+ return had_error, produced, saw_interrupt
2457
2511
 
2458
2512
 
2459
2513
  # Chunk keys that carry turn output a user sees (text, reasoning, tool frames).
@@ -2498,6 +2552,76 @@ async def _render_empty_turn(agent: Any, thread_id: str) -> bool:
2498
2552
  return False
2499
2553
 
2500
2554
 
2555
+ class _DaemonThreadPool(concurrent.futures.ThreadPoolExecutor):
2556
+ """The turn loop's default executor: daemon worker threads nothing waits for (gh #192).
2557
+
2558
+ LangGraph runs sync nodes and tools on the loop's default executor. A stock
2559
+ ``ThreadPoolExecutor`` is joined twice when Ctrl-C ends a turn: ``asyncio.run``
2560
+ shuts the default executor down and waits, and the interpreter joins every pool
2561
+ thread at exit. A cancelled future can't stop a thread, so a hung ``def`` tool kept
2562
+ the process alive after ``Goodbye!``/``Aborted!``. These threads are daemons and
2563
+ ``shutdown`` never joins them, so an abandoned call dies with the process. It
2564
+ subclasses ``ThreadPoolExecutor`` only because ``set_default_executor`` requires one;
2565
+ ``submit`` and ``shutdown`` replace the base pool, whose threads are never started.
2566
+ """
2567
+
2568
+ def __init__(self) -> None:
2569
+ super().__init__(thread_name_prefix="langstage-cli-turn")
2570
+ self._jobs: "queue.SimpleQueue[Any]" = queue.SimpleQueue()
2571
+ self._idle = threading.Semaphore(0)
2572
+ self._workers = 0
2573
+ self._lock = threading.Lock()
2574
+ self._shutdown = False
2575
+
2576
+ def submit(self, fn, /, *args, **kwargs): # type: ignore[override]
2577
+ with self._lock:
2578
+ if self._shutdown:
2579
+ raise RuntimeError("cannot schedule new futures after shutdown")
2580
+ future: concurrent.futures.Future = concurrent.futures.Future()
2581
+ self._jobs.put((future, fn, args, kwargs))
2582
+ if not self._idle.acquire(blocking=False):
2583
+ self._workers += 1
2584
+ threading.Thread(target=self._work, name="langstage-cli-turn", daemon=True).start()
2585
+ return future
2586
+
2587
+ def _work(self) -> None:
2588
+ while True:
2589
+ job = self._jobs.get()
2590
+ if job is None:
2591
+ return
2592
+ future, fn, args, kwargs = job
2593
+ if future.set_running_or_notify_cancel():
2594
+ try:
2595
+ result = fn(*args, **kwargs)
2596
+ except BaseException as exc: # noqa: BLE001 - delivered to the awaiting task
2597
+ future.set_exception(exc)
2598
+ else:
2599
+ future.set_result(result)
2600
+ del job, future, fn, args, kwargs
2601
+ self._idle.release()
2602
+
2603
+ def shutdown(self, wait: bool = True, *, cancel_futures: bool = False) -> None:
2604
+ # Never joins (see the class docstring). Idle workers exit on their sentinel; a
2605
+ # worker still inside a call finishes it, or dies with the process.
2606
+ with self._lock:
2607
+ if self._shutdown:
2608
+ return
2609
+ self._shutdown = True
2610
+ for _ in range(self._workers):
2611
+ self._jobs.put(None)
2612
+
2613
+
2614
+ def _run_turn(coro: Any) -> Any:
2615
+ """``asyncio.run`` for one turn, on a loop whose sync work can be abandoned (gh #192).
2616
+
2617
+ Ctrl-C handling is ``asyncio.run``'s own (a cancel, then ``KeyboardInterrupt``); only
2618
+ the executor differs, so a sync tool that is still running no longer holds the exit.
2619
+ """
2620
+ with asyncio.Runner() as runner:
2621
+ runner.get_loop().set_default_executor(_DaemonThreadPool())
2622
+ return runner.run(coro)
2623
+
2624
+
2501
2625
  async def _run_turn_persistent(
2502
2626
  graph: Any,
2503
2627
  sqlite_path: Path,
@@ -2616,7 +2740,7 @@ def run_conversation_loop(
2616
2740
  # first-message snippet.
2617
2741
  on_turn(msg, thread_id)
2618
2742
  if persist_sqlite_path is not None:
2619
- return asyncio.run(
2743
+ return _run_turn(
2620
2744
  _run_turn_persistent(
2621
2745
  graph,
2622
2746
  persist_sqlite_path,
@@ -2628,7 +2752,7 @@ def run_conversation_loop(
2628
2752
  session_config=session_config,
2629
2753
  )
2630
2754
  )
2631
- return asyncio.run(run_single_turn_agui(agui_agent, msg, thread_id, interactive, verbose))
2755
+ return _run_turn(run_single_turn_agui(agui_agent, msg, thread_id, interactive, verbose))
2632
2756
 
2633
2757
  # Process initial message if provided
2634
2758
  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.47
3
+ Version: 0.6.48
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,9 @@ 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.
176
179
 
177
180
  State lives in `~/.langstage/sessions/<workspace-hash>.sqlite` (honoring
178
181
  `LANGSTAGE_CONFIG_HOME`; override the whole location with `LANGSTAGE_CLI_SESSIONS_DIR`).
@@ -25,11 +25,13 @@ 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
28
29
  tests/test_deferred_pass.py
29
30
  tests/test_dumb_term.py
30
31
  tests/test_exit_codes.py
31
32
  tests/test_generic_interrupt.py
32
33
  tests/test_help_render.py
34
+ tests/test_hidden_option_suggestions.py
33
35
  tests/test_history_persist.py
34
36
  tests/test_hitl_approval_preview.py
35
37
  tests/test_hitl_resume_warning.py
@@ -41,6 +43,7 @@ tests/test_message_boundaries.py
41
43
  tests/test_no_color.py
42
44
  tests/test_no_interactive_approve.py
43
45
  tests/test_no_persist_resume.py
46
+ tests/test_paused_session_message.py
44
47
  tests/test_persist_env.py
45
48
  tests/test_quiet_output.py
46
49
  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.47"
7
+ version = "0.6.48"
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,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)
@@ -0,0 +1,27 @@
1
+ """A mistyped option is never pointed at a hidden, deprecated no-op flag (gh #193)."""
2
+
3
+ import pytest
4
+ from click.testing import CliRunner
5
+
6
+ from langstage_cli.cli import main
7
+
8
+ _HIDDEN = ("--agui", "--async-mode", "--sync-mode", "--stream-mode")
9
+
10
+
11
+ @pytest.mark.parametrize("typo", ["--agnet", "--model", "--sync", "--stream", "--asyn"])
12
+ def test_suggestions_skip_hidden_flags(typo):
13
+ r = CliRunner().invoke(main, [typo, "x", "hi"])
14
+ assert r.exit_code == 64, r.output
15
+ assert typo in r.output
16
+ for flag in _HIDDEN:
17
+ assert flag not in r.output, r.output
18
+
19
+
20
+ def test_a_near_miss_still_suggests_the_documented_option():
21
+ r = CliRunner().invoke(main, ["--agnet", "x", "hi"])
22
+ assert "--agent" in r.output
23
+
24
+
25
+ def test_hidden_flags_still_parse():
26
+ r = CliRunner().invoke(main, ["--agui", "--version"])
27
+ assert r.exit_code == 0, r.output
@@ -0,0 +1,100 @@
1
+ """A new message on a session paused at an approval is answered, not dropped (gh #191).
2
+
3
+ ``-c "msg"`` on a session left paused (exit 2) used to re-raise the old interrupt in the
4
+ message's place. The message never reached the graph, ``--no-interactive`` approved the
5
+ old action and exited 0, and nothing said the message was gone. Now the pending approval
6
+ is resolved the way this run resolves any approval, then the message is sent; a run that
7
+ can't answer it (no terminal) exits 2 and says the message was not sent.
8
+ """
9
+
10
+ import textwrap
11
+
12
+ import pytest
13
+ from click.testing import CliRunner
14
+
15
+ pytest.importorskip("ag_ui_langgraph")
16
+ pytest.importorskip("langgraph.checkpoint.sqlite.aio")
17
+
18
+ from langstage_cli import cli # noqa: E402
19
+ from langstage_cli.cli import main # noqa: E402
20
+
21
+ _AGENT = textwrap.dedent(
22
+ """
23
+ from langgraph.graph import StateGraph, START, END
24
+ from langgraph.graph.message import MessagesState
25
+ from langgraph.types import interrupt
26
+ from langchain_core.messages import AIMessage
27
+
28
+ def respond(state):
29
+ last = state["messages"][-1].content
30
+ if "deploy" in last:
31
+ ok = interrupt("Deploy to production?")
32
+ return {"messages": [AIMessage(content=f"deploy answered: {ok!r}")]}
33
+ humans = [m.content for m in state["messages"] if m.type == "human"]
34
+ return {"messages": [AIMessage(content=f"You said: {last} | humans: {humans}")]}
35
+
36
+ g = StateGraph(MessagesState)
37
+ g.add_node("respond", respond)
38
+ g.add_edge(START, "respond")
39
+ g.add_edge("respond", END)
40
+ graph = g.compile()
41
+ """
42
+ )
43
+
44
+
45
+ @pytest.fixture
46
+ def paused(tmp_path, monkeypatch):
47
+ """A workspace whose most recent session is paused at the deploy approval."""
48
+ ws = tmp_path / "ws"
49
+ ws.mkdir()
50
+ (ws / "hitl_191.py").write_text(_AGENT, encoding="utf-8")
51
+ (ws / "langstage.toml").write_text('[agent]\nspec = "hitl_191.py:graph"\n')
52
+ monkeypatch.setenv("LANGSTAGE_CONFIG_HOME", str(tmp_path / "empty_home"))
53
+ monkeypatch.chdir(ws)
54
+ r = CliRunner().invoke(main, ["please deploy"])
55
+ assert r.exit_code == 2, r.output
56
+
57
+
58
+ def _history(runner: CliRunner) -> str:
59
+ r = runner.invoke(main, ["-c", "--no-interactive", "check"])
60
+ assert r.exit_code == 0, r.output
61
+ return r.output
62
+
63
+
64
+ def test_no_terminal_refuses_and_says_the_message_was_not_sent(paused):
65
+ runner = CliRunner()
66
+ r = runner.invoke(main, ["-c", "what is 2+2"])
67
+ assert r.exit_code == 2, r.output
68
+ assert "paused at an approval from its previous turn" in r.output
69
+ assert "Your message was not sent" in r.output
70
+ assert "what is 2+2" not in _history(runner)
71
+
72
+
73
+ def test_no_interactive_approves_the_old_action_then_sends_the_message(paused):
74
+ runner = CliRunner()
75
+ r = runner.invoke(main, ["-c", "--no-interactive", "what is 2+2"])
76
+ assert r.exit_code == 0, r.output
77
+ assert "auto-approving it first" in r.output
78
+ assert "deploy answered:" in r.output
79
+ assert "You said: what is 2+2" in r.output
80
+ assert _history(runner).count("what is 2+2") == 1 # in history exactly once
81
+
82
+
83
+ def test_terminal_answers_the_old_approval_then_sends_the_message(paused, monkeypatch):
84
+ # A terminal answer at the approval prompt.
85
+ monkeypatch.setattr(cli, "handle_interrupt_input", lambda *a, **k: "yes")
86
+ r = CliRunner().invoke(main, ["-c", "what is 2+2"])
87
+ assert r.exit_code == 0, r.output
88
+ assert "answer it first" in r.output
89
+ out = r.output
90
+ assert out.index("deploy answered: 'yes'") < out.index("You said: what is 2+2")
91
+ assert "humans: ['please deploy', 'what is 2+2']" in out
92
+
93
+
94
+ def test_a_session_that_is_not_paused_sends_the_message_once(paused):
95
+ runner = CliRunner()
96
+ runner.invoke(main, ["-c", "--no-interactive", "first"])
97
+ r = runner.invoke(main, ["-c", "second"])
98
+ assert r.exit_code == 0, r.output
99
+ assert "paused at an approval" not in r.output
100
+ assert "humans: ['please deploy', 'first', 'second']" in r.output
File without changes
File without changes