langstage-cli 0.6.46__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.
- {langstage_cli-0.6.46/langstage_cli.egg-info → langstage_cli-0.6.48}/PKG-INFO +4 -1
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/README.md +3 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/langstage_cli/cli.py +165 -14
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/langstage_cli/exit_codes.py +17 -1
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/langstage_cli/sessions.py +26 -3
- {langstage_cli-0.6.46 → langstage_cli-0.6.48/langstage_cli.egg-info}/PKG-INFO +4 -1
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/langstage_cli.egg-info/SOURCES.txt +4 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/pyproject.toml +1 -1
- langstage_cli-0.6.48/tests/test_ctrl_c_sync_tool.py +80 -0
- langstage_cli-0.6.48/tests/test_hidden_option_suggestions.py +27 -0
- langstage_cli-0.6.48/tests/test_paused_session_message.py +100 -0
- langstage_cli-0.6.48/tests/test_routine_1024.py +122 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/LICENSE +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/deepagent_code/__init__.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/langstage_cli/__init__.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/langstage_cli/agui_stream.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/langstage_cli/config.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/langstage_cli.egg-info/dependency_links.txt +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/langstage_cli.egg-info/entry_points.txt +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/langstage_cli.egg-info/requires.txt +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/langstage_cli.egg-info/top_level.txt +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/setup.cfg +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_advertised_wave4.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_agui_stream.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_approval_menu_abort.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_async_mode.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_checkpointer.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_cli.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_cli_help.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_codeconfig.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_config.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_config_command.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_configurable.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_deferred_pass.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_dumb_term.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_exit_codes.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_generic_interrupt.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_help_render.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_history_persist.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_hitl_approval_preview.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_hitl_resume_warning.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_init.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_interrupt_non_tty.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_legacy_config_home.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_load_error.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_message_boundaries.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_no_color.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_no_interactive_approve.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_no_persist_resume.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_persist_env.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_quiet_output.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_reasoning_render.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_rename_shim.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_render_markdown.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_session_lifecycle.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_sessions.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_show_config.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_show_config_malformed.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_spec_loading_core.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_spec_resolution.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_spinner_reply_survives.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_stdin_interactive.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_stdin_single_shot.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_stream_mode.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_streaming_marker.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_terminal_width.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_toml_relative_paths.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_tool_card_args.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_tool_output_escape.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_turn_error_verbose.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_turn_exit_and_render.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_unicode_console.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_usage_hint_186.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_verbose_command.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_verify_flag.py +0 -0
- {langstage_cli-0.6.46 → langstage_cli-0.6.48}/tests/test_workspace.py +0 -0
- {langstage_cli-0.6.46 → 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.
|
|
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,10 +4,13 @@ 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
|
|
13
|
+
import signal
|
|
11
14
|
import subprocess
|
|
12
15
|
import sys
|
|
13
16
|
import threading
|
|
@@ -1741,7 +1744,7 @@ def _select_option_typed(options: List[str], prompt: str) -> int:
|
|
|
1741
1744
|
print(f" {i}. {opt}")
|
|
1742
1745
|
while True:
|
|
1743
1746
|
try:
|
|
1744
|
-
raw =
|
|
1747
|
+
raw = _prompt_line(f"Choose 1-{len(options)} [1]: ").strip()
|
|
1745
1748
|
except (KeyboardInterrupt, EOFError):
|
|
1746
1749
|
print()
|
|
1747
1750
|
sys.exit(EXIT_PAUSED)
|
|
@@ -1752,6 +1755,25 @@ def _select_option_typed(options: List[str], prompt: str) -> int:
|
|
|
1752
1755
|
print(f"Enter a number from 1 to {len(options)}.")
|
|
1753
1756
|
|
|
1754
1757
|
|
|
1758
|
+
def _prompt_line(prompt: str) -> str:
|
|
1759
|
+
"""``input()`` at an approval prompt, where one Ctrl-C raises ``KeyboardInterrupt``.
|
|
1760
|
+
|
|
1761
|
+
The approval prompts run inside the turn's ``asyncio.Runner``, whose SIGINT handler
|
|
1762
|
+
(Python 3.11+) only schedules a task cancel on the first Ctrl-C. A blocking
|
|
1763
|
+
``input()`` never yields to the loop, so that press was swallowed and only a
|
|
1764
|
+
second one exited (gh #189). The default handler is put back for the duration of
|
|
1765
|
+
the read, so the first press reaches the caller's ``except KeyboardInterrupt``.
|
|
1766
|
+
"""
|
|
1767
|
+
try:
|
|
1768
|
+
previous = signal.signal(signal.SIGINT, signal.default_int_handler)
|
|
1769
|
+
except ValueError: # not the main thread: signal handlers can't be changed here
|
|
1770
|
+
return input(prompt)
|
|
1771
|
+
try:
|
|
1772
|
+
return input(prompt)
|
|
1773
|
+
finally:
|
|
1774
|
+
signal.signal(signal.SIGINT, previous)
|
|
1775
|
+
|
|
1776
|
+
|
|
1755
1777
|
def handle_interrupt_input(num_actions: int = 1, is_generic: bool = False) -> Any:
|
|
1756
1778
|
"""
|
|
1757
1779
|
Handle user input for an interrupt using arrow key navigation, returning the
|
|
@@ -1843,7 +1865,7 @@ def _approval_input() -> str:
|
|
|
1843
1865
|
turn stays paused on the interrupt, so exit 2 (ADR 0007, gh #174).
|
|
1844
1866
|
"""
|
|
1845
1867
|
try:
|
|
1846
|
-
return
|
|
1868
|
+
return _prompt_line(make_prompt("❯", BLUE))
|
|
1847
1869
|
except (KeyboardInterrupt, EOFError):
|
|
1848
1870
|
print()
|
|
1849
1871
|
sys.exit(EXIT_PAUSED)
|
|
@@ -1972,7 +1994,8 @@ def cmd_status(args: str, context: Dict[str, Any]) -> Optional[str]:
|
|
|
1972
1994
|
print(f"\n{BOLD}{BRIGHT_CYAN}Session Status{RESET}")
|
|
1973
1995
|
print(f"{DIM}{'─' * 30}{RESET}")
|
|
1974
1996
|
print(f" {DIM}Agent:{RESET} {agent_name}")
|
|
1975
|
-
|
|
1997
|
+
shown_id = sessions.display_id(thread_id)
|
|
1998
|
+
print(f" {DIM}Thread ID:{RESET} {shown_id}{'...' if shown_id != thread_id else ''}")
|
|
1976
1999
|
# No "Mode: async/sync" line: since ADR 0003 there is exactly one (async) path,
|
|
1977
2000
|
# so the value was reporting a distinction the runtime does not have (gh #88).
|
|
1978
2001
|
print(f" {DIM}Verbose:{RESET} {'on' if verbose else 'off'}")
|
|
@@ -2359,14 +2382,68 @@ async def run_single_turn_agui(
|
|
|
2359
2382
|
exception inside a node/tool arrives with its traceback on the error frame and
|
|
2360
2383
|
``print_chunk`` shows it (gh #153).
|
|
2361
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
|
+
"""
|
|
2362
2439
|
from langstage_cli.agui_stream import agui_stream_updates
|
|
2363
2440
|
|
|
2364
2441
|
print_chunk._streaming_text = False # fresh marker state per turn (gh #34)
|
|
2365
2442
|
print_chunk._streaming_reasoning = False
|
|
2366
2443
|
_md_stream.reset()
|
|
2367
|
-
start_time = time.time()
|
|
2368
2444
|
had_error = False
|
|
2369
2445
|
produced = False # any text / reasoning / tool frame / interrupt this turn (gh #120)
|
|
2446
|
+
saw_interrupt = False
|
|
2370
2447
|
resume = None # first pass sends the message; later passes carry the decision
|
|
2371
2448
|
|
|
2372
2449
|
while True:
|
|
@@ -2394,7 +2471,7 @@ async def run_single_turn_agui(
|
|
|
2394
2471
|
):
|
|
2395
2472
|
produced = True
|
|
2396
2473
|
if chunk.get("status") == "interrupt":
|
|
2397
|
-
has_interrupt = True
|
|
2474
|
+
has_interrupt = saw_interrupt = True
|
|
2398
2475
|
interrupt_data = chunk.get("interrupt", {})
|
|
2399
2476
|
action_requests = interrupt_data.get("action_requests", [])
|
|
2400
2477
|
num_pending_actions = len(action_requests) if action_requests else 1
|
|
@@ -2430,9 +2507,7 @@ async def run_single_turn_agui(
|
|
|
2430
2507
|
else:
|
|
2431
2508
|
break
|
|
2432
2509
|
|
|
2433
|
-
|
|
2434
|
-
had_error = not await _render_empty_turn(agent, thread_id)
|
|
2435
|
-
return time.time() - start_time, had_error
|
|
2510
|
+
return had_error, produced, saw_interrupt
|
|
2436
2511
|
|
|
2437
2512
|
|
|
2438
2513
|
# Chunk keys that carry turn output a user sees (text, reasoning, tool frames).
|
|
@@ -2477,6 +2552,76 @@ async def _render_empty_turn(agent: Any, thread_id: str) -> bool:
|
|
|
2477
2552
|
return False
|
|
2478
2553
|
|
|
2479
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
|
+
|
|
2480
2625
|
async def _run_turn_persistent(
|
|
2481
2626
|
graph: Any,
|
|
2482
2627
|
sqlite_path: Path,
|
|
@@ -2595,7 +2740,7 @@ def run_conversation_loop(
|
|
|
2595
2740
|
# first-message snippet.
|
|
2596
2741
|
on_turn(msg, thread_id)
|
|
2597
2742
|
if persist_sqlite_path is not None:
|
|
2598
|
-
return
|
|
2743
|
+
return _run_turn(
|
|
2599
2744
|
_run_turn_persistent(
|
|
2600
2745
|
graph,
|
|
2601
2746
|
persist_sqlite_path,
|
|
@@ -2607,7 +2752,7 @@ def run_conversation_loop(
|
|
|
2607
2752
|
session_config=session_config,
|
|
2608
2753
|
)
|
|
2609
2754
|
)
|
|
2610
|
-
return
|
|
2755
|
+
return _run_turn(run_single_turn_agui(agui_agent, msg, thread_id, interactive, verbose))
|
|
2611
2756
|
|
|
2612
2757
|
# Process initial message if provided
|
|
2613
2758
|
if initial_message is not None:
|
|
@@ -2844,7 +2989,8 @@ def _resolve_resume_thread(
|
|
|
2844
2989
|
matches = sessions.match_threads(workspace, resume_id)
|
|
2845
2990
|
if len(matches) > 1:
|
|
2846
2991
|
# An ambiguous prefix is not "no match" (gh #124): say so and list them.
|
|
2847
|
-
|
|
2992
|
+
# Each match in a form --resume accepts and that tells them apart (gh #188).
|
|
2993
|
+
shown = ", ".join(sessions.display_id(t, matches) for t in matches[:10])
|
|
2848
2994
|
more = f", +{len(matches) - 10} more" if len(matches) > 10 else ""
|
|
2849
2995
|
_status(
|
|
2850
2996
|
f"{RED}⏺ Error: prefix '{resume_id}' is ambiguous — it matches "
|
|
@@ -2864,7 +3010,7 @@ def _resolve_resume_thread(
|
|
|
2864
3010
|
# The session's state lives in the agent's own checkpointer (gh #128): the CLI
|
|
2865
3011
|
# holds no history for it, so the resume restores only what that checkpointer kept.
|
|
2866
3012
|
_status(
|
|
2867
|
-
f"{YELLOW}note: session {thread
|
|
3013
|
+
f"{YELLOW}note: session {sessions.display_id(thread)} ran on the agent's own checkpointer; "
|
|
2868
3014
|
f"the CLI stored no history for it, so this resume restores only what that "
|
|
2869
3015
|
f"checkpointer kept (nothing, if it is in-memory).{RESET}"
|
|
2870
3016
|
)
|
|
@@ -3048,6 +3194,9 @@ def _print_sessions(workspace: Path) -> None:
|
|
|
3048
3194
|
return
|
|
3049
3195
|
print(f"\n{BOLD}{BRIGHT_CYAN}Sessions{RESET} {DIM}({workspace}){RESET}")
|
|
3050
3196
|
print(f"{DIM}{'─' * 40}{RESET}")
|
|
3197
|
+
all_ids = [tid for tid, _ in rows]
|
|
3198
|
+
shown = {tid: sessions.display_id(tid, all_ids) for tid in all_ids}
|
|
3199
|
+
width = max(len(s) for s in shown.values())
|
|
3051
3200
|
for tid, entry in rows:
|
|
3052
3201
|
when = _format_ts(entry.get("updated"))
|
|
3053
3202
|
first = entry.get("first_message") or f"{DIM}(no message yet){RESET}"
|
|
@@ -3058,7 +3207,9 @@ def _print_sessions(workspace: Path) -> None:
|
|
|
3058
3207
|
if entry.get("checkpointer") == "agent"
|
|
3059
3208
|
else ""
|
|
3060
3209
|
)
|
|
3061
|
-
|
|
3210
|
+
# A pinned id is shown in full and a minted UUID by its shortest unique prefix, so
|
|
3211
|
+
# two sessions never look alike and each shown id works with --resume (gh #188).
|
|
3212
|
+
print(f" {CYAN}{shown[tid]:<{width}}{RESET} {DIM}{when}{RESET} {first}{mark}")
|
|
3062
3213
|
print(f"\n{DIM}Resume with: langstage-cli --resume <id> (or -c for the most recent){RESET}\n")
|
|
3063
3214
|
|
|
3064
3215
|
|
|
@@ -3602,7 +3753,7 @@ def main(
|
|
|
3602
3753
|
if use_durable:
|
|
3603
3754
|
persist_sqlite_path = _snapshot_session_store(workspace)
|
|
3604
3755
|
_status(
|
|
3605
|
-
f"{DIM}⏺ --no-persist: resuming session {session_thread
|
|
3756
|
+
f"{DIM}⏺ --no-persist: resuming session {sessions.display_id(session_thread)} read-only — "
|
|
3606
3757
|
f"this run will not be saved.{RESET}"
|
|
3607
3758
|
)
|
|
3608
3759
|
if persist_sqlite_path is None and use_durable:
|
|
@@ -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
|
|
@@ -26,9 +26,10 @@ Two pieces live here:
|
|
|
26
26
|
import hashlib
|
|
27
27
|
import json
|
|
28
28
|
import os
|
|
29
|
+
import re
|
|
29
30
|
import time
|
|
30
31
|
from pathlib import Path
|
|
31
|
-
from typing import Dict, List, Optional, Tuple
|
|
32
|
+
from typing import Dict, Iterable, List, Optional, Tuple
|
|
32
33
|
|
|
33
34
|
from langstage_core.host.config import _global_toml_path
|
|
34
35
|
|
|
@@ -40,6 +41,10 @@ _SESSIONS_DIR_ENV = "LANGSTAGE_CLI_SESSIONS_DIR"
|
|
|
40
41
|
|
|
41
42
|
_SNIPPET_MAX = 60
|
|
42
43
|
|
|
44
|
+
# The ids the CLI mints itself (uuid4). Only these are shortened for display.
|
|
45
|
+
_UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
|
|
46
|
+
_SHORT_ID_MIN = 8
|
|
47
|
+
|
|
43
48
|
|
|
44
49
|
def _config_home() -> Path:
|
|
45
50
|
"""The LangStage config home — ``LANGSTAGE_CONFIG_HOME`` (then legacy
|
|
@@ -185,8 +190,8 @@ def most_recent_thread(workspace: Path) -> Optional[str]:
|
|
|
185
190
|
def resolve_thread(workspace: Path, ref: str) -> Optional[str]:
|
|
186
191
|
"""Resolve a ``--resume`` reference to a full thread id.
|
|
187
192
|
|
|
188
|
-
Accepts an exact id or an unambiguous prefix (
|
|
189
|
-
|
|
193
|
+
Accepts an exact id or an unambiguous prefix (``--list-sessions`` shows CLI-minted
|
|
194
|
+
UUIDs in a short form, see ``display_id``). Returns the full id, or ``None`` if it matches nothing / is
|
|
190
195
|
ambiguous.
|
|
191
196
|
"""
|
|
192
197
|
matches = match_threads(workspace, ref)
|
|
@@ -208,6 +213,24 @@ def match_threads(workspace: Path, ref: str) -> List[str]:
|
|
|
208
213
|
return [tid for tid, _ in matches]
|
|
209
214
|
|
|
210
215
|
|
|
216
|
+
def display_id(thread_id: str, others: Iterable[str] = ()) -> str:
|
|
217
|
+
"""How a session id is printed (gh #188).
|
|
218
|
+
|
|
219
|
+
A CLI-minted UUID is shortened to its shortest prefix of at least 8 characters
|
|
220
|
+
that no id in ``others`` shares, like ``git log --abbrev``. Any other id (a pinned
|
|
221
|
+
``[configurable] thread_id`` the user named, e.g. ``project-alpha``) is printed in
|
|
222
|
+
full: such names often share a prefix, and the user has to type one back to
|
|
223
|
+
``--resume``. Either form is accepted by ``--resume``.
|
|
224
|
+
"""
|
|
225
|
+
if not _UUID_RE.match(thread_id):
|
|
226
|
+
return thread_id
|
|
227
|
+
rivals = [o for o in others if o != thread_id]
|
|
228
|
+
n = _SHORT_ID_MIN
|
|
229
|
+
while n < len(thread_id) and any(o.startswith(thread_id[:n]) for o in rivals):
|
|
230
|
+
n += 1
|
|
231
|
+
return thread_id[:n]
|
|
232
|
+
|
|
233
|
+
|
|
211
234
|
def list_sessions(workspace: Path) -> List[Tuple[str, dict]]:
|
|
212
235
|
"""All sessions for this workspace, most-recently-updated first."""
|
|
213
236
|
sessions = load_index(workspace)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: langstage-cli
|
|
3
|
-
Version: 0.6.
|
|
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,11 +43,13 @@ 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
|
|
47
50
|
tests/test_rename_shim.py
|
|
48
51
|
tests/test_render_markdown.py
|
|
52
|
+
tests/test_routine_1024.py
|
|
49
53
|
tests/test_session_lifecycle.py
|
|
50
54
|
tests/test_sessions.py
|
|
51
55
|
tests/test_show_config.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.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
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""gh #188: session ids are printed so they can be told apart and typed back.
|
|
2
|
+
gh #189: one Ctrl-C at a typed approval prompt exits 2.
|
|
3
|
+
|
|
4
|
+
- ``--list-sessions`` and the ambiguous-``--resume`` error cut every id to 8
|
|
5
|
+
characters, so pinned ``[configurable] thread_id``s sharing a prefix
|
|
6
|
+
(``project-alpha`` / ``project-beta``) both showed as ``project-``. A pinned id is
|
|
7
|
+
now shown in full and a CLI-minted UUID by its shortest unique prefix.
|
|
8
|
+
- The typed prompts (``TERM=dumb`` menu, free-text reply, custom JSON) block in
|
|
9
|
+
``input()`` inside the turn's ``asyncio.run``, whose SIGINT handler only schedules a
|
|
10
|
+
cancel on the first press, so that press was swallowed.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import asyncio
|
|
14
|
+
import signal
|
|
15
|
+
import uuid
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
import pytest
|
|
19
|
+
from click.testing import CliRunner
|
|
20
|
+
|
|
21
|
+
from langstage_cli import cli, sessions
|
|
22
|
+
from langstage_cli.cli import main
|
|
23
|
+
from langstage_cli.exit_codes import EXIT_PAUSED
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _ws(tmp_path, monkeypatch) -> Path:
|
|
27
|
+
ws = tmp_path / "ws"
|
|
28
|
+
ws.mkdir()
|
|
29
|
+
monkeypatch.setenv("LANGSTAGE_CONFIG_HOME", str(tmp_path / "empty_home"))
|
|
30
|
+
monkeypatch.chdir(ws)
|
|
31
|
+
return ws.resolve()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# --- gh #188 ---
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def test_display_id_keeps_pinned_names_whole():
|
|
38
|
+
assert sessions.display_id("project-alpha", ["project-beta"]) == "project-alpha"
|
|
39
|
+
assert sessions.display_id("x") == "x"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def test_display_id_shortens_minted_uuids_to_a_unique_prefix():
|
|
43
|
+
a = "abcdef12-0000-4000-8000-000000000001"
|
|
44
|
+
b = "abcdef12-3000-4000-8000-000000000002"
|
|
45
|
+
assert sessions.display_id(a) == "abcdef12"
|
|
46
|
+
assert sessions.display_id(a, [a]) == "abcdef12" # itself is not a rival
|
|
47
|
+
assert sessions.display_id(a, [a, b]) == "abcdef12-0"
|
|
48
|
+
assert sessions.display_id(b, [a, b]) == "abcdef12-3"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def test_list_sessions_shows_pinned_ids_in_full(tmp_path, monkeypatch):
|
|
52
|
+
ws = _ws(tmp_path, monkeypatch)
|
|
53
|
+
sessions.touch_session(ws, "project-alpha", first_message="alpha msg")
|
|
54
|
+
sessions.touch_session(ws, "project-beta", first_message="beta msg")
|
|
55
|
+
minted = str(uuid.uuid4())
|
|
56
|
+
sessions.touch_session(ws, minted, first_message="minted msg")
|
|
57
|
+
r = CliRunner().invoke(main, ["--demo", "--list-sessions"])
|
|
58
|
+
assert r.exit_code == 0, r.output
|
|
59
|
+
assert "project-alpha" in r.output and "project-beta" in r.output, r.output
|
|
60
|
+
assert minted[:8] in r.output and minted not in r.output, r.output
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_ambiguous_resume_lists_ids_resume_accepts(tmp_path, monkeypatch):
|
|
64
|
+
ws = _ws(tmp_path, monkeypatch)
|
|
65
|
+
sessions.touch_session(ws, "project-alpha", first_message="one")
|
|
66
|
+
sessions.touch_session(ws, "project-beta", first_message="two")
|
|
67
|
+
r = CliRunner().invoke(main, ["--demo", "--resume", "project-", "go"])
|
|
68
|
+
assert r.exit_code == 1, r.output
|
|
69
|
+
assert "project-alpha" in r.output and "project-beta" in r.output, r.output
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
# --- gh #189 ---
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _ctrl_c_then_answer(answer: str):
|
|
76
|
+
"""An ``input()`` that gets one Ctrl-C mid-read, and would answer if it survived."""
|
|
77
|
+
|
|
78
|
+
def fake_input(prompt=""):
|
|
79
|
+
signal.raise_signal(signal.SIGINT)
|
|
80
|
+
return answer
|
|
81
|
+
|
|
82
|
+
return fake_input
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
async def _in_loop(fn, *args):
|
|
86
|
+
return fn(*args)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@pytest.mark.parametrize(
|
|
90
|
+
"call",
|
|
91
|
+
[
|
|
92
|
+
lambda: cli._select_option_typed(["Approve", "Reject"], "Proceed?"),
|
|
93
|
+
lambda: cli._approval_input(),
|
|
94
|
+
],
|
|
95
|
+
ids=["dumb-term-menu", "reply-prompt"],
|
|
96
|
+
)
|
|
97
|
+
def test_one_ctrl_c_inside_asyncio_run_exits_paused(monkeypatch, call):
|
|
98
|
+
monkeypatch.setattr("builtins.input", _ctrl_c_then_answer("1"))
|
|
99
|
+
before = signal.getsignal(signal.SIGINT)
|
|
100
|
+
with pytest.raises(SystemExit) as e:
|
|
101
|
+
asyncio.run(_in_loop(call))
|
|
102
|
+
assert e.value.code == EXIT_PAUSED
|
|
103
|
+
assert signal.getsignal(signal.SIGINT) is before # handler restored after the read
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def test_prompt_line_restores_the_loops_handler(monkeypatch):
|
|
107
|
+
seen = {}
|
|
108
|
+
|
|
109
|
+
def fake_input(prompt=""):
|
|
110
|
+
seen["during"] = signal.getsignal(signal.SIGINT)
|
|
111
|
+
return "ok"
|
|
112
|
+
|
|
113
|
+
monkeypatch.setattr("builtins.input", fake_input)
|
|
114
|
+
|
|
115
|
+
async def body():
|
|
116
|
+
outer = signal.getsignal(signal.SIGINT)
|
|
117
|
+
assert cli._prompt_line("> ") == "ok"
|
|
118
|
+
return outer, signal.getsignal(signal.SIGINT)
|
|
119
|
+
|
|
120
|
+
outer, after = asyncio.run(body())
|
|
121
|
+
assert seen["during"] is signal.default_int_handler
|
|
122
|
+
assert after is outer
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|