threadify-sdk 0.3.1__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.
Files changed (38) hide show
  1. threadify_sdk-0.5.0/CHANGELOG.md +64 -0
  2. {threadify_sdk-0.3.1/threadify_sdk.egg-info → threadify_sdk-0.5.0}/PKG-INFO +98 -69
  3. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/README.md +97 -67
  4. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/pyproject.toml +1 -2
  5. threadify_sdk-0.5.0/tests/test_client.py +63 -0
  6. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/tests/test_connection.py +24 -1
  7. threadify_sdk-0.5.0/tests/test_decisions.py +56 -0
  8. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/tests/test_models.py +6 -33
  9. threadify_sdk-0.5.0/tests/test_otel_correlation.py +273 -0
  10. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/tests/test_parity.py +3 -6
  11. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/tests/test_step.py +0 -8
  12. threadify_sdk-0.5.0/tests/test_thread_key.py +200 -0
  13. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/threadify/__init__.py +8 -5
  14. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/threadify/client.py +22 -69
  15. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/threadify/connection.py +82 -4
  16. threadify_sdk-0.5.0/threadify/decisions.py +99 -0
  17. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/threadify/models.py +19 -25
  18. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/threadify/otel_exporter.py +204 -47
  19. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/threadify/step.py +0 -11
  20. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/threadify/thread.py +40 -1
  21. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0/threadify_sdk.egg-info}/PKG-INFO +98 -69
  22. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/threadify_sdk.egg-info/SOURCES.txt +4 -2
  23. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/threadify_sdk.egg-info/requires.txt +0 -1
  24. threadify_sdk-0.3.1/CHANGELOG.md +0 -13
  25. threadify_sdk-0.3.1/tests/test_client.py +0 -76
  26. threadify_sdk-0.3.1/tests/test_management.py +0 -115
  27. threadify_sdk-0.3.1/threadify/management.py +0 -134
  28. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/LICENSE +0 -0
  29. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/MANIFEST.in +0 -0
  30. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/setup.cfg +0 -0
  31. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/tests/test_data_retriever.py +0 -0
  32. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/tests/test_notification.py +0 -0
  33. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/tests/test_thread.py +0 -0
  34. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/threadify/data_retriever.py +0 -0
  35. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/threadify/notification.py +0 -0
  36. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/threadify/waiting.py +0 -0
  37. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/threadify_sdk.egg-info/dependency_links.txt +0 -0
  38. {threadify_sdk-0.3.1 → threadify_sdk-0.5.0}/threadify_sdk.egg-info/top_level.txt +0 -0
