unfoldx 0.6.0__py3-none-any.whl
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.
- unfoldx-0.6.0.dist-info/METADATA +39 -0
- unfoldx-0.6.0.dist-info/RECORD +19 -0
- unfoldx-0.6.0.dist-info/WHEEL +4 -0
- unfoldx-0.6.0.dist-info/entry_points.txt +2 -0
- unfoldx-0.6.0.dist-info/licenses/LICENSE +202 -0
- unfoldx_cli/__init__.py +5 -0
- unfoldx_cli/__main__.py +3 -0
- unfoldx_cli/api.py +248 -0
- unfoldx_cli/command_ids.py +53 -0
- unfoldx_cli/commands.py +304 -0
- unfoldx_cli/config.py +60 -0
- unfoldx_cli/credentials.py +113 -0
- unfoldx_cli/errors.py +74 -0
- unfoldx_cli/exports.py +176 -0
- unfoldx_cli/main.py +230 -0
- unfoldx_cli/openapi.json +2939 -0
- unfoldx_cli/output.py +146 -0
- unfoldx_cli/redact.py +30 -0
- unfoldx_cli/resources.py +196 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: unfoldx
|
|
3
|
+
Version: 0.6.0
|
|
4
|
+
Summary: UnfoldX CLI - delegate explainer videos to the UnfoldX main agent and follow them to the finished film.
|
|
5
|
+
Project-URL: Homepage, https://unfoldx.ai
|
|
6
|
+
Project-URL: Source, https://github.com/unfoldx-ai/unfoldx
|
|
7
|
+
Project-URL: Issues, https://github.com/unfoldx-ai/unfoldx/issues
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Python: >=3.11
|
|
11
|
+
Provides-Extra: keychain
|
|
12
|
+
Requires-Dist: keyring>=24; extra == 'keychain'
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# unfoldx
|
|
16
|
+
|
|
17
|
+
Thin HTTPS client for the UnfoldX public API (`unfoldx.v2`, contract shipped in the
|
|
18
|
+
package as `unfoldx_cli/openapi.json`). Stdlib-only; install the `keychain`
|
|
19
|
+
extra to keep the token in the OS keychain instead of a 0600 file.
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pip install unfoldx
|
|
23
|
+
unfoldx login # approve the code in the browser
|
|
24
|
+
unfoldx runs submit --goal "讲清楚量子纠缠" --file notes.pdf --json
|
|
25
|
+
unfoldx runs wait <run_id> --json # until the film is ready or a question is open
|
|
26
|
+
unfoldx runs answer <run_id> --route template --json # within the approved budget
|
|
27
|
+
unfoldx artifacts download <run_id>.video --out ./out --json
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Designed to be driven by AI agents: non-interactive, one JSON object on stdout in
|
|
31
|
+
machine mode (`--json`, or whenever stdout is not a TTY), progress on stderr,
|
|
32
|
+
closed-set `error.type` with a precise `error.code`, and stable exit codes
|
|
33
|
+
(0 ok / 2 usage / 3 auth / 4 quota-or-rate / 5 input or open question /
|
|
34
|
+
6 environment / 7 failed / 8 timeout / 9 policy / 130 interrupt).
|
|
35
|
+
See [`../docs/cli-reference.md`](../docs/cli-reference.md).
|
|
36
|
+
|
|
37
|
+
Publishing receipts distinguish saved drafts from accepted publication. `published_url` is a validated link returned by the platform, or null when unavailable; acceptance does not prove public visibility or moderation approval. Follow `next_action` without uploading again.
|
|
38
|
+
|
|
39
|
+
`superfast download JOB --out DIR` creates the per-job directory on first use and refuses to overwrite a previous download unless `--overwrite` is explicit.
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
unfoldx_cli/__init__.py,sha256=In3Y63_MpKG0xZWL7YpneO_7le-qzXyfCkv-jx8BYvc,109
|
|
2
|
+
unfoldx_cli/__main__.py,sha256=OZiv2lofXUjrywlMKp0UfawCvpI9mE4Ia2wyUt_oS4U,29
|
|
3
|
+
unfoldx_cli/api.py,sha256=dcLftACIu0LZKSgvKf7bBxdj22A3gTcByD30vpk-LRA,12160
|
|
4
|
+
unfoldx_cli/command_ids.py,sha256=U1O8lNqm8nzooxtACm74dIJxwWiMqNS4PyI18o8LpzM,1760
|
|
5
|
+
unfoldx_cli/commands.py,sha256=QeXjwkRq8JAhjJdGXYJcgEf9DIIBGC_Bjsv1FGCqExE,15232
|
|
6
|
+
unfoldx_cli/config.py,sha256=BjTJ8WJ8yElTf-lV6Q_NQuK-A_fTNjOAt2vUnVPsmEc,2219
|
|
7
|
+
unfoldx_cli/credentials.py,sha256=NXVesLTMq2K2fcgzJR8tke3EdMFWvtGEee2lZaIR9ZI,3700
|
|
8
|
+
unfoldx_cli/errors.py,sha256=-TfCH5nobW5xc57Ul-1AQfQTFOtWlmASP8896pSM9nc,2087
|
|
9
|
+
unfoldx_cli/exports.py,sha256=TPulhMab2Ygdu6ap98s8wvjuKXzVWa0VLeSTUp0_g0k,6883
|
|
10
|
+
unfoldx_cli/main.py,sha256=bX4X5Dxn4vWo4jb1b7E5_Dw4IuhHHvJMeQeVTVE_6bc,12549
|
|
11
|
+
unfoldx_cli/openapi.json,sha256=bBVtTStUhUcuxc3P9NIlIbFA2APPZ-xNwbE7BhUQdJU,117895
|
|
12
|
+
unfoldx_cli/output.py,sha256=Xix2PxuucSNvdwq4GjuUHY1apalit99ncSkpyPyJ5BY,7816
|
|
13
|
+
unfoldx_cli/redact.py,sha256=m1EMSJyV4ekEKs6Uzh2q_LbyMpB_YSXdAzT_8T_XePM,834
|
|
14
|
+
unfoldx_cli/resources.py,sha256=v5XGBO2_qGd4twy7fw0b-IOL-jvDu936JXt_U4Ujy-Y,6994
|
|
15
|
+
unfoldx-0.6.0.dist-info/METADATA,sha256=uttU5oy3c7RKbmSgywwPQnkBaMRd_sI3oIrmc5j2Kmw,2032
|
|
16
|
+
unfoldx-0.6.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
17
|
+
unfoldx-0.6.0.dist-info/entry_points.txt,sha256=3r1lSr6mGp6Mpt_T-P__ligXAhHZe1Q-2_6DTBpll3c,49
|
|
18
|
+
unfoldx-0.6.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
19
|
+
unfoldx-0.6.0.dist-info/RECORD,,
|
|
@@ -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.
|
unfoldx_cli/__init__.py
ADDED
unfoldx_cli/__main__.py
ADDED
unfoldx_cli/api.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""Thin HTTPS client for the unfoldx.v2 public API (stdlib only).
|
|
2
|
+
|
|
3
|
+
Robustness rules:
|
|
4
|
+
- https required except for localhost (contract tests).
|
|
5
|
+
- Retries dropped connections and errors the server marks retryable, honoring
|
|
6
|
+
retry_after_sec. Every call here is a read or carries its own idempotency; the
|
|
7
|
+
device-code poll retries in its own loop until the grant expires.
|
|
8
|
+
- Every failure is normalized into the closed-set UnfoldxError taxonomy; the
|
|
9
|
+
server's `code`, `outcome` and `details` pass through unchanged.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import hashlib
|
|
15
|
+
import http.client
|
|
16
|
+
import math
|
|
17
|
+
import os
|
|
18
|
+
import tempfile
|
|
19
|
+
from datetime import datetime, timezone
|
|
20
|
+
from email.utils import parsedate_to_datetime
|
|
21
|
+
import json
|
|
22
|
+
import socket
|
|
23
|
+
import time
|
|
24
|
+
import urllib.error
|
|
25
|
+
import urllib.parse
|
|
26
|
+
import urllib.request
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
|
|
29
|
+
from . import SCHEMA, __version__
|
|
30
|
+
from .errors import UnfoldxError
|
|
31
|
+
|
|
32
|
+
_LOCAL_HOSTS = {"127.0.0.1", "localhost", "::1"}
|
|
33
|
+
_MAX_RETRIES = 2
|
|
34
|
+
_MAX_BACKOFF_SEC = 30.0
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class _NoApiRedirect(urllib.request.HTTPRedirectHandler):
|
|
38
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
39
|
+
raise UnfoldxError(
|
|
40
|
+
"environment", "The API redirected this request. Configure the final --api-base explicitly.",
|
|
41
|
+
code="api_redirect",
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _require_safe_url(url: str, purpose: str) -> None:
|
|
46
|
+
parsed = urllib.parse.urlparse(url)
|
|
47
|
+
if parsed.scheme not in {"http", "https"} or (parsed.scheme == "http" and parsed.hostname not in _LOCAL_HOSTS):
|
|
48
|
+
raise UnfoldxError(
|
|
49
|
+
"environment",
|
|
50
|
+
f"{purpose} must use https (got {parsed.scheme or 'no scheme'}); "
|
|
51
|
+
"plain http is only allowed for localhost testing.",
|
|
52
|
+
code="insecure_url",
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def quote(value: str) -> str:
|
|
57
|
+
return urllib.parse.quote(str(value), safe="")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
CLIENTS = ("cli", "mcp")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class ApiClient:
|
|
64
|
+
def __init__(self, api_base: str, token: str | None, timeout_sec: float = 30.0, *, client: str):
|
|
65
|
+
_require_safe_url(api_base, "API base URL")
|
|
66
|
+
if client not in CLIENTS:
|
|
67
|
+
raise ValueError(f"client {client!r} is not one of {', '.join(CLIENTS)}")
|
|
68
|
+
self.api_base = api_base.rstrip("/")
|
|
69
|
+
self.token = token
|
|
70
|
+
self.timeout_sec = timeout_sec
|
|
71
|
+
self.identity = {"User-Agent": f"unfoldx-cli/{__version__}", "X-Unfoldx-Client": client}
|
|
72
|
+
self._opener = urllib.request.build_opener(_NoApiRedirect())
|
|
73
|
+
|
|
74
|
+
def get(self, path: str, **query) -> dict:
|
|
75
|
+
params = {key: value for key, value in query.items() if value is not None}
|
|
76
|
+
return self.request("GET", path + (f"?{urllib.parse.urlencode(params)}" if params else ""))
|
|
77
|
+
|
|
78
|
+
def post(self, path: str, body: dict | None = None, *, retries: int = _MAX_RETRIES,
|
|
79
|
+
headers: dict | None = None) -> dict:
|
|
80
|
+
return self.request("POST", path, body=body or {}, retries=retries, headers=headers)
|
|
81
|
+
|
|
82
|
+
def delete(self, path: str) -> dict:
|
|
83
|
+
return self.request("DELETE", path)
|
|
84
|
+
|
|
85
|
+
def request(self, method: str, path: str, *, body: dict | None = None, retries: int = _MAX_RETRIES,
|
|
86
|
+
headers: dict | None = None) -> dict:
|
|
87
|
+
"""Send one operation within its time budget; preserve the write identity on failure."""
|
|
88
|
+
try:
|
|
89
|
+
return self._request(method, path, body=body, retries=retries, headers=headers)
|
|
90
|
+
except UnfoldxError as exc:
|
|
91
|
+
key = (headers or {}).get("Idempotency-Key")
|
|
92
|
+
if key:
|
|
93
|
+
exc.details = {**(exc.details or {}), "command_id": key,
|
|
94
|
+
"recovery_command": f"unfoldx commands show {key}"}
|
|
95
|
+
raise
|
|
96
|
+
|
|
97
|
+
def _request(self, method, path, *, body, retries, headers):
|
|
98
|
+
deadline = time.monotonic() + self.timeout_sec
|
|
99
|
+
url = self.api_base + path
|
|
100
|
+
payload = None if body is None else json.dumps(body).encode("utf-8")
|
|
101
|
+
attempt = 0
|
|
102
|
+
while True:
|
|
103
|
+
request = urllib.request.Request(url, data=payload, method=method, headers=self.identity)
|
|
104
|
+
request.add_header("Accept", "application/json")
|
|
105
|
+
if payload is not None:
|
|
106
|
+
request.add_header("Content-Type", "application/json")
|
|
107
|
+
if self.token:
|
|
108
|
+
request.add_header("Authorization", f"Bearer {self.token}")
|
|
109
|
+
for name, value in (headers or {}).items():
|
|
110
|
+
request.add_header(name, value)
|
|
111
|
+
try:
|
|
112
|
+
with self._opener.open(request, timeout=max(0.001, deadline - time.monotonic())) as response:
|
|
113
|
+
envelope = json.loads(response.read().decode("utf-8"))
|
|
114
|
+
except urllib.error.HTTPError as exc:
|
|
115
|
+
error = self._parse_error(exc)
|
|
116
|
+
if attempt < retries and error.retryable:
|
|
117
|
+
delay = (float(error.retry_after_sec) if error.retry_after_sec is not None
|
|
118
|
+
else min(2.0 ** (attempt + 1), _MAX_BACKOFF_SEC))
|
|
119
|
+
if time.monotonic() + delay < deadline:
|
|
120
|
+
attempt += 1
|
|
121
|
+
time.sleep(delay)
|
|
122
|
+
continue
|
|
123
|
+
raise error from None
|
|
124
|
+
except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException) as exc:
|
|
125
|
+
reason = getattr(exc, "reason", exc)
|
|
126
|
+
timed_out = isinstance(reason, (socket.timeout, TimeoutError))
|
|
127
|
+
error = UnfoldxError(
|
|
128
|
+
"timeout" if timed_out else "environment",
|
|
129
|
+
"Request timed out." if timed_out else "The API connection was interrupted; retry with the same command id.",
|
|
130
|
+
code="request_timeout" if timed_out else "connection_failed", retryable=True,
|
|
131
|
+
)
|
|
132
|
+
delay = min(2.0 ** (attempt + 1), _MAX_BACKOFF_SEC)
|
|
133
|
+
if attempt < retries and time.monotonic() + delay < deadline:
|
|
134
|
+
attempt += 1
|
|
135
|
+
time.sleep(delay)
|
|
136
|
+
continue
|
|
137
|
+
raise error from None
|
|
138
|
+
except ValueError:
|
|
139
|
+
raise UnfoldxError("server_error", "The API returned a non-JSON response.", code="bad_response") from None
|
|
140
|
+
if not isinstance(envelope, dict) or envelope.get("schema") != SCHEMA or envelope.get("ok") is not True:
|
|
141
|
+
raise UnfoldxError(
|
|
142
|
+
"server_error", f"The API did not answer with a {SCHEMA} envelope.", code="bad_response"
|
|
143
|
+
)
|
|
144
|
+
return envelope.get("data") or {}
|
|
145
|
+
|
|
146
|
+
@staticmethod
|
|
147
|
+
def _parse_error(exc: urllib.error.HTTPError) -> UnfoldxError:
|
|
148
|
+
retry_after = None
|
|
149
|
+
header = exc.headers.get("Retry-After") if exc.headers else None
|
|
150
|
+
if header:
|
|
151
|
+
try:
|
|
152
|
+
retry_after = (max(0, int(header)) if header.isdigit() else
|
|
153
|
+
max(0, math.ceil((parsedate_to_datetime(header) - datetime.now(timezone.utc)).total_seconds())))
|
|
154
|
+
except (ValueError, TypeError, OverflowError):
|
|
155
|
+
pass
|
|
156
|
+
try:
|
|
157
|
+
error = json.loads(exc.read().decode("utf-8"))["error"]
|
|
158
|
+
return UnfoldxError(
|
|
159
|
+
str(error["type"]),
|
|
160
|
+
str(error.get("message") or ""),
|
|
161
|
+
code=error.get("code"),
|
|
162
|
+
retryable=bool(error.get("retryable", False)),
|
|
163
|
+
retry_after_sec=max([v for v in (error.get("retry_after_sec"), retry_after)
|
|
164
|
+
if isinstance(v, (int, float)) and v >= 0], default=None),
|
|
165
|
+
outcome=error.get("outcome"),
|
|
166
|
+
details=error.get("details"),
|
|
167
|
+
)
|
|
168
|
+
except (ValueError, KeyError, TypeError):
|
|
169
|
+
pass
|
|
170
|
+
if exc.code == 401:
|
|
171
|
+
return UnfoldxError("auth_failed", "Authentication failed.", code="http_401")
|
|
172
|
+
if exc.code == 404:
|
|
173
|
+
return UnfoldxError("not_found", "Resource not found.", code="http_404")
|
|
174
|
+
if exc.code == 429:
|
|
175
|
+
return UnfoldxError("rate_limited", "Rate limited.", code="http_429", retryable=True,
|
|
176
|
+
retry_after_sec=retry_after)
|
|
177
|
+
if exc.code >= 500:
|
|
178
|
+
return UnfoldxError("server_error", f"Server error (HTTP {exc.code}).", code=f"http_{exc.code}",
|
|
179
|
+
retryable=True)
|
|
180
|
+
return UnfoldxError("invalid_request", f"HTTP {exc.code}.", code=f"http_{exc.code}")
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def download_signed(client: ApiClient, url: str, dest: Path, timeout_sec: float, *,
|
|
184
|
+
overwrite: bool = False) -> tuple[int, str]:
|
|
185
|
+
"""Download completely before publishing a file; default publication never replaces another file."""
|
|
186
|
+
_require_safe_url(url, "Download URL")
|
|
187
|
+
if not overwrite and dest.exists():
|
|
188
|
+
raise UnfoldxError("usage", f"File already exists: {dest}. Use --overwrite to replace it.", code="file_exists")
|
|
189
|
+
total = 0
|
|
190
|
+
digest = hashlib.sha256()
|
|
191
|
+
fd, name = tempfile.mkstemp(prefix=".unfoldx-", suffix=".part", dir=dest.parent)
|
|
192
|
+
partial = Path(name)
|
|
193
|
+
try:
|
|
194
|
+
with os.fdopen(fd, "wb") as fh:
|
|
195
|
+
with urllib.request.urlopen(urllib.request.Request(url, headers=client.identity),
|
|
196
|
+
timeout=timeout_sec) as response:
|
|
197
|
+
while chunk := response.read(1024 * 256):
|
|
198
|
+
fh.write(chunk)
|
|
199
|
+
digest.update(chunk)
|
|
200
|
+
total += len(chunk)
|
|
201
|
+
expected = response.headers.get('Content-Length')
|
|
202
|
+
if expected is not None and total != int(expected):
|
|
203
|
+
raise http.client.IncompleteRead(b'', int(expected) - total)
|
|
204
|
+
if overwrite:
|
|
205
|
+
partial.replace(dest)
|
|
206
|
+
else:
|
|
207
|
+
try:
|
|
208
|
+
os.link(partial, dest) # atomic no-clobber, including a concurrent download
|
|
209
|
+
except FileExistsError:
|
|
210
|
+
raise UnfoldxError("usage", f"File already exists: {dest}. Use --overwrite to replace it.",
|
|
211
|
+
code="file_exists") from None
|
|
212
|
+
except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException):
|
|
213
|
+
raise UnfoldxError("environment", "Download interrupted; the existing file was preserved.",
|
|
214
|
+
code="download_failed", retryable=True) from None
|
|
215
|
+
finally:
|
|
216
|
+
partial.unlink(missing_ok=True)
|
|
217
|
+
return total, digest.hexdigest()
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def upload_form(client: ApiClient, upload: dict, path: Path, timeout_sec: float) -> None:
|
|
221
|
+
"""POST a file to the signed object-storage form the API issued, streaming it from disk."""
|
|
222
|
+
_require_safe_url(upload["url"], "Upload URL")
|
|
223
|
+
boundary = "unfoldx-" + hashlib.sha256(str(time.time_ns()).encode()).hexdigest()[:24]
|
|
224
|
+
head = b"".join(
|
|
225
|
+
f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode()
|
|
226
|
+
for name, value in upload["fields"].items())
|
|
227
|
+
head += (f'--{boundary}\r\nContent-Disposition: form-data; name="{upload.get("file_field", "file")}"; '
|
|
228
|
+
f'filename="{path.name}"\r\nContent-Type: application/octet-stream\r\n\r\n').encode()
|
|
229
|
+
tail = f"\r\n--{boundary}--\r\n".encode()
|
|
230
|
+
size = path.stat().st_size
|
|
231
|
+
with open(path, "rb") as fh:
|
|
232
|
+
def chunks():
|
|
233
|
+
yield head
|
|
234
|
+
while chunk := fh.read(1024 * 1024):
|
|
235
|
+
yield chunk
|
|
236
|
+
yield tail
|
|
237
|
+
request = urllib.request.Request(upload["url"], data=chunks(), method="POST", headers={
|
|
238
|
+
"Content-Type": f"multipart/form-data; boundary={boundary}",
|
|
239
|
+
"Content-Length": str(len(head) + size + len(tail)), **client.identity})
|
|
240
|
+
try:
|
|
241
|
+
with urllib.request.urlopen(request, timeout=timeout_sec):
|
|
242
|
+
pass
|
|
243
|
+
except urllib.error.HTTPError as exc:
|
|
244
|
+
raise UnfoldxError("invalid_request", f"Object storage refused the upload (HTTP {exc.code}).",
|
|
245
|
+
code="upload_rejected", retryable=exc.code >= 500) from None
|
|
246
|
+
except (urllib.error.URLError, TimeoutError, ConnectionError, http.client.HTTPException) as exc:
|
|
247
|
+
raise UnfoldxError("environment", f"Upload failed: {getattr(exc, 'reason', exc)}",
|
|
248
|
+
code="upload_failed", retryable=True) from None
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Client command ids: the Idempotency-Key a write carries.
|
|
2
|
+
|
|
3
|
+
An id is recorded under <config>/commands/ before the request goes out, keyed by what the command
|
|
4
|
+
asks for (goal, sources, the files' bytes), so running the same command again after a crash or a
|
|
5
|
+
lost response replays the run the server already accepted instead of starting a second one. `--new`
|
|
6
|
+
starts a fresh command on purpose.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import secrets
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from .config import config_dir
|
|
18
|
+
from .errors import UnfoldxError
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _record_path(request: dict) -> Path:
|
|
22
|
+
digest = hashlib.sha256(json.dumps(request, sort_keys=True, ensure_ascii=False).encode()).hexdigest()
|
|
23
|
+
return config_dir() / "commands" / f"{digest}.json"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def recall(request: dict) -> dict | None:
|
|
27
|
+
try:
|
|
28
|
+
return json.loads(_record_path(request).read_text(encoding="utf-8"))
|
|
29
|
+
except FileNotFoundError:
|
|
30
|
+
return None
|
|
31
|
+
except ValueError:
|
|
32
|
+
raise UnfoldxError("environment", "Command receipt is corrupt; recover the existing command before submitting again.",
|
|
33
|
+
code="invalid_command_receipt") from None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def record(request: dict, entry: dict) -> None:
|
|
37
|
+
path = _record_path(request)
|
|
38
|
+
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
39
|
+
partial = path.with_suffix(".part")
|
|
40
|
+
partial.write_text(json.dumps(entry, ensure_ascii=False), encoding="utf-8")
|
|
41
|
+
os.replace(partial, path)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def new_command_id() -> str:
|
|
45
|
+
return "cli_" + secrets.token_urlsafe(18)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def file_digest(path: Path) -> str:
|
|
49
|
+
digest = hashlib.sha256()
|
|
50
|
+
with open(path, "rb") as fh:
|
|
51
|
+
while chunk := fh.read(1024 * 1024):
|
|
52
|
+
digest.update(chunk)
|
|
53
|
+
return digest.hexdigest()
|