nutria-plugin 0.6.2__tar.gz → 0.7.0__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 (57) hide show
  1. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/CHANGELOG.md +21 -0
  2. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/PKG-INFO +1 -1
  3. nutria_plugin-0.7.0/docs/conversation-ownership.md +35 -0
  4. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/docs/index.md +2 -1
  5. nutria_plugin-0.7.0/docs/outside-audience.md +38 -0
  6. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/docs/python-api.md +11 -0
  7. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/pyproject.toml +1 -1
  8. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/src/nutria_plugin/__init__.py +23 -1
  9. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/src/nutria_plugin/capabilities.py +35 -0
  10. nutria_plugin-0.7.0/src/nutria_plugin/conversation_scope.py +50 -0
  11. nutria_plugin-0.7.0/src/nutria_plugin/ownership.py +95 -0
  12. nutria_plugin-0.7.0/tests/test_conversation_scope.py +120 -0
  13. nutria_plugin-0.7.0/tests/test_ownership.py +47 -0
  14. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/uv.lock +1 -1
  15. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/.github/workflows/publish.yml +0 -0
  16. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/.gitignore +0 -0
  17. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/README.md +0 -0
  18. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/docs/admin-extensions.md +0 -0
  19. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/docs/admin-flows.md +0 -0
  20. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/docs/capability-authoring.md +0 -0
  21. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/docs/cli.md +0 -0
  22. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/docs/connection-types.md +0 -0
  23. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/docs/manifest.md +0 -0
  24. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/docs/migration-6.0.md +0 -0
  25. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/docs/quickstart.md +0 -0
  26. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/docs/reviewable-actions.md +0 -0
  27. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/docs/security.md +0 -0
  28. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/docs/skill-format.md +0 -0
  29. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/examples/my-first-plugin/README.md +0 -0
  30. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/examples/my-first-plugin/hooks/hooks.json +0 -0
  31. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/examples/my-first-plugin/plugin.json +0 -0
  32. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/examples/my-first-plugin/settings.schema.json +0 -0
  33. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/src/nutria_plugin/bundle.py +0 -0
  34. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/src/nutria_plugin/cli.py +0 -0
  35. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/src/nutria_plugin/domains.py +0 -0
  36. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/src/nutria_plugin/hierarchy.py +0 -0
  37. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/src/nutria_plugin/manifest.py +0 -0
  38. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/src/nutria_plugin/mcp_results.py +0 -0
  39. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/src/nutria_plugin/migrate.py +0 -0
  40. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/src/nutria_plugin/operation_facts.py +0 -0
  41. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/src/nutria_plugin/packaging.py +0 -0
  42. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/src/nutria_plugin/prepared_preview.py +0 -0
  43. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/src/nutria_plugin/signing.py +0 -0
  44. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/src/nutria_plugin/skills.py +0 -0
  45. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/tests/__init__.py +0 -0
  46. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/tests/test_bundle.py +0 -0
  47. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/tests/test_capability_contracts.py +0 -0
  48. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/tests/test_cli.py +0 -0
  49. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/tests/test_contract_vnext.py +0 -0
  50. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/tests/test_hierarchy.py +0 -0
  51. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/tests/test_manifest.py +0 -0
  52. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/tests/test_mcp_results.py +0 -0
  53. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/tests/test_packaging.py +0 -0
  54. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/tests/test_prepared_preview.py +0 -0
  55. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/tests/test_reviewable_actions.py +0 -0
  56. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/tests/test_signing.py +0 -0
  57. {nutria_plugin-0.6.2 → nutria_plugin-0.7.0}/tests/test_skill_format_docs.py +0 -0