@@ -0,0 +1,64 @@
1
+ # Changelog
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
+
33
+ ## [0.4.0] - 2026-09-23
34
+
35
+ ### Breaking changes
36
+
37
+ - Remove `Threadify.entity_profiles`, `EntityProfileManager`, `ManagementAPIError`
38
+ and `profile_slug`. Create profile types and named profiles with `threadify-cli`;
39
+ configure metrics in the Engine UI. Tracing and reference-based profile
40
+ generation are unchanged. Remove the unused PyYAML dependency.
41
+
42
+ ### Added
43
+
44
+ - Add `connection.thread(thread_key, label=, contract=, refs=, tags=)` to
45
+ atomically create or resume a thread using a durable application identifier,
46
+ with a new `ThreadOptions` type for the create/resume options.
47
+
48
+ ### Changed
49
+
50
+ - Use `threadify.thread_key` throughout the OpenTelemetry exporter and OTLP
51
+ ingestion for trace correlation, replacing the previous external-reference
52
+ correlation attribute.
53
+
54
+ ## [0.2.0](https://github.com/creativeJoe007/ThreadifyEngine/compare/threadify-sdk-python-v0.1.0...threadify-sdk-python-v0.2.0) (2026-02-19)
55
+
56
+
57
+ ### Features
58
+
59
+ * Add GitHub Actions CI workflows for Go and Python SDKs and remove unnecessary docstrings from Python test files. ([2a48d71](https://github.com/creativeJoe007/ThreadifyEngine/commit/2a48d71641ca2101b600746e234041aa09951ac8))
60
+ * Configure automated releases for Go and Python SDKs, update Go … ([ac7c46d](https://github.com/creativeJoe007/ThreadifyEngine/commit/ac7c46d658c2bc3b91ceff5d629851d89825d3b9))
61
+ * Configure automated releases for Go and Python SDKs, update Go module import path, and add versioning. ([6dbcf36](https://github.com/creativeJoe007/ThreadifyEngine/commit/6dbcf360eeeb0bf7edeab9db9a26c84bdff3da18))
62
+ * improve Go and Python SDK step method chaining by propagating errors internally rather than returning them directly. ([fa3199b](https://github.com/creativeJoe007/ThreadifyEngine/commit/fa3199b419c9415681126a3c17ded69cd9a69ba0))
63
+ * Introduce basic usage and notification examples for Python and Go SDKs, alongside new thread tests and CI/CD workflow updates. ([755b3e3](https://github.com/creativeJoe007/ThreadifyEngine/commit/755b3e35cd21b0e76457add21d17db90afff344d))
64
+ * python sdk impl ([c3a54a4](https://github.com/creativeJoe007/ThreadifyEngine/commit/c3a54a453631c8fb3e3bef360386578263606b75))
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: threadify-sdk
3
- Version: 0.3.1
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
@@ -19,7 +19,6 @@ Description-Content-Type: text/markdown
19
19
  License-File: LICENSE
20
20
  Requires-Dist: websockets>=12.0
21
21
  Requires-Dist: httpx>=0.27.0
22
- Requires-Dist: PyYAML>=6.0
23
22
  Provides-Extra: otel
24
23
  Requires-Dist: opentelemetry-sdk>=1.20; extra == "otel"
25
24
  Provides-Extra: dev
@@ -59,6 +58,7 @@ from threadify import Threadify
59
58
  async def main():
60
59
  try:
61
60
  conn = await Threadify.connect(
61
+ "https://threadify.example.com", # your Engine URL
62
62
  "your-api-key",
63
63
  service_name="orders-service",
64
64
  )
@@ -67,12 +67,13 @@ async def main():
67
67
  return
68
68
 
69
69
  try:
70
- thread = await conn.start(
71
- contract_name="order_processing",
72
- role="customer",
73
- refs={"order_id": "ORD-123"},
74
- tags=["priority"],
75
- )
70
+ thread = await conn.thread("order:ORD-123", {
71
+ "label": "Order ORD-123",
72
+ "contract": "order_processing",
73
+ "role": "customer",
74
+ "refs": {"order_id": "ORD-123"},
75
+ "tags": ["priority"],
76
+ })
76
77
 
77
78
  await thread.add_refs({"crm_id": "CRM-456"})
78
79
 
@@ -92,66 +93,40 @@ if __name__ == "__main__":
92
93
  asyncio.run(main())
93
94
  ```
94
95
 
95
- For self-hosting, pass `engine_url="https://threadify.example.com"`. WebSocket and GraphQL paths are derived from that base, including reverse-proxy prefixes. Explicit `ws_url` and `graphql_url` remain available for split deployments.
96
-
97
- ## Entity profile config as code
98
-
99
- The management client sends a complete desired declaration to Threadify. The
100
- server performs metric reconciliation by name; SDK callers do not send database
101
- metric IDs or calculate deletions.
102
-
103
- ```python
104
- profiles = Threadify.entity_profiles(
105
- "your-service-api-key",
106
- web_api_url="https://web.threadify.dev/api",
107
- )
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.
108
97
 
109
- declaration = {
110
- "name": "Customer",
111
- "description": "Customer delivery intelligence",
112
- "type": ["customer_id", "customer_email"],
113
- "metrics": [
114
- {
115
- "name": "Delivery success rate",
116
- "template_id": "delivery_success_rate",
117
- "parameters": {"window": "30d"},
118
- }
119
- ],
120
- }
121
-
122
- plan = await profiles.apply(declaration, dry_run=True)
123
- result = await profiles.apply(declaration)
124
- await profiles.rename("Customer", "Account") # explicit identity change
125
- await profiles.close()
126
- ```
98
+ ## Entity profiles
127
99
 
128
- The SDK can also load the declaration directly from YAML:
100
+ Track a customer's activity across workflows by setting up a profile type with
101
+ the [Threadify CLI](https://docs.threadify.dev/cli):
129
102
 
130
103
  ```yaml
131
- # threadify-profile.yaml
132
- name: Customer
133
- description: Customer delivery intelligence
134
- type:
135
- - customer_id
136
- - customer_email
137
- metrics: []
104
+ # customers.yaml
105
+ name: Customers
106
+ type: [customer_id]
107
+ description: Customer workflows
138
108
  ```
139
109
 
140
- ```python
141
- plan = await profiles.apply_file("threadify-profile.yaml", dry_run=True)
142
- result = await profiles.apply_file("threadify-profile.yaml")
110
+ ```sh
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'
143
115
  ```
144
116
 
117
+ Use the returned profile type ID for `TYPE_ID`. Include `customer_id` in your
118
+ thread references to connect each workflow to its customer. Threadify can also
119
+ create profiles as matching activity arrives. Open **Entity Profiles** in the
120
+ dashboard to explore that history and configure metrics.
121
+
145
122
  ## Configuration
146
123
 
147
124
  ### Connect options
148
125
 
149
- Use keyword arguments with `Threadify.connect(...)`:
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:
150
128
 
151
129
  - `service_name`
152
- - `engine_url` (one HTTP(S) deployment base, including any proxy prefix)
153
- - `ws_url` (optional, defaults to production)
154
- - `graphql_url`
155
130
  - `debug`
156
131
  - `max_in_flight`
157
132
  - `connect_timeout`
@@ -162,6 +137,7 @@ Example:
162
137
  from threadify import Threadify
163
138
 
164
139
  conn = await Threadify.connect(
140
+ "https://threadify.example.com",
165
141
  "your-api-key",
166
142
  service_name="inventory-service",
167
143
  debug=True,
@@ -190,22 +166,46 @@ thread = await conn.join(
190
166
  )
191
167
  ```
192
168
 
193
- ### Start options
169
+ ### Create or resume a thread
194
170
 
195
- `Connection.start(...)` supports named options for contract, role, refs, and tags, while preserving the older positional forms:
171
+ `await connection.thread(thread_key, options=None)` atomically creates or resumes
172
+ an application-owned key within the tenant. Use a session, order, or process ID
173
+ that your application already knows; you do not need to persist Threadify's
174
+ internal `thread_id` between requests.
196
175
 
197
176
  ```python
198
- thread = await conn.start(
199
- contract_name="order_processing",
200
- role="customer",
201
- refs={"customer_id": "123"},
202
- tags=["priority"],
203
- )
204
- thread = await conn.start("Order-123", "customer")
205
- thread = await conn.start({"customer_id": "123"}, "customer")
206
- thread = await conn.start("Order-123") # contract is optional
177
+ thread = await conn.thread("agent-session:123", {
178
+ "label": "Agent session",
179
+ "contract": "agent_contract",
180
+ "refs": {"customer_id": "123"},
181
+ "tags": ["priority"],
182
+ })
183
+
184
+ # A later request or another worker uses the same key without repeating options.
185
+ thread = await conn.thread("agent-session:123")
186
+ await thread.step("tool_call").add_context({"tool": "search"}).success()
207
187
  ```
208
188
 
189
+ The optional dictionary accepts `label`, `contract`, `refs`, `tags`,
190
+ `service_name`, and `role`. `ThreadOptions` is exported for type annotations.
191
+ Labels, contracts, service names, and roles must be non-empty strings when
192
+ supplied; refs map non-empty string keys to string values, and tags are a list
193
+ of non-empty strings.
194
+
195
+ Options are creation defaults. Resuming loads the stored label, refs, tags,
196
+ contract name, and pinned contract version into the returned handle. Repeating
197
+ an existing contract is allowed; supplying a conflicting contract fails without
198
+ changing the thread. Use `await thread.add_refs({...})` to change references
199
+ explicitly. Metadata is available as `thread.thread_key`, `thread.label`,
200
+ `thread.contract_name`, `thread.contract_version`, `thread.refs`, and `thread.tags`.
201
+
202
+ Keys are trimmed, case-sensitive strings of at most 1024 UTF-8 bytes. Concurrent
203
+ calls with the same key resolve to one thread. A key-only call on an unknown key
204
+ creates a free-form thread, so initialize contracted sessions before collectors
205
+ or other workers report activity. Closed, completed, and cancelled threads reject
206
+ acquisition and further writes; use a new key for a new process. `join()` remains
207
+ available for internal IDs and invitation tokens.
208
+
209
209
  ## Subscriptions
210
210
 
211
211
  Preferred API:
@@ -245,7 +245,15 @@ This SDK follows [Semantic Versioning](https://semver.org/) and [Conventional Co
245
245
 
246
246
  ## OpenTelemetry Integration
247
247
 
248
- The Python SDK includes the OpenTelemetry SpanExporter in the core package.
248
+ The Python SDK includes the OpenTelemetry SpanExporter in the core package. Use
249
+ `BatchSpanProcessor`: synchronous `export()` waits for Engine acknowledgements
250
+ on its worker thread and returns failure if any span fails or the deadline expires.
251
+ It continues attempting unrelated spans in a failed batch and does not complete
252
+ sessions from that batch. Calling synchronous export on the connection event
253
+ loop is rejected to avoid a deadlock. Before closing that loop or the connection,
254
+ run `await asyncio.to_thread(provider.shutdown)` to drain queued spans. Use
255
+ `await asyncio.to_thread(provider.force_flush)` for an explicit flush.
256
+
249
257
 
250
258
  ```python
251
259
  from opentelemetry import trace
@@ -253,7 +261,7 @@ from opentelemetry.sdk.trace import TracerProvider
253
261
  from opentelemetry.sdk.trace.export import BatchSpanProcessor
254
262
  from threadify import Threadify
255
263
 
256
- 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")
257
265
 
258
266
  # Create exporter
259
267
  exporter = conn.create_span_exporter(options={"refs": ["order.id", "customer.id"]})
@@ -267,8 +275,21 @@ exporter = conn.create_span_exporter(options={
267
275
  provider = TracerProvider()
268
276
  provider.add_span_processor(BatchSpanProcessor(exporter))
269
277
  trace.set_tracer_provider(provider)
278
+
279
+ # Initialize before exporting spans when this session has a contract.
280
+ await conn.thread("agent-session:123", {"contract": "agent_contract"})
281
+ tracer = trace.get_tracer("agent")
282
+ with tracer.start_as_current_span("tool_call", attributes={
283
+ "threadify.thread_key": "agent-session:123",
284
+ }):
285
+ pass # Perform the instrumented operation.
270
286
  ```
271
287
 
288
+ The exporter resolves `threadify.thread_key` using the same create-or-resume
289
+ operation as `connection.thread()`. Omit the contract on later spans; the stored
290
+ contract version is loaded automatically. Shared root spans keep the session open.
291
+ See [OTel correlation](OTEL_CORRELATION.md) for identity precedence and completion.
292
+
272
293
  **Filter patterns:**
273
294
 
274
295
  - `"invoke_llm"` — exact match
@@ -295,9 +316,14 @@ python3 -m pytest
295
316
  ```python
296
317
  from threadify import Threadify, WaitOptions, ThreadifyError
297
318
 
298
- connection = await Threadify.connect(api_key, engine_url="https://threadify.example.com", service_name="payments")
319
+ connection = await Threadify.connect("https://threadify.example.com", api_key, service_name="payments")
299
320
  threads = await connection.get_threads_by_ref({"order_id": "ORD-1001"}, status="active", limit=25)
300
- thread = await connection.join(thread_id, "processor")
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.
301
327
  grant = await thread.wait_for("charge", WaitOptions(timeout=15))
302
328
  # Execute the permitted business operation here.
303
329
  result = await thread.step("charge").add_context({"amount": 42}).success("charged", wait_for=True, timeout=15)
@@ -310,6 +336,9 @@ await thread.wait_for_validation("charge", result.step_id)
310
336
  ID into the subsequent step report and its default idempotency key. It sends one
311
337
  request and waits for a final correlated response. The old notification-only
312
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.
313
342
 
314
343
  Timeouts are in **seconds**, at most 300. Cancelling the Python task or reaching
315
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
  )
@@ -36,12 +37,13 @@ async def main():
36
37
  return
37
38
 
38
39
  try:
39
- thread = await conn.start(
40
- contract_name="order_processing",
41
- role="customer",
42
- refs={"order_id": "ORD-123"},
43
- tags=["priority"],
44
- )
40
+ thread = await conn.thread("order:ORD-123", {
41
+ "label": "Order ORD-123",
42
+ "contract": "order_processing",
43
+ "role": "customer",
44
+ "refs": {"order_id": "ORD-123"},
45
+ "tags": ["priority"],
46
+ })
45
47
 
46
48
  await thread.add_refs({"crm_id": "CRM-456"})
47
49
 
@@ -61,66 +63,40 @@ if __name__ == "__main__":
61
63
  asyncio.run(main())
62
64
  ```
63
65
 
64
- For self-hosting, pass `engine_url="https://threadify.example.com"`. WebSocket and GraphQL paths are derived from that base, including reverse-proxy prefixes. Explicit `ws_url` and `graphql_url` remain available for split deployments.
65
-
66
- ## Entity profile config as code
67
-
68
- The management client sends a complete desired declaration to Threadify. The
69
- server performs metric reconciliation by name; SDK callers do not send database
70
- metric IDs or calculate deletions.
71
-
72
- ```python
73
- profiles = Threadify.entity_profiles(
74
- "your-service-api-key",
75
- web_api_url="https://web.threadify.dev/api",
76
- )
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.
77
67
 
78
- declaration = {
79
- "name": "Customer",
80
- "description": "Customer delivery intelligence",
81
- "type": ["customer_id", "customer_email"],
82
- "metrics": [
83
- {
84
- "name": "Delivery success rate",
85
- "template_id": "delivery_success_rate",
86
- "parameters": {"window": "30d"},
87
- }
88
- ],
89
- }
90
-
91
- plan = await profiles.apply(declaration, dry_run=True)
92
- result = await profiles.apply(declaration)
93
- await profiles.rename("Customer", "Account") # explicit identity change
94
- await profiles.close()
95
- ```
68
+ ## Entity profiles
96
69
 
97
- The SDK can also load the declaration directly from YAML:
70
+ Track a customer's activity across workflows by setting up a profile type with
71
+ the [Threadify CLI](https://docs.threadify.dev/cli):
98
72
 
99
73
  ```yaml
100
- # threadify-profile.yaml
101
- name: Customer
102
- description: Customer delivery intelligence
103
- type:
104
- - customer_id
105
- - customer_email
106
- metrics: []
74
+ # customers.yaml
75
+ name: Customers
76
+ type: [customer_id]
77
+ description: Customer workflows
107
78
  ```
108
79
 
109
- ```python
110
- plan = await profiles.apply_file("threadify-profile.yaml", dry_run=True)
111
- result = await profiles.apply_file("threadify-profile.yaml")
80
+ ```sh
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'
112
85
  ```
113
86
 
87
+ Use the returned profile type ID for `TYPE_ID`. Include `customer_id` in your
88
+ thread references to connect each workflow to its customer. Threadify can also
89
+ create profiles as matching activity arrives. Open **Entity Profiles** in the
90
+ dashboard to explore that history and configure metrics.
91
+
114
92
  ## Configuration
115
93
 
116
94
  ### Connect options
117
95
 
118
- Use keyword arguments with `Threadify.connect(...)`:
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:
119
98
 
120
99
  - `service_name`
121
- - `engine_url` (one HTTP(S) deployment base, including any proxy prefix)
122
- - `ws_url` (optional, defaults to production)
123
- - `graphql_url`
124
100
  - `debug`
125
101
  - `max_in_flight`
126
102
  - `connect_timeout`
@@ -131,6 +107,7 @@ Example:
131
107
  from threadify import Threadify
132
108
 
133
109
  conn = await Threadify.connect(
110
+ "https://threadify.example.com",
134
111
  "your-api-key",
135
112
  service_name="inventory-service",
136
113
  debug=True,
@@ -159,22 +136,46 @@ thread = await conn.join(
159
136
  )
160
137
  ```
161
138
 
162
- ### Start options
139
+ ### Create or resume a thread
163
140
 
164
- `Connection.start(...)` supports named options for contract, role, refs, and tags, while preserving the older positional forms:
141
+ `await connection.thread(thread_key, options=None)` atomically creates or resumes
142
+ an application-owned key within the tenant. Use a session, order, or process ID
143
+ that your application already knows; you do not need to persist Threadify's
144
+ internal `thread_id` between requests.
165
145
 
166
146
  ```python
167
- thread = await conn.start(
168
- contract_name="order_processing",
169
- role="customer",
170
- refs={"customer_id": "123"},
171
- tags=["priority"],
172
- )
173
- thread = await conn.start("Order-123", "customer")
174
- thread = await conn.start({"customer_id": "123"}, "customer")
175
- thread = await conn.start("Order-123") # contract is optional
147
+ thread = await conn.thread("agent-session:123", {
148
+ "label": "Agent session",
149
+ "contract": "agent_contract",
150
+ "refs": {"customer_id": "123"},
151
+ "tags": ["priority"],
152
+ })
153
+
154
+ # A later request or another worker uses the same key without repeating options.
155
+ thread = await conn.thread("agent-session:123")
156
+ await thread.step("tool_call").add_context({"tool": "search"}).success()
176
157
  ```
177
158
 
159
+ The optional dictionary accepts `label`, `contract`, `refs`, `tags`,
160
+ `service_name`, and `role`. `ThreadOptions` is exported for type annotations.
161
+ Labels, contracts, service names, and roles must be non-empty strings when
162
+ supplied; refs map non-empty string keys to string values, and tags are a list
163
+ of non-empty strings.
164
+
165
+ Options are creation defaults. Resuming loads the stored label, refs, tags,
166
+ contract name, and pinned contract version into the returned handle. Repeating
167
+ an existing contract is allowed; supplying a conflicting contract fails without
168
+ changing the thread. Use `await thread.add_refs({...})` to change references
169
+ explicitly. Metadata is available as `thread.thread_key`, `thread.label`,
170
+ `thread.contract_name`, `thread.contract_version`, `thread.refs`, and `thread.tags`.
171
+
172
+ Keys are trimmed, case-sensitive strings of at most 1024 UTF-8 bytes. Concurrent
173
+ calls with the same key resolve to one thread. A key-only call on an unknown key
174
+ creates a free-form thread, so initialize contracted sessions before collectors
175
+ or other workers report activity. Closed, completed, and cancelled threads reject
176
+ acquisition and further writes; use a new key for a new process. `join()` remains
177
+ available for internal IDs and invitation tokens.
178
+
178
179
  ## Subscriptions
179
180
 
180
181
  Preferred API:
@@ -214,7 +215,15 @@ This SDK follows [Semantic Versioning](https://semver.org/) and [Conventional Co
214
215
 
215
216
  ## OpenTelemetry Integration
216
217
 
217
- The Python SDK includes the OpenTelemetry SpanExporter in the core package.
218
+ The Python SDK includes the OpenTelemetry SpanExporter in the core package. Use
219
+ `BatchSpanProcessor`: synchronous `export()` waits for Engine acknowledgements
220
+ on its worker thread and returns failure if any span fails or the deadline expires.
221
+ It continues attempting unrelated spans in a failed batch and does not complete
222
+ sessions from that batch. Calling synchronous export on the connection event
223
+ loop is rejected to avoid a deadlock. Before closing that loop or the connection,
224
+ run `await asyncio.to_thread(provider.shutdown)` to drain queued spans. Use
225
+ `await asyncio.to_thread(provider.force_flush)` for an explicit flush.
226
+
218
227
 
219
228
  ```python
220
229
  from opentelemetry import trace
@@ -222,7 +231,7 @@ from opentelemetry.sdk.trace import TracerProvider
222
231
  from opentelemetry.sdk.trace.export import BatchSpanProcessor
223
232
  from threadify import Threadify
224
233
 
225
- 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")
226
235
 
227
236
  # Create exporter
228
237
  exporter = conn.create_span_exporter(options={"refs": ["order.id", "customer.id"]})
@@ -236,8 +245,21 @@ exporter = conn.create_span_exporter(options={
236
245
  provider = TracerProvider()
237
246
  provider.add_span_processor(BatchSpanProcessor(exporter))
238
247
  trace.set_tracer_provider(provider)
248
+
249
+ # Initialize before exporting spans when this session has a contract.
250
+ await conn.thread("agent-session:123", {"contract": "agent_contract"})
251
+ tracer = trace.get_tracer("agent")
252
+ with tracer.start_as_current_span("tool_call", attributes={
253
+ "threadify.thread_key": "agent-session:123",
254
+ }):
255
+ pass # Perform the instrumented operation.
239
256
  ```
240
257
 
258
+ The exporter resolves `threadify.thread_key` using the same create-or-resume
259
+ operation as `connection.thread()`. Omit the contract on later spans; the stored
260
+ contract version is loaded automatically. Shared root spans keep the session open.
261
+ See [OTel correlation](OTEL_CORRELATION.md) for identity precedence and completion.
262
+
241
263
  **Filter patterns:**
242
264
 
243
265
  - `"invoke_llm"` — exact match
@@ -264,9 +286,14 @@ python3 -m pytest
264
286
  ```python
265
287
  from threadify import Threadify, WaitOptions, ThreadifyError
266
288
 
267
- connection = await Threadify.connect(api_key, engine_url="https://threadify.example.com", service_name="payments")
289
+ connection = await Threadify.connect("https://threadify.example.com", api_key, service_name="payments")
268
290
  threads = await connection.get_threads_by_ref({"order_id": "ORD-1001"}, status="active", limit=25)
269
- thread = await connection.join(thread_id, "processor")
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.
270
297
  grant = await thread.wait_for("charge", WaitOptions(timeout=15))
271
298
  # Execute the permitted business operation here.
272
299
  result = await thread.step("charge").add_context({"amount": 42}).success("charged", wait_for=True, timeout=15)
@@ -279,6 +306,9 @@ await thread.wait_for_validation("charge", result.step_id)
279
306
  ID into the subsequent step report and its default idempotency key. It sends one
280
307
  request and waits for a final correlated response. The old notification-only
281
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.
282
312
 
283
313
  Timeouts are in **seconds**, at most 300. Cancelling the Python task or reaching
284
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.3.1"
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"
@@ -28,7 +28,6 @@ classifiers = [
28
28
  dependencies = [
29
29
  "websockets>=12.0",
30
30
  "httpx>=0.27.0",
31
- "PyYAML>=6.0",
32
31
  ]
33
32
 
34
33
  [project.optional-dependencies]
@@ -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")