threadify-sdk 0.4.0__tar.gz → 0.5.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.
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/CHANGELOG.md +30 -0
- {threadify_sdk-0.4.0/threadify_sdk.egg-info → threadify_sdk-0.5.0}/PKG-INFO +20 -12
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/README.md +19 -11
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/pyproject.toml +1 -1
- threadify_sdk-0.5.0/tests/test_client.py +63 -0
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/tests/test_connection.py +23 -0
- threadify_sdk-0.5.0/tests/test_decisions.py +56 -0
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/tests/test_models.py +6 -33
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/tests/test_parity.py +2 -5
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/tests/test_step.py +0 -8
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/threadify/__init__.py +6 -1
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/threadify/client.py +22 -59
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/threadify/connection.py +7 -1
- threadify_sdk-0.5.0/threadify/decisions.py +99 -0
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/threadify/models.py +6 -24
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/threadify/otel_exporter.py +1 -1
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/threadify/step.py +0 -11
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/threadify/thread.py +35 -0
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0/threadify_sdk.egg-info}/PKG-INFO +20 -12
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/threadify_sdk.egg-info/SOURCES.txt +2 -0
- threadify_sdk-0.4.0/tests/test_client.py +0 -76
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/LICENSE +0 -0
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/MANIFEST.in +0 -0
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/setup.cfg +0 -0
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/tests/test_data_retriever.py +0 -0
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/tests/test_notification.py +0 -0
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/tests/test_otel_correlation.py +0 -0
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/tests/test_thread.py +0 -0
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/tests/test_thread_key.py +0 -0
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/threadify/data_retriever.py +0 -0
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/threadify/notification.py +0 -0
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/threadify/waiting.py +0 -0
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/threadify_sdk.egg-info/dependency_links.txt +0 -0
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/threadify_sdk.egg-info/requires.txt +0 -0
- {threadify_sdk-0.4.0 → threadify_sdk-0.5.0}/threadify_sdk.egg-info/top_level.txt +0 -0
|
@@ -1,5 +1,35 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [Unreleased]
|
|
4
|
+
|
|
5
|
+
## [0.5.0] - 2026-12-04
|
|
6
|
+
|
|
7
|
+
### Breaking changes
|
|
8
|
+
|
|
9
|
+
- The Engine URL is now the required first argument:
|
|
10
|
+
`Threadify.connect(engine_url, api_key, *, service_name=..., ...)` and
|
|
11
|
+
`Threadify.create(engine_url, api_key, ...)`. There is no default hosted
|
|
12
|
+
Engine any more; the SDK derives the WebSocket and GraphQL paths from the URL.
|
|
13
|
+
- Remove the `engine_url`, `ws_url` and `graphql_url` keyword arguments and the
|
|
14
|
+
matching `ConnectOptions` fields, along with `DEFAULT_WS_URL` and
|
|
15
|
+
`derive_graphql_url`.
|
|
16
|
+
- Remove `ThreadStep.add_private_context()`. Threadify has no private context;
|
|
17
|
+
use `add_context()`.
|
|
18
|
+
- `Threadify.connect()` no longer accepts the legacy positional `service_name`
|
|
19
|
+
and `ConnectOptions` arguments. Pass them as keywords.
|
|
20
|
+
|
|
21
|
+
### Added
|
|
22
|
+
|
|
23
|
+
- Decision helpers on threads: `can()`, `should()` and `next()` return typed
|
|
24
|
+
`CanDecision`, `ShouldDecision` and `NextDecision` results.
|
|
25
|
+
- `subscribe()` and `unsubscribe()` accept the rulebook spelling of thread
|
|
26
|
+
events: `$thread.completed`, `$thread.cancelled` and `$thread.*` work the same
|
|
27
|
+
as `thread.completed`, `thread.cancelled` and `thread.*`.
|
|
28
|
+
|
|
29
|
+
### Changed
|
|
30
|
+
|
|
31
|
+
- Values are no longer sent twice as `private_<key>` fields.
|
|
32
|
+
|
|
3
33
|
## [0.4.0] - 2026-09-23
|
|
4
34
|
|
|
5
35
|
### Breaking changes
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: threadify-sdk
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.5.0
|
|
4
4
|
Summary: Python SDK for Threadify — Service-delivery intelligence. Track every customer request from start to finish across every system, team, and partner. Visit: https://threadify.dev
|
|
5
5
|
Author-email: Threadify Team <team@threadify.dev>
|
|
6
6
|
License: MIT
|
|
@@ -58,6 +58,7 @@ from threadify import Threadify
|
|
|
58
58
|
async def main():
|
|
59
59
|
try:
|
|
60
60
|
conn = await Threadify.connect(
|
|
61
|
+
"https://threadify.example.com", # your Engine URL
|
|
61
62
|
"your-api-key",
|
|
62
63
|
service_name="orders-service",
|
|
63
64
|
)
|
|
@@ -92,7 +93,7 @@ if __name__ == "__main__":
|
|
|
92
93
|
asyncio.run(main())
|
|
93
94
|
```
|
|
94
95
|
|
|
95
|
-
|
|
96
|
+
The Engine URL is the first argument and is required: Threadify is self-hosted, so there is no default Engine. Use the URL from **Settings → Engine**. WebSocket and GraphQL paths are derived from it, including reverse-proxy prefixes.
|
|
96
97
|
|
|
97
98
|
## Entity profiles
|
|
98
99
|
|
|
@@ -107,10 +108,10 @@ description: Customer workflows
|
|
|
107
108
|
```
|
|
108
109
|
|
|
109
110
|
```sh
|
|
110
|
-
threadify
|
|
111
|
-
threadify
|
|
112
|
-
threadify
|
|
113
|
-
threadify
|
|
111
|
+
threadify config set api-url https://threadify.example.com
|
|
112
|
+
threadify login
|
|
113
|
+
threadify profile-types create --file customers.yaml
|
|
114
|
+
threadify profiles create --type-id TYPE_ID --ref-value CUST-001 --name 'Jane Doe'
|
|
114
115
|
```
|
|
115
116
|
|
|
116
117
|
Use the returned profile type ID for `TYPE_ID`. Include `customer_id` in your
|
|
@@ -122,12 +123,10 @@ dashboard to explore that history and configure metrics.
|
|
|
122
123
|
|
|
123
124
|
### Connect options
|
|
124
125
|
|
|
125
|
-
|
|
126
|
+
`Threadify.connect(engine_url, api_key, ...)` takes the Engine URL (one HTTP(S)
|
|
127
|
+
base, including any proxy prefix) and API key first, then these keyword arguments:
|
|
126
128
|
|
|
127
129
|
- `service_name`
|
|
128
|
-
- `engine_url` (one HTTP(S) deployment base, including any proxy prefix)
|
|
129
|
-
- `ws_url` (optional, defaults to production)
|
|
130
|
-
- `graphql_url`
|
|
131
130
|
- `debug`
|
|
132
131
|
- `max_in_flight`
|
|
133
132
|
- `connect_timeout`
|
|
@@ -138,6 +137,7 @@ Example:
|
|
|
138
137
|
from threadify import Threadify
|
|
139
138
|
|
|
140
139
|
conn = await Threadify.connect(
|
|
140
|
+
"https://threadify.example.com",
|
|
141
141
|
"your-api-key",
|
|
142
142
|
service_name="inventory-service",
|
|
143
143
|
debug=True,
|
|
@@ -261,7 +261,7 @@ from opentelemetry.sdk.trace import TracerProvider
|
|
|
261
261
|
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
|
262
262
|
from threadify import Threadify
|
|
263
263
|
|
|
264
|
-
conn = await Threadify.connect("api-key", service_name="checkout-service")
|
|
264
|
+
conn = await Threadify.connect("https://threadify.example.com", "api-key", service_name="checkout-service")
|
|
265
265
|
|
|
266
266
|
# Create exporter
|
|
267
267
|
exporter = conn.create_span_exporter(options={"refs": ["order.id", "customer.id"]})
|
|
@@ -316,9 +316,14 @@ python3 -m pytest
|
|
|
316
316
|
```python
|
|
317
317
|
from threadify import Threadify, WaitOptions, ThreadifyError
|
|
318
318
|
|
|
319
|
-
connection = await Threadify.connect(
|
|
319
|
+
connection = await Threadify.connect("https://threadify.example.com", api_key, service_name="payments")
|
|
320
320
|
threads = await connection.get_threads_by_ref({"order_id": "ORD-1001"}, status="active", limit=25)
|
|
321
321
|
thread = await connection.thread("order:ORD-1001")
|
|
322
|
+
paths = await thread.next() # Unranked possible Contract paths.
|
|
323
|
+
eligibility = await thread.can(action="charge")
|
|
324
|
+
if not eligibility.allowed:
|
|
325
|
+
raise RuntimeError(eligibility.reason)
|
|
326
|
+
advice = await thread.should(action="charge") # Optional; never grants execution.
|
|
322
327
|
grant = await thread.wait_for("charge", WaitOptions(timeout=15))
|
|
323
328
|
# Execute the permitted business operation here.
|
|
324
329
|
result = await thread.step("charge").add_context({"amount": 42}).success("charged", wait_for=True, timeout=15)
|
|
@@ -331,6 +336,9 @@ await thread.wait_for_validation("charge", result.step_id)
|
|
|
331
336
|
ID into the subsequent step report and its default idempotency key. It sends one
|
|
332
337
|
request and waits for a final correlated response. The old notification-only
|
|
333
338
|
helper is named `wait_for_notification()`; it does not authorize execution.
|
|
339
|
+
`can()`, `should()`, and `next()` are read-only GraphQL decisions. `next()`
|
|
340
|
+
returns multiple paths without ranking them; `wait_for()` makes the atomic
|
|
341
|
+
claim before a guarded side effect.
|
|
334
342
|
|
|
335
343
|
Timeouts are in **seconds**, at most 300. Cancelling the Python task or reaching
|
|
336
344
|
its timeout cancels the remote wait. Before reporting a granted operation, use
|
|
@@ -28,6 +28,7 @@ from threadify import Threadify
|
|
|
28
28
|
async def main():
|
|
29
29
|
try:
|
|
30
30
|
conn = await Threadify.connect(
|
|
31
|
+
"https://threadify.example.com", # your Engine URL
|
|
31
32
|
"your-api-key",
|
|
32
33
|
service_name="orders-service",
|
|
33
34
|
)
|
|
@@ -62,7 +63,7 @@ if __name__ == "__main__":
|
|
|
62
63
|
asyncio.run(main())
|
|
63
64
|
```
|
|
64
65
|
|
|
65
|
-
|
|
66
|
+
The Engine URL is the first argument and is required: Threadify is self-hosted, so there is no default Engine. Use the URL from **Settings → Engine**. WebSocket and GraphQL paths are derived from it, including reverse-proxy prefixes.
|
|
66
67
|
|
|
67
68
|
## Entity profiles
|
|
68
69
|
|
|
@@ -77,10 +78,10 @@ description: Customer workflows
|
|
|
77
78
|
```
|
|
78
79
|
|
|
79
80
|
```sh
|
|
80
|
-
threadify
|
|
81
|
-
threadify
|
|
82
|
-
threadify
|
|
83
|
-
threadify
|
|
81
|
+
threadify config set api-url https://threadify.example.com
|
|
82
|
+
threadify login
|
|
83
|
+
threadify profile-types create --file customers.yaml
|
|
84
|
+
threadify profiles create --type-id TYPE_ID --ref-value CUST-001 --name 'Jane Doe'
|
|
84
85
|
```
|
|
85
86
|
|
|
86
87
|
Use the returned profile type ID for `TYPE_ID`. Include `customer_id` in your
|
|
@@ -92,12 +93,10 @@ dashboard to explore that history and configure metrics.
|
|
|
92
93
|
|
|
93
94
|
### Connect options
|
|
94
95
|
|
|
95
|
-
|
|
96
|
+
`Threadify.connect(engine_url, api_key, ...)` takes the Engine URL (one HTTP(S)
|
|
97
|
+
base, including any proxy prefix) and API key first, then these keyword arguments:
|
|
96
98
|
|
|
97
99
|
- `service_name`
|
|
98
|
-
- `engine_url` (one HTTP(S) deployment base, including any proxy prefix)
|
|
99
|
-
- `ws_url` (optional, defaults to production)
|
|
100
|
-
- `graphql_url`
|
|
101
100
|
- `debug`
|
|
102
101
|
- `max_in_flight`
|
|
103
102
|
- `connect_timeout`
|
|
@@ -108,6 +107,7 @@ Example:
|
|
|
108
107
|
from threadify import Threadify
|
|
109
108
|
|
|
110
109
|
conn = await Threadify.connect(
|
|
110
|
+
"https://threadify.example.com",
|
|
111
111
|
"your-api-key",
|
|
112
112
|
service_name="inventory-service",
|
|
113
113
|
debug=True,
|
|
@@ -231,7 +231,7 @@ from opentelemetry.sdk.trace import TracerProvider
|
|
|
231
231
|
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
|
232
232
|
from threadify import Threadify
|
|
233
233
|
|
|
234
|
-
conn = await Threadify.connect("api-key", service_name="checkout-service")
|
|
234
|
+
conn = await Threadify.connect("https://threadify.example.com", "api-key", service_name="checkout-service")
|
|
235
235
|
|
|
236
236
|
# Create exporter
|
|
237
237
|
exporter = conn.create_span_exporter(options={"refs": ["order.id", "customer.id"]})
|
|
@@ -286,9 +286,14 @@ python3 -m pytest
|
|
|
286
286
|
```python
|
|
287
287
|
from threadify import Threadify, WaitOptions, ThreadifyError
|
|
288
288
|
|
|
289
|
-
connection = await Threadify.connect(
|
|
289
|
+
connection = await Threadify.connect("https://threadify.example.com", api_key, service_name="payments")
|
|
290
290
|
threads = await connection.get_threads_by_ref({"order_id": "ORD-1001"}, status="active", limit=25)
|
|
291
291
|
thread = await connection.thread("order:ORD-1001")
|
|
292
|
+
paths = await thread.next() # Unranked possible Contract paths.
|
|
293
|
+
eligibility = await thread.can(action="charge")
|
|
294
|
+
if not eligibility.allowed:
|
|
295
|
+
raise RuntimeError(eligibility.reason)
|
|
296
|
+
advice = await thread.should(action="charge") # Optional; never grants execution.
|
|
292
297
|
grant = await thread.wait_for("charge", WaitOptions(timeout=15))
|
|
293
298
|
# Execute the permitted business operation here.
|
|
294
299
|
result = await thread.step("charge").add_context({"amount": 42}).success("charged", wait_for=True, timeout=15)
|
|
@@ -301,6 +306,9 @@ await thread.wait_for_validation("charge", result.step_id)
|
|
|
301
306
|
ID into the subsequent step report and its default idempotency key. It sends one
|
|
302
307
|
request and waits for a final correlated response. The old notification-only
|
|
303
308
|
helper is named `wait_for_notification()`; it does not authorize execution.
|
|
309
|
+
`can()`, `should()`, and `next()` are read-only GraphQL decisions. `next()`
|
|
310
|
+
returns multiple paths without ranking them; `wait_for()` makes the atomic
|
|
311
|
+
claim before a guarded side effect.
|
|
304
312
|
|
|
305
313
|
Timeouts are in **seconds**, at most 300. Cancelling the Python task or reaching
|
|
306
314
|
its timeout cancels the remote wait. Before reporting a granted operation, use
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "threadify-sdk"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.5.0"
|
|
8
8
|
description = "Python SDK for Threadify — Service-delivery intelligence. Track every customer request from start to finish across every system, team, and partner. Visit: https://threadify.dev"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from unittest.mock import AsyncMock
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from threadify.client import Threadify
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class TestThreadifyConnect:
|
|
10
|
+
@pytest.mark.asyncio
|
|
11
|
+
async def test_connect_derives_paths_from_the_engine_url(self, monkeypatch):
|
|
12
|
+
ws = AsyncMock()
|
|
13
|
+
ws.send = AsyncMock()
|
|
14
|
+
ws.recv = AsyncMock(return_value=json.dumps({"action": "connect", "status": "success"}))
|
|
15
|
+
ws.close = AsyncMock()
|
|
16
|
+
|
|
17
|
+
ws_connect = AsyncMock(return_value=ws)
|
|
18
|
+
monkeypatch.setattr("threadify.client.websockets.connect", ws_connect)
|
|
19
|
+
|
|
20
|
+
conn = await Threadify.connect(
|
|
21
|
+
"https://example.com/proxy",
|
|
22
|
+
"test-api-key",
|
|
23
|
+
service_name="test-service",
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
ws_connect.assert_awaited_once_with("wss://example.com/proxy/threads")
|
|
27
|
+
sent_msg = json.loads(ws.send.call_args.args[0])
|
|
28
|
+
assert sent_msg["action"] == "connect"
|
|
29
|
+
assert sent_msg["apiKey"] == "test-api-key"
|
|
30
|
+
assert sent_msg["serviceName"] == "test-service"
|
|
31
|
+
assert conn._graphql_url == "https://example.com/proxy/graphql"
|
|
32
|
+
assert conn.is_connected is True
|
|
33
|
+
|
|
34
|
+
@pytest.mark.asyncio
|
|
35
|
+
@pytest.mark.parametrize("engine_url", ["", " ", None])
|
|
36
|
+
async def test_connect_requires_an_engine_url(self, monkeypatch, engine_url):
|
|
37
|
+
ws_connect = AsyncMock()
|
|
38
|
+
monkeypatch.setattr("threadify.client.websockets.connect", ws_connect)
|
|
39
|
+
with pytest.raises(ValueError, match="engine_url is required"):
|
|
40
|
+
await Threadify.connect(engine_url, "test-api-key")
|
|
41
|
+
ws_connect.assert_not_awaited()
|
|
42
|
+
|
|
43
|
+
@pytest.mark.asyncio
|
|
44
|
+
async def test_old_signature_is_rejected_before_connecting(self, monkeypatch):
|
|
45
|
+
ws_connect = AsyncMock()
|
|
46
|
+
monkeypatch.setattr("threadify.client.websockets.connect", ws_connect)
|
|
47
|
+
with pytest.raises(TypeError):
|
|
48
|
+
await Threadify.connect("test-api-key", service_name="svc") # type: ignore[call-arg]
|
|
49
|
+
with pytest.raises(TypeError):
|
|
50
|
+
await Threadify.connect( # type: ignore[call-arg]
|
|
51
|
+
"https://example.com", "key", ws_url="wss://example.com/threads"
|
|
52
|
+
)
|
|
53
|
+
ws_connect.assert_not_awaited()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class TestThreadifyFactory:
|
|
57
|
+
def test_create_keeps_the_engine_url(self):
|
|
58
|
+
factory = Threadify.create("https://threadify.example.com", "test-api-key")
|
|
59
|
+
assert factory._engine_url == "https://threadify.example.com"
|
|
60
|
+
|
|
61
|
+
def test_create_requires_an_engine_url(self):
|
|
62
|
+
with pytest.raises(ValueError, match="engine_url is required"):
|
|
63
|
+
Threadify.create("", "test-api-key")
|
|
@@ -353,6 +353,29 @@ class TestNotificationHandling:
|
|
|
353
353
|
conn.unsubscribe("step.success", "order_placed")
|
|
354
354
|
assert "step.success:order_placed" not in conn._notification_handlers
|
|
355
355
|
|
|
356
|
+
@pytest.mark.asyncio
|
|
357
|
+
async def test_subscribe_accepts_rulebook_thread_event_spelling(self):
|
|
358
|
+
conn = _make_connection()
|
|
359
|
+
calls = []
|
|
360
|
+
|
|
361
|
+
conn.subscribe("$thread.completed", calls.append)
|
|
362
|
+
assert "thread.completed:global" in conn._notification_handlers
|
|
363
|
+
|
|
364
|
+
conn._handle_notification(
|
|
365
|
+
{
|
|
366
|
+
"notificationId": "n-thread-1",
|
|
367
|
+
"threadId": "t-1",
|
|
368
|
+
"stepName": "global",
|
|
369
|
+
"source": "thread",
|
|
370
|
+
"notificationType": "thread.completed",
|
|
371
|
+
},
|
|
372
|
+
"ack-thread-1",
|
|
373
|
+
)
|
|
374
|
+
assert len(calls) == 1
|
|
375
|
+
|
|
376
|
+
conn.unsubscribe("$thread.completed")
|
|
377
|
+
assert "thread.completed:global" not in conn._notification_handlers
|
|
378
|
+
|
|
356
379
|
@pytest.mark.asyncio
|
|
357
380
|
async def test_subscribe_none_handler(self):
|
|
358
381
|
conn = _make_connection()
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from threadify.decisions import CanDecision, NextDecision, ShouldDecision
|
|
6
|
+
from threadify.thread import ThreadInstance
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class DecisionClient:
|
|
10
|
+
def __init__(self):
|
|
11
|
+
self.calls = []
|
|
12
|
+
|
|
13
|
+
async def query(self, query, variables):
|
|
14
|
+
self.calls.append((query, variables))
|
|
15
|
+
if "query Can" in query:
|
|
16
|
+
return {"can": {
|
|
17
|
+
"threadId": "thread-1", "stepName": "issue_refund", "allowed": True,
|
|
18
|
+
"status": "allowed", "matchedBy": "classifier", "requiredSteps": [],
|
|
19
|
+
"satisfiedSteps": [], "missingSteps": [], "previousStep": None,
|
|
20
|
+
"reason": "eligible",
|
|
21
|
+
}}
|
|
22
|
+
if "query Should" in query:
|
|
23
|
+
return {"should": {
|
|
24
|
+
"threadId": "thread-1", "stepName": "issue_refund",
|
|
25
|
+
"eligible": True, "recommendation": "uncertain", "reason": "unclear",
|
|
26
|
+
}}
|
|
27
|
+
return {"next": {
|
|
28
|
+
"threadId": "thread-1", "paths": [
|
|
29
|
+
{"actions": ["issue_refund"], "status": "allowed", "reason": "eligible"}
|
|
30
|
+
],
|
|
31
|
+
}}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_thread_decisions_use_authenticated_graphql_client():
|
|
35
|
+
asyncio.run(_exercise_decisions())
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
async def _exercise_decisions():
|
|
39
|
+
client = DecisionClient()
|
|
40
|
+
retriever = type("Retriever", (), {"_client": client})()
|
|
41
|
+
connection = type("Connection", (), {"_get_data_retriever": lambda self: retriever})()
|
|
42
|
+
thread = ThreadInstance(connection, "thread-1")
|
|
43
|
+
|
|
44
|
+
can = await thread.can(goal="I want to process a refund", context={"amount": 12})
|
|
45
|
+
should = await thread.should(action="issue_refund")
|
|
46
|
+
next_decision = await thread.next()
|
|
47
|
+
|
|
48
|
+
assert isinstance(can, CanDecision) and can.matched_by == "classifier"
|
|
49
|
+
assert isinstance(should, ShouldDecision) and should.recommendation == "uncertain"
|
|
50
|
+
assert isinstance(next_decision, NextDecision)
|
|
51
|
+
assert next_decision.paths[0].actions == ["issue_refund"]
|
|
52
|
+
assert [variables["threadId"] for _, variables in client.calls] == ["thread-1"] * 3
|
|
53
|
+
assert client.calls[0][1]["context"] == {"amount": 12}
|
|
54
|
+
assert client.calls[1][1]["action"] == "issue_refund"
|
|
55
|
+
with pytest.raises(ValueError, match="exactly one"):
|
|
56
|
+
await thread.can(action="issue_refund", goal="refund")
|
|
@@ -3,35 +3,16 @@ import pytest
|
|
|
3
3
|
from threadify.models import (
|
|
4
4
|
DEFAULT_CONNECT_TIMEOUT,
|
|
5
5
|
DEFAULT_MAX_IN_FLIGHT,
|
|
6
|
-
DEFAULT_WS_URL,
|
|
7
6
|
ConnectOptions,
|
|
8
7
|
StepResult,
|
|
9
8
|
StepStatus,
|
|
10
9
|
ValidationSeverity,
|
|
11
|
-
derive_graphql_url,
|
|
12
10
|
first_non_empty,
|
|
13
11
|
now_iso,
|
|
14
12
|
require_non_empty,
|
|
15
13
|
)
|
|
16
14
|
|
|
17
15
|
|
|
18
|
-
class TestDeriveGraphQLURL:
|
|
19
|
-
def test_wss_to_https(self):
|
|
20
|
-
assert (
|
|
21
|
-
derive_graphql_url("wss://api.example.com/threads") == "https://api.example.com/graphql"
|
|
22
|
-
)
|
|
23
|
-
|
|
24
|
-
def test_ws_to_http(self):
|
|
25
|
-
assert derive_graphql_url("ws://localhost:8080/threads") == "http://localhost:8080/graphql"
|
|
26
|
-
|
|
27
|
-
def test_no_replacement_needed(self):
|
|
28
|
-
url = "https://already-http.com/api"
|
|
29
|
-
assert derive_graphql_url(url) == url
|
|
30
|
-
|
|
31
|
-
def test_empty_string(self):
|
|
32
|
-
assert derive_graphql_url("") == ""
|
|
33
|
-
|
|
34
|
-
|
|
35
16
|
class TestRequireNonEmpty:
|
|
36
17
|
def test_valid(self):
|
|
37
18
|
require_non_empty("test", "hello") # Should not raise.
|
|
@@ -78,46 +59,38 @@ class TestConnectOptions:
|
|
|
78
59
|
def test_defaults(self):
|
|
79
60
|
opts = ConnectOptions()
|
|
80
61
|
opts.with_defaults()
|
|
81
|
-
assert opts.ws_url == DEFAULT_WS_URL
|
|
82
62
|
assert opts.max_in_flight == DEFAULT_MAX_IN_FLIGHT
|
|
83
63
|
assert opts.connect_timeout == DEFAULT_CONNECT_TIMEOUT
|
|
84
|
-
assert opts
|
|
64
|
+
assert not hasattr(opts, "ws_url") and not hasattr(opts, "engine_url")
|
|
85
65
|
|
|
86
66
|
def test_preserves_custom(self):
|
|
87
67
|
opts = ConnectOptions(
|
|
88
|
-
ws_url="wss://custom.com/threads",
|
|
89
68
|
max_in_flight=50,
|
|
90
69
|
connect_timeout=30.0,
|
|
91
70
|
)
|
|
92
71
|
opts.with_defaults()
|
|
93
|
-
assert opts.ws_url == "wss://custom.com/threads"
|
|
94
72
|
assert opts.max_in_flight == 50
|
|
95
73
|
assert opts.connect_timeout == 30.0
|
|
96
74
|
|
|
97
75
|
def test_validate_valid(self):
|
|
98
|
-
opts = ConnectOptions(
|
|
76
|
+
opts = ConnectOptions(max_in_flight=1)
|
|
99
77
|
opts.validate() # Should not raise.
|
|
100
78
|
|
|
101
|
-
opts2 = ConnectOptions(
|
|
79
|
+
opts2 = ConnectOptions(max_in_flight=100)
|
|
102
80
|
opts2.validate() # Should not raise.
|
|
103
81
|
|
|
104
|
-
def test_validate_requires_non_empty_ws_url(self):
|
|
105
|
-
opts = ConnectOptions(ws_url="")
|
|
106
|
-
with pytest.raises(ValueError, match="ws_url is required"):
|
|
107
|
-
opts.validate()
|
|
108
|
-
|
|
109
82
|
def test_validate_too_low(self):
|
|
110
|
-
opts = ConnectOptions(
|
|
83
|
+
opts = ConnectOptions(max_in_flight=0)
|
|
111
84
|
with pytest.raises(ValueError, match="max_in_flight"):
|
|
112
85
|
opts.validate()
|
|
113
86
|
|
|
114
87
|
def test_validate_too_high(self):
|
|
115
|
-
opts = ConnectOptions(
|
|
88
|
+
opts = ConnectOptions(max_in_flight=101)
|
|
116
89
|
with pytest.raises(ValueError, match="max_in_flight"):
|
|
117
90
|
opts.validate()
|
|
118
91
|
|
|
119
92
|
def test_validate_negative(self):
|
|
120
|
-
opts = ConnectOptions(
|
|
93
|
+
opts = ConnectOptions(max_in_flight=-1)
|
|
121
94
|
with pytest.raises(ValueError, match="max_in_flight"):
|
|
122
95
|
opts.validate()
|
|
123
96
|
|
|
@@ -4,7 +4,7 @@ from unittest.mock import AsyncMock
|
|
|
4
4
|
|
|
5
5
|
import pytest
|
|
6
6
|
|
|
7
|
-
from threadify import
|
|
7
|
+
from threadify import ThreadifyError, WaitOptions
|
|
8
8
|
from threadify.connection import Connection
|
|
9
9
|
from threadify.models import engine_endpoints, reference_query
|
|
10
10
|
from threadify.thread import ThreadInstance
|
|
@@ -72,9 +72,6 @@ async def cleanup(ws, conn):
|
|
|
72
72
|
)
|
|
73
73
|
def test_engine_url_preserves_prefix(base, expected):
|
|
74
74
|
assert engine_endpoints(base) == expected
|
|
75
|
-
cfg = ConnectOptions(engine_url=base).with_defaults()
|
|
76
|
-
assert (cfg.ws_url, cfg.graphql_url) == expected
|
|
77
|
-
assert cfg.with_defaults().graphql_url == expected[1]
|
|
78
75
|
|
|
79
76
|
|
|
80
77
|
@pytest.mark.parametrize(
|
|
@@ -305,7 +302,7 @@ async def test_http_policy_errors_keep_status_and_code(monkeypatch, status, code
|
|
|
305
302
|
rejection.response = SimpleNamespace(status_code=status)
|
|
306
303
|
monkeypatch.setattr("threadify.client.websockets.connect", AsyncMock(side_effect=rejection))
|
|
307
304
|
with pytest.raises(ThreadifyError) as error:
|
|
308
|
-
await Threadify.connect("
|
|
305
|
+
await Threadify.connect("https://example.com", "fixture-key")
|
|
309
306
|
assert (error.value.status, error.value.code) == (status, code)
|
|
310
307
|
client = GraphQLClient("https://example.com/graphql", "fixture-key")
|
|
311
308
|
await client._client.aclose()
|
|
@@ -42,14 +42,6 @@ class TestThreadStepFluent:
|
|
|
42
42
|
step.add_context(None)
|
|
43
43
|
assert step.context == {}
|
|
44
44
|
|
|
45
|
-
def test_private_context(self):
|
|
46
|
-
thread = _make_thread()
|
|
47
|
-
step = ThreadStep("s", thread, "svc")
|
|
48
|
-
step.add_private_context({"secret": "xyz"})
|
|
49
|
-
ctx = step.context
|
|
50
|
-
assert ctx["secret"] == "xyz"
|
|
51
|
-
assert ctx["private_secret"] == "xyz"
|
|
52
|
-
|
|
53
45
|
|
|
54
46
|
class TestIdempotencyKey:
|
|
55
47
|
def test_manual_key(self):
|
|
@@ -4,6 +4,7 @@ from threadify.client import (
|
|
|
4
4
|
)
|
|
5
5
|
from threadify.connection import Connection
|
|
6
6
|
from threadify.data_retriever import ArchivedStep, ArchivedThread, DataRetriever
|
|
7
|
+
from threadify.decisions import CanDecision, NextDecision, NextPath, ShouldDecision
|
|
7
8
|
from threadify.models import (
|
|
8
9
|
AccessLevel,
|
|
9
10
|
CompleteDataOptions,
|
|
@@ -26,6 +27,10 @@ from threadify.thread import ThreadInstance
|
|
|
26
27
|
from threadify.waiting import PermissionGrant, ThreadifyError, WaitResult
|
|
27
28
|
|
|
28
29
|
__all__ = [
|
|
30
|
+
"CanDecision",
|
|
31
|
+
"ShouldDecision",
|
|
32
|
+
"NextDecision",
|
|
33
|
+
"NextPath",
|
|
29
34
|
"PermissionGrant",
|
|
30
35
|
"ThreadifyError",
|
|
31
36
|
"WaitResult",
|
|
@@ -56,4 +61,4 @@ __all__ = [
|
|
|
56
61
|
"AccessLevel",
|
|
57
62
|
]
|
|
58
63
|
|
|
59
|
-
__version__ = "0.
|
|
64
|
+
__version__ = "0.5.0"
|
|
@@ -4,7 +4,6 @@ import asyncio
|
|
|
4
4
|
import json
|
|
5
5
|
import logging
|
|
6
6
|
from dataclasses import fields
|
|
7
|
-
from typing import Any
|
|
8
7
|
|
|
9
8
|
import websockets
|
|
10
9
|
|
|
@@ -19,6 +18,7 @@ from threadify.models import (
|
|
|
19
18
|
FIELD_STATUS,
|
|
20
19
|
STATUS_SUCCESS,
|
|
21
20
|
ConnectOptions,
|
|
21
|
+
engine_endpoints,
|
|
22
22
|
require_non_empty,
|
|
23
23
|
)
|
|
24
24
|
|
|
@@ -31,10 +31,7 @@ def _copy_connect_options(src: ConnectOptions) -> ConnectOptions:
|
|
|
31
31
|
def _build_connect_options(
|
|
32
32
|
*,
|
|
33
33
|
base: ConnectOptions | None,
|
|
34
|
-
engine_url: str | None = None,
|
|
35
34
|
service_name: str | None,
|
|
36
|
-
ws_url: str | None,
|
|
37
|
-
graphql_url: str | None,
|
|
38
35
|
debug: bool | None,
|
|
39
36
|
max_in_flight: int | None,
|
|
40
37
|
connect_timeout: float | None,
|
|
@@ -42,16 +39,8 @@ def _build_connect_options(
|
|
|
42
39
|
) -> ConnectOptions:
|
|
43
40
|
cfg = _copy_connect_options(base) if base else ConnectOptions()
|
|
44
41
|
|
|
45
|
-
if engine_url is not None:
|
|
46
|
-
if ws_url is not None or graphql_url is not None:
|
|
47
|
-
raise ValueError("Use engine_url without separate transport URLs")
|
|
48
|
-
cfg.engine_url = engine_url
|
|
49
42
|
if service_name is not None:
|
|
50
43
|
cfg.service_name = service_name
|
|
51
|
-
if ws_url is not None:
|
|
52
|
-
cfg.ws_url = ws_url
|
|
53
|
-
if graphql_url is not None:
|
|
54
|
-
cfg.graphql_url = graphql_url
|
|
55
44
|
if debug is not None:
|
|
56
45
|
cfg.debug = debug
|
|
57
46
|
if max_in_flight is not None:
|
|
@@ -75,39 +64,27 @@ class Threadify:
|
|
|
75
64
|
|
|
76
65
|
@staticmethod
|
|
77
66
|
async def connect(
|
|
67
|
+
engine_url: str,
|
|
78
68
|
api_key: str,
|
|
79
|
-
|
|
69
|
+
*,
|
|
80
70
|
service_name: str | None = None,
|
|
81
|
-
engine_url: str | None = None,
|
|
82
|
-
ws_url: str | None = None,
|
|
83
|
-
graphql_url: str | None = None,
|
|
84
71
|
debug: bool | None = None,
|
|
85
72
|
max_in_flight: int | None = None,
|
|
86
73
|
connect_timeout: float | None = None,
|
|
87
74
|
logger: logging.Logger | None = None,
|
|
88
75
|
options: ConnectOptions | None = None,
|
|
89
76
|
) -> Connection:
|
|
90
|
-
|
|
77
|
+
"""Connect to your Threadify Engine.
|
|
91
78
|
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
continue
|
|
98
|
-
if isinstance(arg, ConnectOptions) and legacy_config is None:
|
|
99
|
-
legacy_config = arg
|
|
100
|
-
continue
|
|
101
|
-
raise TypeError(
|
|
102
|
-
"invalid connect argument; expected service_name (str) or ConnectOptions"
|
|
103
|
-
)
|
|
79
|
+
``engine_url`` is your Engine's base URL, e.g. ``https://threadify.example.com``;
|
|
80
|
+
the SDK derives its WebSocket and GraphQL paths, including any proxy prefix.
|
|
81
|
+
"""
|
|
82
|
+
ws_url, graphql_url = engine_endpoints(engine_url)
|
|
83
|
+
require_non_empty("api_key", api_key)
|
|
104
84
|
|
|
105
85
|
cfg = _build_connect_options(
|
|
106
|
-
base=options
|
|
107
|
-
service_name=service_name
|
|
108
|
-
engine_url=engine_url,
|
|
109
|
-
ws_url=ws_url,
|
|
110
|
-
graphql_url=graphql_url,
|
|
86
|
+
base=options,
|
|
87
|
+
service_name=service_name,
|
|
111
88
|
debug=debug,
|
|
112
89
|
max_in_flight=max_in_flight,
|
|
113
90
|
connect_timeout=connect_timeout,
|
|
@@ -116,7 +93,7 @@ class Threadify:
|
|
|
116
93
|
|
|
117
94
|
try:
|
|
118
95
|
ws = await asyncio.wait_for(
|
|
119
|
-
websockets.connect(
|
|
96
|
+
websockets.connect(ws_url),
|
|
120
97
|
timeout=cfg.connect_timeout,
|
|
121
98
|
)
|
|
122
99
|
except Exception as exc:
|
|
@@ -148,7 +125,7 @@ class Threadify:
|
|
|
148
125
|
ws=ws,
|
|
149
126
|
api_key=api_key,
|
|
150
127
|
service_name=cfg.service_name,
|
|
151
|
-
graphql_url=
|
|
128
|
+
graphql_url=graphql_url,
|
|
152
129
|
debug=cfg.debug,
|
|
153
130
|
max_in_flight=cfg.max_in_flight,
|
|
154
131
|
logger=cfg.logger,
|
|
@@ -158,43 +135,27 @@ class Threadify:
|
|
|
158
135
|
|
|
159
136
|
@staticmethod
|
|
160
137
|
def create(
|
|
138
|
+
engine_url: str,
|
|
161
139
|
api_key: str,
|
|
162
|
-
|
|
140
|
+
*,
|
|
163
141
|
service_name: str | None = None,
|
|
164
|
-
engine_url: str | None = None,
|
|
165
|
-
ws_url: str | None = None,
|
|
166
|
-
graphql_url: str | None = None,
|
|
167
142
|
debug: bool | None = None,
|
|
168
143
|
max_in_flight: int | None = None,
|
|
169
144
|
connect_timeout: float | None = None,
|
|
170
145
|
logger: logging.Logger | None = None,
|
|
171
146
|
options: ConnectOptions | None = None,
|
|
172
147
|
) -> ThreadifyFactory:
|
|
173
|
-
|
|
174
|
-
legacy_config: ConnectOptions | None = None
|
|
175
|
-
for arg in args:
|
|
176
|
-
if isinstance(arg, str) and legacy_service_name is None:
|
|
177
|
-
legacy_service_name = arg
|
|
178
|
-
continue
|
|
179
|
-
if isinstance(arg, ConnectOptions) and legacy_config is None:
|
|
180
|
-
legacy_config = arg
|
|
181
|
-
continue
|
|
182
|
-
raise TypeError(
|
|
183
|
-
"invalid create argument; expected service_name (str) or ConnectOptions"
|
|
184
|
-
)
|
|
185
|
-
|
|
148
|
+
engine_endpoints(engine_url) # fail early on a missing or invalid URL
|
|
186
149
|
cfg = _build_connect_options(
|
|
187
|
-
base=options
|
|
188
|
-
service_name=service_name
|
|
189
|
-
engine_url=engine_url,
|
|
190
|
-
ws_url=ws_url,
|
|
191
|
-
graphql_url=graphql_url,
|
|
150
|
+
base=options,
|
|
151
|
+
service_name=service_name,
|
|
192
152
|
debug=debug,
|
|
193
153
|
max_in_flight=max_in_flight,
|
|
194
154
|
connect_timeout=connect_timeout,
|
|
195
155
|
logger=logger,
|
|
196
156
|
)
|
|
197
157
|
return ThreadifyFactory(
|
|
158
|
+
engine_url=engine_url,
|
|
198
159
|
api_key=api_key,
|
|
199
160
|
options=cfg,
|
|
200
161
|
)
|
|
@@ -203,11 +164,13 @@ class Threadify:
|
|
|
203
164
|
class ThreadifyFactory:
|
|
204
165
|
def __init__(
|
|
205
166
|
self,
|
|
167
|
+
engine_url: str,
|
|
206
168
|
api_key: str,
|
|
207
169
|
options: ConnectOptions,
|
|
208
170
|
):
|
|
171
|
+
self._engine_url = engine_url
|
|
209
172
|
self._api_key = api_key
|
|
210
173
|
self._options = _copy_connect_options(options)
|
|
211
174
|
|
|
212
175
|
async def connect(self) -> Connection:
|
|
213
|
-
return await Threadify.connect(self._api_key, options=self._options)
|
|
176
|
+
return await Threadify.connect(self._engine_url, self._api_key, options=self._options)
|
|
@@ -508,6 +508,7 @@ class Connection:
|
|
|
508
508
|
if actual_handler is None:
|
|
509
509
|
raise ValueError("handler cannot be None")
|
|
510
510
|
|
|
511
|
+
event = _normalize_event(event)
|
|
511
512
|
source, event_type = _parse_event(event)
|
|
512
513
|
event_types = _build_event_types(source, event_type)
|
|
513
514
|
asyncio.ensure_future(self._send_subscription(step_name, event_types))
|
|
@@ -524,7 +525,7 @@ class Connection:
|
|
|
524
525
|
step_name: Step name (default: global / thread-level).
|
|
525
526
|
"""
|
|
526
527
|
target_step = step_name or "global"
|
|
527
|
-
key = f"{event}:{target_step}"
|
|
528
|
+
key = f"{_normalize_event(event)}:{target_step}"
|
|
528
529
|
self._notification_handlers.pop(key, None)
|
|
529
530
|
|
|
530
531
|
has_handlers = any(k.endswith(f":{target_step}") for k in self._notification_handlers)
|
|
@@ -706,6 +707,11 @@ class Connection:
|
|
|
706
707
|
self._threads.pop(thread_id, None)
|
|
707
708
|
|
|
708
709
|
|
|
710
|
+
def _normalize_event(event: str) -> str:
|
|
711
|
+
"""Rulebooks name thread events with a "$" ("$thread.completed"); accept that spelling too."""
|
|
712
|
+
return event[1:] if event.startswith("$thread.") else event
|
|
713
|
+
|
|
714
|
+
|
|
709
715
|
def _parse_event(event: str) -> tuple[str, str]:
|
|
710
716
|
parts = event.split(".", 1)
|
|
711
717
|
source = parts[0] if parts[0] else "*"
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Typed, read-only Contract decisions for an active Thread."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
CAN_QUERY = """
|
|
9
|
+
query Can($threadId: ID!, $action: String, $goal: String, $context: JSON) {
|
|
10
|
+
can(threadId: $threadId, action: $action, goal: $goal, context: $context) {
|
|
11
|
+
threadId stepName allowed status matchedBy requiredSteps
|
|
12
|
+
satisfiedSteps missingSteps previousStep reason
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
"""
|
|
16
|
+
SHOULD_QUERY = """
|
|
17
|
+
query Should($threadId: ID!, $action: String, $goal: String) {
|
|
18
|
+
should(threadId: $threadId, action: $action, goal: $goal) {
|
|
19
|
+
threadId stepName eligible recommendation reason
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
"""
|
|
23
|
+
NEXT_QUERY = """
|
|
24
|
+
query Next($threadId: ID!) {
|
|
25
|
+
next(threadId: $threadId) { threadId paths { actions status reason } }
|
|
26
|
+
}
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def candidate_variables(action: str | None, goal: str | None) -> dict[str, str | None]:
|
|
31
|
+
if (action is not None and not isinstance(action, str)) or (
|
|
32
|
+
goal is not None and not isinstance(goal, str)
|
|
33
|
+
):
|
|
34
|
+
raise TypeError("action and goal must be strings")
|
|
35
|
+
action = action.strip() if action else None
|
|
36
|
+
goal = goal.strip() if goal else None
|
|
37
|
+
if bool(action) == bool(goal):
|
|
38
|
+
raise ValueError("provide exactly one non-empty action or goal")
|
|
39
|
+
if goal and len(goal) > 4096:
|
|
40
|
+
raise ValueError("goal must be at most 4096 characters")
|
|
41
|
+
return {"action": action, "goal": goal}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class CanDecision:
|
|
46
|
+
thread_id: str
|
|
47
|
+
step_name: str
|
|
48
|
+
allowed: bool
|
|
49
|
+
status: str
|
|
50
|
+
matched_by: str
|
|
51
|
+
required_steps: list[str]
|
|
52
|
+
satisfied_steps: list[str]
|
|
53
|
+
missing_steps: list[str]
|
|
54
|
+
previous_step: str | None
|
|
55
|
+
reason: str
|
|
56
|
+
|
|
57
|
+
@classmethod
|
|
58
|
+
def from_payload(cls, data: dict[str, Any]) -> CanDecision:
|
|
59
|
+
return cls(
|
|
60
|
+
data["threadId"], data["stepName"], data["allowed"], data["status"],
|
|
61
|
+
data["matchedBy"], data["requiredSteps"], data["satisfiedSteps"],
|
|
62
|
+
data["missingSteps"], data.get("previousStep"), data["reason"],
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass(frozen=True)
|
|
67
|
+
class ShouldDecision:
|
|
68
|
+
thread_id: str
|
|
69
|
+
step_name: str
|
|
70
|
+
eligible: bool
|
|
71
|
+
recommendation: str
|
|
72
|
+
reason: str
|
|
73
|
+
|
|
74
|
+
@classmethod
|
|
75
|
+
def from_payload(cls, data: dict[str, Any]) -> ShouldDecision:
|
|
76
|
+
return cls(
|
|
77
|
+
data["threadId"], data["stepName"], data["eligible"],
|
|
78
|
+
data["recommendation"], data["reason"],
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass(frozen=True)
|
|
83
|
+
class NextPath:
|
|
84
|
+
actions: list[str]
|
|
85
|
+
status: str
|
|
86
|
+
reason: str
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@dataclass(frozen=True)
|
|
90
|
+
class NextDecision:
|
|
91
|
+
thread_id: str
|
|
92
|
+
paths: list[NextPath]
|
|
93
|
+
|
|
94
|
+
@classmethod
|
|
95
|
+
def from_payload(cls, data: dict[str, Any]) -> NextDecision:
|
|
96
|
+
return cls(
|
|
97
|
+
data["threadId"],
|
|
98
|
+
[NextPath(path["actions"], path["status"], path["reason"]) for path in data["paths"]],
|
|
99
|
+
)
|
|
@@ -7,7 +7,6 @@ from typing import Any, TypedDict
|
|
|
7
7
|
# --- Constants ---
|
|
8
8
|
|
|
9
9
|
DEFAULT_CONNECT_TIMEOUT = 10.0 # seconds
|
|
10
|
-
DEFAULT_WS_URL = "wss://eng.threadify.dev/threads"
|
|
11
10
|
DEFAULT_REQUEST_TIMEOUT = 10.0
|
|
12
11
|
DEFAULT_WAIT_TIMEOUT = 5.0
|
|
13
12
|
DEFAULT_MAX_IN_FLIGHT = 10
|
|
@@ -119,27 +118,16 @@ class AccessLevel(str, Enum):
|
|
|
119
118
|
|
|
120
119
|
@dataclass
|
|
121
120
|
class ConnectOptions:
|
|
122
|
-
"""
|
|
121
|
+
"""Connection settings. The Engine URL is not one of them: it is the first
|
|
122
|
+
argument to ``Threadify.connect()``."""
|
|
123
123
|
|
|
124
124
|
service_name: str = ""
|
|
125
|
-
engine_url: str = ""
|
|
126
|
-
ws_url: str = ""
|
|
127
|
-
graphql_url: str = ""
|
|
128
125
|
debug: bool = False
|
|
129
126
|
max_in_flight: int = DEFAULT_MAX_IN_FLIGHT
|
|
130
127
|
connect_timeout: float = DEFAULT_CONNECT_TIMEOUT
|
|
131
128
|
logger: logging.Logger | None = None
|
|
132
129
|
|
|
133
130
|
def with_defaults(self) -> "ConnectOptions":
|
|
134
|
-
if self.engine_url:
|
|
135
|
-
ws, gql = engine_endpoints(self.engine_url)
|
|
136
|
-
if self.ws_url and self.ws_url != ws or self.graphql_url and self.graphql_url != gql:
|
|
137
|
-
raise ValueError("Use engine_url without separate transport URLs")
|
|
138
|
-
self.ws_url, self.graphql_url = ws, gql
|
|
139
|
-
if not self.ws_url:
|
|
140
|
-
self.ws_url = DEFAULT_WS_URL
|
|
141
|
-
if not self.graphql_url and self.ws_url:
|
|
142
|
-
self.graphql_url = derive_graphql_url(self.ws_url)
|
|
143
131
|
if self.max_in_flight == 0:
|
|
144
132
|
self.max_in_flight = DEFAULT_MAX_IN_FLIGHT
|
|
145
133
|
if self.connect_timeout == 0:
|
|
@@ -147,8 +135,6 @@ class ConnectOptions:
|
|
|
147
135
|
return self
|
|
148
136
|
|
|
149
137
|
def validate(self) -> None:
|
|
150
|
-
if not self.ws_url or not self.ws_url.strip():
|
|
151
|
-
raise ValueError("ws_url is required")
|
|
152
138
|
if not (MIN_MAX_IN_FLIGHT <= self.max_in_flight <= MAX_MAX_IN_FLIGHT):
|
|
153
139
|
raise ValueError(
|
|
154
140
|
f"max_in_flight must be between {MIN_MAX_IN_FLIGHT} and {MAX_MAX_IN_FLIGHT}"
|
|
@@ -279,13 +265,6 @@ class HistoryQueryOptions:
|
|
|
279
265
|
actor: str = ""
|
|
280
266
|
|
|
281
267
|
|
|
282
|
-
def derive_graphql_url(ws_url: str) -> str:
|
|
283
|
-
"""Convert a WebSocket URL to its corresponding GraphQL URL."""
|
|
284
|
-
out = ws_url.replace("ws://", "http://", 1)
|
|
285
|
-
out = out.replace("wss://", "https://", 1)
|
|
286
|
-
return out.replace("/threads", "/graphql", 1)
|
|
287
|
-
|
|
288
|
-
|
|
289
268
|
def require_non_empty(name: str, value: str) -> None:
|
|
290
269
|
"""Raise ValueError if value is empty or whitespace."""
|
|
291
270
|
if not value or not value.strip():
|
|
@@ -306,10 +285,13 @@ def now_iso() -> str:
|
|
|
306
285
|
|
|
307
286
|
|
|
308
287
|
def engine_endpoints(base: str) -> tuple[str, str]:
|
|
288
|
+
"""Return the WebSocket and GraphQL URLs for an Engine base URL."""
|
|
309
289
|
from urllib.parse import urlsplit, urlunsplit
|
|
310
290
|
|
|
311
291
|
if not isinstance(base, str) or not base.strip():
|
|
312
|
-
raise ValueError(
|
|
292
|
+
raise ValueError(
|
|
293
|
+
"engine_url is required: pass your Threadify Engine URL, e.g. https://threadify.example.com"
|
|
294
|
+
)
|
|
313
295
|
base = base.strip()
|
|
314
296
|
parsed = urlsplit(base)
|
|
315
297
|
if (
|
|
@@ -52,7 +52,7 @@ class ThreadifySpanExporter(_SpanExporterBase):
|
|
|
52
52
|
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
|
53
53
|
from threadify import Threadify
|
|
54
54
|
|
|
55
|
-
conn = await Threadify.connect("api-key", service_name="my-service"
|
|
55
|
+
conn = await Threadify.connect("https://threadify.example.com", "api-key", service_name="my-service")
|
|
56
56
|
thread = await conn.thread("order:ORD-123", {"label": "Order 123"})
|
|
57
57
|
|
|
58
58
|
exporter = thread.create_span_exporter(options={"refs": ["orderId"]})
|
|
@@ -94,17 +94,6 @@ class ThreadStep:
|
|
|
94
94
|
self._context[k] = str(v)
|
|
95
95
|
return self
|
|
96
96
|
|
|
97
|
-
def add_private_context(self, data: dict[str, Any] | None) -> ThreadStep:
|
|
98
|
-
"""Add private context data (prefixed with 'private_')."""
|
|
99
|
-
if self._error is not None:
|
|
100
|
-
return self
|
|
101
|
-
if data:
|
|
102
|
-
for k, v in data.items():
|
|
103
|
-
s = str(v)
|
|
104
|
-
self._context[k] = s
|
|
105
|
-
self._context[f"private_{k}"] = s
|
|
106
|
-
return self
|
|
107
|
-
|
|
108
97
|
def sub_step(
|
|
109
98
|
self,
|
|
110
99
|
name: str,
|
|
@@ -139,6 +139,41 @@ class ThreadInstance:
|
|
|
139
139
|
|
|
140
140
|
return await wait_for_permission(self, step_name, options)
|
|
141
141
|
|
|
142
|
+
async def can(
|
|
143
|
+
self,
|
|
144
|
+
*,
|
|
145
|
+
action: str | None = None,
|
|
146
|
+
goal: str | None = None,
|
|
147
|
+
context: dict[str, str | int | float | bool] | None = None,
|
|
148
|
+
):
|
|
149
|
+
"""Check Contract eligibility without claiming execution."""
|
|
150
|
+
from threadify.decisions import CAN_QUERY, CanDecision, candidate_variables
|
|
151
|
+
|
|
152
|
+
variables = candidate_variables(action, goal)
|
|
153
|
+
if context is not None and not isinstance(context, dict):
|
|
154
|
+
raise TypeError("context must be a JSON object")
|
|
155
|
+
variables.update({"threadId": self.thread_id, "context": context})
|
|
156
|
+
data = await self._conn._get_data_retriever()._client.query(CAN_QUERY, variables)
|
|
157
|
+
return CanDecision.from_payload(data["can"])
|
|
158
|
+
|
|
159
|
+
async def should(self, *, action: str | None = None, goal: str | None = None):
|
|
160
|
+
"""Get classifier advice about a candidate; this is not permission."""
|
|
161
|
+
from threadify.decisions import SHOULD_QUERY, ShouldDecision, candidate_variables
|
|
162
|
+
|
|
163
|
+
variables = candidate_variables(action, goal)
|
|
164
|
+
variables["threadId"] = self.thread_id
|
|
165
|
+
data = await self._conn._get_data_retriever()._client.query(SHOULD_QUERY, variables)
|
|
166
|
+
return ShouldDecision.from_payload(data["should"])
|
|
167
|
+
|
|
168
|
+
async def next(self):
|
|
169
|
+
"""List bounded Contract-valid paths from the current Thread state."""
|
|
170
|
+
from threadify.decisions import NEXT_QUERY, NextDecision
|
|
171
|
+
|
|
172
|
+
data = await self._conn._get_data_retriever()._client.query(
|
|
173
|
+
NEXT_QUERY, {"threadId": self.thread_id}
|
|
174
|
+
)
|
|
175
|
+
return NextDecision.from_payload(data["next"])
|
|
176
|
+
|
|
142
177
|
async def wait_for_validation(
|
|
143
178
|
self, step_name: str, step_id: str, options: WaitOptions | None = None
|
|
144
179
|
):
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: threadify-sdk
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.5.0
|
|
4
4
|
Summary: Python SDK for Threadify — Service-delivery intelligence. Track every customer request from start to finish across every system, team, and partner. Visit: https://threadify.dev
|
|
5
5
|
Author-email: Threadify Team <team@threadify.dev>
|
|
6
6
|
License: MIT
|
|
@@ -58,6 +58,7 @@ from threadify import Threadify
|
|
|
58
58
|
async def main():
|
|
59
59
|
try:
|
|
60
60
|
conn = await Threadify.connect(
|
|
61
|
+
"https://threadify.example.com", # your Engine URL
|
|
61
62
|
"your-api-key",
|
|
62
63
|
service_name="orders-service",
|
|
63
64
|
)
|
|
@@ -92,7 +93,7 @@ if __name__ == "__main__":
|
|
|
92
93
|
asyncio.run(main())
|
|
93
94
|
```
|
|
94
95
|
|
|
95
|
-
|
|
96
|
+
The Engine URL is the first argument and is required: Threadify is self-hosted, so there is no default Engine. Use the URL from **Settings → Engine**. WebSocket and GraphQL paths are derived from it, including reverse-proxy prefixes.
|
|
96
97
|
|
|
97
98
|
## Entity profiles
|
|
98
99
|
|
|
@@ -107,10 +108,10 @@ description: Customer workflows
|
|
|
107
108
|
```
|
|
108
109
|
|
|
109
110
|
```sh
|
|
110
|
-
threadify
|
|
111
|
-
threadify
|
|
112
|
-
threadify
|
|
113
|
-
threadify
|
|
111
|
+
threadify config set api-url https://threadify.example.com
|
|
112
|
+
threadify login
|
|
113
|
+
threadify profile-types create --file customers.yaml
|
|
114
|
+
threadify profiles create --type-id TYPE_ID --ref-value CUST-001 --name 'Jane Doe'
|
|
114
115
|
```
|
|
115
116
|
|
|
116
117
|
Use the returned profile type ID for `TYPE_ID`. Include `customer_id` in your
|
|
@@ -122,12 +123,10 @@ dashboard to explore that history and configure metrics.
|
|
|
122
123
|
|
|
123
124
|
### Connect options
|
|
124
125
|
|
|
125
|
-
|
|
126
|
+
`Threadify.connect(engine_url, api_key, ...)` takes the Engine URL (one HTTP(S)
|
|
127
|
+
base, including any proxy prefix) and API key first, then these keyword arguments:
|
|
126
128
|
|
|
127
129
|
- `service_name`
|
|
128
|
-
- `engine_url` (one HTTP(S) deployment base, including any proxy prefix)
|
|
129
|
-
- `ws_url` (optional, defaults to production)
|
|
130
|
-
- `graphql_url`
|
|
131
130
|
- `debug`
|
|
132
131
|
- `max_in_flight`
|
|
133
132
|
- `connect_timeout`
|
|
@@ -138,6 +137,7 @@ Example:
|
|
|
138
137
|
from threadify import Threadify
|
|
139
138
|
|
|
140
139
|
conn = await Threadify.connect(
|
|
140
|
+
"https://threadify.example.com",
|
|
141
141
|
"your-api-key",
|
|
142
142
|
service_name="inventory-service",
|
|
143
143
|
debug=True,
|
|
@@ -261,7 +261,7 @@ from opentelemetry.sdk.trace import TracerProvider
|
|
|
261
261
|
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
|
262
262
|
from threadify import Threadify
|
|
263
263
|
|
|
264
|
-
conn = await Threadify.connect("api-key", service_name="checkout-service")
|
|
264
|
+
conn = await Threadify.connect("https://threadify.example.com", "api-key", service_name="checkout-service")
|
|
265
265
|
|
|
266
266
|
# Create exporter
|
|
267
267
|
exporter = conn.create_span_exporter(options={"refs": ["order.id", "customer.id"]})
|
|
@@ -316,9 +316,14 @@ python3 -m pytest
|
|
|
316
316
|
```python
|
|
317
317
|
from threadify import Threadify, WaitOptions, ThreadifyError
|
|
318
318
|
|
|
319
|
-
connection = await Threadify.connect(
|
|
319
|
+
connection = await Threadify.connect("https://threadify.example.com", api_key, service_name="payments")
|
|
320
320
|
threads = await connection.get_threads_by_ref({"order_id": "ORD-1001"}, status="active", limit=25)
|
|
321
321
|
thread = await connection.thread("order:ORD-1001")
|
|
322
|
+
paths = await thread.next() # Unranked possible Contract paths.
|
|
323
|
+
eligibility = await thread.can(action="charge")
|
|
324
|
+
if not eligibility.allowed:
|
|
325
|
+
raise RuntimeError(eligibility.reason)
|
|
326
|
+
advice = await thread.should(action="charge") # Optional; never grants execution.
|
|
322
327
|
grant = await thread.wait_for("charge", WaitOptions(timeout=15))
|
|
323
328
|
# Execute the permitted business operation here.
|
|
324
329
|
result = await thread.step("charge").add_context({"amount": 42}).success("charged", wait_for=True, timeout=15)
|
|
@@ -331,6 +336,9 @@ await thread.wait_for_validation("charge", result.step_id)
|
|
|
331
336
|
ID into the subsequent step report and its default idempotency key. It sends one
|
|
332
337
|
request and waits for a final correlated response. The old notification-only
|
|
333
338
|
helper is named `wait_for_notification()`; it does not authorize execution.
|
|
339
|
+
`can()`, `should()`, and `next()` are read-only GraphQL decisions. `next()`
|
|
340
|
+
returns multiple paths without ranking them; `wait_for()` makes the atomic
|
|
341
|
+
claim before a guarded side effect.
|
|
334
342
|
|
|
335
343
|
Timeouts are in **seconds**, at most 300. Cancelling the Python task or reaching
|
|
336
344
|
its timeout cancels the remote wait. Before reporting a granted operation, use
|
|
@@ -6,6 +6,7 @@ pyproject.toml
|
|
|
6
6
|
tests/test_client.py
|
|
7
7
|
tests/test_connection.py
|
|
8
8
|
tests/test_data_retriever.py
|
|
9
|
+
tests/test_decisions.py
|
|
9
10
|
tests/test_models.py
|
|
10
11
|
tests/test_notification.py
|
|
11
12
|
tests/test_otel_correlation.py
|
|
@@ -17,6 +18,7 @@ threadify/__init__.py
|
|
|
17
18
|
threadify/client.py
|
|
18
19
|
threadify/connection.py
|
|
19
20
|
threadify/data_retriever.py
|
|
21
|
+
threadify/decisions.py
|
|
20
22
|
threadify/models.py
|
|
21
23
|
threadify/notification.py
|
|
22
24
|
threadify/otel_exporter.py
|
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
import json
|
|
2
|
-
from unittest.mock import AsyncMock
|
|
3
|
-
|
|
4
|
-
import pytest
|
|
5
|
-
|
|
6
|
-
from threadify.client import Threadify
|
|
7
|
-
from threadify.models import ConnectOptions
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
class TestThreadifyConnect:
|
|
11
|
-
@pytest.mark.asyncio
|
|
12
|
-
async def test_connect_uses_default_ws_url_when_not_provided(self, monkeypatch):
|
|
13
|
-
ws = AsyncMock()
|
|
14
|
-
ws.send = AsyncMock()
|
|
15
|
-
ws.recv = AsyncMock(return_value=json.dumps({"action": "connect", "status": "success"}))
|
|
16
|
-
ws.close = AsyncMock()
|
|
17
|
-
|
|
18
|
-
ws_connect = AsyncMock(return_value=ws)
|
|
19
|
-
monkeypatch.setattr("threadify.client.websockets.connect", ws_connect)
|
|
20
|
-
|
|
21
|
-
conn = await Threadify.connect("test-api-key", "test-service")
|
|
22
|
-
|
|
23
|
-
ws_connect.assert_awaited_once_with("wss://eng.threadify.dev/threads")
|
|
24
|
-
sent_msg = json.loads(ws.send.call_args.args[0])
|
|
25
|
-
assert sent_msg["serviceName"] == "test-service"
|
|
26
|
-
assert conn.is_connected is True
|
|
27
|
-
|
|
28
|
-
@pytest.mark.asyncio
|
|
29
|
-
async def test_connect_with_explicit_ws_url(self, monkeypatch):
|
|
30
|
-
ws = AsyncMock()
|
|
31
|
-
ws.send = AsyncMock()
|
|
32
|
-
ws.recv = AsyncMock(return_value=json.dumps({"action": "connect", "status": "success"}))
|
|
33
|
-
ws.close = AsyncMock()
|
|
34
|
-
|
|
35
|
-
ws_connect = AsyncMock(return_value=ws)
|
|
36
|
-
monkeypatch.setattr("threadify.client.websockets.connect", ws_connect)
|
|
37
|
-
|
|
38
|
-
conn = await Threadify.connect(
|
|
39
|
-
"test-api-key",
|
|
40
|
-
service_name="test-service",
|
|
41
|
-
ws_url="wss://example.com/threads",
|
|
42
|
-
)
|
|
43
|
-
|
|
44
|
-
ws_connect.assert_awaited_once_with("wss://example.com/threads")
|
|
45
|
-
sent = ws.send.call_args.args[0]
|
|
46
|
-
sent_msg = json.loads(sent)
|
|
47
|
-
assert sent_msg["action"] == "connect"
|
|
48
|
-
assert sent_msg["apiKey"] == "test-api-key"
|
|
49
|
-
assert sent_msg["serviceName"] == "test-service"
|
|
50
|
-
assert conn.is_connected is True
|
|
51
|
-
|
|
52
|
-
@pytest.mark.asyncio
|
|
53
|
-
async def test_connect_legacy_signature_still_supported(self, monkeypatch):
|
|
54
|
-
ws = AsyncMock()
|
|
55
|
-
ws.send = AsyncMock()
|
|
56
|
-
ws.recv = AsyncMock(return_value=json.dumps({"action": "connect", "status": "success"}))
|
|
57
|
-
ws.close = AsyncMock()
|
|
58
|
-
|
|
59
|
-
ws_connect = AsyncMock(return_value=ws)
|
|
60
|
-
monkeypatch.setattr("threadify.client.websockets.connect", ws_connect)
|
|
61
|
-
|
|
62
|
-
conn = await Threadify.connect(
|
|
63
|
-
"test-api-key",
|
|
64
|
-
"legacy-service",
|
|
65
|
-
ConnectOptions(ws_url="wss://example.com/threads"),
|
|
66
|
-
)
|
|
67
|
-
|
|
68
|
-
sent_msg = json.loads(ws.send.call_args.args[0])
|
|
69
|
-
assert sent_msg["serviceName"] == "legacy-service"
|
|
70
|
-
assert conn.is_connected is True
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
class TestThreadifyFactory:
|
|
74
|
-
def test_create_uses_default_ws_url(self):
|
|
75
|
-
factory = Threadify.create("test-api-key")
|
|
76
|
-
assert factory._options.ws_url == "wss://eng.threadify.dev/threads"
|
|
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
|