diff --git a/CHANGELOG.md b/CHANGELOG.md index aadd94d..7a1c101 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,22 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/), and this project adheres to [Semantic Versioning](https://semver.org/). +## [Unreleased] + +### New + +- **Choose AI disclosure.** + `sessions.update_config(ai_disclosure="on_request")` sets whether the + assistant says it is an AI, on both async and sync clients. Requires a + server with session disclosure support; an older server may silently accept + the setting for test accounts without applying it. +- **`caller_id` is no longer required.** `update_config()` changes only the + settings given; `None` leaves a setting unchanged. A call with nothing to + change, or an unknown value, raises `ValueError` before sending. +- **Read AI disclosure.** `SessionConfig` has the effective `ai_disclosure`, + and the public `AIDisclosure` type describes the modes. The server decides + which modes a user may set. + ## [0.5.0rc4] - 2026-10-23 ### New diff --git a/docs/http-api.md b/docs/http-api.md index 1575fc9..293e20a 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -154,8 +154,8 @@ These routes take the two headers above. | `POST /v2/sessions` | Creates a session. | `sessions.create()` | | `GET /v2/sessions` | Lists the user's sessions. | `sessions.list()` | | `GET /v2/sessions/{id}` | Returns one session. | `sessions.get()` | -| `GET /v2/sessions/{id}/config` | Returns the session config, for example `{"caller_id": "platform"}`, or `{}`. | `sessions.get_config()` | -| `PUT /v2/sessions/{id}/config` | Sets the caller ID. Body: `{"caller_id": "user"}` or `{"caller_id": "platform"}`. See "Caller ID". | `sessions.update_config()` | +| `GET /v2/sessions/{id}/config` | Returns session config with the effective `ai_disclosure` value. | `sessions.get_config()` | +| `PUT /v2/sessions/{id}/config` | Updates supplied session settings. See "Caller ID" and "AI disclosure". | `sessions.update_config()` | | `POST /v2/sessions/{id}/messages` | Sends a message. Body: `{"content": "...", "client_now_date": "..."}`; `client_now_date` is optional, see "The user's time". | `sessions.send_message()` | | `GET /v2/sessions/{id}/messages` | Reads the stored messages, newest first. | `sessions.history()` | | `POST /v2/sessions/{id}/start` | Starts a prepared or paused task, or continues a stopped session. See "Stop and continue". | `sessions.start_task()` | @@ -205,9 +205,35 @@ caller ID. `caller_id` is a session setting that selects it: while the session is paused applies when the session resumes. - `caller_id` does not change how the agent reaches the user. The agent still uses the user's phone for that. -- Any other key or value returns 400 `invalid_request`. -- 503 `session_config_push_failed` means that the value is saved, but the - running agent did not get it yet. Send the same request again. +- Invalid values or unsupported config keys return 400 `invalid_request`. +- 503 `session_config_push_failed` means that the value is saved, but delivery to + the running agent was not confirmed. Send the same request again. A 500 normally + means the change was not saved; if unsure, GET the settings or resend the same + PUT. + +### AI disclosure + +The config API also accepts `ai_disclosure`, which controls whether the +assistant says it is an AI on a call: + +| Value | Meaning | +|---|---| +| `"proactive"` | Introduce itself as AI. | +| `"on_request"` | Disclose that identity when asked. | +| `"disabled"` | Do not disclose it. | + +For example, `PUT /v2/sessions/{id}/config` with +`{"ai_disclosure": "on_request"}` changes it. Omitted fields stay unchanged; +`null` is invalid. Changes affect subsequent calls; calls already placed keep +their settings. The same 503 and 500 behavior described above applies. + +`GET` returns the effective value, including the default. Managed users default +to `"proactive"`; Pine test accounts default to `"disabled"`. The server decides +which modes a user may set: managed users cannot set `ai_disclosure="disabled"`, +and the request returns 400 `invalid_request`. + +This field requires a server with session disclosure support. An older server +may silently accept it for test accounts without applying it. ### The user's time diff --git a/docs/sdk-api.md b/docs/sdk-api.md index 83f6af4..6fa2f4d 100644 --- a/docs/sdk-api.md +++ b/docs/sdk-api.md @@ -122,7 +122,7 @@ user = await partner_client.platform.managed_users.update( | `sessions.list(...)` | `SessionListResponse` | | `sessions.get(session_id)` | `SessionInfo` | | `sessions.get_config(session_id)` | `SessionConfig` | -| `sessions.update_config(session_id, *, caller_id)` | `SessionConfig` after the change | +| `sessions.update_config(session_id, *, caller_id=None, ai_disclosure=None)` | `SessionConfig` after the change | | `sessions.send_message(session_id, content, ..., client_now_date=None)` | `SessionMessageStatus` | | `sessions.history(session_id, *, limit=30, before_message_id=None)` | `SessionHistoryPage`: one page of stored messages, newest first | | `sessions.start_task(session_id)` | `dict` | @@ -162,8 +162,11 @@ caller ID. `caller_id` is a session setting that selects it: while the session is paused applies when the session resumes. - `caller_id` does not change how the agent reaches the user. The agent still uses the user's phone for that. -- A 503 `session_config_push_failed` means that the value is saved, but the - running agent did not get it yet. Send the same value again. +- A 503 `session_config_push_failed` means that the value is saved, but delivery to + the running agent was not confirmed. Send the same value again. A 500 normally means + that the change was not saved. After a timeout, a dropped connection or a 502/504 + the change may or may not be saved. If unsure, call `get_config()` or send the + same value again; sending it again is safe. - Any other value raises `ValueError` before any request is sent. ```python @@ -172,6 +175,44 @@ await client.sessions.update_config(session["id"], caller_id="platform") await client.sessions.send_message(session["id"], "Call the clinic to book a visit") ``` +### AI disclosure + +`ai_disclosure` controls whether the assistant says it is an AI on a call: + +| Value | Meaning | +|---|---| +| `"proactive"` | Introduce itself as AI. | +| `"on_request"` | Disclose that identity when asked. | +| `"disabled"` | Do not disclose it. | + +Managed-user sessions default to `"proactive"`. Pine test accounts default to +`"disabled"`. The server decides which modes a user may set: it rejects +`ai_disclosure="disabled"` for managed users with 400 `invalid_request`. + +This setting requires a server with session disclosure support. An older +server may silently accept it for test accounts without applying it. + +```python +session = await client.sessions.create() +config = await client.sessions.update_config( + session["id"], ai_disclosure="on_request", +) +await client.sessions.send_message(session["id"], "Call the clinic to book a visit") +``` + +Both `AsyncPineAI` and `PineAI` support this setting. `update_config()` +changes only the settings given; `None` leaves a setting unchanged and is not +sent. A call with no setting to change, a non-string or an unknown mode raises +`ValueError` before any request is sent. Changes affect subsequent calls; calls +already placed keep their settings. The same 503 and 500 behavior described +above applies. + +`sessions.get_config()` returns the effective `ai_disclosure` from the server. +It is `None` when an older server omits it. It is read as a plain string, so a +mode added later by the server still parses. The SDK does not choose product +defaults locally. `AIDisclosure`, exported from `pine_assistant`, types the +modes accepted by `update_config()`. + ### The user's time The agent must know the user's time zone to understand words such as @@ -253,9 +294,11 @@ from `auth.*`, and `SessionError` from `sessions.list`, `get`, `get_config`, | 404 | `platform_managed_user_not_found` | No managed user of yours has this `external_id`. | | 429 | `too_many_requests` | Too many requests. | -`SessionError` from `sessions.get_config()` and `update_config()`: 403 -`forbidden` when the client is neither a managed user nor a test account, and 503 -`session_config_push_failed` (see "Caller ID"). +`SessionError` from `sessions.get_config()` and `update_config()`: 400 +`invalid_request` when the server rejects a value (for example +`ai_disclosure="disabled"` for a managed user), 403 `forbidden` when the user +may not use the config API, 503 `session_config_push_failed` when the change is +saved but not delivered, and 500 when it was normally not saved (see "Caller ID"). The codes for managed users are listed in [docs/http-api.md](http-api.md). Error messages never contain the key, the `external_id` or the user ID. diff --git a/src/pine_assistant/__init__.py b/src/pine_assistant/__init__.py index 02c0e85..accee25 100644 --- a/src/pine_assistant/__init__.py +++ b/src/pine_assistant/__init__.py @@ -22,6 +22,7 @@ ) from pine_assistant.models.platform import ManagedUser, ManagedUserAssistant from pine_assistant.models.session import ( + AIDisclosure, CallerID, SessionConfig, SessionHistoryMessage, @@ -75,6 +76,7 @@ "SessionInfo", "SessionConfig", "CallerID", + "AIDisclosure", "SessionHistoryMessage", "SessionHistoryPage", "SessionListResponse", diff --git a/src/pine_assistant/models/session.py b/src/pine_assistant/models/session.py index 6677051..b46f6c5 100644 --- a/src/pine_assistant/models/session.py +++ b/src/pine_assistant/models/session.py @@ -7,6 +7,7 @@ from pydantic import BaseModel, ConfigDict, field_validator CallerID = Literal["user", "platform"] +AIDisclosure = Literal["disabled", "on_request", "proactive"] class SessionInfo(BaseModel): @@ -40,6 +41,9 @@ class SessionConfig(BaseModel): model_config = ConfigDict(extra="allow") caller_id: str | None = None + # None means a server predating disclosure settings. A plain string, not the + # update Literal, on purpose: a mode added by the server still parses. + ai_disclosure: str | None = None class SessionListResponse(BaseModel): diff --git a/src/pine_assistant/sessions.py b/src/pine_assistant/sessions.py index 20d641e..dd0fa57 100644 --- a/src/pine_assistant/sessions.py +++ b/src/pine_assistant/sessions.py @@ -12,6 +12,7 @@ from pine_assistant.errors import PineAIError, SessionError from pine_assistant.models.session import ( + AIDisclosure, CallerID, SessionConfig, SessionHistoryPage, @@ -54,6 +55,23 @@ def _caller_id(caller_id: CallerID) -> CallerID: return caller_id +def _ai_disclosure(ai_disclosure: AIDisclosure) -> AIDisclosure: + if ai_disclosure not in get_args(AIDisclosure): + raise ValueError('ai_disclosure must be "disabled", "on_request" or "proactive"') + return ai_disclosure + + +def _config_update(caller_id: CallerID | None, ai_disclosure: AIDisclosure | None) -> dict[str, Any]: + body: dict[str, Any] = {} + if caller_id is not None: + body["caller_id"] = _caller_id(caller_id) + if ai_disclosure is not None: + body["ai_disclosure"] = _ai_disclosure(ai_disclosure) + if not body: + raise ValueError("provide at least one session config setting") + return body + + def _config_path(session_id: str | int) -> str: return f"/v2/sessions/{_session_id(session_id)}/config" @@ -181,17 +199,35 @@ async def get_config(self, session_id: str | int) -> SessionConfig: except PineAIError as exc: raise _session_error(exc) from exc - async def update_config(self, session_id: str | int, *, caller_id: CallerID) -> SessionConfig: - """Set the caller ID of the calls the agent places in this session. - - ``"user"``, or not set, presents the user's assistant number if it has - one, else the user's phone, else a number of the platform's pool; - ``"platform"`` presents a number of the platform's pool. Set it at any - time: the agent uses the value for its next call. A 503 - ``session_config_push_failed`` means the value is saved but has not - reached the running agent yet; send the same value again. + async def update_config( + self, + session_id: str | int, + *, + caller_id: CallerID | None = None, + ai_disclosure: AIDisclosure | None = None, + ) -> SessionConfig: + """Update settings for the next calls the agent places in this session. + + Change only the settings given; ``None`` leaves a setting unchanged. + Calls already placed keep their settings. A 503 + ``session_config_push_failed`` means the value is saved but delivery to + the running agent was not confirmed; send the same value again. A 500 + normally means the change was not saved. After a timeout, a dropped + connection or a 502/504 it may or may not be saved. If unsure, call + :meth:`get_config` or send the same value again; resending is safe. + + caller_id selects the number the call shows. ``"user"``, or not set, + presents the user's assistant number if it has one, else the user's + phone, else a number of the platform's pool; ``"platform"`` presents a + number of the platform's pool. + + ai_disclosure controls whether the assistant says it is an AI on the + call. Managed users default to ``"proactive"`` and the server rejects + ai_disclosure="disabled" for them with 400 ``invalid_request``; the + server decides which modes a user may set. ai_disclosure="on_request" + discloses AI identity only when asked. """ - body = {"caller_id": _caller_id(caller_id)} + body = _config_update(caller_id, ai_disclosure) try: return _parse_session_config(await self._http.put(_config_path(session_id), body)) except PineAIError as exc: @@ -362,8 +398,15 @@ def get_config(self, session_id: str | int) -> SessionConfig: except PineAIError as exc: raise _session_error(exc) from exc - def update_config(self, session_id: str | int, *, caller_id: CallerID) -> SessionConfig: - body = {"caller_id": _caller_id(caller_id)} + def update_config( + self, + session_id: str | int, + *, + caller_id: CallerID | None = None, + ai_disclosure: AIDisclosure | None = None, + ) -> SessionConfig: + """Update next-call settings; see :meth:`SessionsAPI.update_config` for semantics.""" + body = _config_update(caller_id, ai_disclosure) try: return _parse_session_config(self._http.put(_config_path(session_id), body)) except PineAIError as exc: diff --git a/tests/test_profile_and_session_config.py b/tests/test_profile_and_session_config.py index a0183df..91967f7 100644 --- a/tests/test_profile_and_session_config.py +++ b/tests/test_profile_and_session_config.py @@ -228,7 +228,7 @@ async def test_update_config_puts_the_caller_id_as_the_managed_user(caller_id): @pytest.mark.asyncio -@pytest.mark.parametrize("caller_id", ["pine", "", None, "PLATFORM"]) +@pytest.mark.parametrize("caller_id", ["pine", "", "PLATFORM"]) async def test_invalid_caller_id_is_refused_before_any_request(caller_id): recorder = Recorder() async with async_client(recorder, user_id=PINE_USER_ID) as client: @@ -366,3 +366,100 @@ def test_socketio_message_carries_client_now_date_only_when_given(): ) with pytest.raises(ValueError, match="client_now_date"): ChatEngine._build_message_data("hi", client_now_date="2026-10-21T09:00:00") + + +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize("settings", [ + {"ai_disclosure": "proactive"}, + {"ai_disclosure": "on_request"}, + {"caller_id": "platform", "ai_disclosure": "on_request"}, + {"caller_id": None, "ai_disclosure": "on_request"}, +]) +async def test_disclosure_update_sends_only_provided_fields(sync, settings): + effective = {"caller_id": "platform", "ai_disclosure": "proactive"} + recorder = Recorder(httpx.Response(200, json=success(effective))) + if sync: + with PineAI( + api_key=API_KEY, user_id=PINE_USER_ID, base_url=BASE_URL, http_transport=httpx.MockTransport(recorder), + ) as client: + config = client.sessions.update_config(7, **settings) + else: + async with async_client(recorder, user_id=PINE_USER_ID) as client: + config = await client.sessions.update_config(7, **settings) + + assert recorder.body() == {key: value for key, value in settings.items() if value is not None} + assert config == SessionConfig(**effective) + [request] = recorder.requests + assert (request.method, request.url.path) == ("PUT", "/api/v2/sessions/7/config") + assert request.headers[MANAGED_USER_HEADER] == PINE_USER_ID + + +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize("settings", [ + {}, + {"caller_id": None, "ai_disclosure": None}, + {"ai_disclosure": "off"}, + {"ai_disclosure": "PROACTIVE"}, + {"ai_disclosure": True}, + {"ai_disclosure": 0}, +]) +async def test_invalid_disclosure_update_never_sends_request(sync, settings): + recorder = Recorder() + if sync: + with PineAI( + api_key=API_KEY, user_id=PINE_USER_ID, base_url=BASE_URL, http_transport=httpx.MockTransport(recorder), + ) as client, pytest.raises(ValueError): + client.sessions.update_config(7, **settings) + else: + async with async_client(recorder, user_id=PINE_USER_ID) as client: + with pytest.raises(ValueError): + await client.sessions.update_config(7, **settings) + assert recorder.requests == [] + + +@pytest.mark.parametrize("sync", [False, True]) +async def test_server_rejection_of_disclosure_mode_surfaces_as_session_error(sync): + recorder = Recorder(httpx.Response( + 400, json={"status": "error", "error": {"code": "invalid_request", "message": "invalid ai_disclosure"}}, + )) + if sync: + with PineAI( + api_key=API_KEY, user_id=PINE_USER_ID, base_url=BASE_URL, http_transport=httpx.MockTransport(recorder), + ) as client, pytest.raises(SessionError) as excinfo: + client.sessions.update_config(7, ai_disclosure="disabled") + else: + async with async_client(recorder, user_id=PINE_USER_ID) as client: + with pytest.raises(SessionError) as excinfo: + await client.sessions.update_config(7, ai_disclosure="disabled") + + assert (excinfo.value.code, excinfo.value.status_code) == ("invalid_request", 400) + assert recorder.body() == {"ai_disclosure": "disabled"} + + +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize("payload", [ + {"ai_disclosure": "proactive"}, + {"ai_disclosure": "on_request"}, + {"ai_disclosure": "disabled"}, + {"ai_disclosure": "a_future_mode"}, + {}, +]) +async def test_read_disclosure_config_and_older_servers(sync, payload): + recorder = Recorder(httpx.Response(200, json=success(payload))) + if sync: + with PineAI( + api_key=API_KEY, user_id=PINE_USER_ID, base_url=BASE_URL, http_transport=httpx.MockTransport(recorder), + ) as client: + config = client.sessions.get_config(7) + else: + async with async_client(recorder, user_id=PINE_USER_ID) as client: + config = await client.sessions.get_config(7) + assert config.ai_disclosure == payload.get("ai_disclosure") + + +@pytest.mark.parametrize("value", [True, 0, 1]) +async def test_malformed_disclosure_response_is_not_coerced(value): + recorder = Recorder(httpx.Response(200, json=success({"ai_disclosure": value}))) + async with async_client(recorder, user_id=PINE_USER_ID) as client: + with pytest.raises(SessionError, match="invalid session config response"): + await client.sessions.get_config(7)