mirror of
https://github.com/NCBM/plyngent.git
synced 2026-07-23 05:55:16 +08:00
core/prompting+tools: shared ask/choose/form and chat tools
Add process-wide prompting backends for interactive human I/O; wire CLI limit/confirm/workspace prompts through it. Expose ask_user, choose_user, and form_user under tools/chat and include them in DEFAULT_TOOLS.
This commit is contained in:
@@ -1,45 +1,32 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from plyngent.cli.limits import install_cli_limit_hooks, prompt_confirm_tool, prompt_continue_limit
|
||||
from plyngent.prompting import get_prompt_backend, temporary_backend
|
||||
from plyngent.tools.process.pty_session import PtyManager
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import pytest
|
||||
from tests.test_prompting import ScriptedBackend
|
||||
|
||||
|
||||
def test_prompt_continue_limit_yes(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
def _confirm(*_a: object, **_k: object) -> bool:
|
||||
return True
|
||||
|
||||
monkeypatch.setattr("click.confirm", _confirm)
|
||||
assert prompt_continue_limit("hit a wall") is True
|
||||
def test_prompt_continue_limit_yes() -> None:
|
||||
backend = ScriptedBackend([], confirms=[True])
|
||||
with temporary_backend(backend):
|
||||
assert prompt_continue_limit("hit a wall") is True
|
||||
|
||||
|
||||
def test_prompt_continue_limit_no(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
def _confirm(*_a: object, **_k: object) -> bool:
|
||||
return False
|
||||
|
||||
monkeypatch.setattr("click.confirm", _confirm)
|
||||
assert prompt_continue_limit("hit a wall") is False
|
||||
def test_prompt_continue_limit_no() -> None:
|
||||
backend = ScriptedBackend([], confirms=[False])
|
||||
with temporary_backend(backend):
|
||||
assert prompt_continue_limit("hit a wall") is False
|
||||
|
||||
|
||||
def test_prompt_confirm_tool_default_deny(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
def _confirm(message: str, **kwargs: object) -> bool:
|
||||
seen["message"] = message
|
||||
seen["default"] = kwargs.get("default")
|
||||
return False
|
||||
|
||||
monkeypatch.setattr("click.confirm", _confirm)
|
||||
assert prompt_confirm_tool("delete_path", {"path": "x"}, "delete path 'x'") is False
|
||||
assert seen["default"] is False
|
||||
def test_prompt_confirm_tool_default_deny() -> None:
|
||||
backend = ScriptedBackend([], confirms=[False])
|
||||
with temporary_backend(backend):
|
||||
assert prompt_confirm_tool("delete_path", {"path": "x"}, "delete path 'x'") is False
|
||||
|
||||
|
||||
def test_install_cli_limit_hooks() -> None:
|
||||
install_cli_limit_hooks()
|
||||
# Hook is installed process-wide for the CLI session.
|
||||
assert callable(getattr(PtyManager, "_limit_continue", None))
|
||||
PtyManager.set_limit_continue_hook(None)
|
||||
# Backend remains usable after install.
|
||||
assert get_prompt_backend().is_interactive() or True
|
||||
|
||||
@@ -88,22 +88,18 @@ def _make_state(memory: MemoryStore, workspace: Path) -> ReplState:
|
||||
return st
|
||||
|
||||
|
||||
def test_prompt_workspace_mismatch_choices(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
def prompt_u(*_a: object, **_k: object) -> str:
|
||||
return "u"
|
||||
def test_prompt_workspace_mismatch_choices() -> None:
|
||||
from plyngent.prompting import temporary_backend
|
||||
from tests.test_prompting import ScriptedBackend
|
||||
|
||||
def prompt_k(*_a: object, **_k: object) -> str:
|
||||
return "k"
|
||||
|
||||
def prompt_a(*_a: object, **_k: object) -> str:
|
||||
return "a"
|
||||
|
||||
monkeypatch.setattr("click.prompt", prompt_u)
|
||||
assert prompt_workspace_mismatch(1, "/old", "/new") == "rebind"
|
||||
monkeypatch.setattr("click.prompt", prompt_k)
|
||||
assert prompt_workspace_mismatch(1, "/old", "/new") == "keep"
|
||||
monkeypatch.setattr("click.prompt", prompt_a)
|
||||
assert prompt_workspace_mismatch(1, "/old", "/new") == "abort"
|
||||
with temporary_backend(ScriptedBackend(["2"])):
|
||||
assert prompt_workspace_mismatch(1, "/old", "/new") == "rebind"
|
||||
with temporary_backend(ScriptedBackend(["1"])):
|
||||
assert prompt_workspace_mismatch(1, "/old", "/new") == "keep"
|
||||
with temporary_backend(ScriptedBackend(["3"])):
|
||||
assert prompt_workspace_mismatch(1, "/old", "/new") == "abort"
|
||||
with temporary_backend(ScriptedBackend(["abort"])):
|
||||
assert prompt_workspace_mismatch(1, "/old", "/new") == "abort"
|
||||
|
||||
|
||||
async def test_resume_mismatch_rebind(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from plyngent.prompting import (
|
||||
ChoiceOption,
|
||||
FormField,
|
||||
NonInteractiveBackend,
|
||||
NonInteractiveError,
|
||||
ask,
|
||||
choose,
|
||||
confirm,
|
||||
form,
|
||||
temporary_backend,
|
||||
)
|
||||
|
||||
|
||||
class ScriptedBackend:
|
||||
"""Deterministic backend for unit tests."""
|
||||
|
||||
def __init__(self, lines: list[str], *, confirms: list[bool] | None = None) -> None:
|
||||
self.lines = list(lines)
|
||||
self.confirms = list(confirms or [])
|
||||
self.interactive = True
|
||||
self.echoes: list[str] = []
|
||||
|
||||
def is_interactive(self) -> bool:
|
||||
return self.interactive
|
||||
|
||||
def read_line(self, prompt: str, *, default: str | None = None) -> str:
|
||||
del prompt
|
||||
if self.lines:
|
||||
return self.lines.pop(0)
|
||||
if default is not None:
|
||||
return default
|
||||
msg = "no scripted lines left"
|
||||
raise NonInteractiveError(msg)
|
||||
|
||||
def confirm(self, prompt: str, *, default: bool = False) -> bool:
|
||||
del prompt
|
||||
if self.confirms:
|
||||
return self.confirms.pop(0)
|
||||
return default
|
||||
|
||||
def echo(self, message: str = "", *, err: bool = False) -> None:
|
||||
del err
|
||||
self.echoes.append(message)
|
||||
|
||||
def secho(self, message: str, *, fg: str | None = None, err: bool = False) -> None:
|
||||
del fg, err
|
||||
self.echoes.append(message)
|
||||
|
||||
|
||||
def test_ask_free_text() -> None:
|
||||
backend = ScriptedBackend(["hello world"])
|
||||
with temporary_backend(backend):
|
||||
assert ask("Name?") == "hello world"
|
||||
|
||||
|
||||
def test_ask_default_when_empty_uses_backend_default() -> None:
|
||||
backend = ScriptedBackend([])
|
||||
with temporary_backend(backend):
|
||||
assert ask("Name?", default="anon") == "anon"
|
||||
|
||||
|
||||
def test_choose_by_index() -> None:
|
||||
backend = ScriptedBackend(["2"])
|
||||
with temporary_backend(backend):
|
||||
assert (
|
||||
choose(
|
||||
"Pick",
|
||||
[
|
||||
ChoiceOption(label="a", value="A"),
|
||||
ChoiceOption(label="b", value="B"),
|
||||
],
|
||||
allow_custom=False,
|
||||
)
|
||||
== "B"
|
||||
)
|
||||
|
||||
|
||||
def test_choose_by_label() -> None:
|
||||
backend = ScriptedBackend(["keep"])
|
||||
with temporary_backend(backend):
|
||||
assert choose("Pick", ["keep", "abort"], allow_custom=False) == "keep"
|
||||
|
||||
|
||||
def test_choose_custom_text() -> None:
|
||||
backend = ScriptedBackend(["something else"])
|
||||
with temporary_backend(backend):
|
||||
assert choose("Pick", ["a", "b"], allow_custom=True) == "something else"
|
||||
|
||||
|
||||
def test_choose_rejects_custom_when_disabled() -> None:
|
||||
backend = ScriptedBackend(["nope", "1"])
|
||||
with temporary_backend(backend):
|
||||
assert choose("Pick", ["a", "b"], allow_custom=False) == "a"
|
||||
|
||||
|
||||
def test_confirm_yes() -> None:
|
||||
backend = ScriptedBackend([], confirms=[True])
|
||||
with temporary_backend(backend):
|
||||
assert confirm("ok?", default=False) is True
|
||||
|
||||
|
||||
def test_form_with_confirm() -> None:
|
||||
backend = ScriptedBackend(["alice", "2"], confirms=[True])
|
||||
with temporary_backend(backend):
|
||||
answers = form(
|
||||
"Profile",
|
||||
[
|
||||
FormField(name="name", prompt="Name?"),
|
||||
FormField(
|
||||
name="role",
|
||||
prompt="Role?",
|
||||
options=["dev", "ops"],
|
||||
allow_custom=False,
|
||||
),
|
||||
],
|
||||
confirm_submit=True,
|
||||
)
|
||||
assert answers == {"name": "alice", "role": "ops"}
|
||||
|
||||
|
||||
def test_non_interactive_ask_requires_default() -> None:
|
||||
with temporary_backend(NonInteractiveBackend()), pytest.raises(NonInteractiveError):
|
||||
_ = ask("Name?")
|
||||
|
||||
|
||||
def test_non_interactive_ask_uses_default() -> None:
|
||||
with temporary_backend(NonInteractiveBackend()):
|
||||
assert ask("Name?", default="x") == "x"
|
||||
|
||||
|
||||
def test_non_interactive_confirm_uses_default() -> None:
|
||||
with temporary_backend(NonInteractiveBackend()):
|
||||
assert confirm("ok?", default=False) is False
|
||||
assert confirm("ok?", default=True) is True
|
||||
@@ -0,0 +1,66 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from plyngent.agent import ToolRegistry
|
||||
from plyngent.prompting import NonInteractiveBackend, temporary_backend
|
||||
from plyngent.tools.chat import CHAT_TOOLS, ask_user, choose_user, form_user
|
||||
from tests.test_prompting import ScriptedBackend
|
||||
|
||||
|
||||
async def test_ask_user_tool() -> None:
|
||||
backend = ScriptedBackend(["42"])
|
||||
with temporary_backend(backend):
|
||||
registry = ToolRegistry([ask_user])
|
||||
out = await registry.execute("ask_user", '{"question": "Answer?"}')
|
||||
assert out == "42"
|
||||
|
||||
|
||||
async def test_choose_user_tool_index() -> None:
|
||||
backend = ScriptedBackend(["1"])
|
||||
with temporary_backend(backend):
|
||||
registry = ToolRegistry([choose_user])
|
||||
out = await registry.execute(
|
||||
"choose_user",
|
||||
json.dumps(
|
||||
{
|
||||
"question": "Pick",
|
||||
"options": json.dumps(["alpha", "beta"]),
|
||||
"allow_custom": False,
|
||||
}
|
||||
),
|
||||
)
|
||||
assert out == "alpha"
|
||||
|
||||
|
||||
async def test_choose_user_bad_options() -> None:
|
||||
registry = ToolRegistry([choose_user])
|
||||
out = await registry.execute(
|
||||
"choose_user",
|
||||
json.dumps({"question": "Pick", "options": "not-json"}),
|
||||
)
|
||||
assert out.startswith("error:")
|
||||
|
||||
|
||||
async def test_form_user_tool() -> None:
|
||||
backend = ScriptedBackend(["ncbm"], confirms=[True])
|
||||
fields = json.dumps([{"name": "user", "prompt": "User?"}])
|
||||
with temporary_backend(backend):
|
||||
registry = ToolRegistry([form_user])
|
||||
out = await registry.execute(
|
||||
"form_user",
|
||||
json.dumps({"title": "Setup", "fields": fields, "confirm_submit": True}),
|
||||
)
|
||||
assert json.loads(out) == {"user": "ncbm"}
|
||||
|
||||
|
||||
async def test_chat_tools_in_default_list() -> None:
|
||||
names = {t.name for t in CHAT_TOOLS}
|
||||
assert names == {"ask_user", "choose_user", "form_user"}
|
||||
|
||||
|
||||
async def test_ask_user_non_interactive_error() -> None:
|
||||
with temporary_backend(NonInteractiveBackend()):
|
||||
registry = ToolRegistry([ask_user])
|
||||
out = await registry.execute("ask_user", '{"question": "hi"}')
|
||||
assert out.startswith("error:")
|
||||
Reference in New Issue
Block a user