tidefold-client 0.0.226__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.

Potentially problematic release.


This version of tidefold-client might be problematic. Click here for more details.

@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,120 @@
1
+ Metadata-Version: 2.4
2
+ Name: tidefold-client
3
+ Version: 0.0.226
4
+ Summary: Python client for starting and following tidefold workflow runs
5
+ Author: tidefold
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.13
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Typing :: Typed
12
+ Requires-Dist: httpx>=0.27.0,<1.0.0
13
+ Requires-Python: >=3.13, <4.0
14
+ Description-Content-Type: text/markdown
15
+
16
+ # tidefold-client
17
+
18
+ A small Python client for starting workflow runs on a tidefold deployment,
19
+ waiting for them, and reading what they produced.
20
+
21
+ ```sh
22
+ pip install "tidefold-client==<your platform version>"
23
+ ```
24
+
25
+ Install the version that matches your deployment's platform release. The
26
+ client warns when it talks to a server on a different release. There is no
27
+ compatibility promise across versions.
28
+
29
+ ## Quick start
30
+
31
+ ```python
32
+ from tidefold_client import Client
33
+
34
+ client = Client.from_env() # TIDEFOLD_API_URL, TIDEFOLD_API_TOKEN
35
+
36
+ run = client.workflows.start(
37
+ "invoice_review",
38
+ inputs={"reference": "INV-1042"},
39
+ files={"document": "invoice.pdf"},
40
+ subject="INV-1042",
41
+ )
42
+ run.wait(timeout=1800)
43
+ print(run.results()["marked_results"])
44
+ ```
45
+
46
+ `TIDEFOLD_API_URL` is the API root: `https://<your host>/api` on a
47
+ deployment, `http://localhost:8000` on a local stack. There is no default.
48
+
49
+ ## The API token
50
+
51
+ An administrator creates tokens under **Settings → API tokens**. A token is
52
+ shown once; keep it in a secret store and pass it through the environment.
53
+ Grant only the scopes your script needs:
54
+
55
+ | Scope | Needed for |
56
+ | --- | --- |
57
+ | `workflow_read` | `workflows.list()`, `workflows.get_id()`, `workflows.start()` by name |
58
+ | `run_create` | `workflows.start()` |
59
+ | `run_file_write` | `files.upload()`, `workflows.start()` with `files` |
60
+ | `run_read` | `runs.get()`, `runs.wait()`, `runs.results()`, `runs.usage()`, `files.download()` |
61
+ | `run_cancel` | `runs.cancel()` |
62
+ | `inbox_read` | `runs.requests()` |
63
+
64
+ "Own data only" visibility suits scripts: the token then sees only the runs
65
+ it started. A local stack running without auth takes no token.
66
+
67
+ ## The subclients
68
+
69
+ The client has one subclient per resource, all sharing one session.
70
+
71
+ **`client.workflows`**
72
+
73
+ - `start(name, *, inputs, files, subject, correlation_id)` uploads each
74
+ file and starts a run on the workflow's latest published release
75
+ (`channel="draft"` runs the current draft). It returns a `Run` at once.
76
+ `workflow_id=` starts by id instead of name.
77
+ - `list()` returns the workflows the token can see; `get_id(name)` resolves
78
+ a name to its stable id.
79
+
80
+ **`client.runs`**, each taking a run id
81
+
82
+ - `get()` reads the run as it stands.
83
+ - `wait()` polls until the run ends. It returns the run on `COMPLETED` and
84
+ raises `RunFailed`, `RunCancelled` or `WaitTimeout`. A server restarting
85
+ during a deploy is waited out.
86
+ - `results()` returns `results` per step and `marked_results`, the outputs
87
+ the workflow declares. `usage()`, `requests()` and `cancel()` do what
88
+ their names say.
89
+
90
+ **`client.files`**
91
+
92
+ - `upload(path)` declares the file, uploads it to the signed URL (never
93
+ with the token) and finalizes it; it returns the file's record.
94
+ - `download(file_id, path)` saves a file, such as a produced document.
95
+
96
+ A `Run` is `client.runs` with the id filled in: `run.wait()`,
97
+ `run.results()` and so on. `client.run(run_id)` gives one for a run started
98
+ earlier.
99
+
100
+ **Starting is not idempotent.** The client never retries `start()`, and
101
+ calling it twice starts two runs, even with the same `correlation_id`.
102
+
103
+ ## Errors
104
+
105
+ Every exception derives from `TidefoldError`.
106
+
107
+ | Exception | Meaning |
108
+ | --- | --- |
109
+ | `AuthError` | 401: token missing, wrong, expired or revoked |
110
+ | `PermissionDenied` | 403: the token lacks the scope named in the message |
111
+ | `NotFound` | 404: no such run or file; for a workflow, also a category the token cannot see |
112
+ | `Conflict` | 409: workflow never published, or results read while the run is still running |
113
+ | `InvalidRequest` | 400, 413, 422: a missing input, an oversized or unsupported file |
114
+ | `UploadError` | a file did not upload; no run was started |
115
+ | `RunFailed`, `RunCancelled`, `WaitTimeout` | raised by `wait()` |
116
+ | `NetworkError` | the server could not be reached after retries |
117
+
118
+ ## License
119
+
120
+ Apache-2.0.
@@ -0,0 +1,105 @@
1
+ # tidefold-client
2
+
3
+ A small Python client for starting workflow runs on a tidefold deployment,
4
+ waiting for them, and reading what they produced.
5
+
6
+ ```sh
7
+ pip install "tidefold-client==<your platform version>"
8
+ ```
9
+
10
+ Install the version that matches your deployment's platform release. The
11
+ client warns when it talks to a server on a different release. There is no
12
+ compatibility promise across versions.
13
+
14
+ ## Quick start
15
+
16
+ ```python
17
+ from tidefold_client import Client
18
+
19
+ client = Client.from_env() # TIDEFOLD_API_URL, TIDEFOLD_API_TOKEN
20
+
21
+ run = client.workflows.start(
22
+ "invoice_review",
23
+ inputs={"reference": "INV-1042"},
24
+ files={"document": "invoice.pdf"},
25
+ subject="INV-1042",
26
+ )
27
+ run.wait(timeout=1800)
28
+ print(run.results()["marked_results"])
29
+ ```
30
+
31
+ `TIDEFOLD_API_URL` is the API root: `https://<your host>/api` on a
32
+ deployment, `http://localhost:8000` on a local stack. There is no default.
33
+
34
+ ## The API token
35
+
36
+ An administrator creates tokens under **Settings → API tokens**. A token is
37
+ shown once; keep it in a secret store and pass it through the environment.
38
+ Grant only the scopes your script needs:
39
+
40
+ | Scope | Needed for |
41
+ | --- | --- |
42
+ | `workflow_read` | `workflows.list()`, `workflows.get_id()`, `workflows.start()` by name |
43
+ | `run_create` | `workflows.start()` |
44
+ | `run_file_write` | `files.upload()`, `workflows.start()` with `files` |
45
+ | `run_read` | `runs.get()`, `runs.wait()`, `runs.results()`, `runs.usage()`, `files.download()` |
46
+ | `run_cancel` | `runs.cancel()` |
47
+ | `inbox_read` | `runs.requests()` |
48
+
49
+ "Own data only" visibility suits scripts: the token then sees only the runs
50
+ it started. A local stack running without auth takes no token.
51
+
52
+ ## The subclients
53
+
54
+ The client has one subclient per resource, all sharing one session.
55
+
56
+ **`client.workflows`**
57
+
58
+ - `start(name, *, inputs, files, subject, correlation_id)` uploads each
59
+ file and starts a run on the workflow's latest published release
60
+ (`channel="draft"` runs the current draft). It returns a `Run` at once.
61
+ `workflow_id=` starts by id instead of name.
62
+ - `list()` returns the workflows the token can see; `get_id(name)` resolves
63
+ a name to its stable id.
64
+
65
+ **`client.runs`**, each taking a run id
66
+
67
+ - `get()` reads the run as it stands.
68
+ - `wait()` polls until the run ends. It returns the run on `COMPLETED` and
69
+ raises `RunFailed`, `RunCancelled` or `WaitTimeout`. A server restarting
70
+ during a deploy is waited out.
71
+ - `results()` returns `results` per step and `marked_results`, the outputs
72
+ the workflow declares. `usage()`, `requests()` and `cancel()` do what
73
+ their names say.
74
+
75
+ **`client.files`**
76
+
77
+ - `upload(path)` declares the file, uploads it to the signed URL (never
78
+ with the token) and finalizes it; it returns the file's record.
79
+ - `download(file_id, path)` saves a file, such as a produced document.
80
+
81
+ A `Run` is `client.runs` with the id filled in: `run.wait()`,
82
+ `run.results()` and so on. `client.run(run_id)` gives one for a run started
83
+ earlier.
84
+
85
+ **Starting is not idempotent.** The client never retries `start()`, and
86
+ calling it twice starts two runs, even with the same `correlation_id`.
87
+
88
+ ## Errors
89
+
90
+ Every exception derives from `TidefoldError`.
91
+
92
+ | Exception | Meaning |
93
+ | --- | --- |
94
+ | `AuthError` | 401: token missing, wrong, expired or revoked |
95
+ | `PermissionDenied` | 403: the token lacks the scope named in the message |
96
+ | `NotFound` | 404: no such run or file; for a workflow, also a category the token cannot see |
97
+ | `Conflict` | 409: workflow never published, or results read while the run is still running |
98
+ | `InvalidRequest` | 400, 413, 422: a missing input, an oversized or unsupported file |
99
+ | `UploadError` | a file did not upload; no run was started |
100
+ | `RunFailed`, `RunCancelled`, `WaitTimeout` | raised by `wait()` |
101
+ | `NetworkError` | the server could not be reached after retries |
102
+
103
+ ## License
104
+
105
+ Apache-2.0.
@@ -0,0 +1,39 @@
1
+ [project]
2
+ name = "tidefold-client"
3
+ license = "Apache-2.0"
4
+ license-files = ["LICENSE"]
5
+ # Every release tag stamps its own version into a copy of this file before
6
+ # building (.github/workflows/publish-client.yml); 0.0.0+dev marks a
7
+ # workspace install, which the client's server-version check ignores.
8
+ version = "0.0.226"
9
+ description = "Python client for starting and following tidefold workflow runs"
10
+ authors = [
11
+ {name = "tidefold"}
12
+ ]
13
+ readme = "README.md"
14
+ requires-python = ">=3.13, <4.0"
15
+ # Standalone by contract: published to public PyPI, so it imports nothing
16
+ # from the platform libraries or the api.
17
+ dependencies = [
18
+ "httpx (>=0.27.0,<1.0.0)",
19
+ ]
20
+ classifiers = [
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Operating System :: OS Independent",
24
+ "Typing :: Typed",
25
+ ]
26
+
27
+ [tool.uv]
28
+ package = true
29
+
30
+ [build-system]
31
+ # Pinned below the next minor, as uv_build's versions track uv's.
32
+ requires = ["uv_build>=0.10.9,<0.11"]
33
+ build-backend = "uv_build"
34
+
35
+ # Flat layout. The sdist holds the module, pyproject.toml, README.md and
36
+ # LICENSE; the tests are outside the module and never ship.
37
+ [tool.uv.build-backend]
38
+ module-name = "tidefold_client"
39
+ module-root = ""
@@ -0,0 +1,48 @@
1
+ """Start and follow tidefold workflow runs over the REST API."""
2
+
3
+ from tidefold_client._client import Client
4
+ from tidefold_client._errors import (
5
+ ApiError,
6
+ AuthError,
7
+ Conflict,
8
+ InvalidRequest,
9
+ NetworkError,
10
+ NotFound,
11
+ PermissionDenied,
12
+ RunCancelled,
13
+ RunError,
14
+ RunFailed,
15
+ TidefoldError,
16
+ UploadError,
17
+ WaitTimeout,
18
+ )
19
+ from tidefold_client._files import FilePath, Files
20
+ from tidefold_client._runs import Run, Runs
21
+ from tidefold_client._transport import CLIENT_VERSION
22
+ from tidefold_client._workflows import FileInputs, Workflows
23
+
24
+ __version__ = CLIENT_VERSION
25
+
26
+ __all__ = [
27
+ "ApiError",
28
+ "AuthError",
29
+ "Client",
30
+ "Conflict",
31
+ "FileInputs",
32
+ "FilePath",
33
+ "Files",
34
+ "InvalidRequest",
35
+ "NetworkError",
36
+ "NotFound",
37
+ "PermissionDenied",
38
+ "Run",
39
+ "RunCancelled",
40
+ "RunError",
41
+ "RunFailed",
42
+ "Runs",
43
+ "TidefoldError",
44
+ "UploadError",
45
+ "WaitTimeout",
46
+ "Workflows",
47
+ "__version__",
48
+ ]
@@ -0,0 +1,76 @@
1
+ """The client: one API root, one subclient per resource."""
2
+
3
+ import os
4
+ from types import TracebackType
5
+ from typing import Any, Self
6
+
7
+ import httpx
8
+
9
+ from tidefold_client._files import Files
10
+ from tidefold_client._runs import Run, Runs
11
+ from tidefold_client._transport import DEFAULT_TIMEOUT_SECONDS, Transport
12
+ from tidefold_client._workflows import Workflows
13
+
14
+
15
+ class Client:
16
+ """A client for one tidefold API.
17
+
18
+ ``base_url`` is the API root as the API is mounted:
19
+ ``https://<host>/api`` on a deployment, ``http://localhost:8000`` on a
20
+ local stack. ``token`` is an API token (``sk_...``); a local stack
21
+ running without auth takes none. ``http`` replaces the client's own
22
+ ``httpx.Client``, for proxies, custom transports or tests.
23
+
24
+ Each resource is a subclient sharing one session: ``workflows``,
25
+ ``runs`` and ``files``.
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ base_url: str,
31
+ token: str | None = None,
32
+ *,
33
+ http: httpx.Client | None = None,
34
+ timeout: float = DEFAULT_TIMEOUT_SECONDS,
35
+ ) -> None:
36
+ self._transport = Transport(base_url, token, http=http, timeout=timeout)
37
+ self.files = Files(self._transport)
38
+ self.runs = Runs(self._transport)
39
+ self.workflows = Workflows(self._transport, files=self.files, runs=self.runs)
40
+
41
+ @classmethod
42
+ def from_env(cls, *, http: httpx.Client | None = None) -> Self:
43
+ """A client configured by ``TIDEFOLD_API_URL`` and ``TIDEFOLD_API_TOKEN``."""
44
+ base_url = os.environ.get("TIDEFOLD_API_URL", "")
45
+ if not base_url:
46
+ msg = "TIDEFOLD_API_URL is not set"
47
+ raise ValueError(msg)
48
+ token = os.environ.get("TIDEFOLD_API_TOKEN") or None
49
+ return cls(base_url, token, http=http)
50
+
51
+ def __enter__(self) -> Self:
52
+ return self
53
+
54
+ def __exit__(
55
+ self,
56
+ exc_type: type[BaseException] | None,
57
+ exc: BaseException | None,
58
+ traceback: TracebackType | None,
59
+ ) -> None:
60
+ self.close()
61
+
62
+ def __repr__(self) -> str:
63
+ token = "set" if self._transport.has_token else "none"
64
+ return f"Client(base_url={self._transport.base!r}, token={token})"
65
+
66
+ def close(self) -> None:
67
+ """Close the underlying HTTP client, unless the caller supplied it."""
68
+ self._transport.close()
69
+
70
+ def server_version(self) -> dict[str, Any]:
71
+ """The server's build: ``{"git_sha": ..., "image_tag": ...}``."""
72
+ return self._transport.server_version()
73
+
74
+ def run(self, run_id: str) -> Run:
75
+ """A handle on a run started earlier: ``client.runs`` with its id."""
76
+ return Run(self.runs, run_id)
@@ -0,0 +1,86 @@
1
+ """The exceptions the client raises, all under :class:`TidefoldError`."""
2
+
3
+ from typing import Any
4
+
5
+
6
+ class TidefoldError(Exception):
7
+ """Base class of every error the client raises."""
8
+
9
+
10
+ class NetworkError(TidefoldError):
11
+ """The server could not be reached, after the client's own retries."""
12
+
13
+
14
+ class ApiError(TidefoldError):
15
+ """The API answered with an error status.
16
+
17
+ ``path`` is the request's path without its query string, so a signed
18
+ URL's signature never ends up in a message or a log line.
19
+ """
20
+
21
+ def __init__(
22
+ self, message: str, *, status: int, method: str, path: str, detail: str
23
+ ) -> None:
24
+ super().__init__(message)
25
+ self.status = status
26
+ self.method = method
27
+ self.path = path
28
+ self.detail = detail
29
+
30
+
31
+ class AuthError(ApiError):
32
+ """401: the token is missing, wrong, expired or revoked."""
33
+
34
+
35
+ class PermissionDenied(ApiError):
36
+ """403: the token lacks the scope this call needs."""
37
+
38
+
39
+ class NotFound(ApiError):
40
+ """404: the run, file or workflow does not exist for this token."""
41
+
42
+
43
+ class Conflict(ApiError):
44
+ """409: the request clashes with the resource's current state."""
45
+
46
+
47
+ class InvalidRequest(ApiError):
48
+ """400, 413 or 422: the API rejected the request as sent."""
49
+
50
+
51
+ class UploadError(TidefoldError):
52
+ """An input file did not upload; no run was started."""
53
+
54
+ def __init__(self, message: str, *, file: str, status: str | int | None) -> None:
55
+ super().__init__(message)
56
+ self.file = file
57
+ self.status = status
58
+
59
+
60
+ class RunError(TidefoldError):
61
+ """A run ended without completing. ``run`` is its last read."""
62
+
63
+ def __init__(self, message: str, *, run: dict[str, Any]) -> None:
64
+ super().__init__(message)
65
+ self.run = run
66
+ self.run_id: str = run.get("id", "")
67
+
68
+
69
+ class RunFailed(RunError):
70
+ """The run ended ``FAILED``."""
71
+
72
+
73
+ class RunCancelled(RunError):
74
+ """The run ended ``CANCELLED``."""
75
+
76
+
77
+ class WaitTimeout(TidefoldError):
78
+ """``Run.wait`` gave up; the run itself keeps going on the server."""
79
+
80
+ def __init__(
81
+ self, message: str, *, run_id: str, timeout: float, last_status: str | None
82
+ ) -> None:
83
+ super().__init__(message)
84
+ self.run_id = run_id
85
+ self.timeout = timeout
86
+ self.last_status = last_status
@@ -0,0 +1,76 @@
1
+ """``client.files``: upload run inputs, download what runs produced."""
2
+
3
+ import hashlib
4
+ import logging
5
+ import mimetypes
6
+ import os
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from tidefold_client._errors import ApiError, UploadError
11
+ from tidefold_client._transport import Transport
12
+
13
+ logger = logging.getLogger("tidefold_client")
14
+
15
+ type FilePath = str | os.PathLike[str]
16
+
17
+
18
+ class Files:
19
+ """The ``/v1/files`` routes."""
20
+
21
+ def __init__(self, transport: Transport) -> None:
22
+ self._transport = transport
23
+
24
+ def upload(self, path: FilePath) -> dict[str, Any]:
25
+ """Upload one file as run data; return its record once ``READY``.
26
+
27
+ Declares the file (size and sha256), sends the bytes to the signed
28
+ URL the API grants (never with the token), and finalizes. The
29
+ record's ``id`` is what a run's file input takes.
30
+ """
31
+ source = Path(path)
32
+ content = source.read_bytes()
33
+ mime_type = mimetypes.guess_type(source.name)[0] or "application/octet-stream"
34
+ grant = self._transport.json(
35
+ "POST",
36
+ "v1/files/uploads",
37
+ scope="run_file_write",
38
+ json_body={
39
+ "name": source.name,
40
+ "mime_type": mime_type,
41
+ "size": len(content),
42
+ "sha256": hashlib.sha256(content).hexdigest(),
43
+ },
44
+ )
45
+ try:
46
+ self._transport.request(
47
+ grant.get("method", "PUT"),
48
+ grant["url"],
49
+ auth=False,
50
+ content=content,
51
+ headers=grant.get("headers") or {},
52
+ )
53
+ except ApiError as exc:
54
+ msg = f"upload of {source.name} was rejected: {exc}"
55
+ raise UploadError(msg, file=source.name, status=exc.status) from exc
56
+ record = self._transport.json(
57
+ "POST", f"v1/files/{grant['file_id']}/finalize", retry=True
58
+ )
59
+ status = record.get("upload_status")
60
+ if status != "READY":
61
+ msg = f"upload of {source.name} is {status}, not READY"
62
+ raise UploadError(msg, file=source.name, status=status)
63
+ logger.debug("uploaded %s as %s", source.name, grant["file_id"])
64
+ return record
65
+
66
+ def download(self, file_id: str, dest: FilePath) -> Path:
67
+ """Write a file's content to ``dest`` and return its path."""
68
+ target = Path(dest)
69
+ path = f"v1/files/{file_id}/content"
70
+ with (
71
+ self._transport.stream(path, scope="run_read") as response,
72
+ target.open("wb") as out,
73
+ ):
74
+ for chunk in response.iter_bytes():
75
+ out.write(chunk)
76
+ return target
@@ -0,0 +1,187 @@
1
+ """``client.runs``: read, wait for and cancel workflow runs."""
2
+
3
+ import logging
4
+ import time
5
+ from typing import Any
6
+
7
+ import httpx
8
+
9
+ from tidefold_client._errors import (
10
+ ApiError,
11
+ NetworkError,
12
+ RunCancelled,
13
+ RunFailed,
14
+ WaitTimeout,
15
+ )
16
+ from tidefold_client._transport import Transport
17
+
18
+ logger = logging.getLogger("tidefold_client")
19
+
20
+ _TRANSIENT = frozenset(
21
+ {
22
+ httpx.codes.BAD_GATEWAY,
23
+ httpx.codes.SERVICE_UNAVAILABLE,
24
+ httpx.codes.GATEWAY_TIMEOUT,
25
+ }
26
+ )
27
+ _RUNNING = frozenset({"RUNNING", "CANCELLING"})
28
+ _FAILED_STEP = frozenset({"FAILED", "BLOCKED"})
29
+ _STEP_ERROR_LIMIT = 200
30
+
31
+
32
+ class Runs:
33
+ """The ``/v1/runs`` routes."""
34
+
35
+ def __init__(self, transport: Transport) -> None:
36
+ self._transport = transport
37
+
38
+ def get(self, run_id: str) -> dict[str, Any]:
39
+ """The run as it stands: status, steps, timestamps, error."""
40
+ return self._transport.json(
41
+ "GET", f"v1/runs/{run_id}", scope="run_read", retry=True
42
+ )
43
+
44
+ def wait(
45
+ self, run_id: str, *, timeout: float | None = 3600, poll_interval: float = 15
46
+ ) -> dict[str, Any]:
47
+ """Poll until the run ends; return it when it ``COMPLETED``.
48
+
49
+ Raises :class:`RunFailed` or :class:`RunCancelled` when it ends
50
+ otherwise, and :class:`WaitTimeout` after ``timeout`` seconds
51
+ (``None`` waits indefinitely); the run keeps going on the server.
52
+ A server restarting during a deploy (502/503/504 or no
53
+ connection) is waited out, not raised.
54
+ """
55
+ if poll_interval < 0:
56
+ msg = "poll_interval must not be negative"
57
+ raise ValueError(msg)
58
+ deadline = None if timeout is None else time.monotonic() + timeout
59
+ status: str | None = None
60
+ while True:
61
+ run = self._poll(run_id)
62
+ if run is not None:
63
+ status = run.get("status")
64
+ if status not in _RUNNING:
65
+ return _settled(run)
66
+ if deadline is not None and time.monotonic() >= deadline:
67
+ msg = (
68
+ f"run {run_id} still {status} after {timeout}s; "
69
+ "it keeps going on the server"
70
+ )
71
+ raise WaitTimeout(
72
+ msg, run_id=run_id, timeout=timeout or 0, last_status=status
73
+ )
74
+ pause = poll_interval
75
+ if deadline is not None:
76
+ pause = max(0.0, min(pause, deadline - time.monotonic()))
77
+ logger.debug("run %s is %s; polling in %.1fs", run_id, status, pause)
78
+ time.sleep(pause)
79
+
80
+ def results(self, run_id: str) -> dict[str, Any]:
81
+ """The ended run's results: ``results`` per step, ``marked_results``."""
82
+ return self._transport.json(
83
+ "GET",
84
+ f"v1/runs/{run_id}/results",
85
+ scope="run_read",
86
+ hints={httpx.codes.CONFLICT: "the run is still running"},
87
+ retry=True,
88
+ )
89
+
90
+ def usage(self, run_id: str) -> dict[str, Any]:
91
+ """The run's model usage and cost."""
92
+ return self._transport.json(
93
+ "GET", f"v1/runs/{run_id}/usage", scope="run_read", retry=True
94
+ )
95
+
96
+ def requests(self, run_id: str) -> list[dict[str, Any]]:
97
+ """The review requests the run raised, pending and resolved."""
98
+ return self._transport.json(
99
+ "GET", f"v1/runs/{run_id}/hitl", scope="inbox_read", retry=True
100
+ )
101
+
102
+ def cancel(self, run_id: str) -> None:
103
+ """Ask the server to cancel the run; it moves to ``CANCELLING``."""
104
+ self._transport.request(
105
+ "POST",
106
+ f"v1/runs/{run_id}/cancel",
107
+ scope="run_cancel",
108
+ hints={httpx.codes.CONFLICT: "the run has already finished"},
109
+ )
110
+
111
+ def _poll(self, run_id: str) -> dict[str, Any] | None:
112
+ """One read, or ``None`` when the server is briefly unavailable."""
113
+ try:
114
+ return self.get(run_id)
115
+ except NetworkError:
116
+ logger.debug("run %s: server unreachable, waiting", run_id)
117
+ except ApiError as exc:
118
+ if exc.status not in _TRANSIENT:
119
+ raise
120
+ logger.debug("run %s: server answered %s, waiting", run_id, exc.status)
121
+ return None
122
+
123
+
124
+ class Run:
125
+ """A handle on one run: ``client.runs`` with the id filled in.
126
+
127
+ ``status`` is the status from this handle's last read.
128
+ """
129
+
130
+ def __init__(self, runs: Runs, run_id: str) -> None:
131
+ self._runs = runs
132
+ self.id = run_id
133
+ self.status: str | None = None
134
+
135
+ def __repr__(self) -> str:
136
+ return f"Run(id={self.id!r}, status={self.status!r})"
137
+
138
+ def get(self) -> dict[str, Any]:
139
+ return self._read(self._runs.get(self.id))
140
+
141
+ def wait(
142
+ self, *, timeout: float | None = 3600, poll_interval: float = 15
143
+ ) -> dict[str, Any]:
144
+ try:
145
+ return self._read(
146
+ self._runs.wait(self.id, timeout=timeout, poll_interval=poll_interval)
147
+ )
148
+ except (RunFailed, RunCancelled) as exc:
149
+ self._read(exc.run)
150
+ raise
151
+ except WaitTimeout as exc:
152
+ self.status = exc.last_status
153
+ raise
154
+
155
+ def results(self) -> dict[str, Any]:
156
+ return self._runs.results(self.id)
157
+
158
+ def usage(self) -> dict[str, Any]:
159
+ return self._runs.usage(self.id)
160
+
161
+ def requests(self) -> list[dict[str, Any]]:
162
+ return self._runs.requests(self.id)
163
+
164
+ def cancel(self) -> None:
165
+ self._runs.cancel(self.id)
166
+
167
+ def _read(self, run: dict[str, Any]) -> dict[str, Any]:
168
+ self.status = run.get("status")
169
+ return run
170
+
171
+
172
+ def _settled(run: dict[str, Any]) -> dict[str, Any]:
173
+ status = run.get("status")
174
+ run_id = run.get("id", "")
175
+ if status == "FAILED":
176
+ failed = [
177
+ f"{step.get('step_name')}: {step.get('error_type') or 'error'}: "
178
+ f"{(step.get('error_message') or '')[:_STEP_ERROR_LIMIT]}"
179
+ for step in run.get("steps") or []
180
+ if step.get("status") in _FAILED_STEP
181
+ ]
182
+ msg = f"run {run_id} failed" + (f": {'; '.join(failed)}" if failed else "")
183
+ raise RunFailed(msg, run=run)
184
+ if status == "CANCELLED":
185
+ msg = f"run {run_id} was cancelled"
186
+ raise RunCancelled(msg, run=run)
187
+ return run
@@ -0,0 +1,260 @@
1
+ """One HTTP session against one tidefold API: URLs, auth, retries, errors.
2
+
3
+ The token is attached per request, never as a default header on the
4
+ underlying ``httpx.Client``, so a signed upload URL and a caller-supplied
5
+ client never carry it.
6
+ """
7
+
8
+ import json
9
+ import logging
10
+ import re
11
+ import time
12
+ from collections.abc import Iterator
13
+ from contextlib import contextmanager
14
+ from importlib.metadata import PackageNotFoundError
15
+ from importlib.metadata import version as dist_version
16
+ from typing import Any
17
+ from urllib.parse import urlsplit
18
+
19
+ import httpx
20
+
21
+ from tidefold_client._errors import (
22
+ ApiError,
23
+ AuthError,
24
+ Conflict,
25
+ InvalidRequest,
26
+ NetworkError,
27
+ NotFound,
28
+ PermissionDenied,
29
+ )
30
+
31
+ logger = logging.getLogger("tidefold_client")
32
+
33
+ try:
34
+ CLIENT_VERSION = dist_version("tidefold-client")
35
+ except PackageNotFoundError: # pragma: no cover - only outside an install
36
+ CLIENT_VERSION = "0.0.0+unknown"
37
+
38
+ USER_AGENT = f"tidefold-client/{CLIENT_VERSION}"
39
+ DEFAULT_TIMEOUT_SECONDS = 60.0
40
+
41
+ _RETRY_ATTEMPTS = 4
42
+ _RETRY_BACKOFF_SECONDS = 0.5
43
+ _DETAIL_LIMIT = 300
44
+ _SEMVER = re.compile(r"^\d+\.\d+\.\d+$")
45
+
46
+ _INVALID = frozenset(
47
+ {
48
+ httpx.codes.BAD_REQUEST,
49
+ httpx.codes.REQUEST_ENTITY_TOO_LARGE,
50
+ httpx.codes.UNPROCESSABLE_ENTITY,
51
+ }
52
+ )
53
+
54
+
55
+ class Transport:
56
+ """Requests against one API root, mapping error statuses to exceptions."""
57
+
58
+ def __init__(
59
+ self,
60
+ base_url: str,
61
+ token: str | None,
62
+ *,
63
+ http: httpx.Client | None,
64
+ timeout: float,
65
+ ) -> None:
66
+ if not base_url:
67
+ msg = (
68
+ "base_url is required: the API root, e.g. https://<host>/api "
69
+ "or http://localhost:8000"
70
+ )
71
+ raise ValueError(msg)
72
+ self.base = base_url.rstrip("/") + "/"
73
+ self._token = token
74
+ self._owns_http = http is None
75
+ self._http = http if http is not None else httpx.Client(timeout=timeout)
76
+ self._version_checked = False
77
+
78
+ @property
79
+ def has_token(self) -> bool:
80
+ return bool(self._token)
81
+
82
+ def close(self) -> None:
83
+ if self._owns_http:
84
+ self._http.close()
85
+
86
+ def url(self, path_or_url: str) -> str:
87
+ """An absolute URL; a relative one is resolved against the API root.
88
+
89
+ A grant URL the API returns relative (``/v1/files/...``) is relative
90
+ to the API root, not to the host, so ``/api`` on a deployment stays.
91
+ """
92
+ if path_or_url.startswith(("http://", "https://")):
93
+ return path_or_url
94
+ return self.base + path_or_url.lstrip("/")
95
+
96
+ def request( # noqa: PLR0913 - one keyword per request facet
97
+ self,
98
+ method: str,
99
+ path: str,
100
+ *,
101
+ scope: str | None = None,
102
+ hints: dict[int, str] | None = None,
103
+ retry: bool = False,
104
+ auth: bool = True,
105
+ json_body: dict[str, Any] | None = None,
106
+ content: bytes | None = None,
107
+ headers: dict[str, str] | None = None,
108
+ ) -> httpx.Response:
109
+ """Send one request; raise the mapped error for an error status."""
110
+ self.check_server_version()
111
+ target = self.url(path)
112
+ response = self._send(
113
+ method,
114
+ target,
115
+ retry=retry,
116
+ auth=auth,
117
+ json_body=json_body,
118
+ content=content,
119
+ headers=headers,
120
+ )
121
+ if response.is_error:
122
+ raise_for_status(response, method, scope=scope, hints=hints)
123
+ return response
124
+
125
+ def json(
126
+ self,
127
+ method: str,
128
+ path: str,
129
+ *,
130
+ scope: str | None = None,
131
+ hints: dict[int, str] | None = None,
132
+ retry: bool = False,
133
+ json_body: dict[str, Any] | None = None,
134
+ ) -> Any: # noqa: ANN401 - the API's JSON, passed through as is
135
+ return self.request(
136
+ method, path, scope=scope, hints=hints, retry=retry, json_body=json_body
137
+ ).json()
138
+
139
+ @contextmanager
140
+ def stream(self, path: str, *, scope: str | None) -> Iterator[httpx.Response]:
141
+ """A streamed GET, raising the mapped error before any byte is read."""
142
+ self.check_server_version()
143
+ with self._http.stream("GET", self.url(path), headers=self._headers()) as resp:
144
+ if resp.is_error:
145
+ resp.read()
146
+ raise_for_status(resp, "GET", scope=scope)
147
+ yield resp
148
+
149
+ def check_server_version(self) -> None:
150
+ """Warn once when the server runs a different release than this client.
151
+
152
+ Best effort: a server that cannot be read is left to the request
153
+ that follows, which reports the failure itself.
154
+ """
155
+ if self._version_checked:
156
+ return
157
+ self._version_checked = True
158
+ try:
159
+ server = self._send("GET", self.url("version"), retry=False, auth=False)
160
+ image_tag = server.json().get("image_tag") if server.is_success else None
161
+ except (httpx.HTTPError, NetworkError, ValueError, AttributeError):
162
+ logger.debug("could not read the server version", exc_info=True)
163
+ return
164
+ if (
165
+ isinstance(image_tag, str)
166
+ and _SEMVER.match(image_tag)
167
+ and _SEMVER.match(CLIENT_VERSION)
168
+ and image_tag != CLIENT_VERSION
169
+ ):
170
+ logger.warning(
171
+ "tidefold-client %s is talking to a server on %s; "
172
+ "install tidefold-client==%s to match it",
173
+ CLIENT_VERSION,
174
+ image_tag,
175
+ image_tag,
176
+ )
177
+
178
+ def server_version(self) -> dict[str, Any]:
179
+ return self.json("GET", "version", retry=True)
180
+
181
+ def _headers(self, *, auth: bool = True) -> dict[str, str]:
182
+ headers = {"User-Agent": USER_AGENT}
183
+ if auth and self._token:
184
+ headers["Authorization"] = f"Bearer {self._token}"
185
+ return headers
186
+
187
+ def _send(
188
+ self,
189
+ method: str,
190
+ target: str,
191
+ *,
192
+ retry: bool,
193
+ auth: bool,
194
+ json_body: dict[str, Any] | None = None,
195
+ content: bytes | None = None,
196
+ headers: dict[str, str] | None = None,
197
+ ) -> httpx.Response:
198
+ merged = {**self._headers(auth=auth), **(headers or {})}
199
+
200
+ def attempt() -> httpx.Response:
201
+ return self._http.request(
202
+ method, target, json=json_body, content=content, headers=merged
203
+ )
204
+
205
+ for retry_number in range(1, _RETRY_ATTEMPTS if retry else 1):
206
+ try:
207
+ return attempt()
208
+ except httpx.TransportError as exc:
209
+ logger.debug("retrying %s after %s", method, type(exc).__name__)
210
+ time.sleep(_RETRY_BACKOFF_SECONDS * retry_number)
211
+ try:
212
+ return attempt()
213
+ except httpx.TransportError as exc:
214
+ msg = f"{method} {urlsplit(target).path}: {type(exc).__name__}: {exc}"
215
+ raise NetworkError(msg) from exc
216
+
217
+
218
+ def raise_for_status(
219
+ response: httpx.Response,
220
+ method: str,
221
+ *,
222
+ scope: str | None = None,
223
+ hints: dict[int, str] | None = None,
224
+ ) -> None:
225
+ """Raise the exception for an error response."""
226
+ status = response.status_code
227
+ path = response.request.url.path
228
+ detail = _detail(response)
229
+ message = f"{method} {path} -> {status}: {detail}"
230
+ hint = (hints or {}).get(status)
231
+ if hint is None and status == httpx.codes.UNAUTHORIZED:
232
+ hint = "the token is missing, wrong, expired or revoked"
233
+ if hint is None and status == httpx.codes.FORBIDDEN and scope:
234
+ hint = f"this call needs the token scope {scope!r}"
235
+ if hint:
236
+ message = f"{message} ({hint})"
237
+ kind: type[ApiError]
238
+ if status == httpx.codes.UNAUTHORIZED:
239
+ kind = AuthError
240
+ elif status == httpx.codes.FORBIDDEN:
241
+ kind = PermissionDenied
242
+ elif status == httpx.codes.NOT_FOUND:
243
+ kind = NotFound
244
+ elif status == httpx.codes.CONFLICT:
245
+ kind = Conflict
246
+ elif status in _INVALID:
247
+ kind = InvalidRequest
248
+ else:
249
+ kind = ApiError
250
+ raise kind(message, status=status, method=method, path=path, detail=detail)
251
+
252
+
253
+ def _detail(response: httpx.Response) -> str:
254
+ try:
255
+ body = response.json()
256
+ except ValueError:
257
+ return response.text[:_DETAIL_LIMIT]
258
+ detail = body.get("detail", body) if isinstance(body, dict) else body
259
+ text = detail if isinstance(detail, str) else json.dumps(detail)
260
+ return text[:_DETAIL_LIMIT]
@@ -0,0 +1,125 @@
1
+ """``client.workflows``: find workflows and start runs of them."""
2
+
3
+ import os
4
+ from collections.abc import Mapping, Sequence
5
+ from pathlib import Path
6
+ from typing import Any, Literal
7
+
8
+ import httpx
9
+
10
+ from tidefold_client._errors import NotFound
11
+ from tidefold_client._files import FilePath, Files
12
+ from tidefold_client._runs import Run, Runs
13
+ from tidefold_client._transport import Transport
14
+
15
+ type FileInputs = Mapping[str, FilePath | Sequence[FilePath]]
16
+
17
+ _START_HINTS: dict[int, str] = {
18
+ httpx.codes.NOT_FOUND: (
19
+ "no such workflow, or its category is not among the token's attributes"
20
+ ),
21
+ httpx.codes.CONFLICT: (
22
+ "the workflow has never been published, or its spec cannot run"
23
+ ),
24
+ }
25
+
26
+
27
+ class Workflows:
28
+ """The ``/v1/workflows`` routes."""
29
+
30
+ def __init__(self, transport: Transport, *, files: Files, runs: Runs) -> None:
31
+ self._transport = transport
32
+ self._files = files
33
+ self._runs = runs
34
+ self._ids: dict[str, str] = {}
35
+
36
+ def list(self) -> list[dict[str, Any]]:
37
+ """Every workflow this token can see, latest version of each."""
38
+ items = self._transport.json(
39
+ "GET", "v1/workflows", scope="workflow_read", retry=True
40
+ )
41
+ self._ids.update({item["name"]: item["id"] for item in items})
42
+ return items
43
+
44
+ def get_id(self, name: str) -> str:
45
+ """The stable id of the workflow whose ``metadata.name`` is ``name``.
46
+
47
+ Cached per client: a workflow's id stays the same across versions.
48
+ """
49
+ if name not in self._ids:
50
+ self.list()
51
+ if name not in self._ids:
52
+ msg = f"no workflow named {name!r} is visible to this token"
53
+ raise NotFound(
54
+ msg, status=404, method="GET", path="/v1/workflows", detail=msg
55
+ )
56
+ return self._ids[name]
57
+
58
+ def start(
59
+ self,
60
+ workflow: str | None = None,
61
+ *,
62
+ workflow_id: str | None = None,
63
+ inputs: Mapping[str, str] | None = None,
64
+ files: FileInputs | None = None,
65
+ subject: str | None = None,
66
+ correlation_id: str | None = None,
67
+ channel: Literal["published", "draft"] = "published",
68
+ ) -> Run:
69
+ """Upload ``files``, start a run of the workflow, return it unawaited.
70
+
71
+ ``workflow`` is the workflow's ``metadata.name``; ``workflow_id``
72
+ its stable id. Give exactly one. ``inputs`` are the data inputs,
73
+ all strings. ``files`` maps a file input to one path or a list of
74
+ paths. ``correlation_id`` is the caller's own reference; it does
75
+ not deduplicate, so starting twice starts two runs.
76
+ """
77
+ if (workflow is None) == (workflow_id is None):
78
+ msg = "give exactly one of workflow (its name) or workflow_id"
79
+ raise ValueError(msg)
80
+ data = _data_inputs(inputs)
81
+ file_paths = _file_inputs(files)
82
+ target = workflow_id or self.get_id(workflow or "")
83
+ body: dict[str, Any] = {
84
+ "data_inputs": data,
85
+ "file_inputs": [
86
+ {"name": name, "file_id": self._files.upload(path)["id"]}
87
+ for name, path in file_paths
88
+ ],
89
+ "channel": channel,
90
+ }
91
+ if subject is not None:
92
+ body["subject"] = subject
93
+ if correlation_id is not None:
94
+ body["correlation_id"] = correlation_id
95
+ created = self._transport.json(
96
+ "POST",
97
+ f"v1/workflows/{target}/runs",
98
+ scope="run_create",
99
+ hints=_START_HINTS,
100
+ json_body=body,
101
+ )
102
+ return Run(self._runs, created["run_id"])
103
+
104
+
105
+ def _data_inputs(inputs: Mapping[str, str] | None) -> dict[str, str]:
106
+ data = dict(inputs or {})
107
+ for name, value in data.items():
108
+ if not isinstance(value, str):
109
+ msg = f"input {name!r} must be a string, got {type(value).__name__}"
110
+ raise TypeError(msg)
111
+ return data
112
+
113
+
114
+ def _file_inputs(files: FileInputs | None) -> list[tuple[str, Path]]:
115
+ """``(input name, path)`` pairs, every path checked before any upload."""
116
+ pairs: list[tuple[str, Path]] = []
117
+ for name, value in (files or {}).items():
118
+ paths = [value] if isinstance(value, (str, os.PathLike)) else list(value)
119
+ for raw in paths:
120
+ path = Path(raw)
121
+ if not path.is_file():
122
+ msg = f"file input {name!r}: {path} is not a file"
123
+ raise FileNotFoundError(msg)
124
+ pairs.append((name, path))
125
+ return pairs
File without changes