@@ -1,5 +1,26 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.0
4
+
5
+ Additive; manifests that do not use the new field are unchanged.
6
+
7
+ - Add `scope: "conversation_contact"` on a capability value input: the argument that names the person the conversation is with.
8
+ In a `public_customer` turn the host sets it itself, so neither the model nor the outside person chooses whose data is read.
9
+ - New validators: only a `personal_identifier` value input of a read capability can be scoped (one per capability); a
10
+ `public_customer` capability must be a read, must not take another person-identifying input, and must scope an input when it
11
+ returns personal or special-category content.
12
+ - Add `nutria_plugin.conversation_scope` (`scoped_argument`, `offered_to_outside_audience`, `apply_conversation_scope`): the one
13
+ definition of the pinning rule for hosts and plugin tests. See `docs/outside-audience.md`.
14
+
15
+ ## 0.6.3
16
+
17
+ Additive.
18
+
19
+ - Add `nutria_plugin.ownership`: `OwnerKind` (`human`, `agent`, `customer_service`), `ConversationOwnership` and
20
+ `ownership_from_event_payload`. One definition of who answers an outside person (priority human > agent > customer service,
21
+ a person's lock holds against every agent). Channel plugins report it as `conversation_ownership` in each inbound event;
22
+ the keys older plugins send (`ownership_state`, `human_owned`, `reply_blocked`) are still read. See `docs/conversation-ownership.md`.
23
+
3
24
  ## 0.6.2
4
25
 
5
26
  Additive.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: nutria-plugin
3
- Version: 0.6.2
3
+ Version: 0.7.0
4
4
  Summary: SDK for building, validating, signing, and packaging Nutria plugins
5
5
  Project-URL: Homepage, https://github.com/AlRos14/nutria-plugin-sdk
6
6
  Project-URL: Repository, https://github.com/AlRos14/nutria-plugin-sdk
@@ -0,0 +1,35 @@
1
+ # Conversation ownership
2
+
3
+ A conversation with an outside person has one owner at a time. A channel plugin reports it in every inbound event; the host
4
+ decides which agent answers. The words are defined once, in `nutria_plugin.ownership`.
5
+
6
+ | Owner kind | Meaning | Answers |
7
+ | --- | --- | --- |
8
+ | `human` | A team member took the conversation | Nobody else. Agents may draft and open cases. |
9
+ | `agent` | An agent started it or was handed it (`owner_ref` is the agent id) | That agent, with its own identity and rules |
10
+ | `customer_service` | Nobody above owns it (the default) | The customer-service agent |
11
+
12
+ A weaker owner never takes a conversation from a stronger one. `locked: true` (set by a person) holds it against every agent,
13
+ including the owning one.
14
+
15
+ ## In the event payload
16
+ ```json
17
+ {"conversation_ownership": {"owner_kind": "human", "owner_ref": "alejandro", "locked": false, "reason": "manual_takeover"}}
18
+ ```
19
+ A plugin that knows only who is a human (as the WhatsApp plugin did with `ownership_state`, `human_owned`, `reply_blocked`) keeps working:
20
+ `ownership_from_event_payload` maps those keys to the same model. A plugin that does not send ownership leaves the choice to the host.
21
+
22
+ ## What a plugin must do
23
+ - Report the human state it can observe (a person answered from the phone or the web client, a manual lock) as `owner_kind: human`.
24
+ - Never decide which agent answers; that is the host's job (it also records agent ownership from its own deliveries).
25
+ - Refuse to deliver an agent message to a conversation the plugin knows is human-owned and locked.
26
+
27
+ ## What a host must do
28
+ Resolve the answering agent from the plugin's report and its own ownership record, with the priority above; release agent ownership when the agent closes the
29
+ conversation, the contact asks to stop, a person takes over, or the conversation has been idle for the host's configured time.
30
+
31
+ ## Ids and granularity (new channels)
32
+ - `contact_id` in the event is the unit that has one owner. Choose it per channel: a user for direct messages, a thread for channel threads.
33
+ - Outbound recipients must use the same form as `contact_id`, so a message an agent sends is matched with the replies it receives.
34
+ - The host keeps ids as written (trimmed, lowercased). Emails and phone numbers get a canonical form; nothing else is rewritten.
35
+
@@ -1,6 +1,6 @@
1
1
  # nutria-plugin SDK documentation
2
2
 
3
- Developer reference for SDK `0.6.2` and manifest schema `6.0`.
3
+ Developer reference for SDK `0.7.0` and manifest schema `6.0`.
4
4
 
5
5
  | Document | Purpose |
6
6
  |---|---|
@@ -8,6 +8,7 @@ Developer reference for SDK `0.6.2` and manifest schema `6.0`.
8
8
  | [migration-6.0.md](migration-6.0.md) | Migrate a 5.0 plugin to 6.0 |
9
9
  | [manifest.md](manifest.md) | Manifest, capability, and provider contracts |
10
10
  | [capability-authoring.md](capability-authoring.md) | Effect scope, completion, operation facts, data classes, PreparedActions, validation errors |
11
+ | [outside-audience.md](outside-audience.md) | Capabilities offered to an outside audience, scoped to the conversation contact |
11
12
  | [reviewable-actions.md](reviewable-actions.md) | Host-owned drafts and external delivery |
12
13
  | [python-api.md](python-api.md) | Public Python API |
13
14
  | [connection-types.md](connection-types.md) | Supported runtime/connection types |
@@ -0,0 +1,38 @@
1
+ # Capabilities for an outside audience
2
+
3
+ An agent that answers a person outside the company works in a `public_customer` turn. A capability is offered to that
4
+ audience only if its manifest says so (`requirements.audience` contains `public_customer`). Most capabilities are not.
5
+
6
+ ## The rule
7
+
8
+ A capability offered to `public_customer`:
9
+
10
+ - is a **read** (`effect: read`); writes and sends go through the host's own approval path;
11
+ - takes **no person-identifying input** (`data_class: personal_identifier`) except the one scoped to the conversation contact;
12
+ - if it returns `personal_content` or `special_category` data, **must scope an input to the conversation contact**.
13
+
14
+ ## Scoping an input
15
+
16
+ ```json
17
+ {"kind": "value", "semantic_field": "chat", "argument_name": "chat", "required": false,
18
+ "data_class": "personal_identifier", "accepted_origins": ["current_user"], "scope": "conversation_contact"}
19
+ ```
20
+
21
+ `scope: "conversation_contact"` means: this argument names the one person the conversation is with. In an outside-audience
22
+ turn the host **sets it itself**, replacing whatever the model sent and filling it when the model left it out. The person
23
+ writing to the agent cannot choose another chat by mentioning it. Only a `value` input of class `personal_identifier` can carry
24
+ the scope, and a capability has at most one.
25
+
26
+ `nutria_plugin.apply_conversation_scope(capability, arguments, contact)` is the reference rule hosts and plugin tests share.
27
+
28
+ ## What the plugin must guarantee
29
+
30
+ The host fixes the argument; the plugin must make sure that, when the argument is given, **every** result belongs to that
31
+ person: a search with a chat never returns another chat, an item fetched by id is refused when it is not part of that chat,
32
+ and a list is limited to that chat. A capability that cannot guarantee this must not declare `public_customer`.
33
+
34
+ ## What is not covered
35
+
36
+ A capability that needs no contact (for example public pickup points) declares `public_customer` without a scope. It must not
37
+ return personal content. A resource a person quotes (such as a tracking number) is not a conversation scope: decide whether the
38
+ data behind it is safe to show to whoever sends that number.
@@ -76,3 +76,14 @@ status = verify_manifest(payload)
76
76
  ```
77
77
 
78
78
  Signing uses ECDSA P-256 over canonical JSON with the `signature` field removed.
79
+
80
+ ## Conversation scope
81
+
82
+ ```python
83
+ from nutria_plugin import apply_conversation_scope, scoped_argument
84
+
85
+ arguments = apply_conversation_scope(capability, {"chat": "whatever the model sent"}, contact="34600000000")
86
+ ```
87
+
88
+ For a capability offered to `public_customer`, the argument declared with `scope: "conversation_contact"` is replaced by the
89
+ conversation contact. See `outside-audience.md`.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "nutria-plugin"
7
- version = "0.6.2"
7
+ version = "0.7.0"
8
8
  description = "SDK for building, validating, signing, and packaging Nutria plugins"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
@@ -15,7 +15,7 @@ Signing:
15
15
  generate_keypair, sign_manifest, verify_manifest, SignatureStatus
16
16
  """
17
17
 
18
- __version__ = "0.6.2"
18
+ __version__ = "0.6.3"
19
19
 
20
20
  from .capabilities import (
21
21
  CapabilityDescriptor,
@@ -37,6 +37,18 @@ from .capabilities import (
37
37
  WorldProjectionDescriptor,
38
38
  WorldProviderDescriptor,
39
39
  )
40
+ from .conversation_scope import (
41
+ CONVERSATION_CONTACT,
42
+ apply_conversation_scope,
43
+ offered_to_outside_audience,
44
+ scoped_argument,
45
+ )
46
+ from .ownership import (
47
+ OWNER_PRIORITY,
48
+ ConversationOwnership,
49
+ OwnerKind,
50
+ ownership_from_event_payload,
51
+ )
40
52
  from .prepared_preview import (
41
53
  PREVIEW_CONFORMANCE_VECTORS,
42
54
  check_prepared_preview,
@@ -84,6 +96,16 @@ from .skills import SkillFrontmatter, parse_skill_frontmatter
84
96
 
85
97
  __all__ = [
86
98
  "__version__",
99
+ # Conversation scope for outside audiences
100
+ "CONVERSATION_CONTACT",
101
+ "apply_conversation_scope",
102
+ "offered_to_outside_audience",
103
+ "scoped_argument",
104
+ # Conversation ownership
105
+ "OWNER_PRIORITY",
106
+ "ConversationOwnership",
107
+ "OwnerKind",
108
+ "ownership_from_event_payload",
87
109
  # Manifest
88
110
  "PluginManifest",
89
111
  "PluginPaths",
@@ -213,6 +213,10 @@ class CapabilityInputBinding(BaseModel):
213
213
  data_class: DataClass
214
214
  requires_provenance: bool = False
215
215
  accepted_origins: list[Literal["current_user", "world_resource"]] = Field(min_length=1)
216
+ # ``conversation_contact``: this argument names the one person the conversation is with. When the host
217
+ # runs the capability for an outside audience it sets the argument itself, whatever the model sent
218
+ # or left empty. See ``nutria_plugin.conversation_scope``.
219
+ scope: Literal["conversation_contact"] | None = None
216
220
 
217
221
  model_config = {"extra": "forbid"}
218
222
 
@@ -225,6 +229,11 @@ class CapabilityInputBinding(BaseModel):
225
229
 
226
230
  @model_validator(mode="after")
227
231
  def _validate_kind(self) -> "CapabilityInputBinding":
232
+ if self.scope is not None:
233
+ if self.kind != "value":
234
+ raise ValueError("a conversation-scoped input must be a value input")
235
+ if self.data_class != DataClass.PERSONAL_IDENTIFIER:
236
+ raise ValueError("a conversation-scoped input must have data_class personal_identifier")
228
237
  if self.kind == "resource" and self.resource_type is None:
229
238
  raise ValueError("resource inputs require resource_type")
230
239
  if self.kind == "value" and self.resource_type is not None:
@@ -405,6 +414,32 @@ class CapabilityDescriptor(BaseModel):
405
414
  input_names = [item.semantic_field for item in self.inputs]
406
415
  if len(input_names) != len(set(input_names)):
407
416
  raise ValueError("capability inputs must not repeat semantic fields")
417
+ scoped = [item for item in self.inputs if item.scope is not None]
418
+ if len(scoped) > 1:
419
+ raise ValueError("a capability may scope only one input to the conversation contact")
420
+ if scoped and self.effect != CapabilityEffect.READ:
421
+ raise ValueError("only read capabilities may scope an input to the conversation contact")
422
+ if "public_customer" in self.requirements.audience:
423
+ if self.effect != CapabilityEffect.READ:
424
+ raise ValueError("only read capabilities may be offered to the public_customer audience")
425
+ others = [
426
+ item
427
+ for item in self.inputs
428
+ if item.scope is None and item.data_class == DataClass.PERSONAL_IDENTIFIER
429
+ ]
430
+ if others:
431
+ raise ValueError(
432
+ "a public_customer capability must not take another person-identifying input: "
433
+ "scope it to the conversation contact"
434
+ )
435
+ if not scoped and any(
436
+ out.data_class in {DataClass.PERSONAL_CONTENT, DataClass.SPECIAL_CATEGORY}
437
+ for out in self.produces
438
+ ):
439
+ raise ValueError(
440
+ "a public_customer capability that returns personal content must scope an input "
441
+ "to the conversation contact"
442
+ )
408
443
  output_names = [item.output_name for item in self.produces]
409
444
  if len(output_names) != len(set(output_names)):
410
445
  raise ValueError("capability outputs must not repeat output names")
@@ -0,0 +1,50 @@
1
+ """Pin a capability to the person a conversation is with.
2
+
3
+ A capability offered to an outside audience (``public_customer``) must never let the model, or the person
4
+ writing to it, choose whose data is read. The capability declares which argument names that person
5
+ (``scope: "conversation_contact"`` on the input); a host runs this rule before every call in such a turn.
6
+ It is pure (no I/O) so a plugin's tests and every host share one definition.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Mapping
12
+ from typing import Any
13
+
14
+ CONVERSATION_CONTACT = "conversation_contact"
15
+ OUTSIDE_AUDIENCE = "public_customer"
16
+
17
+
18
+ def scoped_argument(capability: Mapping[str, Any]) -> str | None:
19
+ """The argument that names the conversation contact, or None when the capability declares none."""
20
+ for item in capability.get("inputs") or []:
21
+ if isinstance(item, Mapping) and item.get("scope") == CONVERSATION_CONTACT:
22
+ name = item.get("argument_name")
23
+ return str(name) if name else None
24
+ return None
25
+
26
+
27
+ def offered_to_outside_audience(capability: Mapping[str, Any]) -> bool:
28
+ requirements = capability.get("requirements")
29
+ audience = requirements.get("audience") if isinstance(requirements, Mapping) else None
30
+ return isinstance(audience, list) and OUTSIDE_AUDIENCE in audience
31
+
32
+
33
+ def apply_conversation_scope(
34
+ capability: Mapping[str, Any], arguments: Mapping[str, Any], contact: str
35
+ ) -> dict[str, Any]:
36
+ """Arguments for one call in an outside-audience turn: the contact replaces whatever was sent.
37
+
38
+ Raises ``ValueError`` when the capability is not offered to the outside audience, when it declares a
39
+ person-identifying input without scope, or when the contact is empty. A capability that declares no
40
+ scoped input is returned unchanged (it reads nothing about a person).
41
+ """
42
+ if not offered_to_outside_audience(capability):
43
+ raise ValueError("capability is not offered to the public_customer audience")
44
+ if not str(contact or "").strip():
45
+ raise ValueError("an outside-audience call needs the conversation contact")
46
+ argument = scoped_argument(capability)
47
+ result = dict(arguments)
48
+ if argument is not None:
49
+ result[argument] = str(contact).strip()
50
+ return result
@@ -0,0 +1,95 @@
1
+ """Conversation ownership: who answers an outside person right now.
2
+
3
+ A channel plugin that talks to outside people (WhatsApp, email, chat widgets) reports, with each inbound
4
+ event, who owns the conversation. A host resolves the answering agent from it. One definition, so every
5
+ plugin and every host agree on the words.
6
+
7
+ Priority, strongest first: ``human`` > ``agent`` > ``customer_service``. A weaker owner never takes a
8
+ conversation from a stronger one. A lock (set by a person) holds the conversation against every agent.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from collections.abc import Mapping
14
+ from enum import Enum
15
+ from typing import Any
16
+
17
+ from pydantic import BaseModel, ConfigDict, Field
18
+
19
+
20
+ class OwnerKind(str, Enum):
21
+ HUMAN = "human"
22
+ AGENT = "agent"
23
+ CUSTOMER_SERVICE = "customer_service"
24
+
25
+
26
+ OWNER_PRIORITY: dict[OwnerKind, int] = {
27
+ OwnerKind.HUMAN: 3,
28
+ OwnerKind.AGENT: 2,
29
+ OwnerKind.CUSTOMER_SERVICE: 1,
30
+ }
31
+
32
+ # States older plugins already send in the event payload (``owner_state`` / ``ownership_state``).
33
+ _LEGACY_HUMAN_STATES = frozenset({"human_owned", "locked", "human"})
34
+
35
+
36
+ class ConversationOwnership(BaseModel):
37
+ """Who owns one conversation with one contact on one channel."""
38
+
39
+ model_config = ConfigDict(extra="forbid", frozen=True)
40
+
41
+ owner_kind: OwnerKind = OwnerKind.CUSTOMER_SERVICE
42
+ owner_ref: str | None = Field(
43
+ default=None,
44
+ description="Agent id when owner_kind is 'agent'; the person's id when 'human'; empty otherwise.",
45
+ )
46
+ locked: bool = Field(
47
+ default=False,
48
+ description="A person locked the conversation: no agent replies, whatever the owner kind.",
49
+ )
50
+ reason: str | None = None
51
+
52
+ @property
53
+ def priority(self) -> int:
54
+ return OWNER_PRIORITY[self.owner_kind] + (10 if self.locked else 0)
55
+
56
+ @property
57
+ def agents_may_reply(self) -> bool:
58
+ return self.owner_kind != OwnerKind.HUMAN and not self.locked
59
+
60
+ def may_be_taken_by(self, kind: OwnerKind, *, ref: str | None = None) -> bool:
61
+ """Whether a new owner of ``kind`` may take this conversation.
62
+
63
+ Equal rank may only re-take its own conversation (same ``ref``); a locked conversation is taken
64
+ only by a human.
65
+ """
66
+ if self.locked:
67
+ return kind == OwnerKind.HUMAN
68
+ if OWNER_PRIORITY[kind] > OWNER_PRIORITY[self.owner_kind]:
69
+ return True
70
+ return kind == self.owner_kind and (ref or None) == (self.owner_ref or None)
71
+
72
+
73
+ def ownership_from_event_payload(payload: Mapping[str, Any] | None) -> ConversationOwnership | None:
74
+ """Read ownership from an external-channel event payload.
75
+
76
+ Prefers the structured ``conversation_ownership`` object. Falls back to the keys older plugins send
77
+ (``ownership_state`` / ``owner_state`` / ``human_owned`` / ``reply_blocked``) so they keep working.
78
+ Returns ``None`` when the payload says nothing about ownership.
79
+ """
80
+ if not isinstance(payload, Mapping):
81
+ return None
82
+ structured = payload.get("conversation_ownership")
83
+ if isinstance(structured, Mapping):
84
+ return ConversationOwnership.model_validate(dict(structured))
85
+ state = str(payload.get("ownership_state") or payload.get("owner_state") or "").strip().lower()
86
+ human = bool(payload.get("human_owned")) or state in _LEGACY_HUMAN_STATES
87
+ if human:
88
+ return ConversationOwnership(
89
+ owner_kind=OwnerKind.HUMAN,
90
+ locked=state == "locked",
91
+ reason=str(payload.get("block_reason") or "") or None,
92
+ )
93
+ if state or "reply_blocked" in payload:
94
+ return ConversationOwnership(owner_kind=OwnerKind.CUSTOMER_SERVICE)
95
+ return None
@@ -0,0 +1,120 @@
1
+ """A capability offered to an outside audience is pinned to the person the conversation is with."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pytest
6
+ from pydantic import ValidationError
7
+
8
+ from nutria_plugin import (
9
+ CapabilityDescriptor,
10
+ apply_conversation_scope,
11
+ offered_to_outside_audience,
12
+ scoped_argument,
13
+ )
14
+
15
+
16
+ def _read(
17
+ audience=("private_internal", "public_customer"), inputs=None, data_class="personal_content"
18
+ ):
19
+ return {
20
+ "id": "chat.recent",
21
+ "title": "Recent messages",
22
+ "description": "Recent messages of one chat.",
23
+ "domains": ["whatsapp"],
24
+ "effect": "read",
25
+ "effect_scope": "world",
26
+ "tool": "recent",
27
+ "requirements": {"authority": "read", "audience": list(audience)},
28
+ "exposure": "model",
29
+ "produces": [
30
+ {
31
+ "result_path": ".messages",
32
+ "resource_type": "whatsapp_message",
33
+ "output_name": "messages",
34
+ "many": True,
35
+ "data_class": data_class,
36
+ }
37
+ ],
38
+ "inputs": inputs
39
+ if inputs is not None
40
+ else [
41
+ {
42
+ "kind": "value",
43
+ "semantic_field": "chat",
44
+ "argument_name": "chat",
45
+ "required": False,
46
+ "data_class": "personal_identifier",
47
+ "accepted_origins": ["current_user"],
48
+ "scope": "conversation_contact",
49
+ }
50
+ ],
51
+ }
52
+
53
+
54
+ def test_a_scoped_read_is_valid_and_names_its_argument():
55
+ payload = _read()
56
+ CapabilityDescriptor.model_validate(payload)
57
+
58
+ assert scoped_argument(payload) == "chat" and offered_to_outside_audience(payload)
59
+
60
+
61
+ def test_the_contact_replaces_what_the_model_sent_or_left_empty():
62
+ payload = _read()
63
+
64
+ assert apply_conversation_scope(
65
+ payload, {"chat": "34600000000", "limit": 5}, " 34611111111 "
66
+ ) == {
67
+ "chat": "34611111111",
68
+ "limit": 5,
69
+ }
70
+ assert apply_conversation_scope(payload, {}, "34611111111") == {"chat": "34611111111"}
71
+
72
+
73
+ def test_a_capability_not_offered_to_the_outside_is_never_pinned():
74
+ with pytest.raises(ValueError):
75
+ apply_conversation_scope(_read(audience=("private_internal",)), {}, "34611111111")
76
+ with pytest.raises(ValueError):
77
+ apply_conversation_scope(_read(), {}, " ")
78
+
79
+
80
+ def test_personal_content_for_the_outside_needs_a_scoped_input():
81
+ with pytest.raises(ValidationError, match="scope an input"):
82
+ CapabilityDescriptor.model_validate(_read(inputs=[]))
83
+
84
+
85
+ def test_another_person_identifying_input_is_refused_for_the_outside():
86
+ other = {
87
+ "kind": "value",
88
+ "semantic_field": "recipient",
89
+ "argument_name": "recipient",
90
+ "data_class": "personal_identifier",
91
+ "accepted_origins": ["current_user"],
92
+ }
93
+ scoped = _read()["inputs"][0]
94
+
95
+ with pytest.raises(ValidationError, match="another person-identifying input"):
96
+ CapabilityDescriptor.model_validate(_read(inputs=[scoped, other]))
97
+
98
+
99
+ def test_only_a_personal_identifier_value_can_be_scoped_and_only_one():
100
+ base = _read()["inputs"][0]
101
+
102
+ with pytest.raises(ValidationError, match="personal_identifier"):
103
+ CapabilityDescriptor.model_validate(_read(inputs=[{**base, "data_class": "non_personal"}]))
104
+ with pytest.raises(ValidationError, match="only one input"):
105
+ CapabilityDescriptor.model_validate(
106
+ _read(inputs=[base, {**base, "semantic_field": "peer", "argument_name": "peer"}])
107
+ )
108
+
109
+
110
+ def test_a_write_cannot_be_scoped_or_offered_to_the_outside():
111
+ payload = _read()
112
+ payload.update(effect="write", effect_scope="internal_state", produces=[])
113
+ payload["requirements"]["authority"] = "write_internal"
114
+
115
+ with pytest.raises(ValidationError):
116
+ CapabilityDescriptor.model_validate(payload)
117
+
118
+
119
+ def test_a_capability_without_scope_keeps_working_for_internal_audiences():
120
+ CapabilityDescriptor.model_validate(_read(audience=("private_internal",), inputs=[]))
@@ -0,0 +1,47 @@
1
+ import pytest
2
+
3
+ from nutria_plugin import ConversationOwnership, OwnerKind, ownership_from_event_payload
4
+
5
+
6
+ def test_structured_payload_is_read():
7
+ owner = ownership_from_event_payload(
8
+ {"conversation_ownership": {"owner_kind": "agent", "owner_ref": "lia", "locked": False}}
9
+ )
10
+ assert owner.owner_kind is OwnerKind.AGENT and owner.owner_ref == "lia"
11
+
12
+
13
+ @pytest.mark.parametrize(
14
+ "payload,locked",
15
+ [
16
+ ({"ownership_state": "human_owned", "reply_blocked": True}, False),
17
+ ({"owner_state": "locked"}, True),
18
+ ({"human_owned": True}, False),
19
+ ],
20
+ )
21
+ def test_legacy_keys_map_to_human(payload, locked):
22
+ owner = ownership_from_event_payload(payload)
23
+ assert owner.owner_kind is OwnerKind.HUMAN
24
+ assert owner.locked is locked
25
+
26
+
27
+ def test_unknown_or_silent_payloads():
28
+ assert ownership_from_event_payload(None) is None
29
+ assert ownership_from_event_payload({"preview": "hola"}) is None
30
+ assert ownership_from_event_payload({"ownership_state": "agent_owned"}).owner_kind is OwnerKind.CUSTOMER_SERVICE
31
+
32
+
33
+ def test_priority_and_locks():
34
+ customer_service = ConversationOwnership()
35
+ agent = ConversationOwnership(owner_kind=OwnerKind.AGENT, owner_ref="lia")
36
+ human = ConversationOwnership(owner_kind=OwnerKind.HUMAN, owner_ref="ana")
37
+ locked_agent = ConversationOwnership(owner_kind=OwnerKind.AGENT, owner_ref="lia", locked=True)
38
+
39
+ assert customer_service.may_be_taken_by(OwnerKind.AGENT, ref="lia")
40
+ assert not agent.may_be_taken_by(OwnerKind.CUSTOMER_SERVICE)
41
+ assert agent.may_be_taken_by(OwnerKind.AGENT, ref="lia")
42
+ assert not agent.may_be_taken_by(OwnerKind.AGENT, ref="marcos")
43
+ assert agent.may_be_taken_by(OwnerKind.HUMAN)
44
+ assert not human.may_be_taken_by(OwnerKind.AGENT, ref="lia")
45
+ assert not locked_agent.may_be_taken_by(OwnerKind.AGENT, ref="lia")
46
+ assert locked_agent.may_be_taken_by(OwnerKind.HUMAN)
47
+ assert not human.agents_may_reply and not locked_agent.agents_may_reply and agent.agents_may_reply
@@ -262,7 +262,7 @@ wheels = [
262
262
 
263
263
  [[package]]
264
264
  name = "nutria-plugin"
265
- version = "0.6.0"
265
+ version = "0.7.0"
266
266
  source = { editable = "." }
267
267
  dependencies = [
268
268
  { name = "cryptography" },
File without changes
File without changes
File without changes