sharkmagic 0.1.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.
@@ -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,110 @@
1
+ Metadata-Version: 2.4
2
+ Name: sharkmagic
3
+ Version: 0.1.0
4
+ Summary: Python SDK for Shark: persistent Spaces for AI agents, every command in a fresh microVM
5
+ Author: Shark Magic
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://sharkmagic.si
8
+ Keywords: sandbox,microvm,ai-agents,code-execution,shark
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Provides-Extra: langchain
19
+ Requires-Dist: langchain-core>=0.3; extra == "langchain"
20
+ Provides-Extra: langgraph
21
+ Requires-Dist: langchain-core>=0.3; extra == "langgraph"
22
+ Requires-Dist: langgraph>=0.3; extra == "langgraph"
23
+ Provides-Extra: smolagents
24
+ Requires-Dist: smolagents>=1.20; extra == "smolagents"
25
+ Provides-Extra: prefect
26
+ Requires-Dist: prefect>=3; extra == "prefect"
27
+ Dynamic: license-file
28
+
29
+ # Shark SDK for Python
30
+
31
+ Persistent Spaces for AI agents: every command runs in a fresh microVM, the files stay. Python 3.9+, standard
32
+ library only (no dependencies).
33
+
34
+ ```sh
35
+ pip install sharkmagic
36
+ ```
37
+
38
+ ## Use
39
+
40
+ ```python
41
+ from sharkmagic import Shark
42
+
43
+ shark = Shark() # reads SHARK_API_KEY
44
+ space = shark.spaces.create(name="quickstart")
45
+
46
+ r = space.run("echo hello > hello.txt && cat hello.txt")
47
+ print(r.exit, r.stdout.strip()) # 0 hello
48
+
49
+ print(space.files.read_text("hello.txt")) # served from the committed tree, no VM
50
+
51
+ for fork in space.fork(count=2): # copies of the Space at the same commit, nothing copied
52
+ print(fork.id, fork.run("cat hello.txt").stdout.strip())
53
+
54
+ print(space.run("exit 7").exit) # a failing command is a result, not an exception
55
+ ```
56
+
57
+ Also: `space.run(cmd, cwd=..., env=..., timeout=..., check=True)`, `space.stream(cmd)` (live events),
58
+ `space.start(cmd)` (an `Op` at once), `space.files.write(...)`, `space.files.upload_dir(...)`, `space.hibernate()`,
59
+ `space.delete()`. Async: `AsyncShark`.
60
+
61
+ ## SDK Spaces: nothing of your account unless asked
62
+
63
+ Spaces made by the SDK are `sdk` Spaces (`space.profile`): your account's secrets, GitHub connection, background jobs
64
+ and the in-Space CLI credential do **not** reach them unless the Space asks
65
+ (docs: [api.md#sdk-spaces-and-devbox-spaces-profile](../../site-docs/api.md#sdk-spaces-and-devbox-spaces-profile)).
66
+
67
+ ```python
68
+ sp = shark.spaces.create(labels={"customer": "acme"}, egress="coding", # "deny" | "coding" | "open" | a policy
69
+ account_secrets=["OPENAI_API_KEY"], # "all" | "none" (default) | names
70
+ github=False, git={"name": "Acme Bot", "email": "bot@acme.test"},
71
+ keep_background=False, keep_awake=False, space_cli=False) # space_cli=["spaces:read"]: scopes
72
+ sp.update(account_secrets=None) # None: back to the profile's default
73
+ sp.run("python srv.py &", background=True) # this command's leftovers stay as a job
74
+ forks = sp.fork(count=3, account_secrets="none") # forks keep the source's choices unless overridden
75
+ [s.id for s in shark.spaces.list(label="customer:acme")]
76
+
77
+ sp.secrets.set("STRIPE_KEY", key, hosts=["api.stripe.com"], in_=["bearer"]) # inject (the value never enters the VM)
78
+ sp.secrets.set("GITHUB_TOKEN", tok, preset="github", allow_egress=True) # bring your own GitHub token
79
+ sp.secrets.set("DB_URL", url, exec=True); sp.run("…", secrets=["DB_URL"]) # exec: in that command's env
80
+ sp.secrets.rotate("STRIPE_KEY", new_key); sp.secrets.edit("STRIPE_KEY", hosts=[…]); sp.secrets.remove("DB_URL")
81
+ sp.secrets.reference("OPENAI_API_KEY") # use one account secret here
82
+ shark.secrets.set("OPENAI_API_KEY", key, preset="openai", apply="ref") # account secrets; shark.secrets.presets()
83
+ shark.space_defaults.set(account_secrets="none") # the account's default for unset fields
84
+ ```
85
+
86
+ `profile="devbox"` makes a Space as `shark create` / `shark code` do (account secrets, GitHub, background jobs).
87
+
88
+ Your own GitHub App (control-plane mode): `shark.github_app.register(app_id, pem)` once, then
89
+ `shark.github_app.link(space, installation_id, repos=["site"])` stores that installation's token as the Space's
90
+ `GITHUB_TOKEN` (its node keeps it fresh); `status()`, `remove()`.
91
+
92
+ ## Credentials
93
+
94
+ - `SHARK_API_KEY`: an API key from the Shark console (`shk_live_…`). Keep it in the environment, never in code.
95
+ - The SDK exchanges the key at the control plane (`https://api.sharkmagic.si`, or `SHARK_CP`) for short-lived node
96
+ credentials and sends each call to the node that holds the Space. The key itself never reaches a node.
97
+ - Self-hosted node: `Shark(base_url=..., api_key=...)` or `SHARK_API` (the node's own key).
98
+
99
+ ## Errors
100
+
101
+ Every API error is a `sharkmagic.SharkError` subclass with a stable `code` (`credits_exhausted`, `not_found`,
102
+ `quota_exceeded`, …). Retries keep the same `op_id`, so a command never runs twice.
103
+
104
+ ## Framework integrations
105
+
106
+ Optional extras: `sharkmagic[langchain]`, `[langgraph]`, `[smolagents]`, `[prefect]` (`sharkmagic.integrations.*`).
107
+
108
+ ## Docs
109
+
110
+ https://sharkmagic.si — quickstart, API reference, error codes and limits are linked from there.
@@ -0,0 +1,82 @@
1
+ # Shark SDK for Python
2
+
3
+ Persistent Spaces for AI agents: every command runs in a fresh microVM, the files stay. Python 3.9+, standard
4
+ library only (no dependencies).
5
+
6
+ ```sh
7
+ pip install sharkmagic
8
+ ```
9
+
10
+ ## Use
11
+
12
+ ```python
13
+ from sharkmagic import Shark
14
+
15
+ shark = Shark() # reads SHARK_API_KEY
16
+ space = shark.spaces.create(name="quickstart")
17
+
18
+ r = space.run("echo hello > hello.txt && cat hello.txt")
19
+ print(r.exit, r.stdout.strip()) # 0 hello
20
+
21
+ print(space.files.read_text("hello.txt")) # served from the committed tree, no VM
22
+
23
+ for fork in space.fork(count=2): # copies of the Space at the same commit, nothing copied
24
+ print(fork.id, fork.run("cat hello.txt").stdout.strip())
25
+
26
+ print(space.run("exit 7").exit) # a failing command is a result, not an exception
27
+ ```
28
+
29
+ Also: `space.run(cmd, cwd=..., env=..., timeout=..., check=True)`, `space.stream(cmd)` (live events),
30
+ `space.start(cmd)` (an `Op` at once), `space.files.write(...)`, `space.files.upload_dir(...)`, `space.hibernate()`,
31
+ `space.delete()`. Async: `AsyncShark`.
32
+
33
+ ## SDK Spaces: nothing of your account unless asked
34
+
35
+ Spaces made by the SDK are `sdk` Spaces (`space.profile`): your account's secrets, GitHub connection, background jobs
36
+ and the in-Space CLI credential do **not** reach them unless the Space asks
37
+ (docs: [api.md#sdk-spaces-and-devbox-spaces-profile](../../site-docs/api.md#sdk-spaces-and-devbox-spaces-profile)).
38
+
39
+ ```python
40
+ sp = shark.spaces.create(labels={"customer": "acme"}, egress="coding", # "deny" | "coding" | "open" | a policy
41
+ account_secrets=["OPENAI_API_KEY"], # "all" | "none" (default) | names
42
+ github=False, git={"name": "Acme Bot", "email": "bot@acme.test"},
43
+ keep_background=False, keep_awake=False, space_cli=False) # space_cli=["spaces:read"]: scopes
44
+ sp.update(account_secrets=None) # None: back to the profile's default
45
+ sp.run("python srv.py &", background=True) # this command's leftovers stay as a job
46
+ forks = sp.fork(count=3, account_secrets="none") # forks keep the source's choices unless overridden
47
+ [s.id for s in shark.spaces.list(label="customer:acme")]
48
+
49
+ sp.secrets.set("STRIPE_KEY", key, hosts=["api.stripe.com"], in_=["bearer"]) # inject (the value never enters the VM)
50
+ sp.secrets.set("GITHUB_TOKEN", tok, preset="github", allow_egress=True) # bring your own GitHub token
51
+ sp.secrets.set("DB_URL", url, exec=True); sp.run("…", secrets=["DB_URL"]) # exec: in that command's env
52
+ sp.secrets.rotate("STRIPE_KEY", new_key); sp.secrets.edit("STRIPE_KEY", hosts=[…]); sp.secrets.remove("DB_URL")
53
+ sp.secrets.reference("OPENAI_API_KEY") # use one account secret here
54
+ shark.secrets.set("OPENAI_API_KEY", key, preset="openai", apply="ref") # account secrets; shark.secrets.presets()
55
+ shark.space_defaults.set(account_secrets="none") # the account's default for unset fields
56
+ ```
57
+
58
+ `profile="devbox"` makes a Space as `shark create` / `shark code` do (account secrets, GitHub, background jobs).
59
+
60
+ Your own GitHub App (control-plane mode): `shark.github_app.register(app_id, pem)` once, then
61
+ `shark.github_app.link(space, installation_id, repos=["site"])` stores that installation's token as the Space's
62
+ `GITHUB_TOKEN` (its node keeps it fresh); `status()`, `remove()`.
63
+
64
+ ## Credentials
65
+
66
+ - `SHARK_API_KEY`: an API key from the Shark console (`shk_live_…`). Keep it in the environment, never in code.
67
+ - The SDK exchanges the key at the control plane (`https://api.sharkmagic.si`, or `SHARK_CP`) for short-lived node
68
+ credentials and sends each call to the node that holds the Space. The key itself never reaches a node.
69
+ - Self-hosted node: `Shark(base_url=..., api_key=...)` or `SHARK_API` (the node's own key).
70
+
71
+ ## Errors
72
+
73
+ Every API error is a `sharkmagic.SharkError` subclass with a stable `code` (`credits_exhausted`, `not_found`,
74
+ `quota_exceeded`, …). Retries keep the same `op_id`, so a command never runs twice.
75
+
76
+ ## Framework integrations
77
+
78
+ Optional extras: `sharkmagic[langchain]`, `[langgraph]`, `[smolagents]`, `[prefect]` (`sharkmagic.integrations.*`).
79
+
80
+ ## Docs
81
+
82
+ https://sharkmagic.si — quickstart, API reference, error codes and limits are linked from there.
@@ -0,0 +1,40 @@
1
+ [project]
2
+ name = "sharkmagic"
3
+ version = "0.1.0"
4
+ description = "Python SDK for Shark: persistent Spaces for AI agents, every command in a fresh microVM"
5
+ readme = "README.md"
6
+ requires-python = ">=3.9"
7
+ dependencies = []
8
+ license = "Apache-2.0"
9
+ license-files = ["LICENSE"]
10
+ authors = [{ name = "Shark Magic" }]
11
+ keywords = ["sandbox", "microvm", "ai-agents", "code-execution", "shark"]
12
+ classifiers = [
13
+ "Development Status :: 3 - Alpha",
14
+ "Intended Audience :: Developers",
15
+ "Operating System :: OS Independent",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3 :: Only",
18
+ "Typing :: Typed",
19
+ ]
20
+
21
+ [project.urls]
22
+ Homepage = "https://sharkmagic.si"
23
+
24
+ # Framework integrations (sharkmagic.integrations.*): optional, imported only when used.
25
+ # Tested versions are pinned in tests/integrations-constraints.txt.
26
+ [project.optional-dependencies]
27
+ langchain = ["langchain-core>=0.3"]
28
+ langgraph = ["langchain-core>=0.3", "langgraph>=0.3"]
29
+ smolagents = ["smolagents>=1.20"]
30
+ prefect = ["prefect>=3"]
31
+
32
+ [build-system]
33
+ requires = ["setuptools>=77"]
34
+ build-backend = "setuptools.build_meta"
35
+
36
+ [tool.setuptools]
37
+ packages = ["sharkmagic", "sharkmagic.integrations"]
38
+
39
+ [tool.setuptools.package-data]
40
+ sharkmagic = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,25 @@
1
+ """Shark SDK for Python (docs/spec/v1/sdk.md). Standard library only.
2
+
3
+ from sharkmagic import Shark
4
+ shark = Shark() # SHARK_API_KEY, SHARK_API
5
+ space = shark.spaces.create(name="demo")
6
+ print(space.run("echo hi").stdout)
7
+ """
8
+
9
+ from ._errors import (AuthenticationError, CapacityError, CommandFailedError, CommandTimeoutError, ConflictError,
10
+ CreditsExhaustedError, DurableUnavailableError, IdempotencyMismatchError, InfraError,
11
+ InvalidRequestError, LeaseCapError, NotFoundError, OpExpiredError, PermissionDeniedError,
12
+ QuotaExceededError, RateLimitError, ServerError, SharkError, SpaceLimitError, UnsupportedError,
13
+ WaitTimeoutError)
14
+ from ._errors import ConnectionError
15
+ from ._transport import ROUTES, VERSION, Event, Transport
16
+ from .client import (AccountPorts, AccountSecrets, AsyncShark, Egress, ExecResult, FileEntry, Op, Ports, Shark, Space, SpaceDefaults,
17
+ SpaceEgress, SpaceSecrets, new_op_id)
18
+
19
+ __version__ = VERSION
20
+ __all__ = ["Shark", "AsyncShark", "Space", "SpaceSecrets", "SpaceEgress", "Egress", "AccountSecrets", "SpaceDefaults", "Ports", "AccountPorts", "Op", "ExecResult", "FileEntry", "Event", "Transport", "ROUTES", "new_op_id",
21
+ "SharkError", "AuthenticationError", "PermissionDeniedError", "NotFoundError", "ConflictError",
22
+ "IdempotencyMismatchError", "OpExpiredError", "InvalidRequestError", "UnsupportedError", "RateLimitError",
23
+ "LeaseCapError", "SpaceLimitError", "QuotaExceededError", "CreditsExhaustedError", "ServerError",
24
+ "CapacityError", "DurableUnavailableError", "CommandFailedError", "InfraError", "CommandTimeoutError",
25
+ "WaitTimeoutError", "ConnectionError"]
@@ -0,0 +1,172 @@
1
+ """Typed errors (docs/spec/v1/sdk.md §5): one class per error.code family."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Optional
6
+
7
+
8
+ class SharkError(Exception):
9
+ """Base of every SDK error. ``code`` is the API's stable error code."""
10
+
11
+ def __init__(self, message: str, *, code: str = "", status: int = 0, request_id: str = "",
12
+ details: Optional[dict] = None, retryable: bool = False, retry_after: Optional[float] = None):
13
+ super().__init__(message)
14
+ self.message = message
15
+ self.code = code
16
+ self.status = status
17
+ self.request_id = request_id
18
+ self.details = details or {}
19
+ self.retryable = retryable
20
+ self.retry_after = retry_after
21
+
22
+ def __repr__(self) -> str:
23
+ return f"{type(self).__name__}(code={self.code!r}, status={self.status}, message={self.message!r})"
24
+
25
+
26
+ class AuthenticationError(SharkError):
27
+ pass
28
+
29
+
30
+ class PermissionDeniedError(SharkError):
31
+ pass
32
+
33
+
34
+ class NotFoundError(SharkError):
35
+ pass
36
+
37
+
38
+ class ConflictError(SharkError):
39
+ pass
40
+
41
+
42
+ class IdempotencyMismatchError(ConflictError):
43
+ pass
44
+
45
+
46
+ class OpExpiredError(SharkError):
47
+ pass
48
+
49
+
50
+ class InvalidRequestError(SharkError):
51
+ pass
52
+
53
+
54
+ class UnsupportedError(SharkError):
55
+ pass
56
+
57
+
58
+ class RateLimitError(SharkError):
59
+ pass
60
+
61
+
62
+ class LeaseCapError(RateLimitError):
63
+ @property
64
+ def scope(self) -> str:
65
+ return str(self.details.get("scope", ""))
66
+
67
+
68
+ class SpaceLimitError(RateLimitError):
69
+ pass
70
+
71
+
72
+ class QuotaExceededError(SharkError):
73
+ pass
74
+
75
+
76
+ class CreditsExhaustedError(SharkError):
77
+ pass
78
+
79
+
80
+ class ServerError(SharkError):
81
+ pass
82
+
83
+
84
+ class CapacityError(ServerError):
85
+ pass
86
+
87
+
88
+ class DurableUnavailableError(ServerError):
89
+ pass
90
+
91
+
92
+ class ConnectionError(SharkError): # noqa: A001 - the SDK's own, raised after retries
93
+ pass
94
+
95
+
96
+ class CommandFailedError(SharkError):
97
+ """Raised by run(..., check=True) when the command exits non-zero."""
98
+
99
+ def __init__(self, result: Any):
100
+ super().__init__(f"command exited {result.exit}", code="command_failed")
101
+ self.result = result
102
+ self.exit = result.exit
103
+ self.stdout = result.stdout
104
+ self.stderr = result.stderr
105
+ self.op_id = result.op_id
106
+
107
+
108
+ class InfraError(SharkError):
109
+ pass
110
+
111
+
112
+ class CommandTimeoutError(SharkError):
113
+ pass
114
+
115
+
116
+ class WaitTimeoutError(SharkError):
117
+ """op.wait(timeout=...) ran out of time (code ``wait_timeout``). The command keeps running: wait again,
118
+ ``op.refresh()``, or ``op.signal()`` it. ``.op_id``, ``.timeout`` (seconds)."""
119
+
120
+ def __init__(self, op_id: str, timeout: float):
121
+ super().__init__(f"op {op_id} still running after {timeout:g} s", code="wait_timeout",
122
+ details={"op_id": op_id, "timeout_s": timeout})
123
+ self.op_id = op_id
124
+ self.timeout = timeout
125
+
126
+
127
+ # code -> class (sdk.md §5)
128
+ CODE_CLASSES = {
129
+ "unauthenticated": AuthenticationError,
130
+ "auth_rate_limited": AuthenticationError,
131
+ "insufficient_scope": PermissionDeniedError,
132
+ "plan_restriction": PermissionDeniedError,
133
+ "tenant_not_allowed": PermissionDeniedError,
134
+ "not_found": NotFoundError,
135
+ "conflict": ConflictError,
136
+ "idempotency_mismatch": IdempotencyMismatchError,
137
+ "idempotency_in_progress": IdempotencyMismatchError,
138
+ "op_expired": OpExpiredError,
139
+ "invalid_request": InvalidRequestError,
140
+ "invalid_op_id": InvalidRequestError,
141
+ "path_outside_space": InvalidRequestError,
142
+ "payload_too_large": InvalidRequestError,
143
+ "precondition_failed": ConflictError,
144
+ "upgrade_required": InvalidRequestError,
145
+ "unsupported": UnsupportedError,
146
+ "rate_limited": RateLimitError,
147
+ "lease_cap_reached": LeaseCapError,
148
+ "space_limit_reached": SpaceLimitError,
149
+ "quota_exceeded": QuotaExceededError,
150
+ "credits_exhausted": CreditsExhaustedError,
151
+ "internal": ServerError,
152
+ "capacity_unavailable": CapacityError,
153
+ "out_of_capacity": CapacityError,
154
+ "insufficient_storage": QuotaExceededError,
155
+ "canceled": CapacityError,
156
+ "durable_unavailable": DurableUnavailableError,
157
+ }
158
+
159
+ # HTTP status -> class, for codes this SDK does not know yet
160
+ STATUS_CLASSES = {400: InvalidRequestError, 401: AuthenticationError, 402: CreditsExhaustedError, 403: PermissionDeniedError,
161
+ 404: NotFoundError, 409: ConflictError, 410: OpExpiredError, 412: ConflictError, 413: InvalidRequestError,
162
+ 422: UnsupportedError, 429: RateLimitError}
163
+
164
+
165
+ def error_class(code: str, status: int) -> type:
166
+ if code in CODE_CLASSES:
167
+ return CODE_CLASSES[code]
168
+ if status in STATUS_CLASSES:
169
+ return STATUS_CLASSES[status]
170
+ if status >= 500:
171
+ return ServerError
172
+ return SharkError