elicitation.py 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. """A canonical ``clarify`` prompt in an ACP editor, answered through ``clarify.respond``.
  2. A client that advertises ``elicitation.form`` in ``initialize`` gets the question as an
  3. ``elicitation/create`` form (free text or the offered choices); any other client gets a permission
  4. card whose options are the choices plus Skip, the one interaction every ACP client renders.
  5. Form schema and capability detection adapted from #126313 (Utku Bakir).
  6. """
  7. from __future__ import annotations
  8. import json
  9. from typing import Any
  10. ELICITATION_METHOD = "elicitation/create"
  11. SKIP_OPTION = "skip"
  12. def client_supports_form_elicitation(initialize_params: Any) -> bool:
  13. """ACP names an elicitation mode as supported only by its presence (``"form": {}``), under
  14. v1 ``clientCapabilities`` or v2 ``capabilities``. Read from the raw initialize params:
  15. the pinned SDK's ``ClientCapabilities`` model drops the field."""
  16. if not isinstance(initialize_params, dict):
  17. return False
  18. for key in ("clientCapabilities", "capabilities"):
  19. capabilities = initialize_params.get(key)
  20. elicitation = capabilities.get("elicitation") if isinstance(capabilities, dict) else None
  21. if isinstance(elicitation, dict) and elicitation.get("form") is not None:
  22. return True
  23. return False
  24. def build_clarify_elicitation(session_id: str, prompt: dict) -> dict[str, Any]:
  25. choices = list(prompt.get("choices") or [])
  26. schema: dict[str, Any] = {"type": "string"}
  27. if choices:
  28. schema = {"type": "string", "enum": choices}
  29. if prompt.get("multi_select"):
  30. schema = {"type": "array", "items": schema}
  31. return {"sessionId": session_id, "mode": "form", "message": prompt["question"],
  32. "requestedSchema": {"type": "object", "properties": {"answer": schema}, "required": ["answer"]}}
  33. def elicited_answer(response: Any) -> str | None:
  34. """Accept -> the answer (a multi-select list as the JSON array clarify decodes); decline or
  35. cancel -> ``""``, the skip every surface sends; anything else -> ``None`` (not answered)."""
  36. if not isinstance(response, dict) or response.get("action") not in {"accept", "decline", "cancel"}:
  37. return None
  38. if response["action"] != "accept":
  39. return ""
  40. value = (response.get("content") or {}).get("answer")
  41. if isinstance(value, list) and all(isinstance(item, str) for item in value):
  42. return json.dumps(value, ensure_ascii=False)
  43. return value if isinstance(value, str) else None
  44. def build_clarify_permission(prompt: dict):
  45. """``(tool_call, options, answers)``: one option per offered choice plus Skip; ``answers``
  46. maps each option id to the exact ``clarify.respond`` answer."""
  47. import acp
  48. from acp.schema import PermissionOption
  49. choices = list(prompt.get("choices") or [])
  50. options = [PermissionOption(option_id=f"choice-{index}", kind="allow_once", name=choice)
  51. for index, choice in enumerate(choices)]
  52. options.append(PermissionOption(option_id=SKIP_OPTION, kind="reject_once", name="Skip"))
  53. answers = {f"choice-{index}": choice for index, choice in enumerate(choices)}
  54. answers[SKIP_OPTION] = ""
  55. tool_call = acp.update_tool_call(
  56. f"clarify-{prompt['prompt_id']}", title=prompt["question"], kind="other", status="pending",
  57. content=[acp.tool_content(acp.text_block(prompt["question"]))],
  58. raw_input={"question": prompt["question"], "choices": choices})
  59. return tool_call, options, answers